]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
pg_dump: Fix some minor memory leaks
[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         PQclear(res);
2376
2377         return 1;
2378 }
2379
2380 static void
2381 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2382                                                                                  PQExpBuffer upgrade_buffer,
2383                                                                                  Oid pg_type_oid)
2384 {
2385         PQExpBuffer upgrade_query = createPQExpBuffer();
2386         PGresult   *upgrade_res;
2387         Oid                     pg_type_array_oid;
2388
2389         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2390         appendPQExpBuffer(upgrade_buffer,
2391          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2392                                           pg_type_oid);
2393
2394         /* we only support old >= 8.3 for binary upgrades */
2395         appendPQExpBuffer(upgrade_query,
2396                                           "SELECT typarray "
2397                                           "FROM pg_catalog.pg_type "
2398                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2399                                           pg_type_oid);
2400
2401         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2402
2403         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2404
2405         if (OidIsValid(pg_type_array_oid))
2406         {
2407                 appendPQExpBuffer(upgrade_buffer,
2408                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2409                 appendPQExpBuffer(upgrade_buffer,
2410                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2411                                                   pg_type_array_oid);
2412         }
2413
2414         PQclear(upgrade_res);
2415         destroyPQExpBuffer(upgrade_query);
2416 }
2417
2418 static bool
2419 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2420                                                                                 PQExpBuffer upgrade_buffer,
2421                                                                                 Oid pg_rel_oid)
2422 {
2423         PQExpBuffer upgrade_query = createPQExpBuffer();
2424         PGresult   *upgrade_res;
2425         Oid                     pg_type_oid;
2426         bool            toast_set = false;
2427
2428         /* we only support old >= 8.3 for binary upgrades */
2429         appendPQExpBuffer(upgrade_query,
2430                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2431                                           "FROM pg_catalog.pg_class c "
2432                                           "LEFT JOIN pg_catalog.pg_class t ON "
2433                                           "  (c.reltoastrelid = t.oid) "
2434                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2435                                           pg_rel_oid);
2436
2437         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2438
2439         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2440
2441         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2442                                                                                          pg_type_oid);
2443
2444         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2445         {
2446                 /* Toast tables do not have pg_type array rows */
2447                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2448                                                                                         PQfnumber(upgrade_res, "trel")));
2449
2450                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2451                 appendPQExpBuffer(upgrade_buffer,
2452                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2453                                                   pg_type_toast_oid);
2454
2455                 toast_set = true;
2456         }
2457
2458         PQclear(upgrade_res);
2459         destroyPQExpBuffer(upgrade_query);
2460
2461         return toast_set;
2462 }
2463
2464 static void
2465 binary_upgrade_set_pg_class_oids(Archive *fout,
2466                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2467                                                                  bool is_index)
2468 {
2469         PQExpBuffer upgrade_query = createPQExpBuffer();
2470         PGresult   *upgrade_res;
2471         Oid                     pg_class_reltoastrelid;
2472         Oid                     pg_class_reltoastidxid;
2473
2474         appendPQExpBuffer(upgrade_query,
2475                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2476                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2477                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2478                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2479                                           pg_class_oid);
2480
2481         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2482
2483         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2484         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2485
2486         appendPQExpBuffer(upgrade_buffer,
2487                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2488
2489         if (!is_index)
2490         {
2491                 appendPQExpBuffer(upgrade_buffer,
2492                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2493                                                   pg_class_oid);
2494                 /* only tables have toast tables, not indexes */
2495                 if (OidIsValid(pg_class_reltoastrelid))
2496                 {
2497                         /*
2498                          * One complexity is that the table definition might not require
2499                          * the creation of a TOAST table, and the TOAST table might have
2500                          * been created long after table creation, when the table was
2501                          * loaded with wide data.  By setting the TOAST oid we force
2502                          * creation of the TOAST heap and TOAST index by the backend so we
2503                          * can cleanly copy the files during binary upgrade.
2504                          */
2505
2506                         appendPQExpBuffer(upgrade_buffer,
2507                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2508                                                           pg_class_reltoastrelid);
2509
2510                         /* every toast table has an index */
2511                         appendPQExpBuffer(upgrade_buffer,
2512                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2513                                                           pg_class_reltoastidxid);
2514                 }
2515         }
2516         else
2517                 appendPQExpBuffer(upgrade_buffer,
2518                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2519                                                   pg_class_oid);
2520
2521         appendPQExpBuffer(upgrade_buffer, "\n");
2522
2523         PQclear(upgrade_res);
2524         destroyPQExpBuffer(upgrade_query);
2525 }
2526
2527 /*
2528  * If the DumpableObject is a member of an extension, add a suitable
2529  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2530  */
2531 static void
2532 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2533                                                                 DumpableObject *dobj,
2534                                                                 const char *objlabel)
2535 {
2536         DumpableObject *extobj = NULL;
2537         int                     i;
2538
2539         if (!dobj->ext_member)
2540                 return;
2541
2542         /*
2543          * Find the parent extension.  We could avoid this search if we wanted to
2544          * add a link field to DumpableObject, but the space costs of that would
2545          * be considerable.  We assume that member objects could only have a
2546          * direct dependency on their own extension, not any others.
2547          */
2548         for (i = 0; i < dobj->nDeps; i++)
2549         {
2550                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2551                 if (extobj && extobj->objType == DO_EXTENSION)
2552                         break;
2553                 extobj = NULL;
2554         }
2555         if (extobj == NULL)
2556                 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2557
2558         appendPQExpBuffer(upgrade_buffer,
2559           "\n-- For binary upgrade, handle extension membership the hard way\n");
2560         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2561                                           fmtId(extobj->name),
2562                                           objlabel);
2563 }
2564
2565 /*
2566  * getNamespaces:
2567  *        read all namespaces in the system catalogs and return them in the
2568  * NamespaceInfo* structure
2569  *
2570  *      numNamespaces is set to the number of namespaces read in
2571  */
2572 NamespaceInfo *
2573 getNamespaces(Archive *fout, int *numNamespaces)
2574 {
2575         PGresult   *res;
2576         int                     ntups;
2577         int                     i;
2578         PQExpBuffer query;
2579         NamespaceInfo *nsinfo;
2580         int                     i_tableoid;
2581         int                     i_oid;
2582         int                     i_nspname;
2583         int                     i_rolname;
2584         int                     i_nspacl;
2585
2586         /*
2587          * Before 7.3, there are no real namespaces; create two dummy entries, one
2588          * for user stuff and one for system stuff.
2589          */
2590         if (fout->remoteVersion < 70300)
2591         {
2592                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2593
2594                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2595                 nsinfo[0].dobj.catId.tableoid = 0;
2596                 nsinfo[0].dobj.catId.oid = 0;
2597                 AssignDumpId(&nsinfo[0].dobj);
2598                 nsinfo[0].dobj.name = pg_strdup("public");
2599                 nsinfo[0].rolname = pg_strdup("");
2600                 nsinfo[0].nspacl = pg_strdup("");
2601
2602                 selectDumpableNamespace(&nsinfo[0]);
2603
2604                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2605                 nsinfo[1].dobj.catId.tableoid = 0;
2606                 nsinfo[1].dobj.catId.oid = 1;
2607                 AssignDumpId(&nsinfo[1].dobj);
2608                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2609                 nsinfo[1].rolname = pg_strdup("");
2610                 nsinfo[1].nspacl = pg_strdup("");
2611
2612                 selectDumpableNamespace(&nsinfo[1]);
2613
2614                 g_namespaces = nsinfo;
2615                 g_numNamespaces = *numNamespaces = 2;
2616
2617                 return nsinfo;
2618         }
2619
2620         query = createPQExpBuffer();
2621
2622         /* Make sure we are in proper schema */
2623         selectSourceSchema(fout, "pg_catalog");
2624
2625         /*
2626          * we fetch all namespaces including system ones, so that every object we
2627          * read in can be linked to a containing namespace.
2628          */
2629         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2630                                           "(%s nspowner) AS rolname, "
2631                                           "nspacl FROM pg_namespace",
2632                                           username_subquery);
2633
2634         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2635
2636         ntups = PQntuples(res);
2637
2638         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2639
2640         i_tableoid = PQfnumber(res, "tableoid");
2641         i_oid = PQfnumber(res, "oid");
2642         i_nspname = PQfnumber(res, "nspname");
2643         i_rolname = PQfnumber(res, "rolname");
2644         i_nspacl = PQfnumber(res, "nspacl");
2645
2646         for (i = 0; i < ntups; i++)
2647         {
2648                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2649                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2650                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2651                 AssignDumpId(&nsinfo[i].dobj);
2652                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2653                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2654                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2655
2656                 /* Decide whether to dump this namespace */
2657                 selectDumpableNamespace(&nsinfo[i]);
2658
2659                 if (strlen(nsinfo[i].rolname) == 0)
2660                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2661                                           nsinfo[i].dobj.name);
2662         }
2663
2664         PQclear(res);
2665         destroyPQExpBuffer(query);
2666
2667         g_namespaces = nsinfo;
2668         g_numNamespaces = *numNamespaces = ntups;
2669
2670         return nsinfo;
2671 }
2672
2673 /*
2674  * findNamespace:
2675  *              given a namespace OID and an object OID, look up the info read by
2676  *              getNamespaces
2677  *
2678  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2679  * a system object or not.      In 7.3 and later there is no guessing.
2680  */
2681 static NamespaceInfo *
2682 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2683 {
2684         int                     i;
2685
2686         if (fout->remoteVersion >= 70300)
2687         {
2688                 for (i = 0; i < g_numNamespaces; i++)
2689                 {
2690                         NamespaceInfo *nsinfo = &g_namespaces[i];
2691
2692                         if (nsoid == nsinfo->dobj.catId.oid)
2693                                 return nsinfo;
2694                 }
2695                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2696         }
2697         else
2698         {
2699                 /* This code depends on the layout set up by getNamespaces. */
2700                 if (objoid > g_last_builtin_oid)
2701                         i = 0;                          /* user object */
2702                 else
2703                         i = 1;                          /* system object */
2704                 return &g_namespaces[i];
2705         }
2706
2707         return NULL;                            /* keep compiler quiet */
2708 }
2709
2710 /*
2711  * getExtensions:
2712  *        read all extensions in the system catalogs and return them in the
2713  * ExtensionInfo* structure
2714  *
2715  *      numExtensions is set to the number of extensions read in
2716  */
2717 ExtensionInfo *
2718 getExtensions(Archive *fout, int *numExtensions)
2719 {
2720         PGresult   *res;
2721         int                     ntups;
2722         int                     i;
2723         PQExpBuffer query;
2724         ExtensionInfo *extinfo;
2725         int                     i_tableoid;
2726         int                     i_oid;
2727         int                     i_extname;
2728         int                     i_nspname;
2729         int                     i_extrelocatable;
2730         int                     i_extversion;
2731         int                     i_extconfig;
2732         int                     i_extcondition;
2733
2734         /*
2735          * Before 9.1, there are no extensions.
2736          */
2737         if (fout->remoteVersion < 90100)
2738         {
2739                 *numExtensions = 0;
2740                 return NULL;
2741         }
2742
2743         query = createPQExpBuffer();
2744
2745         /* Make sure we are in proper schema */
2746         selectSourceSchema(fout, "pg_catalog");
2747
2748         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2749                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2750                                           "FROM pg_extension x "
2751                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2752
2753         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2754
2755         ntups = PQntuples(res);
2756
2757         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2758
2759         i_tableoid = PQfnumber(res, "tableoid");
2760         i_oid = PQfnumber(res, "oid");
2761         i_extname = PQfnumber(res, "extname");
2762         i_nspname = PQfnumber(res, "nspname");
2763         i_extrelocatable = PQfnumber(res, "extrelocatable");
2764         i_extversion = PQfnumber(res, "extversion");
2765         i_extconfig = PQfnumber(res, "extconfig");
2766         i_extcondition = PQfnumber(res, "extcondition");
2767
2768         for (i = 0; i < ntups; i++)
2769         {
2770                 extinfo[i].dobj.objType = DO_EXTENSION;
2771                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2772                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2773                 AssignDumpId(&extinfo[i].dobj);
2774                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2775                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2776                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2777                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2778                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2779                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2780
2781                 /* Decide whether we want to dump it */
2782                 selectDumpableExtension(&(extinfo[i]));
2783         }
2784
2785         PQclear(res);
2786         destroyPQExpBuffer(query);
2787
2788         *numExtensions = ntups;
2789
2790         return extinfo;
2791 }
2792
2793 /*
2794  * getTypes:
2795  *        read all types in the system catalogs and return them in the
2796  * TypeInfo* structure
2797  *
2798  *      numTypes is set to the number of types read in
2799  *
2800  * NB: this must run after getFuncs() because we assume we can do
2801  * findFuncByOid().
2802  */
2803 TypeInfo *
2804 getTypes(Archive *fout, int *numTypes)
2805 {
2806         PGresult   *res;
2807         int                     ntups;
2808         int                     i;
2809         PQExpBuffer query = createPQExpBuffer();
2810         TypeInfo   *tyinfo;
2811         ShellTypeInfo *stinfo;
2812         int                     i_tableoid;
2813         int                     i_oid;
2814         int                     i_typname;
2815         int                     i_typnamespace;
2816         int                     i_rolname;
2817         int                     i_typinput;
2818         int                     i_typoutput;
2819         int                     i_typelem;
2820         int                     i_typrelid;
2821         int                     i_typrelkind;
2822         int                     i_typtype;
2823         int                     i_typisdefined;
2824         int                     i_isarray;
2825
2826         /*
2827          * we include even the built-in types because those may be used as array
2828          * elements by user-defined types
2829          *
2830          * we filter out the built-in types when we dump out the types
2831          *
2832          * same approach for undefined (shell) types and array types
2833          *
2834          * Note: as of 8.3 we can reliably detect whether a type is an
2835          * auto-generated array type by checking the element type's typarray.
2836          * (Before that the test is capable of generating false positives.) We
2837          * still check for name beginning with '_', though, so as to avoid the
2838          * cost of the subselect probe for all standard types.  This would have to
2839          * be revisited if the backend ever allows renaming of array types.
2840          */
2841
2842         /* Make sure we are in proper schema */
2843         selectSourceSchema(fout, "pg_catalog");
2844
2845         if (fout->remoteVersion >= 80300)
2846         {
2847                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2848                                                   "typnamespace, "
2849                                                   "(%s typowner) AS rolname, "
2850                                                   "typinput::oid AS typinput, "
2851                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2852                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2853                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2854                                                   "typtype, typisdefined, "
2855                                                   "typname[0] = '_' AND typelem != 0 AND "
2856                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2857                                                   "FROM pg_type",
2858                                                   username_subquery);
2859         }
2860         else if (fout->remoteVersion >= 70300)
2861         {
2862                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2863                                                   "typnamespace, "
2864                                                   "(%s typowner) AS rolname, "
2865                                                   "typinput::oid AS typinput, "
2866                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2867                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2868                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2869                                                   "typtype, typisdefined, "
2870                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2871                                                   "FROM pg_type",
2872                                                   username_subquery);
2873         }
2874         else if (fout->remoteVersion >= 70100)
2875         {
2876                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2877                                                   "0::oid AS typnamespace, "
2878                                                   "(%s typowner) AS rolname, "
2879                                                   "typinput::oid AS typinput, "
2880                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2881                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2882                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2883                                                   "typtype, typisdefined, "
2884                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2885                                                   "FROM pg_type",
2886                                                   username_subquery);
2887         }
2888         else
2889         {
2890                 appendPQExpBuffer(query, "SELECT "
2891                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2892                                                   "oid, typname, "
2893                                                   "0::oid AS typnamespace, "
2894                                                   "(%s typowner) AS rolname, "
2895                                                   "typinput::oid AS typinput, "
2896                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2897                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2898                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2899                                                   "typtype, typisdefined, "
2900                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2901                                                   "FROM pg_type",
2902                                                   username_subquery);
2903         }
2904
2905         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2906
2907         ntups = PQntuples(res);
2908
2909         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2910
2911         i_tableoid = PQfnumber(res, "tableoid");
2912         i_oid = PQfnumber(res, "oid");
2913         i_typname = PQfnumber(res, "typname");
2914         i_typnamespace = PQfnumber(res, "typnamespace");
2915         i_rolname = PQfnumber(res, "rolname");
2916         i_typinput = PQfnumber(res, "typinput");
2917         i_typoutput = PQfnumber(res, "typoutput");
2918         i_typelem = PQfnumber(res, "typelem");
2919         i_typrelid = PQfnumber(res, "typrelid");
2920         i_typrelkind = PQfnumber(res, "typrelkind");
2921         i_typtype = PQfnumber(res, "typtype");
2922         i_typisdefined = PQfnumber(res, "typisdefined");
2923         i_isarray = PQfnumber(res, "isarray");
2924
2925         for (i = 0; i < ntups; i++)
2926         {
2927                 tyinfo[i].dobj.objType = DO_TYPE;
2928                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2929                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2930                 AssignDumpId(&tyinfo[i].dobj);
2931                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2932                 tyinfo[i].dobj.namespace =
2933                         findNamespace(fout,
2934                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2935                                                   tyinfo[i].dobj.catId.oid);
2936                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2937                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2938                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2939                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2940                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2941                 tyinfo[i].shellType = NULL;
2942
2943                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2944                         tyinfo[i].isDefined = true;
2945                 else
2946                         tyinfo[i].isDefined = false;
2947
2948                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2949                         tyinfo[i].isArray = true;
2950                 else
2951                         tyinfo[i].isArray = false;
2952
2953                 /* Decide whether we want to dump it */
2954                 selectDumpableType(&tyinfo[i]);
2955
2956                 /*
2957                  * If it's a domain, fetch info about its constraints, if any
2958                  */
2959                 tyinfo[i].nDomChecks = 0;
2960                 tyinfo[i].domChecks = NULL;
2961                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2962                         getDomainConstraints(fout, &(tyinfo[i]));
2963
2964                 /*
2965                  * If it's a base type, make a DumpableObject representing a shell
2966                  * definition of the type.      We will need to dump that ahead of the I/O
2967                  * functions for the type.  Similarly, range types need a shell
2968                  * definition in case they have a canonicalize function.
2969                  *
2970                  * Note: the shell type doesn't have a catId.  You might think it
2971                  * should copy the base type's catId, but then it might capture the
2972                  * pg_depend entries for the type, which we don't want.
2973                  */
2974                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2975                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
2976                 {
2977                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2978                         stinfo->dobj.objType = DO_SHELL_TYPE;
2979                         stinfo->dobj.catId = nilCatalogId;
2980                         AssignDumpId(&stinfo->dobj);
2981                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2982                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2983                         stinfo->baseType = &(tyinfo[i]);
2984                         tyinfo[i].shellType = stinfo;
2985
2986                         /*
2987                          * Initially mark the shell type as not to be dumped.  We'll only
2988                          * dump it if the I/O or canonicalize functions need to be dumped;
2989                          * this is taken care of while sorting dependencies.
2990                          */
2991                         stinfo->dobj.dump = false;
2992
2993                         /*
2994                          * However, if dumping from pre-7.3, there will be no dependency
2995                          * info so we have to fake it here.  We only need to worry about
2996                          * typinput and typoutput since the other functions only exist
2997                          * post-7.3.
2998                          */
2999                         if (fout->remoteVersion < 70300)
3000                         {
3001                                 Oid                     typinput;
3002                                 Oid                     typoutput;
3003                                 FuncInfo   *funcInfo;
3004
3005                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3006                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3007
3008                                 funcInfo = findFuncByOid(typinput);
3009                                 if (funcInfo && funcInfo->dobj.dump)
3010                                 {
3011                                         /* base type depends on function */
3012                                         addObjectDependency(&tyinfo[i].dobj,
3013                                                                                 funcInfo->dobj.dumpId);
3014                                         /* function depends on shell type */
3015                                         addObjectDependency(&funcInfo->dobj,
3016                                                                                 stinfo->dobj.dumpId);
3017                                         /* mark shell type as to be dumped */
3018                                         stinfo->dobj.dump = true;
3019                                 }
3020
3021                                 funcInfo = findFuncByOid(typoutput);
3022                                 if (funcInfo && funcInfo->dobj.dump)
3023                                 {
3024                                         /* base type depends on function */
3025                                         addObjectDependency(&tyinfo[i].dobj,
3026                                                                                 funcInfo->dobj.dumpId);
3027                                         /* function depends on shell type */
3028                                         addObjectDependency(&funcInfo->dobj,
3029                                                                                 stinfo->dobj.dumpId);
3030                                         /* mark shell type as to be dumped */
3031                                         stinfo->dobj.dump = true;
3032                                 }
3033                         }
3034                 }
3035
3036                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3037                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3038                                           tyinfo[i].dobj.name);
3039         }
3040
3041         *numTypes = ntups;
3042
3043         PQclear(res);
3044
3045         destroyPQExpBuffer(query);
3046
3047         return tyinfo;
3048 }
3049
3050 /*
3051  * getOperators:
3052  *        read all operators in the system catalogs and return them in the
3053  * OprInfo* structure
3054  *
3055  *      numOprs is set to the number of operators read in
3056  */
3057 OprInfo *
3058 getOperators(Archive *fout, int *numOprs)
3059 {
3060         PGresult   *res;
3061         int                     ntups;
3062         int                     i;
3063         PQExpBuffer query = createPQExpBuffer();
3064         OprInfo    *oprinfo;
3065         int                     i_tableoid;
3066         int                     i_oid;
3067         int                     i_oprname;
3068         int                     i_oprnamespace;
3069         int                     i_rolname;
3070         int                     i_oprkind;
3071         int                     i_oprcode;
3072
3073         /*
3074          * find all operators, including builtin operators; we filter out
3075          * system-defined operators at dump-out time.
3076          */
3077
3078         /* Make sure we are in proper schema */
3079         selectSourceSchema(fout, "pg_catalog");
3080
3081         if (fout->remoteVersion >= 70300)
3082         {
3083                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3084                                                   "oprnamespace, "
3085                                                   "(%s oprowner) AS rolname, "
3086                                                   "oprkind, "
3087                                                   "oprcode::oid AS oprcode "
3088                                                   "FROM pg_operator",
3089                                                   username_subquery);
3090         }
3091         else if (fout->remoteVersion >= 70100)
3092         {
3093                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3094                                                   "0::oid AS oprnamespace, "
3095                                                   "(%s oprowner) AS rolname, "
3096                                                   "oprkind, "
3097                                                   "oprcode::oid AS oprcode "
3098                                                   "FROM pg_operator",
3099                                                   username_subquery);
3100         }
3101         else
3102         {
3103                 appendPQExpBuffer(query, "SELECT "
3104                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3105                                                   "oid, oprname, "
3106                                                   "0::oid AS oprnamespace, "
3107                                                   "(%s oprowner) AS rolname, "
3108                                                   "oprkind, "
3109                                                   "oprcode::oid AS oprcode "
3110                                                   "FROM pg_operator",
3111                                                   username_subquery);
3112         }
3113
3114         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3115
3116         ntups = PQntuples(res);
3117         *numOprs = ntups;
3118
3119         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3120
3121         i_tableoid = PQfnumber(res, "tableoid");
3122         i_oid = PQfnumber(res, "oid");
3123         i_oprname = PQfnumber(res, "oprname");
3124         i_oprnamespace = PQfnumber(res, "oprnamespace");
3125         i_rolname = PQfnumber(res, "rolname");
3126         i_oprkind = PQfnumber(res, "oprkind");
3127         i_oprcode = PQfnumber(res, "oprcode");
3128
3129         for (i = 0; i < ntups; i++)
3130         {
3131                 oprinfo[i].dobj.objType = DO_OPERATOR;
3132                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3133                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3134                 AssignDumpId(&oprinfo[i].dobj);
3135                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3136                 oprinfo[i].dobj.namespace =
3137                         findNamespace(fout,
3138                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3139                                                   oprinfo[i].dobj.catId.oid);
3140                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3141                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3142                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3143
3144                 /* Decide whether we want to dump it */
3145                 selectDumpableObject(&(oprinfo[i].dobj));
3146
3147                 if (strlen(oprinfo[i].rolname) == 0)
3148                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3149                                           oprinfo[i].dobj.name);
3150         }
3151
3152         PQclear(res);
3153
3154         destroyPQExpBuffer(query);
3155
3156         return oprinfo;
3157 }
3158
3159 /*
3160  * getCollations:
3161  *        read all collations in the system catalogs and return them in the
3162  * CollInfo* structure
3163  *
3164  *      numCollations is set to the number of collations read in
3165  */
3166 CollInfo *
3167 getCollations(Archive *fout, int *numCollations)
3168 {
3169         PGresult   *res;
3170         int                     ntups;
3171         int                     i;
3172         PQExpBuffer query;
3173         CollInfo   *collinfo;
3174         int                     i_tableoid;
3175         int                     i_oid;
3176         int                     i_collname;
3177         int                     i_collnamespace;
3178         int                     i_rolname;
3179
3180         /* Collations didn't exist pre-9.1 */
3181         if (fout->remoteVersion < 90100)
3182         {
3183                 *numCollations = 0;
3184                 return NULL;
3185         }
3186
3187         query = createPQExpBuffer();
3188
3189         /*
3190          * find all collations, including builtin collations; we filter out
3191          * system-defined collations at dump-out time.
3192          */
3193
3194         /* Make sure we are in proper schema */
3195         selectSourceSchema(fout, "pg_catalog");
3196
3197         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3198                                           "collnamespace, "
3199                                           "(%s collowner) AS rolname "
3200                                           "FROM pg_collation",
3201                                           username_subquery);
3202
3203         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3204
3205         ntups = PQntuples(res);
3206         *numCollations = ntups;
3207
3208         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3209
3210         i_tableoid = PQfnumber(res, "tableoid");
3211         i_oid = PQfnumber(res, "oid");
3212         i_collname = PQfnumber(res, "collname");
3213         i_collnamespace = PQfnumber(res, "collnamespace");
3214         i_rolname = PQfnumber(res, "rolname");
3215
3216         for (i = 0; i < ntups; i++)
3217         {
3218                 collinfo[i].dobj.objType = DO_COLLATION;
3219                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3220                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3221                 AssignDumpId(&collinfo[i].dobj);
3222                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3223                 collinfo[i].dobj.namespace =
3224                         findNamespace(fout,
3225                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3226                                                   collinfo[i].dobj.catId.oid);
3227                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3228
3229                 /* Decide whether we want to dump it */
3230                 selectDumpableObject(&(collinfo[i].dobj));
3231         }
3232
3233         PQclear(res);
3234
3235         destroyPQExpBuffer(query);
3236
3237         return collinfo;
3238 }
3239
3240 /*
3241  * getConversions:
3242  *        read all conversions in the system catalogs and return them in the
3243  * ConvInfo* structure
3244  *
3245  *      numConversions is set to the number of conversions read in
3246  */
3247 ConvInfo *
3248 getConversions(Archive *fout, int *numConversions)
3249 {
3250         PGresult   *res;
3251         int                     ntups;
3252         int                     i;
3253         PQExpBuffer query = createPQExpBuffer();
3254         ConvInfo   *convinfo;
3255         int                     i_tableoid;
3256         int                     i_oid;
3257         int                     i_conname;
3258         int                     i_connamespace;
3259         int                     i_rolname;
3260
3261         /* Conversions didn't exist pre-7.3 */
3262         if (fout->remoteVersion < 70300)
3263         {
3264                 *numConversions = 0;
3265                 return NULL;
3266         }
3267
3268         /*
3269          * find all conversions, including builtin conversions; we filter out
3270          * system-defined conversions at dump-out time.
3271          */
3272
3273         /* Make sure we are in proper schema */
3274         selectSourceSchema(fout, "pg_catalog");
3275
3276         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3277                                           "connamespace, "
3278                                           "(%s conowner) AS rolname "
3279                                           "FROM pg_conversion",
3280                                           username_subquery);
3281
3282         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3283
3284         ntups = PQntuples(res);
3285         *numConversions = ntups;
3286
3287         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3288
3289         i_tableoid = PQfnumber(res, "tableoid");
3290         i_oid = PQfnumber(res, "oid");
3291         i_conname = PQfnumber(res, "conname");
3292         i_connamespace = PQfnumber(res, "connamespace");
3293         i_rolname = PQfnumber(res, "rolname");
3294
3295         for (i = 0; i < ntups; i++)
3296         {
3297                 convinfo[i].dobj.objType = DO_CONVERSION;
3298                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3299                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3300                 AssignDumpId(&convinfo[i].dobj);
3301                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3302                 convinfo[i].dobj.namespace =
3303                         findNamespace(fout,
3304                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3305                                                   convinfo[i].dobj.catId.oid);
3306                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3307
3308                 /* Decide whether we want to dump it */
3309                 selectDumpableObject(&(convinfo[i].dobj));
3310         }
3311
3312         PQclear(res);
3313
3314         destroyPQExpBuffer(query);
3315
3316         return convinfo;
3317 }
3318
3319 /*
3320  * getOpclasses:
3321  *        read all opclasses in the system catalogs and return them in the
3322  * OpclassInfo* structure
3323  *
3324  *      numOpclasses is set to the number of opclasses read in
3325  */
3326 OpclassInfo *
3327 getOpclasses(Archive *fout, int *numOpclasses)
3328 {
3329         PGresult   *res;
3330         int                     ntups;
3331         int                     i;
3332         PQExpBuffer query = createPQExpBuffer();
3333         OpclassInfo *opcinfo;
3334         int                     i_tableoid;
3335         int                     i_oid;
3336         int                     i_opcname;
3337         int                     i_opcnamespace;
3338         int                     i_rolname;
3339
3340         /*
3341          * find all opclasses, including builtin opclasses; we filter out
3342          * system-defined opclasses at dump-out time.
3343          */
3344
3345         /* Make sure we are in proper schema */
3346         selectSourceSchema(fout, "pg_catalog");
3347
3348         if (fout->remoteVersion >= 70300)
3349         {
3350                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3351                                                   "opcnamespace, "
3352                                                   "(%s opcowner) AS rolname "
3353                                                   "FROM pg_opclass",
3354                                                   username_subquery);
3355         }
3356         else if (fout->remoteVersion >= 70100)
3357         {
3358                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3359                                                   "0::oid AS opcnamespace, "
3360                                                   "''::name AS rolname "
3361                                                   "FROM pg_opclass");
3362         }
3363         else
3364         {
3365                 appendPQExpBuffer(query, "SELECT "
3366                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3367                                                   "oid, opcname, "
3368                                                   "0::oid AS opcnamespace, "
3369                                                   "''::name AS rolname "
3370                                                   "FROM pg_opclass");
3371         }
3372
3373         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3374
3375         ntups = PQntuples(res);
3376         *numOpclasses = ntups;
3377
3378         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3379
3380         i_tableoid = PQfnumber(res, "tableoid");
3381         i_oid = PQfnumber(res, "oid");
3382         i_opcname = PQfnumber(res, "opcname");
3383         i_opcnamespace = PQfnumber(res, "opcnamespace");
3384         i_rolname = PQfnumber(res, "rolname");
3385
3386         for (i = 0; i < ntups; i++)
3387         {
3388                 opcinfo[i].dobj.objType = DO_OPCLASS;
3389                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3390                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3391                 AssignDumpId(&opcinfo[i].dobj);
3392                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3393                 opcinfo[i].dobj.namespace =
3394                         findNamespace(fout,
3395                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3396                                                   opcinfo[i].dobj.catId.oid);
3397                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3398
3399                 /* Decide whether we want to dump it */
3400                 selectDumpableObject(&(opcinfo[i].dobj));
3401
3402                 if (fout->remoteVersion >= 70300)
3403                 {
3404                         if (strlen(opcinfo[i].rolname) == 0)
3405                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3406                                                   opcinfo[i].dobj.name);
3407                 }
3408         }
3409
3410         PQclear(res);
3411
3412         destroyPQExpBuffer(query);
3413
3414         return opcinfo;
3415 }
3416
3417 /*
3418  * getOpfamilies:
3419  *        read all opfamilies in the system catalogs and return them in the
3420  * OpfamilyInfo* structure
3421  *
3422  *      numOpfamilies is set to the number of opfamilies read in
3423  */
3424 OpfamilyInfo *
3425 getOpfamilies(Archive *fout, int *numOpfamilies)
3426 {
3427         PGresult   *res;
3428         int                     ntups;
3429         int                     i;
3430         PQExpBuffer query;
3431         OpfamilyInfo *opfinfo;
3432         int                     i_tableoid;
3433         int                     i_oid;
3434         int                     i_opfname;
3435         int                     i_opfnamespace;
3436         int                     i_rolname;
3437
3438         /* Before 8.3, there is no separate concept of opfamilies */
3439         if (fout->remoteVersion < 80300)
3440         {
3441                 *numOpfamilies = 0;
3442                 return NULL;
3443         }
3444
3445         query = createPQExpBuffer();
3446
3447         /*
3448          * find all opfamilies, including builtin opfamilies; we filter out
3449          * system-defined opfamilies at dump-out time.
3450          */
3451
3452         /* Make sure we are in proper schema */
3453         selectSourceSchema(fout, "pg_catalog");
3454
3455         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3456                                           "opfnamespace, "
3457                                           "(%s opfowner) AS rolname "
3458                                           "FROM pg_opfamily",
3459                                           username_subquery);
3460
3461         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3462
3463         ntups = PQntuples(res);
3464         *numOpfamilies = ntups;
3465
3466         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3467
3468         i_tableoid = PQfnumber(res, "tableoid");
3469         i_oid = PQfnumber(res, "oid");
3470         i_opfname = PQfnumber(res, "opfname");
3471         i_opfnamespace = PQfnumber(res, "opfnamespace");
3472         i_rolname = PQfnumber(res, "rolname");
3473
3474         for (i = 0; i < ntups; i++)
3475         {
3476                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3477                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3478                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3479                 AssignDumpId(&opfinfo[i].dobj);
3480                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3481                 opfinfo[i].dobj.namespace =
3482                         findNamespace(fout,
3483                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3484                                                   opfinfo[i].dobj.catId.oid);
3485                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3486
3487                 /* Decide whether we want to dump it */
3488                 selectDumpableObject(&(opfinfo[i].dobj));
3489
3490                 if (fout->remoteVersion >= 70300)
3491                 {
3492                         if (strlen(opfinfo[i].rolname) == 0)
3493                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3494                                                   opfinfo[i].dobj.name);
3495                 }
3496         }
3497
3498         PQclear(res);
3499
3500         destroyPQExpBuffer(query);
3501
3502         return opfinfo;
3503 }
3504
3505 /*
3506  * getAggregates:
3507  *        read all the user-defined aggregates in the system catalogs and
3508  * return them in the AggInfo* structure
3509  *
3510  * numAggs is set to the number of aggregates read in
3511  */
3512 AggInfo *
3513 getAggregates(Archive *fout, int *numAggs)
3514 {
3515         PGresult   *res;
3516         int                     ntups;
3517         int                     i;
3518         PQExpBuffer query = createPQExpBuffer();
3519         AggInfo    *agginfo;
3520         int                     i_tableoid;
3521         int                     i_oid;
3522         int                     i_aggname;
3523         int                     i_aggnamespace;
3524         int                     i_pronargs;
3525         int                     i_proargtypes;
3526         int                     i_rolname;
3527         int                     i_aggacl;
3528
3529         /* Make sure we are in proper schema */
3530         selectSourceSchema(fout, "pg_catalog");
3531
3532         /*
3533          * Find all user-defined aggregates.  See comment in getFuncs() for the
3534          * rationale behind the filtering logic.
3535          */
3536
3537         if (fout->remoteVersion >= 80200)
3538         {
3539                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3540                                                   "pronamespace AS aggnamespace, "
3541                                                   "pronargs, proargtypes, "
3542                                                   "(%s proowner) AS rolname, "
3543                                                   "proacl AS aggacl "
3544                                                   "FROM pg_proc p "
3545                                                   "WHERE proisagg AND ("
3546                                                   "pronamespace != "
3547                                                   "(SELECT oid FROM pg_namespace "
3548                                                   "WHERE nspname = 'pg_catalog')",
3549                                                   username_subquery);
3550                 if (binary_upgrade && fout->remoteVersion >= 90100)
3551                         appendPQExpBuffer(query,
3552                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3553                                                           "classid = 'pg_proc'::regclass AND "
3554                                                           "objid = p.oid AND "
3555                                                           "refclassid = 'pg_extension'::regclass AND "
3556                                                           "deptype = 'e')");
3557                 appendPQExpBuffer(query, ")");
3558         }
3559         else if (fout->remoteVersion >= 70300)
3560         {
3561                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3562                                                   "pronamespace AS aggnamespace, "
3563                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3564                                                   "proargtypes, "
3565                                                   "(%s proowner) AS rolname, "
3566                                                   "proacl AS aggacl "
3567                                                   "FROM pg_proc "
3568                                                   "WHERE proisagg "
3569                                                   "AND pronamespace != "
3570                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3571                                                   username_subquery);
3572         }
3573         else if (fout->remoteVersion >= 70100)
3574         {
3575                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3576                                                   "0::oid AS aggnamespace, "
3577                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3578                                                   "aggbasetype AS proargtypes, "
3579                                                   "(%s aggowner) AS rolname, "
3580                                                   "'{=X}' AS aggacl "
3581                                                   "FROM pg_aggregate "
3582                                                   "where oid > '%u'::oid",
3583                                                   username_subquery,
3584                                                   g_last_builtin_oid);
3585         }
3586         else
3587         {
3588                 appendPQExpBuffer(query, "SELECT "
3589                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3590                                                   "oid, aggname, "
3591                                                   "0::oid AS aggnamespace, "
3592                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3593                                                   "aggbasetype AS proargtypes, "
3594                                                   "(%s aggowner) AS rolname, "
3595                                                   "'{=X}' AS aggacl "
3596                                                   "FROM pg_aggregate "
3597                                                   "where oid > '%u'::oid",
3598                                                   username_subquery,
3599                                                   g_last_builtin_oid);
3600         }
3601
3602         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3603
3604         ntups = PQntuples(res);
3605         *numAggs = ntups;
3606
3607         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3608
3609         i_tableoid = PQfnumber(res, "tableoid");
3610         i_oid = PQfnumber(res, "oid");
3611         i_aggname = PQfnumber(res, "aggname");
3612         i_aggnamespace = PQfnumber(res, "aggnamespace");
3613         i_pronargs = PQfnumber(res, "pronargs");
3614         i_proargtypes = PQfnumber(res, "proargtypes");
3615         i_rolname = PQfnumber(res, "rolname");
3616         i_aggacl = PQfnumber(res, "aggacl");
3617
3618         for (i = 0; i < ntups; i++)
3619         {
3620                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3621                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3622                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3623                 AssignDumpId(&agginfo[i].aggfn.dobj);
3624                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3625                 agginfo[i].aggfn.dobj.namespace =
3626                         findNamespace(fout,
3627                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3628                                                   agginfo[i].aggfn.dobj.catId.oid);
3629                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3630                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3631                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3632                                           agginfo[i].aggfn.dobj.name);
3633                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3634                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3635                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3636                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3637                 if (agginfo[i].aggfn.nargs == 0)
3638                         agginfo[i].aggfn.argtypes = NULL;
3639                 else
3640                 {
3641                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3642                         if (fout->remoteVersion >= 70300)
3643                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3644                                                           agginfo[i].aggfn.argtypes,
3645                                                           agginfo[i].aggfn.nargs);
3646                         else
3647                                 /* it's just aggbasetype */
3648                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3649                 }
3650
3651                 /* Decide whether we want to dump it */
3652                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3653         }
3654
3655         PQclear(res);
3656
3657         destroyPQExpBuffer(query);
3658
3659         return agginfo;
3660 }
3661
3662 /*
3663  * getFuncs:
3664  *        read all the user-defined functions in the system catalogs and
3665  * return them in the FuncInfo* structure
3666  *
3667  * numFuncs is set to the number of functions read in
3668  */
3669 FuncInfo *
3670 getFuncs(Archive *fout, int *numFuncs)
3671 {
3672         PGresult   *res;
3673         int                     ntups;
3674         int                     i;
3675         PQExpBuffer query = createPQExpBuffer();
3676         FuncInfo   *finfo;
3677         int                     i_tableoid;
3678         int                     i_oid;
3679         int                     i_proname;
3680         int                     i_pronamespace;
3681         int                     i_rolname;
3682         int                     i_prolang;
3683         int                     i_pronargs;
3684         int                     i_proargtypes;
3685         int                     i_prorettype;
3686         int                     i_proacl;
3687
3688         /* Make sure we are in proper schema */
3689         selectSourceSchema(fout, "pg_catalog");
3690
3691         /*
3692          * Find all user-defined functions.  Normally we can exclude functions in
3693          * pg_catalog, which is worth doing since there are several thousand of
3694          * 'em.  However, there are some extensions that create functions in
3695          * pg_catalog.  In normal dumps we can still ignore those --- but in
3696          * binary-upgrade mode, we must dump the member objects of the extension,
3697          * so be sure to fetch any such functions.
3698          *
3699          * Also, in 9.2 and up, exclude functions that are internally dependent on
3700          * something else, since presumably those will be created as a result of
3701          * creating the something else.  This currently only acts to suppress
3702          * constructor functions for range types.  Note that this is OK only
3703          * because the constructors don't have any dependencies the range type
3704          * doesn't have; otherwise we might not get creation ordering correct.
3705          */
3706
3707         if (fout->remoteVersion >= 70300)
3708         {
3709                 appendPQExpBuffer(query,
3710                                                   "SELECT tableoid, oid, proname, prolang, "
3711                                                   "pronargs, proargtypes, prorettype, proacl, "
3712                                                   "pronamespace, "
3713                                                   "(%s proowner) AS rolname "
3714                                                   "FROM pg_proc p "
3715                                                   "WHERE NOT proisagg AND ("
3716                                                   "pronamespace != "
3717                                                   "(SELECT oid FROM pg_namespace "
3718                                                   "WHERE nspname = 'pg_catalog')",
3719                                                   username_subquery);
3720                 if (fout->remoteVersion >= 90200)
3721                         appendPQExpBuffer(query,
3722                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3723                                                           "WHERE classid = 'pg_proc'::regclass AND "
3724                                                           "objid = p.oid AND deptype = 'i')");
3725                 if (binary_upgrade && fout->remoteVersion >= 90100)
3726                         appendPQExpBuffer(query,
3727                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3728                                                           "classid = 'pg_proc'::regclass AND "
3729                                                           "objid = p.oid AND "
3730                                                           "refclassid = 'pg_extension'::regclass AND "
3731                                                           "deptype = 'e')");
3732                 appendPQExpBuffer(query, ")");
3733         }
3734         else if (fout->remoteVersion >= 70100)
3735         {
3736                 appendPQExpBuffer(query,
3737                                                   "SELECT tableoid, oid, proname, prolang, "
3738                                                   "pronargs, proargtypes, prorettype, "
3739                                                   "'{=X}' AS proacl, "
3740                                                   "0::oid AS pronamespace, "
3741                                                   "(%s proowner) AS rolname "
3742                                                   "FROM pg_proc "
3743                                                   "WHERE pg_proc.oid > '%u'::oid",
3744                                                   username_subquery,
3745                                                   g_last_builtin_oid);
3746         }
3747         else
3748         {
3749                 appendPQExpBuffer(query,
3750                                                   "SELECT "
3751                                                   "(SELECT oid FROM pg_class "
3752                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3753                                                   "oid, proname, prolang, "
3754                                                   "pronargs, proargtypes, prorettype, "
3755                                                   "'{=X}' AS proacl, "
3756                                                   "0::oid AS pronamespace, "
3757                                                   "(%s proowner) AS rolname "
3758                                                   "FROM pg_proc "
3759                                                   "where pg_proc.oid > '%u'::oid",
3760                                                   username_subquery,
3761                                                   g_last_builtin_oid);
3762         }
3763
3764         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3765
3766         ntups = PQntuples(res);
3767
3768         *numFuncs = ntups;
3769
3770         finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3771
3772         i_tableoid = PQfnumber(res, "tableoid");
3773         i_oid = PQfnumber(res, "oid");
3774         i_proname = PQfnumber(res, "proname");
3775         i_pronamespace = PQfnumber(res, "pronamespace");
3776         i_rolname = PQfnumber(res, "rolname");
3777         i_prolang = PQfnumber(res, "prolang");
3778         i_pronargs = PQfnumber(res, "pronargs");
3779         i_proargtypes = PQfnumber(res, "proargtypes");
3780         i_prorettype = PQfnumber(res, "prorettype");
3781         i_proacl = PQfnumber(res, "proacl");
3782
3783         for (i = 0; i < ntups; i++)
3784         {
3785                 finfo[i].dobj.objType = DO_FUNC;
3786                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3787                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3788                 AssignDumpId(&finfo[i].dobj);
3789                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3790                 finfo[i].dobj.namespace =
3791                         findNamespace(fout,
3792                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3793                                                   finfo[i].dobj.catId.oid);
3794                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3795                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3796                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3797                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3798                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3799                 if (finfo[i].nargs == 0)
3800                         finfo[i].argtypes = NULL;
3801                 else
3802                 {
3803                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3804                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3805                                                   finfo[i].argtypes, finfo[i].nargs);
3806                 }
3807
3808                 /* Decide whether we want to dump it */
3809                 selectDumpableObject(&(finfo[i].dobj));
3810
3811                 if (strlen(finfo[i].rolname) == 0)
3812                         write_msg(NULL,
3813                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3814                                           finfo[i].dobj.name);
3815         }
3816
3817         PQclear(res);
3818
3819         destroyPQExpBuffer(query);
3820
3821         return finfo;
3822 }
3823
3824 /*
3825  * getTables
3826  *        read all the user-defined tables (no indexes, no catalogs)
3827  * in the system catalogs return them in the TableInfo* structure
3828  *
3829  * numTables is set to the number of tables read in
3830  */
3831 TableInfo *
3832 getTables(Archive *fout, int *numTables)
3833 {
3834         PGresult   *res;
3835         int                     ntups;
3836         int                     i;
3837         PQExpBuffer query = createPQExpBuffer();
3838         TableInfo  *tblinfo;
3839         int                     i_reltableoid;
3840         int                     i_reloid;
3841         int                     i_relname;
3842         int                     i_relnamespace;
3843         int                     i_relkind;
3844         int                     i_relacl;
3845         int                     i_rolname;
3846         int                     i_relchecks;
3847         int                     i_relhastriggers;
3848         int                     i_relhasindex;
3849         int                     i_relhasrules;
3850         int                     i_relhasoids;
3851         int                     i_relfrozenxid;
3852         int                     i_toastoid;
3853         int                     i_toastfrozenxid;
3854         int                     i_relpersistence;
3855         int                     i_owning_tab;
3856         int                     i_owning_col;
3857         int                     i_reltablespace;
3858         int                     i_reloptions;
3859         int                     i_toastreloptions;
3860         int                     i_reloftype;
3861
3862         /* Make sure we are in proper schema */
3863         selectSourceSchema(fout, "pg_catalog");
3864
3865         /*
3866          * Find all the tables (including views and sequences).
3867          *
3868          * We include system catalogs, so that we can work if a user table is
3869          * defined to inherit from a system catalog (pretty weird, but...)
3870          *
3871          * We ignore tables that are not type 'r' (ordinary relation), 'S'
3872          * (sequence), 'v' (view), or 'c' (composite type).
3873          *
3874          * Composite-type table entries won't be dumped as such, but we have to
3875          * make a DumpableObject for them so that we can track dependencies of the
3876          * composite type (pg_depend entries for columns of the composite type
3877          * link to the pg_class entry not the pg_type entry).
3878          *
3879          * Note: in this phase we should collect only a minimal amount of
3880          * information about each table, basically just enough to decide if it is
3881          * interesting. We must fetch all tables in this phase because otherwise
3882          * we cannot correctly identify inherited columns, owned sequences, etc.
3883          */
3884
3885         if (fout->remoteVersion >= 90100)
3886         {
3887                 /*
3888                  * Left join to pick up dependency info linking sequences to their
3889                  * owning column, if any (note this dependency is AUTO as of 8.2)
3890                  */
3891                 appendPQExpBuffer(query,
3892                                                   "SELECT c.tableoid, c.oid, c.relname, "
3893                                                   "c.relacl, c.relkind, c.relnamespace, "
3894                                                   "(%s c.relowner) AS rolname, "
3895                                                   "c.relchecks, c.relhastriggers, "
3896                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3897                                                   "c.relfrozenxid, tc.oid AS toid, "
3898                                                   "tc.relfrozenxid AS tfrozenxid, "
3899                                                   "c.relpersistence, "
3900                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3901                                                   "d.refobjid AS owning_tab, "
3902                                                   "d.refobjsubid AS owning_col, "
3903                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3904                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3905                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3906                                                   "FROM pg_class c "
3907                                                   "LEFT JOIN pg_depend d ON "
3908                                                   "(c.relkind = '%c' AND "
3909                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3910                                                   "d.objsubid = 0 AND "
3911                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3912                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3913                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3914                                                   "ORDER BY c.oid",
3915                                                   username_subquery,
3916                                                   RELKIND_SEQUENCE,
3917                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3918                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3919                                                   RELKIND_FOREIGN_TABLE);
3920         }
3921         else if (fout->remoteVersion >= 90000)
3922         {
3923                 /*
3924                  * Left join to pick up dependency info linking sequences to their
3925                  * owning column, if any (note this dependency is AUTO as of 8.2)
3926                  */
3927                 appendPQExpBuffer(query,
3928                                                   "SELECT c.tableoid, c.oid, c.relname, "
3929                                                   "c.relacl, c.relkind, c.relnamespace, "
3930                                                   "(%s c.relowner) AS rolname, "
3931                                                   "c.relchecks, c.relhastriggers, "
3932                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3933                                                   "c.relfrozenxid, tc.oid AS toid, "
3934                                                   "tc.relfrozenxid AS tfrozenxid, "
3935                                                   "'p' AS relpersistence, "
3936                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3937                                                   "d.refobjid AS owning_tab, "
3938                                                   "d.refobjsubid AS owning_col, "
3939                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3940                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3941                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3942                                                   "FROM pg_class c "
3943                                                   "LEFT JOIN pg_depend d ON "
3944                                                   "(c.relkind = '%c' AND "
3945                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3946                                                   "d.objsubid = 0 AND "
3947                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3948                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3949                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3950                                                   "ORDER BY c.oid",
3951                                                   username_subquery,
3952                                                   RELKIND_SEQUENCE,
3953                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3954                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3955         }
3956         else if (fout->remoteVersion >= 80400)
3957         {
3958                 /*
3959                  * Left join to pick up dependency info linking sequences to their
3960                  * owning column, if any (note this dependency is AUTO as of 8.2)
3961                  */
3962                 appendPQExpBuffer(query,
3963                                                   "SELECT c.tableoid, c.oid, c.relname, "
3964                                                   "c.relacl, c.relkind, c.relnamespace, "
3965                                                   "(%s c.relowner) AS rolname, "
3966                                                   "c.relchecks, c.relhastriggers, "
3967                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3968                                                   "c.relfrozenxid, tc.oid AS toid, "
3969                                                   "tc.relfrozenxid AS tfrozenxid, "
3970                                                   "'p' AS relpersistence, "
3971                                                   "NULL AS reloftype, "
3972                                                   "d.refobjid AS owning_tab, "
3973                                                   "d.refobjsubid AS owning_col, "
3974                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3975                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3976                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3977                                                   "FROM pg_class c "
3978                                                   "LEFT JOIN pg_depend d ON "
3979                                                   "(c.relkind = '%c' AND "
3980                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3981                                                   "d.objsubid = 0 AND "
3982                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3983                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3984                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3985                                                   "ORDER BY c.oid",
3986                                                   username_subquery,
3987                                                   RELKIND_SEQUENCE,
3988                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3989                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3990         }
3991         else if (fout->remoteVersion >= 80200)
3992         {
3993                 /*
3994                  * Left join to pick up dependency info linking sequences to their
3995                  * owning column, if any (note this dependency is AUTO as of 8.2)
3996                  */
3997                 appendPQExpBuffer(query,
3998                                                   "SELECT c.tableoid, c.oid, c.relname, "
3999                                                   "c.relacl, c.relkind, c.relnamespace, "
4000                                                   "(%s c.relowner) AS rolname, "
4001                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4002                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4003                                                   "c.relfrozenxid, tc.oid AS toid, "
4004                                                   "tc.relfrozenxid AS tfrozenxid, "
4005                                                   "'p' AS relpersistence, "
4006                                                   "NULL AS reloftype, "
4007                                                   "d.refobjid AS owning_tab, "
4008                                                   "d.refobjsubid AS owning_col, "
4009                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4010                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4011                                                   "NULL AS toast_reloptions "
4012                                                   "FROM pg_class c "
4013                                                   "LEFT JOIN pg_depend d ON "
4014                                                   "(c.relkind = '%c' AND "
4015                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4016                                                   "d.objsubid = 0 AND "
4017                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4018                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4019                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4020                                                   "ORDER BY c.oid",
4021                                                   username_subquery,
4022                                                   RELKIND_SEQUENCE,
4023                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4024                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4025         }
4026         else if (fout->remoteVersion >= 80000)
4027         {
4028                 /*
4029                  * Left join to pick up dependency info linking sequences to their
4030                  * owning column, if any
4031                  */
4032                 appendPQExpBuffer(query,
4033                                                   "SELECT c.tableoid, c.oid, relname, "
4034                                                   "relacl, relkind, relnamespace, "
4035                                                   "(%s relowner) AS rolname, "
4036                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4037                                                   "relhasindex, relhasrules, relhasoids, "
4038                                                   "0 AS relfrozenxid, "
4039                                                   "0 AS toid, "
4040                                                   "0 AS tfrozenxid, "
4041                                                   "'p' AS relpersistence, "
4042                                                   "NULL AS reloftype, "
4043                                                   "d.refobjid AS owning_tab, "
4044                                                   "d.refobjsubid AS owning_col, "
4045                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4046                                                   "NULL AS reloptions, "
4047                                                   "NULL AS toast_reloptions "
4048                                                   "FROM pg_class c "
4049                                                   "LEFT JOIN pg_depend d ON "
4050                                                   "(c.relkind = '%c' AND "
4051                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4052                                                   "d.objsubid = 0 AND "
4053                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4054                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4055                                                   "ORDER BY c.oid",
4056                                                   username_subquery,
4057                                                   RELKIND_SEQUENCE,
4058                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4059                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4060         }
4061         else if (fout->remoteVersion >= 70300)
4062         {
4063                 /*
4064                  * Left join to pick up dependency info linking sequences to their
4065                  * owning column, if any
4066                  */
4067                 appendPQExpBuffer(query,
4068                                                   "SELECT c.tableoid, c.oid, relname, "
4069                                                   "relacl, relkind, relnamespace, "
4070                                                   "(%s relowner) AS rolname, "
4071                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4072                                                   "relhasindex, relhasrules, relhasoids, "
4073                                                   "0 AS relfrozenxid, "
4074                                                   "0 AS toid, "
4075                                                   "0 AS tfrozenxid, "
4076                                                   "'p' AS relpersistence, "
4077                                                   "NULL AS reloftype, "
4078                                                   "d.refobjid AS owning_tab, "
4079                                                   "d.refobjsubid AS owning_col, "
4080                                                   "NULL AS reltablespace, "
4081                                                   "NULL AS reloptions, "
4082                                                   "NULL AS toast_reloptions "
4083                                                   "FROM pg_class c "
4084                                                   "LEFT JOIN pg_depend d ON "
4085                                                   "(c.relkind = '%c' AND "
4086                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4087                                                   "d.objsubid = 0 AND "
4088                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4089                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4090                                                   "ORDER BY c.oid",
4091                                                   username_subquery,
4092                                                   RELKIND_SEQUENCE,
4093                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4094                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4095         }
4096         else if (fout->remoteVersion >= 70200)
4097         {
4098                 appendPQExpBuffer(query,
4099                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4100                                                   "0::oid AS relnamespace, "
4101                                                   "(%s relowner) AS rolname, "
4102                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4103                                                   "relhasindex, relhasrules, relhasoids, "
4104                                                   "0 AS relfrozenxid, "
4105                                                   "0 AS toid, "
4106                                                   "0 AS tfrozenxid, "
4107                                                   "'p' AS relpersistence, "
4108                                                   "NULL AS reloftype, "
4109                                                   "NULL::oid AS owning_tab, "
4110                                                   "NULL::int4 AS owning_col, "
4111                                                   "NULL AS reltablespace, "
4112                                                   "NULL AS reloptions, "
4113                                                   "NULL AS toast_reloptions "
4114                                                   "FROM pg_class "
4115                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4116                                                   "ORDER BY oid",
4117                                                   username_subquery,
4118                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4119         }
4120         else if (fout->remoteVersion >= 70100)
4121         {
4122                 /* all tables have oids in 7.1 */
4123                 appendPQExpBuffer(query,
4124                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4125                                                   "0::oid AS relnamespace, "
4126                                                   "(%s relowner) AS rolname, "
4127                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4128                                                   "relhasindex, relhasrules, "
4129                                                   "'t'::bool AS relhasoids, "
4130                                                   "0 AS relfrozenxid, "
4131                                                   "0 AS toid, "
4132                                                   "0 AS tfrozenxid, "
4133                                                   "'p' AS relpersistence, "
4134                                                   "NULL AS reloftype, "
4135                                                   "NULL::oid AS owning_tab, "
4136                                                   "NULL::int4 AS owning_col, "
4137                                                   "NULL AS reltablespace, "
4138                                                   "NULL AS reloptions, "
4139                                                   "NULL AS toast_reloptions "
4140                                                   "FROM pg_class "
4141                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4142                                                   "ORDER BY oid",
4143                                                   username_subquery,
4144                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4145         }
4146         else
4147         {
4148                 /*
4149                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4150                  * have a view by looking for a rule in pg_rewrite.
4151                  */
4152                 appendPQExpBuffer(query,
4153                                                   "SELECT "
4154                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4155                                                   "oid, relname, relacl, "
4156                                                   "CASE WHEN relhasrules and relkind = 'r' "
4157                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4158                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4159                                                   "THEN '%c'::\"char\" "
4160                                                   "ELSE relkind END AS relkind,"
4161                                                   "0::oid AS relnamespace, "
4162                                                   "(%s relowner) AS rolname, "
4163                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4164                                                   "relhasindex, relhasrules, "
4165                                                   "'t'::bool AS relhasoids, "
4166                                                   "0 as relfrozenxid, "
4167                                                   "0 AS toid, "
4168                                                   "0 AS tfrozenxid, "
4169                                                   "'p' AS relpersistence, "
4170                                                   "NULL AS reloftype, "
4171                                                   "NULL::oid AS owning_tab, "
4172                                                   "NULL::int4 AS owning_col, "
4173                                                   "NULL AS reltablespace, "
4174                                                   "NULL AS reloptions, "
4175                                                   "NULL AS toast_reloptions "
4176                                                   "FROM pg_class c "
4177                                                   "WHERE relkind IN ('%c', '%c') "
4178                                                   "ORDER BY oid",
4179                                                   RELKIND_VIEW,
4180                                                   username_subquery,
4181                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4182         }
4183
4184         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4185
4186         ntups = PQntuples(res);
4187
4188         *numTables = ntups;
4189
4190         /*
4191          * Extract data from result and lock dumpable tables.  We do the locking
4192          * before anything else, to minimize the window wherein a table could
4193          * disappear under us.
4194          *
4195          * Note that we have to save info about all tables here, even when dumping
4196          * only one, because we don't yet know which tables might be inheritance
4197          * ancestors of the target table.
4198          */
4199         tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4200
4201         i_reltableoid = PQfnumber(res, "tableoid");
4202         i_reloid = PQfnumber(res, "oid");
4203         i_relname = PQfnumber(res, "relname");
4204         i_relnamespace = PQfnumber(res, "relnamespace");
4205         i_relacl = PQfnumber(res, "relacl");
4206         i_relkind = PQfnumber(res, "relkind");
4207         i_rolname = PQfnumber(res, "rolname");
4208         i_relchecks = PQfnumber(res, "relchecks");
4209         i_relhastriggers = PQfnumber(res, "relhastriggers");
4210         i_relhasindex = PQfnumber(res, "relhasindex");
4211         i_relhasrules = PQfnumber(res, "relhasrules");
4212         i_relhasoids = PQfnumber(res, "relhasoids");
4213         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4214         i_toastoid = PQfnumber(res, "toid");
4215         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4216         i_relpersistence = PQfnumber(res, "relpersistence");
4217         i_owning_tab = PQfnumber(res, "owning_tab");
4218         i_owning_col = PQfnumber(res, "owning_col");
4219         i_reltablespace = PQfnumber(res, "reltablespace");
4220         i_reloptions = PQfnumber(res, "reloptions");
4221         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4222         i_reloftype = PQfnumber(res, "reloftype");
4223
4224         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4225         {
4226                 /*
4227                  * Arrange to fail instead of waiting forever for a table lock.
4228                  *
4229                  * NB: this coding assumes that the only queries issued within the
4230                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4231                  * applied to other things too.
4232                  */
4233                 resetPQExpBuffer(query);
4234                 appendPQExpBuffer(query, "SET statement_timeout = ");
4235                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4236                 ExecuteSqlStatement(fout, query->data);
4237         }
4238
4239         for (i = 0; i < ntups; i++)
4240         {
4241                 tblinfo[i].dobj.objType = DO_TABLE;
4242                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4243                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4244                 AssignDumpId(&tblinfo[i].dobj);
4245                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4246                 tblinfo[i].dobj.namespace =
4247                         findNamespace(fout,
4248                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4249                                                   tblinfo[i].dobj.catId.oid);
4250                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4251                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4252                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4253                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4254                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4255                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4256                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4257                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4258                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4259                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4260                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4261                 if (PQgetisnull(res, i, i_reloftype))
4262                         tblinfo[i].reloftype = NULL;
4263                 else
4264                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4265                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4266                 if (PQgetisnull(res, i, i_owning_tab))
4267                 {
4268                         tblinfo[i].owning_tab = InvalidOid;
4269                         tblinfo[i].owning_col = 0;
4270                 }
4271                 else
4272                 {
4273                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4274                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4275                 }
4276                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4277                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4278                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4279
4280                 /* other fields were zeroed above */
4281
4282                 /*
4283                  * Decide whether we want to dump this table.
4284                  */
4285                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4286                         tblinfo[i].dobj.dump = false;
4287                 else
4288                         selectDumpableTable(&tblinfo[i]);
4289                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4290
4291                 /*
4292                  * Read-lock target tables to make sure they aren't DROPPED or altered
4293                  * in schema before we get around to dumping them.
4294                  *
4295                  * Note that we don't explicitly lock parents of the target tables; we
4296                  * assume our lock on the child is enough to prevent schema
4297                  * alterations to parent tables.
4298                  *
4299                  * NOTE: it'd be kinda nice to lock other relations too, not only
4300                  * plain tables, but the backend doesn't presently allow that.
4301                  */
4302                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4303                 {
4304                         resetPQExpBuffer(query);
4305                         appendPQExpBuffer(query,
4306                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4307                                                  fmtQualifiedId(fout,
4308                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4309                                                                                 tblinfo[i].dobj.name));
4310                         ExecuteSqlStatement(fout, query->data);
4311                 }
4312
4313                 /* Emit notice if join for owner failed */
4314                 if (strlen(tblinfo[i].rolname) == 0)
4315                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4316                                           tblinfo[i].dobj.name);
4317         }
4318
4319         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4320         {
4321                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4322         }
4323
4324         PQclear(res);
4325
4326         /*
4327          * Force sequences that are "owned" by table columns to be dumped whenever
4328          * their owning table is being dumped.
4329          */
4330         for (i = 0; i < ntups; i++)
4331         {
4332                 TableInfo  *seqinfo = &tblinfo[i];
4333                 int                     j;
4334
4335                 if (!OidIsValid(seqinfo->owning_tab))
4336                         continue;                       /* not an owned sequence */
4337                 if (seqinfo->dobj.dump)
4338                         continue;                       /* no need to search */
4339
4340                 /* can't use findTableByOid yet, unfortunately */
4341                 for (j = 0; j < ntups; j++)
4342                 {
4343                         if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4344                         {
4345                                 if (tblinfo[j].dobj.dump)
4346                                 {
4347                                         seqinfo->interesting = true;
4348                                         seqinfo->dobj.dump = true;
4349                                 }
4350                                 break;
4351                         }
4352                 }
4353         }
4354
4355         destroyPQExpBuffer(query);
4356
4357         return tblinfo;
4358 }
4359
4360 /*
4361  * getInherits
4362  *        read all the inheritance information
4363  * from the system catalogs return them in the InhInfo* structure
4364  *
4365  * numInherits is set to the number of pairs read in
4366  */
4367 InhInfo *
4368 getInherits(Archive *fout, int *numInherits)
4369 {
4370         PGresult   *res;
4371         int                     ntups;
4372         int                     i;
4373         PQExpBuffer query = createPQExpBuffer();
4374         InhInfo    *inhinfo;
4375
4376         int                     i_inhrelid;
4377         int                     i_inhparent;
4378
4379         /* Make sure we are in proper schema */
4380         selectSourceSchema(fout, "pg_catalog");
4381
4382         /* find all the inheritance information */
4383
4384         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4385
4386         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4387
4388         ntups = PQntuples(res);
4389
4390         *numInherits = ntups;
4391
4392         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4393
4394         i_inhrelid = PQfnumber(res, "inhrelid");
4395         i_inhparent = PQfnumber(res, "inhparent");
4396
4397         for (i = 0; i < ntups; i++)
4398         {
4399                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4400                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4401         }
4402
4403         PQclear(res);
4404
4405         destroyPQExpBuffer(query);
4406
4407         return inhinfo;
4408 }
4409
4410 /*
4411  * getIndexes
4412  *        get information about every index on a dumpable table
4413  *
4414  * Note: index data is not returned directly to the caller, but it
4415  * does get entered into the DumpableObject tables.
4416  */
4417 void
4418 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4419 {
4420         int                     i,
4421                                 j;
4422         PQExpBuffer query = createPQExpBuffer();
4423         PGresult   *res;
4424         IndxInfo   *indxinfo;
4425         ConstraintInfo *constrinfo;
4426         int                     i_tableoid,
4427                                 i_oid,
4428                                 i_indexname,
4429                                 i_indexdef,
4430                                 i_indnkeys,
4431                                 i_indkey,
4432                                 i_indisclustered,
4433                                 i_contype,
4434                                 i_conname,
4435                                 i_condeferrable,
4436                                 i_condeferred,
4437                                 i_contableoid,
4438                                 i_conoid,
4439                                 i_condef,
4440                                 i_tablespace,
4441                                 i_options;
4442         int                     ntups;
4443
4444         for (i = 0; i < numTables; i++)
4445         {
4446                 TableInfo  *tbinfo = &tblinfo[i];
4447
4448                 /* Only plain tables have indexes */
4449                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4450                         continue;
4451
4452                 /* Ignore indexes of tables not to be dumped */
4453                 if (!tbinfo->dobj.dump)
4454                         continue;
4455
4456                 if (g_verbose)
4457                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4458                                           tbinfo->dobj.name);
4459
4460                 /* Make sure we are in proper schema so indexdef is right */
4461                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4462
4463                 /*
4464                  * The point of the messy-looking outer join is to find a constraint
4465                  * that is related by an internal dependency link to the index. If we
4466                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4467                  * assume an index won't have more than one internal dependency.
4468                  *
4469                  * As of 9.0 we don't need to look at pg_depend but can check for a
4470                  * match to pg_constraint.conindid.  The check on conrelid is
4471                  * redundant but useful because that column is indexed while conindid
4472                  * is not.
4473                  */
4474                 resetPQExpBuffer(query);
4475                 if (fout->remoteVersion >= 90000)
4476                 {
4477                         appendPQExpBuffer(query,
4478                                                           "SELECT t.tableoid, t.oid, "
4479                                                           "t.relname AS indexname, "
4480                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4481                                                           "t.relnatts AS indnkeys, "
4482                                                           "i.indkey, i.indisclustered, "
4483                                                           "c.contype, c.conname, "
4484                                                           "c.condeferrable, c.condeferred, "
4485                                                           "c.tableoid AS contableoid, "
4486                                                           "c.oid AS conoid, "
4487                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4488                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4489                                                         "array_to_string(t.reloptions, ', ') AS options "
4490                                                           "FROM pg_catalog.pg_index i "
4491                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4492                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4493                                                           "ON (i.indrelid = c.conrelid AND "
4494                                                           "i.indexrelid = c.conindid AND "
4495                                                           "c.contype IN ('p','u','x')) "
4496                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4497                                                           "ORDER BY indexname",
4498                                                           tbinfo->dobj.catId.oid);
4499                 }
4500                 else if (fout->remoteVersion >= 80200)
4501                 {
4502                         appendPQExpBuffer(query,
4503                                                           "SELECT t.tableoid, t.oid, "
4504                                                           "t.relname AS indexname, "
4505                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4506                                                           "t.relnatts AS indnkeys, "
4507                                                           "i.indkey, i.indisclustered, "
4508                                                           "c.contype, c.conname, "
4509                                                           "c.condeferrable, c.condeferred, "
4510                                                           "c.tableoid AS contableoid, "
4511                                                           "c.oid AS conoid, "
4512                                                           "null AS condef, "
4513                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4514                                                         "array_to_string(t.reloptions, ', ') AS options "
4515                                                           "FROM pg_catalog.pg_index i "
4516                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4517                                                           "LEFT JOIN pg_catalog.pg_depend d "
4518                                                           "ON (d.classid = t.tableoid "
4519                                                           "AND d.objid = t.oid "
4520                                                           "AND d.deptype = 'i') "
4521                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4522                                                           "ON (d.refclassid = c.tableoid "
4523                                                           "AND d.refobjid = c.oid) "
4524                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4525                                                           "ORDER BY indexname",
4526                                                           tbinfo->dobj.catId.oid);
4527                 }
4528                 else if (fout->remoteVersion >= 80000)
4529                 {
4530                         appendPQExpBuffer(query,
4531                                                           "SELECT t.tableoid, t.oid, "
4532                                                           "t.relname AS indexname, "
4533                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4534                                                           "t.relnatts AS indnkeys, "
4535                                                           "i.indkey, i.indisclustered, "
4536                                                           "c.contype, c.conname, "
4537                                                           "c.condeferrable, c.condeferred, "
4538                                                           "c.tableoid AS contableoid, "
4539                                                           "c.oid AS conoid, "
4540                                                           "null AS condef, "
4541                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4542                                                           "null AS options "
4543                                                           "FROM pg_catalog.pg_index i "
4544                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4545                                                           "LEFT JOIN pg_catalog.pg_depend d "
4546                                                           "ON (d.classid = t.tableoid "
4547                                                           "AND d.objid = t.oid "
4548                                                           "AND d.deptype = 'i') "
4549                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4550                                                           "ON (d.refclassid = c.tableoid "
4551                                                           "AND d.refobjid = c.oid) "
4552                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4553                                                           "ORDER BY indexname",
4554                                                           tbinfo->dobj.catId.oid);
4555                 }
4556                 else if (fout->remoteVersion >= 70300)
4557                 {
4558                         appendPQExpBuffer(query,
4559                                                           "SELECT t.tableoid, t.oid, "
4560                                                           "t.relname AS indexname, "
4561                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4562                                                           "t.relnatts AS indnkeys, "
4563                                                           "i.indkey, i.indisclustered, "
4564                                                           "c.contype, c.conname, "
4565                                                           "c.condeferrable, c.condeferred, "
4566                                                           "c.tableoid AS contableoid, "
4567                                                           "c.oid AS conoid, "
4568                                                           "null AS condef, "
4569                                                           "NULL AS tablespace, "
4570                                                           "null AS options "
4571                                                           "FROM pg_catalog.pg_index i "
4572                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4573                                                           "LEFT JOIN pg_catalog.pg_depend d "
4574                                                           "ON (d.classid = t.tableoid "
4575                                                           "AND d.objid = t.oid "
4576                                                           "AND d.deptype = 'i') "
4577                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4578                                                           "ON (d.refclassid = c.tableoid "
4579                                                           "AND d.refobjid = c.oid) "
4580                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4581                                                           "ORDER BY indexname",
4582                                                           tbinfo->dobj.catId.oid);
4583                 }
4584                 else if (fout->remoteVersion >= 70100)
4585                 {
4586                         appendPQExpBuffer(query,
4587                                                           "SELECT t.tableoid, t.oid, "
4588                                                           "t.relname AS indexname, "
4589                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4590                                                           "t.relnatts AS indnkeys, "
4591                                                           "i.indkey, false AS indisclustered, "
4592                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4593                                                           "ELSE '0'::char END AS contype, "
4594                                                           "t.relname AS conname, "
4595                                                           "false AS condeferrable, "
4596                                                           "false AS condeferred, "
4597                                                           "0::oid AS contableoid, "
4598                                                           "t.oid AS conoid, "
4599                                                           "null AS condef, "
4600                                                           "NULL AS tablespace, "
4601                                                           "null AS options "
4602                                                           "FROM pg_index i, pg_class t "
4603                                                           "WHERE t.oid = i.indexrelid "
4604                                                           "AND i.indrelid = '%u'::oid "
4605                                                           "ORDER BY indexname",
4606                                                           tbinfo->dobj.catId.oid);
4607                 }
4608                 else
4609                 {
4610                         appendPQExpBuffer(query,
4611                                                           "SELECT "
4612                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4613                                                           "t.oid, "
4614                                                           "t.relname AS indexname, "
4615                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4616                                                           "t.relnatts AS indnkeys, "
4617                                                           "i.indkey, false AS indisclustered, "
4618                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4619                                                           "ELSE '0'::char END AS contype, "
4620                                                           "t.relname AS conname, "
4621                                                           "false AS condeferrable, "
4622                                                           "false AS condeferred, "
4623                                                           "0::oid AS contableoid, "
4624                                                           "t.oid AS conoid, "
4625                                                           "null AS condef, "
4626                                                           "NULL AS tablespace, "
4627                                                           "null AS options "
4628                                                           "FROM pg_index i, pg_class t "
4629                                                           "WHERE t.oid = i.indexrelid "
4630                                                           "AND i.indrelid = '%u'::oid "
4631                                                           "ORDER BY indexname",
4632                                                           tbinfo->dobj.catId.oid);
4633                 }
4634
4635                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4636
4637                 ntups = PQntuples(res);
4638
4639                 i_tableoid = PQfnumber(res, "tableoid");
4640                 i_oid = PQfnumber(res, "oid");
4641                 i_indexname = PQfnumber(res, "indexname");
4642                 i_indexdef = PQfnumber(res, "indexdef");
4643                 i_indnkeys = PQfnumber(res, "indnkeys");
4644                 i_indkey = PQfnumber(res, "indkey");
4645                 i_indisclustered = PQfnumber(res, "indisclustered");
4646                 i_contype = PQfnumber(res, "contype");
4647                 i_conname = PQfnumber(res, "conname");
4648                 i_condeferrable = PQfnumber(res, "condeferrable");
4649                 i_condeferred = PQfnumber(res, "condeferred");
4650                 i_contableoid = PQfnumber(res, "contableoid");
4651                 i_conoid = PQfnumber(res, "conoid");
4652                 i_condef = PQfnumber(res, "condef");
4653                 i_tablespace = PQfnumber(res, "tablespace");
4654                 i_options = PQfnumber(res, "options");
4655
4656                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4657                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4658
4659                 for (j = 0; j < ntups; j++)
4660                 {
4661                         char            contype;
4662
4663                         indxinfo[j].dobj.objType = DO_INDEX;
4664                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4665                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4666                         AssignDumpId(&indxinfo[j].dobj);
4667                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4668                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4669                         indxinfo[j].indextable = tbinfo;
4670                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4671                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4672                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4673                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4674
4675                         /*
4676                          * In pre-7.4 releases, indkeys may contain more entries than
4677                          * indnkeys says (since indnkeys will be 1 for a functional
4678                          * index).      We don't actually care about this case since we don't
4679                          * examine indkeys except for indexes associated with PRIMARY and
4680                          * UNIQUE constraints, which are never functional indexes. But we
4681                          * have to allocate enough space to keep parseOidArray from
4682                          * complaining.
4683                          */
4684                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4685                         parseOidArray(PQgetvalue(res, j, i_indkey),
4686                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4687                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4688                         contype = *(PQgetvalue(res, j, i_contype));
4689
4690                         if (contype == 'p' || contype == 'u' || contype == 'x')
4691                         {
4692                                 /*
4693                                  * If we found a constraint matching the index, create an
4694                                  * entry for it.
4695                                  *
4696                                  * In a pre-7.3 database, we take this path iff the index was
4697                                  * marked indisprimary.
4698                                  */
4699                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4700                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4701                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4702                                 AssignDumpId(&constrinfo[j].dobj);
4703                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4704                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4705                                 constrinfo[j].contable = tbinfo;
4706                                 constrinfo[j].condomain = NULL;
4707                                 constrinfo[j].contype = contype;
4708                                 if (contype == 'x')
4709                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4710                                 else
4711                                         constrinfo[j].condef = NULL;
4712                                 constrinfo[j].confrelid = InvalidOid;
4713                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4714                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4715                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4716                                 constrinfo[j].conislocal = true;
4717                                 constrinfo[j].separate = true;
4718
4719                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4720
4721                                 /* If pre-7.3 DB, better make sure table comes first */
4722                                 addObjectDependency(&constrinfo[j].dobj,
4723                                                                         tbinfo->dobj.dumpId);
4724                         }
4725                         else
4726                         {
4727                                 /* Plain secondary index */
4728                                 indxinfo[j].indexconstraint = 0;
4729                         }
4730                 }
4731
4732                 PQclear(res);
4733         }
4734
4735         destroyPQExpBuffer(query);
4736 }
4737
4738 /*
4739  * getConstraints
4740  *
4741  * Get info about constraints on dumpable tables.
4742  *
4743  * Currently handles foreign keys only.
4744  * Unique and primary key constraints are handled with indexes,
4745  * while check constraints are processed in getTableAttrs().
4746  */
4747 void
4748 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4749 {
4750         int                     i,
4751                                 j;
4752         ConstraintInfo *constrinfo;
4753         PQExpBuffer query;
4754         PGresult   *res;
4755         int                     i_contableoid,
4756                                 i_conoid,
4757                                 i_conname,
4758                                 i_confrelid,
4759                                 i_condef;
4760         int                     ntups;
4761
4762         /* pg_constraint was created in 7.3, so nothing to do if older */
4763         if (fout->remoteVersion < 70300)
4764                 return;
4765
4766         query = createPQExpBuffer();
4767
4768         for (i = 0; i < numTables; i++)
4769         {
4770                 TableInfo  *tbinfo = &tblinfo[i];
4771
4772                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4773                         continue;
4774
4775                 if (g_verbose)
4776                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4777                                           tbinfo->dobj.name);
4778
4779                 /*
4780                  * select table schema to ensure constraint expr is qualified if
4781                  * needed
4782                  */
4783                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4784
4785                 resetPQExpBuffer(query);
4786                 appendPQExpBuffer(query,
4787                                                   "SELECT tableoid, oid, conname, confrelid, "
4788                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4789                                                   "FROM pg_catalog.pg_constraint "
4790                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4791                                                   "AND contype = 'f'",
4792                                                   tbinfo->dobj.catId.oid);
4793                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4794
4795                 ntups = PQntuples(res);
4796
4797                 i_contableoid = PQfnumber(res, "tableoid");
4798                 i_conoid = PQfnumber(res, "oid");
4799                 i_conname = PQfnumber(res, "conname");
4800                 i_confrelid = PQfnumber(res, "confrelid");
4801                 i_condef = PQfnumber(res, "condef");
4802
4803                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4804
4805                 for (j = 0; j < ntups; j++)
4806                 {
4807                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4808                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4809                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4810                         AssignDumpId(&constrinfo[j].dobj);
4811                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4812                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4813                         constrinfo[j].contable = tbinfo;
4814                         constrinfo[j].condomain = NULL;
4815                         constrinfo[j].contype = 'f';
4816                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4817                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4818                         constrinfo[j].conindex = 0;
4819                         constrinfo[j].condeferrable = false;
4820                         constrinfo[j].condeferred = false;
4821                         constrinfo[j].conislocal = true;
4822                         constrinfo[j].separate = true;
4823                 }
4824
4825                 PQclear(res);
4826         }
4827
4828         destroyPQExpBuffer(query);
4829 }
4830
4831 /*
4832  * getDomainConstraints
4833  *
4834  * Get info about constraints on a domain.
4835  */
4836 static void
4837 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4838 {
4839         int                     i;
4840         ConstraintInfo *constrinfo;
4841         PQExpBuffer query;
4842         PGresult   *res;
4843         int                     i_tableoid,
4844                                 i_oid,
4845                                 i_conname,
4846                                 i_consrc;
4847         int                     ntups;
4848
4849         /* pg_constraint was created in 7.3, so nothing to do if older */
4850         if (fout->remoteVersion < 70300)
4851                 return;
4852
4853         /*
4854          * select appropriate schema to ensure names in constraint are properly
4855          * qualified
4856          */
4857         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4858
4859         query = createPQExpBuffer();
4860
4861         if (fout->remoteVersion >= 90100)
4862                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4863                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4864                                                   "convalidated "
4865                                                   "FROM pg_catalog.pg_constraint "
4866                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4867                                                   "ORDER BY conname",
4868                                                   tyinfo->dobj.catId.oid);
4869
4870         else if (fout->remoteVersion >= 70400)
4871                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4872                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4873                                                   "true as convalidated "
4874                                                   "FROM pg_catalog.pg_constraint "
4875                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4876                                                   "ORDER BY conname",
4877                                                   tyinfo->dobj.catId.oid);
4878         else
4879                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4880                                                   "'CHECK (' || consrc || ')' AS consrc, "
4881                                                   "true as convalidated "
4882                                                   "FROM pg_catalog.pg_constraint "
4883                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4884                                                   "ORDER BY conname",
4885                                                   tyinfo->dobj.catId.oid);
4886
4887         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4888
4889         ntups = PQntuples(res);
4890
4891         i_tableoid = PQfnumber(res, "tableoid");
4892         i_oid = PQfnumber(res, "oid");
4893         i_conname = PQfnumber(res, "conname");
4894         i_consrc = PQfnumber(res, "consrc");
4895
4896         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4897
4898         tyinfo->nDomChecks = ntups;
4899         tyinfo->domChecks = constrinfo;
4900
4901         for (i = 0; i < ntups; i++)
4902         {
4903                 bool    validated = PQgetvalue(res, i, 4)[0] == 't';
4904
4905                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4906                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4907                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4908                 AssignDumpId(&constrinfo[i].dobj);
4909                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4910                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4911                 constrinfo[i].contable = NULL;
4912                 constrinfo[i].condomain = tyinfo;
4913                 constrinfo[i].contype = 'c';
4914                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4915                 constrinfo[i].confrelid = InvalidOid;
4916                 constrinfo[i].conindex = 0;
4917                 constrinfo[i].condeferrable = false;
4918                 constrinfo[i].condeferred = false;
4919                 constrinfo[i].conislocal = true;
4920
4921                 constrinfo[i].separate = !validated;
4922
4923                 /*
4924                  * Make the domain depend on the constraint, ensuring it won't be
4925                  * output till any constraint dependencies are OK.  If the constraint
4926                  * has not been validated, it's going to be dumped after the domain
4927                  * anyway, so this doesn't matter.
4928                  */
4929                 if (validated)
4930                         addObjectDependency(&tyinfo->dobj,
4931                                                                 constrinfo[i].dobj.dumpId);
4932         }
4933
4934         PQclear(res);
4935
4936         destroyPQExpBuffer(query);
4937 }
4938
4939 /*
4940  * getRules
4941  *        get basic information about every rule in the system
4942  *
4943  * numRules is set to the number of rules read in
4944  */
4945 RuleInfo *
4946 getRules(Archive *fout, int *numRules)
4947 {
4948         PGresult   *res;
4949         int                     ntups;
4950         int                     i;
4951         PQExpBuffer query = createPQExpBuffer();
4952         RuleInfo   *ruleinfo;
4953         int                     i_tableoid;
4954         int                     i_oid;
4955         int                     i_rulename;
4956         int                     i_ruletable;
4957         int                     i_ev_type;
4958         int                     i_is_instead;
4959         int                     i_ev_enabled;
4960
4961         /* Make sure we are in proper schema */
4962         selectSourceSchema(fout, "pg_catalog");
4963
4964         if (fout->remoteVersion >= 80300)
4965         {
4966                 appendPQExpBuffer(query, "SELECT "
4967                                                   "tableoid, oid, rulename, "
4968                                                   "ev_class AS ruletable, ev_type, is_instead, "
4969                                                   "ev_enabled "
4970                                                   "FROM pg_rewrite "
4971                                                   "ORDER BY oid");
4972         }
4973         else if (fout->remoteVersion >= 70100)
4974         {
4975                 appendPQExpBuffer(query, "SELECT "
4976                                                   "tableoid, oid, rulename, "
4977                                                   "ev_class AS ruletable, ev_type, is_instead, "
4978                                                   "'O'::char AS ev_enabled "
4979                                                   "FROM pg_rewrite "
4980                                                   "ORDER BY oid");
4981         }
4982         else
4983         {
4984                 appendPQExpBuffer(query, "SELECT "
4985                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4986                                                   "oid, rulename, "
4987                                                   "ev_class AS ruletable, ev_type, is_instead, "
4988                                                   "'O'::char AS ev_enabled "
4989                                                   "FROM pg_rewrite "
4990                                                   "ORDER BY oid");
4991         }
4992
4993         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4994
4995         ntups = PQntuples(res);
4996
4997         *numRules = ntups;
4998
4999         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5000
5001         i_tableoid = PQfnumber(res, "tableoid");
5002         i_oid = PQfnumber(res, "oid");
5003         i_rulename = PQfnumber(res, "rulename");
5004         i_ruletable = PQfnumber(res, "ruletable");
5005         i_ev_type = PQfnumber(res, "ev_type");
5006         i_is_instead = PQfnumber(res, "is_instead");
5007         i_ev_enabled = PQfnumber(res, "ev_enabled");
5008
5009         for (i = 0; i < ntups; i++)
5010         {
5011                 Oid                     ruletableoid;
5012
5013                 ruleinfo[i].dobj.objType = DO_RULE;
5014                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5015                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5016                 AssignDumpId(&ruleinfo[i].dobj);
5017                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5018                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5019                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5020                 if (ruleinfo[i].ruletable == NULL)
5021                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5022                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5023                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5024                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5025                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5026                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5027                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5028                 if (ruleinfo[i].ruletable)
5029                 {
5030                         /*
5031                          * If the table is a view, force its ON SELECT rule to be sorted
5032                          * before the view itself --- this ensures that any dependencies
5033                          * for the rule affect the table's positioning. Other rules are
5034                          * forced to appear after their table.
5035                          */
5036                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5037                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5038                         {
5039                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5040                                                                         ruleinfo[i].dobj.dumpId);
5041                                 /* We'll merge the rule into CREATE VIEW, if possible */
5042                                 ruleinfo[i].separate = false;
5043                         }
5044                         else
5045                         {
5046                                 addObjectDependency(&ruleinfo[i].dobj,
5047                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5048                                 ruleinfo[i].separate = true;
5049                         }
5050                 }
5051                 else
5052                         ruleinfo[i].separate = true;
5053         }
5054
5055         PQclear(res);
5056
5057         destroyPQExpBuffer(query);
5058
5059         return ruleinfo;
5060 }
5061
5062 /*
5063  * getTriggers
5064  *        get information about every trigger on a dumpable table
5065  *
5066  * Note: trigger data is not returned directly to the caller, but it
5067  * does get entered into the DumpableObject tables.
5068  */
5069 void
5070 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5071 {
5072         int                     i,
5073                                 j;
5074         PQExpBuffer query = createPQExpBuffer();
5075         PGresult   *res;
5076         TriggerInfo *tginfo;
5077         int                     i_tableoid,
5078                                 i_oid,
5079                                 i_tgname,
5080                                 i_tgfname,
5081                                 i_tgtype,
5082                                 i_tgnargs,
5083                                 i_tgargs,
5084                                 i_tgisconstraint,
5085                                 i_tgconstrname,
5086                                 i_tgconstrrelid,
5087                                 i_tgconstrrelname,
5088                                 i_tgenabled,
5089                                 i_tgdeferrable,
5090                                 i_tginitdeferred,
5091                                 i_tgdef;
5092         int                     ntups;
5093
5094         for (i = 0; i < numTables; i++)
5095         {
5096                 TableInfo  *tbinfo = &tblinfo[i];
5097
5098                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5099                         continue;
5100
5101                 if (g_verbose)
5102                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5103                                           tbinfo->dobj.name);
5104
5105                 /*
5106                  * select table schema to ensure regproc name is qualified if needed
5107                  */
5108                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5109
5110                 resetPQExpBuffer(query);
5111                 if (fout->remoteVersion >= 90000)
5112                 {
5113                         /*
5114                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5115                          * could result in non-forward-compatible dumps of WHEN clauses
5116                          * due to under-parenthesization.
5117                          */
5118                         appendPQExpBuffer(query,
5119                                                           "SELECT tgname, "
5120                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5121                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5122                                                           "tgenabled, tableoid, oid "
5123                                                           "FROM pg_catalog.pg_trigger t "
5124                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5125                                                           "AND NOT tgisinternal",
5126                                                           tbinfo->dobj.catId.oid);
5127                 }
5128                 else if (fout->remoteVersion >= 80300)
5129                 {
5130                         /*
5131                          * We ignore triggers that are tied to a foreign-key constraint
5132                          */
5133                         appendPQExpBuffer(query,
5134                                                           "SELECT tgname, "
5135                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5136                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5137                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5138                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5139                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5140                                                           "FROM pg_catalog.pg_trigger t "
5141                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5142                                                           "AND tgconstraint = 0",
5143                                                           tbinfo->dobj.catId.oid);
5144                 }
5145                 else if (fout->remoteVersion >= 70300)
5146                 {
5147                         /*
5148                          * We ignore triggers that are tied to a foreign-key constraint,
5149                          * but in these versions we have to grovel through pg_constraint
5150                          * to find out
5151                          */
5152                         appendPQExpBuffer(query,
5153                                                           "SELECT tgname, "
5154                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5155                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5156                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5157                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5158                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5159                                                           "FROM pg_catalog.pg_trigger t "
5160                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5161                                                           "AND (NOT tgisconstraint "
5162                                                           " OR NOT EXISTS"
5163                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5164                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5165                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5166                                                           tbinfo->dobj.catId.oid);
5167                 }
5168                 else if (fout->remoteVersion >= 70100)
5169                 {
5170                         appendPQExpBuffer(query,
5171                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5172                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5173                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5174                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5175                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5176                                                           "             AS tgconstrrelname "
5177                                                           "FROM pg_trigger "
5178                                                           "WHERE tgrelid = '%u'::oid",
5179                                                           tbinfo->dobj.catId.oid);
5180                 }
5181                 else
5182                 {
5183                         appendPQExpBuffer(query,
5184                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5185                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5186                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5187                                                           "tgconstrrelid, tginitdeferred, "
5188                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5189                                                           "oid, "
5190                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5191                                                           "             AS tgconstrrelname "
5192                                                           "FROM pg_trigger "
5193                                                           "WHERE tgrelid = '%u'::oid",
5194                                                           tbinfo->dobj.catId.oid);
5195                 }
5196                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5197
5198                 ntups = PQntuples(res);
5199
5200                 i_tableoid = PQfnumber(res, "tableoid");
5201                 i_oid = PQfnumber(res, "oid");
5202                 i_tgname = PQfnumber(res, "tgname");
5203                 i_tgfname = PQfnumber(res, "tgfname");
5204                 i_tgtype = PQfnumber(res, "tgtype");
5205                 i_tgnargs = PQfnumber(res, "tgnargs");
5206                 i_tgargs = PQfnumber(res, "tgargs");
5207                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5208                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5209                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5210                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5211                 i_tgenabled = PQfnumber(res, "tgenabled");
5212                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5213                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5214                 i_tgdef = PQfnumber(res, "tgdef");
5215
5216                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5217
5218                 for (j = 0; j < ntups; j++)
5219                 {
5220                         tginfo[j].dobj.objType = DO_TRIGGER;
5221                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5222                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5223                         AssignDumpId(&tginfo[j].dobj);
5224                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5225                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5226                         tginfo[j].tgtable = tbinfo;
5227                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5228                         if (i_tgdef >= 0)
5229                         {
5230                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5231
5232                                 /* remaining fields are not valid if we have tgdef */
5233                                 tginfo[j].tgfname = NULL;
5234                                 tginfo[j].tgtype = 0;
5235                                 tginfo[j].tgnargs = 0;
5236                                 tginfo[j].tgargs = NULL;
5237                                 tginfo[j].tgisconstraint = false;
5238                                 tginfo[j].tgdeferrable = false;
5239                                 tginfo[j].tginitdeferred = false;
5240                                 tginfo[j].tgconstrname = NULL;
5241                                 tginfo[j].tgconstrrelid = InvalidOid;
5242                                 tginfo[j].tgconstrrelname = NULL;
5243                         }
5244                         else
5245                         {
5246                                 tginfo[j].tgdef = NULL;
5247
5248                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5249                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5250                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5251                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5252                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5253                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5254                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5255
5256                                 if (tginfo[j].tgisconstraint)
5257                                 {
5258                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5259                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5260                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5261                                         {
5262                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5263                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5264                                                                                   tginfo[j].dobj.name,
5265                                                                                   tbinfo->dobj.name,
5266                                                                                   tginfo[j].tgconstrrelid);
5267                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5268                                         }
5269                                         else
5270                                                 tginfo[j].tgconstrrelname = NULL;
5271                                 }
5272                                 else
5273                                 {
5274                                         tginfo[j].tgconstrname = NULL;
5275                                         tginfo[j].tgconstrrelid = InvalidOid;
5276                                         tginfo[j].tgconstrrelname = NULL;
5277                                 }
5278                         }
5279                 }
5280
5281                 PQclear(res);
5282         }
5283
5284         destroyPQExpBuffer(query);
5285 }
5286
5287 /*
5288  * getProcLangs
5289  *        get basic information about every procedural language in the system
5290  *
5291  * numProcLangs is set to the number of langs read in
5292  *
5293  * NB: this must run after getFuncs() because we assume we can do
5294  * findFuncByOid().
5295  */
5296 ProcLangInfo *
5297 getProcLangs(Archive *fout, int *numProcLangs)
5298 {
5299         PGresult   *res;
5300         int                     ntups;
5301         int                     i;
5302         PQExpBuffer query = createPQExpBuffer();
5303         ProcLangInfo *planginfo;
5304         int                     i_tableoid;
5305         int                     i_oid;
5306         int                     i_lanname;
5307         int                     i_lanpltrusted;
5308         int                     i_lanplcallfoid;
5309         int                     i_laninline;
5310         int                     i_lanvalidator;
5311         int                     i_lanacl;
5312         int                     i_lanowner;
5313
5314         /* Make sure we are in proper schema */
5315         selectSourceSchema(fout, "pg_catalog");
5316
5317         if (fout->remoteVersion >= 90000)
5318         {
5319                 /* pg_language has a laninline column */
5320                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5321                                                   "lanname, lanpltrusted, lanplcallfoid, "
5322                                                   "laninline, lanvalidator,  lanacl, "
5323                                                   "(%s lanowner) AS lanowner "
5324                                                   "FROM pg_language "
5325                                                   "WHERE lanispl "
5326                                                   "ORDER BY oid",
5327                                                   username_subquery);
5328         }
5329         else if (fout->remoteVersion >= 80300)
5330         {
5331                 /* pg_language has a lanowner column */
5332                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5333                                                   "lanname, lanpltrusted, lanplcallfoid, "
5334                                                   "lanvalidator,  lanacl, "
5335                                                   "(%s lanowner) AS lanowner "
5336                                                   "FROM pg_language "
5337                                                   "WHERE lanispl "
5338                                                   "ORDER BY oid",
5339                                                   username_subquery);
5340         }
5341         else if (fout->remoteVersion >= 80100)
5342         {
5343                 /* Languages are owned by the bootstrap superuser, OID 10 */
5344                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5345                                                   "(%s '10') AS lanowner "
5346                                                   "FROM pg_language "
5347                                                   "WHERE lanispl "
5348                                                   "ORDER BY oid",
5349                                                   username_subquery);
5350         }
5351         else if (fout->remoteVersion >= 70400)
5352         {
5353                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5354                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5355                                                   "(%s '1') AS lanowner "
5356                                                   "FROM pg_language "
5357                                                   "WHERE lanispl "
5358                                                   "ORDER BY oid",
5359                                                   username_subquery);
5360         }
5361         else if (fout->remoteVersion >= 70100)
5362         {
5363                 /* No clear notion of an owner at all before 7.4 ... */
5364                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5365                                                   "WHERE lanispl "
5366                                                   "ORDER BY oid");
5367         }
5368         else
5369         {
5370                 appendPQExpBuffer(query, "SELECT "
5371                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5372                                                   "oid, * FROM pg_language "
5373                                                   "WHERE lanispl "
5374                                                   "ORDER BY oid");
5375         }
5376
5377         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5378
5379         ntups = PQntuples(res);
5380
5381         *numProcLangs = ntups;
5382
5383         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5384
5385         i_tableoid = PQfnumber(res, "tableoid");
5386         i_oid = PQfnumber(res, "oid");
5387         i_lanname = PQfnumber(res, "lanname");
5388         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5389         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5390         /* these may fail and return -1: */
5391         i_laninline = PQfnumber(res, "laninline");
5392         i_lanvalidator = PQfnumber(res, "lanvalidator");
5393         i_lanacl = PQfnumber(res, "lanacl");
5394         i_lanowner = PQfnumber(res, "lanowner");
5395
5396         for (i = 0; i < ntups; i++)
5397         {
5398                 planginfo[i].dobj.objType = DO_PROCLANG;
5399                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5400                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5401                 AssignDumpId(&planginfo[i].dobj);
5402
5403                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5404                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5405                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5406                 if (i_laninline >= 0)
5407                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5408                 else
5409                         planginfo[i].laninline = InvalidOid;
5410                 if (i_lanvalidator >= 0)
5411                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5412                 else
5413                         planginfo[i].lanvalidator = InvalidOid;
5414                 if (i_lanacl >= 0)
5415                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5416                 else
5417                         planginfo[i].lanacl = pg_strdup("{=U}");
5418                 if (i_lanowner >= 0)
5419                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5420                 else
5421                         planginfo[i].lanowner = pg_strdup("");
5422
5423                 if (fout->remoteVersion < 70300)
5424                 {
5425                         /*
5426                          * We need to make a dependency to ensure the function will be
5427                          * dumped first.  (In 7.3 and later the regular dependency
5428                          * mechanism will handle this for us.)
5429                          */
5430                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5431
5432                         if (funcInfo)
5433                                 addObjectDependency(&planginfo[i].dobj,
5434                                                                         funcInfo->dobj.dumpId);
5435                 }
5436         }
5437
5438         PQclear(res);
5439
5440         destroyPQExpBuffer(query);
5441
5442         return planginfo;
5443 }
5444
5445 /*
5446  * getCasts
5447  *        get basic information about every cast in the system
5448  *
5449  * numCasts is set to the number of casts read in
5450  */
5451 CastInfo *
5452 getCasts(Archive *fout, int *numCasts)
5453 {
5454         PGresult   *res;
5455         int                     ntups;
5456         int                     i;
5457         PQExpBuffer query = createPQExpBuffer();
5458         CastInfo   *castinfo;
5459         int                     i_tableoid;
5460         int                     i_oid;
5461         int                     i_castsource;
5462         int                     i_casttarget;
5463         int                     i_castfunc;
5464         int                     i_castcontext;
5465         int                     i_castmethod;
5466
5467         /* Make sure we are in proper schema */
5468         selectSourceSchema(fout, "pg_catalog");
5469
5470         if (fout->remoteVersion >= 80400)
5471         {
5472                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5473                                                   "castsource, casttarget, castfunc, castcontext, "
5474                                                   "castmethod "
5475                                                   "FROM pg_cast ORDER BY 3,4");
5476         }
5477         else if (fout->remoteVersion >= 70300)
5478         {
5479                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5480                                                   "castsource, casttarget, castfunc, castcontext, "
5481                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5482                                                   "FROM pg_cast ORDER BY 3,4");
5483         }
5484         else
5485         {
5486                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5487                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5488                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5489                                                   "'f' AS castmethod "
5490                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5491                                                   "WHERE p.pronargs = 1 AND "
5492                                                   "p.proargtypes[0] = t1.oid AND "
5493                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5494                                                   "ORDER BY 3,4");
5495         }
5496
5497         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5498
5499         ntups = PQntuples(res);
5500
5501         *numCasts = ntups;
5502
5503         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5504
5505         i_tableoid = PQfnumber(res, "tableoid");
5506         i_oid = PQfnumber(res, "oid");
5507         i_castsource = PQfnumber(res, "castsource");
5508         i_casttarget = PQfnumber(res, "casttarget");
5509         i_castfunc = PQfnumber(res, "castfunc");
5510         i_castcontext = PQfnumber(res, "castcontext");
5511         i_castmethod = PQfnumber(res, "castmethod");
5512
5513         for (i = 0; i < ntups; i++)
5514         {
5515                 PQExpBufferData namebuf;
5516                 TypeInfo   *sTypeInfo;
5517                 TypeInfo   *tTypeInfo;
5518
5519                 castinfo[i].dobj.objType = DO_CAST;
5520                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5521                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5522                 AssignDumpId(&castinfo[i].dobj);
5523                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5524                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5525                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5526                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5527                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5528
5529                 /*
5530                  * Try to name cast as concatenation of typnames.  This is only used
5531                  * for purposes of sorting.  If we fail to find either type, the name
5532                  * will be an empty string.
5533                  */
5534                 initPQExpBuffer(&namebuf);
5535                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5536                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5537                 if (sTypeInfo && tTypeInfo)
5538                         appendPQExpBuffer(&namebuf, "%s %s",
5539                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5540                 castinfo[i].dobj.name = namebuf.data;
5541
5542                 if (OidIsValid(castinfo[i].castfunc))
5543                 {
5544                         /*
5545                          * We need to make a dependency to ensure the function will be
5546                          * dumped first.  (In 7.3 and later the regular dependency
5547                          * mechanism will handle this for us.)
5548                          */
5549                         FuncInfo   *funcInfo;
5550
5551                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5552                         if (funcInfo)
5553                                 addObjectDependency(&castinfo[i].dobj,
5554                                                                         funcInfo->dobj.dumpId);
5555                 }
5556         }
5557
5558         PQclear(res);
5559
5560         destroyPQExpBuffer(query);
5561
5562         return castinfo;
5563 }
5564
5565 /*
5566  * getTableAttrs -
5567  *        for each interesting table, read info about its attributes
5568  *        (names, types, default values, CHECK constraints, etc)
5569  *
5570  * This is implemented in a very inefficient way right now, looping
5571  * through the tblinfo and doing a join per table to find the attrs and their
5572  * types.  However, because we want type names and so forth to be named
5573  * relative to the schema of each table, we couldn't do it in just one
5574  * query.  (Maybe one query per schema?)
5575  *
5576  *      modifies tblinfo
5577  */
5578 void
5579 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5580 {
5581         int                     i,
5582                                 j;
5583         PQExpBuffer q = createPQExpBuffer();
5584         int                     i_attnum;
5585         int                     i_attname;
5586         int                     i_atttypname;
5587         int                     i_atttypmod;
5588         int                     i_attstattarget;
5589         int                     i_attstorage;
5590         int                     i_typstorage;
5591         int                     i_attnotnull;
5592         int                     i_atthasdef;
5593         int                     i_attisdropped;
5594         int                     i_attlen;
5595         int                     i_attalign;
5596         int                     i_attislocal;
5597         int                     i_attoptions;
5598         int                     i_attcollation;
5599         int                     i_attfdwoptions;
5600         PGresult   *res;
5601         int                     ntups;
5602         bool            hasdefaults;
5603
5604         for (i = 0; i < numTables; i++)
5605         {
5606                 TableInfo  *tbinfo = &tblinfo[i];
5607
5608                 /* Don't bother to collect info for sequences */
5609                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5610                         continue;
5611
5612                 /* Don't bother with uninteresting tables, either */
5613                 if (!tbinfo->interesting)
5614                         continue;
5615
5616                 /*
5617                  * Make sure we are in proper schema for this table; this allows
5618                  * correct retrieval of formatted type names and default exprs
5619                  */
5620                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5621
5622                 /* find all the user attributes and their types */
5623
5624                 /*
5625                  * we must read the attribute names in attribute number order! because
5626                  * we will use the attnum to index into the attnames array later.  We
5627                  * actually ask to order by "attrelid, attnum" because (at least up to
5628                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5629                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5630                  */
5631                 if (g_verbose)
5632                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5633                                           tbinfo->dobj.name);
5634
5635                 resetPQExpBuffer(q);
5636
5637                 if (fout->remoteVersion >= 90200)
5638                 {
5639                         /*
5640                          * attfdwoptions is new in 9.2.
5641                          */
5642                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5643                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5644                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5645                                                           "a.attlen, a.attalign, a.attislocal, "
5646                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5647                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5648                                                           "CASE WHEN a.attcollation <> t.typcollation "
5649                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5650                                                           "pg_catalog.array_to_string(ARRAY("
5651                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5652                                                           "' ' || pg_catalog.quote_literal(option_value) "
5653                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5654                                                           "ORDER BY option_name"
5655                                                           "), E',\n    ') AS attfdwoptions "
5656                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5657                                                           "ON a.atttypid = t.oid "
5658                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5659                                                           "AND a.attnum > 0::pg_catalog.int2 "
5660                                                           "ORDER BY a.attrelid, a.attnum",
5661                                                           tbinfo->dobj.catId.oid);
5662                 }
5663                 else if (fout->remoteVersion >= 90100)
5664                 {
5665                         /*
5666                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5667                          * clauses for attributes whose collation is different from their
5668                          * type's default, we use a CASE here to suppress uninteresting
5669                          * attcollations cheaply.
5670                          */
5671                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5672                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5673                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5674                                                           "a.attlen, a.attalign, a.attislocal, "
5675                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5676                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5677                                                           "CASE WHEN a.attcollation <> t.typcollation "
5678                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5679                                                           "NULL AS attfdwoptions "
5680                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5681                                                           "ON a.atttypid = t.oid "
5682                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5683                                                           "AND a.attnum > 0::pg_catalog.int2 "
5684                                                           "ORDER BY a.attrelid, a.attnum",
5685                                                           tbinfo->dobj.catId.oid);
5686                 }
5687                 else if (fout->remoteVersion >= 90000)
5688                 {
5689                         /* attoptions is new in 9.0 */
5690                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5691                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5692                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5693                                                           "a.attlen, a.attalign, a.attislocal, "
5694                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5695                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5696                                                           "0 AS attcollation, "
5697                                                           "NULL AS attfdwoptions "
5698                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5699                                                           "ON a.atttypid = t.oid "
5700                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5701                                                           "AND a.attnum > 0::pg_catalog.int2 "
5702                                                           "ORDER BY a.attrelid, a.attnum",
5703                                                           tbinfo->dobj.catId.oid);
5704                 }
5705                 else if (fout->remoteVersion >= 70300)
5706                 {
5707                         /* need left join here to not fail on dropped columns ... */
5708                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5709                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5710                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5711                                                           "a.attlen, a.attalign, a.attislocal, "
5712                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5713                                                           "'' AS attoptions, 0 AS attcollation, "
5714                                                           "NULL AS attfdwoptions "
5715                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5716                                                           "ON a.atttypid = t.oid "
5717                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5718                                                           "AND a.attnum > 0::pg_catalog.int2 "
5719                                                           "ORDER BY a.attrelid, a.attnum",
5720                                                           tbinfo->dobj.catId.oid);
5721                 }
5722                 else if (fout->remoteVersion >= 70100)
5723                 {
5724                         /*
5725                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5726                          * we don't dump it because we can't tell whether it's been
5727                          * explicitly set or was just a default.
5728                          *
5729                          * attislocal doesn't exist before 7.3, either; in older databases
5730                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5731                          */
5732                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5733                                                           "-1 AS attstattarget, a.attstorage, "
5734                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5735                                                           "false AS attisdropped, a.attlen, "
5736                                                           "a.attalign, true AS attislocal, "
5737                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5738                                                           "'' AS attoptions, 0 AS attcollation, "
5739                                                           "NULL AS attfdwoptions "
5740                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5741                                                           "ON a.atttypid = t.oid "
5742                                                           "WHERE a.attrelid = '%u'::oid "
5743                                                           "AND a.attnum > 0::int2 "
5744                                                           "ORDER BY a.attrelid, a.attnum",
5745                                                           tbinfo->dobj.catId.oid);
5746                 }
5747                 else
5748                 {
5749                         /* format_type not available before 7.1 */
5750                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5751                                                           "-1 AS attstattarget, "
5752                                                           "attstorage, attstorage AS typstorage, "
5753                                                           "attnotnull, atthasdef, false AS attisdropped, "
5754                                                           "attlen, attalign, "
5755                                                           "true AS attislocal, "
5756                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5757                                                           "'' AS attoptions, 0 AS attcollation, "
5758                                                           "NULL AS attfdwoptions "
5759                                                           "FROM pg_attribute a "
5760                                                           "WHERE attrelid = '%u'::oid "
5761                                                           "AND attnum > 0::int2 "
5762                                                           "ORDER BY attrelid, attnum",
5763                                                           tbinfo->dobj.catId.oid);
5764                 }
5765
5766                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5767
5768                 ntups = PQntuples(res);
5769
5770                 i_attnum = PQfnumber(res, "attnum");
5771                 i_attname = PQfnumber(res, "attname");
5772                 i_atttypname = PQfnumber(res, "atttypname");
5773                 i_atttypmod = PQfnumber(res, "atttypmod");
5774                 i_attstattarget = PQfnumber(res, "attstattarget");
5775                 i_attstorage = PQfnumber(res, "attstorage");
5776                 i_typstorage = PQfnumber(res, "typstorage");
5777                 i_attnotnull = PQfnumber(res, "attnotnull");
5778                 i_atthasdef = PQfnumber(res, "atthasdef");
5779                 i_attisdropped = PQfnumber(res, "attisdropped");
5780                 i_attlen = PQfnumber(res, "attlen");
5781                 i_attalign = PQfnumber(res, "attalign");
5782                 i_attislocal = PQfnumber(res, "attislocal");
5783                 i_attoptions = PQfnumber(res, "attoptions");
5784                 i_attcollation = PQfnumber(res, "attcollation");
5785                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5786
5787                 tbinfo->numatts = ntups;
5788                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5789                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5790                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5791                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5792                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5793                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5794                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5795                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5796                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5797                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5798                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5799                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5800                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5801                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5802                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5803                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5804                 hasdefaults = false;
5805
5806                 for (j = 0; j < ntups; j++)
5807                 {
5808                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5809                                 exit_horribly(NULL,
5810                                                           "invalid column numbering in table \"%s\"\n",
5811                                                           tbinfo->dobj.name);
5812                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5813                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5814                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5815                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5816                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5817                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5818                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5819                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5820                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5821                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5822                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5823                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5824                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5825                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5826                         tbinfo->attrdefs[j] = NULL; /* fix below */
5827                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5828                                 hasdefaults = true;
5829                         /* these flags will be set in flagInhAttrs() */
5830                         tbinfo->inhNotNull[j] = false;
5831                 }
5832
5833                 PQclear(res);
5834
5835                 /*
5836                  * Get info about column defaults
5837                  */
5838                 if (hasdefaults)
5839                 {
5840                         AttrDefInfo *attrdefs;
5841                         int                     numDefaults;
5842
5843                         if (g_verbose)
5844                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5845                                                   tbinfo->dobj.name);
5846
5847                         resetPQExpBuffer(q);
5848                         if (fout->remoteVersion >= 70300)
5849                         {
5850                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5851                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5852                                                                   "FROM pg_catalog.pg_attrdef "
5853                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5854                                                                   tbinfo->dobj.catId.oid);
5855                         }
5856                         else if (fout->remoteVersion >= 70200)
5857                         {
5858                                 /* 7.2 did not have OIDs in pg_attrdef */
5859                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5860                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5861                                                                   "FROM pg_attrdef "
5862                                                                   "WHERE adrelid = '%u'::oid",
5863                                                                   tbinfo->dobj.catId.oid);
5864                         }
5865                         else if (fout->remoteVersion >= 70100)
5866                         {
5867                                 /* no pg_get_expr, so must rely on adsrc */
5868                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5869                                                                   "FROM pg_attrdef "
5870                                                                   "WHERE adrelid = '%u'::oid",
5871                                                                   tbinfo->dobj.catId.oid);
5872                         }
5873                         else
5874                         {
5875                                 /* no pg_get_expr, no tableoid either */
5876                                 appendPQExpBuffer(q, "SELECT "
5877                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5878                                                                   "oid, adnum, adsrc "
5879                                                                   "FROM pg_attrdef "
5880                                                                   "WHERE adrelid = '%u'::oid",
5881                                                                   tbinfo->dobj.catId.oid);
5882                         }
5883                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5884
5885                         numDefaults = PQntuples(res);
5886                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5887
5888                         for (j = 0; j < numDefaults; j++)
5889                         {
5890                                 int                     adnum;
5891
5892                                 adnum = atoi(PQgetvalue(res, j, 2));
5893
5894                                 if (adnum <= 0 || adnum > ntups)
5895                                         exit_horribly(NULL,
5896                                                                   "invalid adnum value %d for table \"%s\"\n",
5897                                                                   adnum, tbinfo->dobj.name);
5898
5899                                 /*
5900                                  * dropped columns shouldn't have defaults, but just in case,
5901                                  * ignore 'em
5902                                  */
5903                                 if (tbinfo->attisdropped[adnum - 1])
5904                                         continue;
5905
5906                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
5907                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5908                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5909                                 AssignDumpId(&attrdefs[j].dobj);
5910                                 attrdefs[j].adtable = tbinfo;
5911                                 attrdefs[j].adnum = adnum;
5912                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5913
5914                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5915                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5916
5917                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5918
5919                                 /*
5920                                  * Defaults on a VIEW must always be dumped as separate ALTER
5921                                  * TABLE commands.      Defaults on regular tables are dumped as
5922                                  * part of the CREATE TABLE if possible, which it won't be
5923                                  * if the column is not going to be emitted explicitly.
5924                                  */
5925                                 if (tbinfo->relkind == RELKIND_VIEW)
5926                                 {
5927                                         attrdefs[j].separate = true;
5928                                         /* needed in case pre-7.3 DB: */
5929                                         addObjectDependency(&attrdefs[j].dobj,
5930                                                                                 tbinfo->dobj.dumpId);
5931                                 }
5932                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5933                                 {
5934                                         /* column will be suppressed, print default separately */
5935                                         attrdefs[j].separate = true;
5936                                         /* needed in case pre-7.3 DB: */
5937                                         addObjectDependency(&attrdefs[j].dobj,
5938                                                                                 tbinfo->dobj.dumpId);
5939                                 }
5940                                 else
5941                                 {
5942                                         attrdefs[j].separate = false;
5943                                         /*
5944                                          * Mark the default as needing to appear before the table,
5945                                          * so that any dependencies it has must be emitted before
5946                                          * the CREATE TABLE.  If this is not possible, we'll
5947                                          * change to "separate" mode while sorting dependencies.
5948                                          */
5949                                         addObjectDependency(&tbinfo->dobj,
5950                                                                                 attrdefs[j].dobj.dumpId);
5951                                 }
5952
5953                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5954                         }
5955                         PQclear(res);
5956                 }
5957
5958                 /*
5959                  * Get info about table CHECK constraints
5960                  */
5961                 if (tbinfo->ncheck > 0)
5962                 {
5963                         ConstraintInfo *constrs;
5964                         int                     numConstrs;
5965
5966                         if (g_verbose)
5967                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5968                                                   tbinfo->dobj.name);
5969
5970                         resetPQExpBuffer(q);
5971                         if (fout->remoteVersion >= 90200)
5972                         {
5973                                 /*
5974                                  * conisonly and convalidated are new in 9.2 (actually, the latter
5975                                  * is there in 9.1, but it wasn't ever false for check constraints
5976                                  * until 9.2).
5977                                  */
5978                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5979                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5980                                                                   "conislocal, convalidated, conisonly "
5981                                                                   "FROM pg_catalog.pg_constraint "
5982                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5983                                                                   "   AND contype = 'c' "
5984                                                                   "ORDER BY conname",
5985                                                                   tbinfo->dobj.catId.oid);
5986                         }
5987                         else if (fout->remoteVersion >= 80400)
5988                         {
5989                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5990                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5991                                                                   "conislocal, true AS convalidated, "
5992                                                                   "false as conisonly "
5993                                                                   "FROM pg_catalog.pg_constraint "
5994                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5995                                                                   "   AND contype = 'c' "
5996                                                                   "ORDER BY conname",
5997                                                                   tbinfo->dobj.catId.oid);
5998                         }
5999                         else if (fout->remoteVersion >= 70400)
6000                         {
6001                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6002                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6003                                                                   "true AS conislocal, true AS convalidated, "
6004                                                                   "false as conisonly "
6005                                                                   "FROM pg_catalog.pg_constraint "
6006                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6007                                                                   "   AND contype = 'c' "
6008                                                                   "ORDER BY conname",
6009                                                                   tbinfo->dobj.catId.oid);
6010                         }
6011                         else if (fout->remoteVersion >= 70300)
6012                         {
6013                                 /* no pg_get_constraintdef, must use consrc */
6014                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6015                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6016                                                                   "true AS conislocal, true AS convalidated, "
6017                                                                   "false as conisonly "
6018                                                                   "FROM pg_catalog.pg_constraint "
6019                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6020                                                                   "   AND contype = 'c' "
6021                                                                   "ORDER BY conname",
6022                                                                   tbinfo->dobj.catId.oid);
6023                         }
6024                         else if (fout->remoteVersion >= 70200)
6025                         {
6026                                 /* 7.2 did not have OIDs in pg_relcheck */
6027                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6028                                                                   "rcname AS conname, "
6029                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6030                                                                   "true AS conislocal, true AS convalidated, "
6031                                                                   "false as conisonly "
6032                                                                   "FROM pg_relcheck "
6033                                                                   "WHERE rcrelid = '%u'::oid "
6034                                                                   "ORDER BY rcname",
6035                                                                   tbinfo->dobj.catId.oid);
6036                         }
6037                         else if (fout->remoteVersion >= 70100)
6038                         {
6039                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6040                                                                   "rcname AS conname, "
6041                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6042                                                                   "true AS conislocal, true AS convalidated, "
6043                                                                   "false as conisonly "
6044                                                                   "FROM pg_relcheck "
6045                                                                   "WHERE rcrelid = '%u'::oid "
6046                                                                   "ORDER BY rcname",
6047                                                                   tbinfo->dobj.catId.oid);
6048                         }
6049                         else
6050                         {
6051                                 /* no tableoid in 7.0 */
6052                                 appendPQExpBuffer(q, "SELECT "
6053                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6054                                                                   "oid, rcname AS conname, "
6055                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6056                                                                   "true AS conislocal, true AS convalidated, "
6057                                                                   "false as conisonly "
6058                                                                   "FROM pg_relcheck "
6059                                                                   "WHERE rcrelid = '%u'::oid "
6060                                                                   "ORDER BY rcname",
6061                                                                   tbinfo->dobj.catId.oid);
6062                         }
6063                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6064
6065                         numConstrs = PQntuples(res);
6066                         if (numConstrs != tbinfo->ncheck)
6067                         {
6068                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6069                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6070                                                                                  tbinfo->ncheck),
6071                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6072                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6073                                 exit_nicely(1);
6074                         }
6075
6076                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6077                         tbinfo->checkexprs = constrs;
6078
6079                         for (j = 0; j < numConstrs; j++)
6080                         {
6081                                 bool    validated = PQgetvalue(res, j, 5)[0] == 't';
6082                                 bool    isonly = PQgetvalue(res, j, 6)[0] == 't';
6083
6084                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6085                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6086                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6087                                 AssignDumpId(&constrs[j].dobj);
6088                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6089                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6090                                 constrs[j].contable = tbinfo;
6091                                 constrs[j].condomain = NULL;
6092                                 constrs[j].contype = 'c';
6093                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6094                                 constrs[j].confrelid = InvalidOid;
6095                                 constrs[j].conindex = 0;
6096                                 constrs[j].condeferrable = false;
6097                                 constrs[j].condeferred = false;
6098                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6099                                 constrs[j].conisonly = isonly;
6100                                 /*
6101                                  * An unvalidated constraint needs to be dumped separately, so
6102                                  * that potentially-violating existing data is loaded before
6103                                  * the constraint.  An ONLY constraint needs to be dumped
6104                                  * separately too.
6105                                  */
6106                                 constrs[j].separate = !validated || isonly;
6107
6108                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6109
6110                                 /*
6111                                  * Mark the constraint as needing to appear before the table
6112                                  * --- this is so that any other dependencies of the
6113                                  * constraint will be emitted before we try to create the
6114                                  * table.  If the constraint is to be dumped separately, it will be
6115                                  * dumped after data is loaded anyway, so don't do it.  (There's
6116                                  * an automatic dependency in the opposite direction anyway, so
6117                                  * don't need to add one manually here.)
6118                                  */
6119                                 if (!constrs[j].separate)
6120                                         addObjectDependency(&tbinfo->dobj,
6121                                                                                 constrs[j].dobj.dumpId);
6122
6123                                 /*
6124                                  * If the constraint is inherited, this will be detected later
6125                                  * (in pre-8.4 databases).      We also detect later if the
6126                                  * constraint must be split out from the table definition.
6127                                  */
6128                         }
6129                         PQclear(res);
6130                 }
6131         }
6132
6133         destroyPQExpBuffer(q);
6134 }
6135
6136 /*
6137  * Test whether a column should be printed as part of table's CREATE TABLE.
6138  * Column number is zero-based.
6139  *
6140  * Normally this is always true, but it's false for dropped columns, as well
6141  * as those that were inherited without any local definition.  (If we print
6142  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6143  * However, in binary_upgrade mode, we must print all such columns anyway and
6144  * fix the attislocal/attisdropped state later, so as to keep control of the
6145  * physical column order.
6146  *
6147  * This function exists because there are scattered nonobvious places that
6148  * must be kept in sync with this decision.
6149  */
6150 bool
6151 shouldPrintColumn(TableInfo *tbinfo, int colno)
6152 {
6153         if (binary_upgrade)
6154                 return true;
6155         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6156 }
6157
6158
6159 /*
6160  * getTSParsers:
6161  *        read all text search parsers in the system catalogs and return them
6162  *        in the TSParserInfo* structure
6163  *
6164  *      numTSParsers is set to the number of parsers read in
6165  */
6166 TSParserInfo *
6167 getTSParsers(Archive *fout, int *numTSParsers)
6168 {
6169         PGresult   *res;
6170         int                     ntups;
6171         int                     i;
6172         PQExpBuffer query;
6173         TSParserInfo *prsinfo;
6174         int                     i_tableoid;
6175         int                     i_oid;
6176         int                     i_prsname;
6177         int                     i_prsnamespace;
6178         int                     i_prsstart;
6179         int                     i_prstoken;
6180         int                     i_prsend;
6181         int                     i_prsheadline;
6182         int                     i_prslextype;
6183
6184         /* Before 8.3, there is no built-in text search support */
6185         if (fout->remoteVersion < 80300)
6186         {
6187                 *numTSParsers = 0;
6188                 return NULL;
6189         }
6190
6191         query = createPQExpBuffer();
6192
6193         /*
6194          * find all text search objects, including builtin ones; we filter out
6195          * system-defined objects at dump-out time.
6196          */
6197
6198         /* Make sure we are in proper schema */
6199         selectSourceSchema(fout, "pg_catalog");
6200
6201         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6202                                           "prsstart::oid, prstoken::oid, "
6203                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6204                                           "FROM pg_ts_parser");
6205
6206         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6207
6208         ntups = PQntuples(res);
6209         *numTSParsers = ntups;
6210
6211         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6212
6213         i_tableoid = PQfnumber(res, "tableoid");
6214         i_oid = PQfnumber(res, "oid");
6215         i_prsname = PQfnumber(res, "prsname");
6216         i_prsnamespace = PQfnumber(res, "prsnamespace");
6217         i_prsstart = PQfnumber(res, "prsstart");
6218         i_prstoken = PQfnumber(res, "prstoken");
6219         i_prsend = PQfnumber(res, "prsend");
6220         i_prsheadline = PQfnumber(res, "prsheadline");
6221         i_prslextype = PQfnumber(res, "prslextype");
6222
6223         for (i = 0; i < ntups; i++)
6224         {
6225                 prsinfo[i].dobj.objType = DO_TSPARSER;
6226                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6227                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6228                 AssignDumpId(&prsinfo[i].dobj);
6229                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6230                 prsinfo[i].dobj.namespace =
6231                         findNamespace(fout,
6232                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6233                                                   prsinfo[i].dobj.catId.oid);
6234                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6235                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6236                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6237                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6238                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6239
6240                 /* Decide whether we want to dump it */
6241                 selectDumpableObject(&(prsinfo[i].dobj));
6242         }
6243
6244         PQclear(res);
6245
6246         destroyPQExpBuffer(query);
6247
6248         return prsinfo;
6249 }
6250
6251 /*
6252  * getTSDictionaries:
6253  *        read all text search dictionaries in the system catalogs and return them
6254  *        in the TSDictInfo* structure
6255  *
6256  *      numTSDicts is set to the number of dictionaries read in
6257  */
6258 TSDictInfo *
6259 getTSDictionaries(Archive *fout, int *numTSDicts)
6260 {
6261         PGresult   *res;
6262         int                     ntups;
6263         int                     i;
6264         PQExpBuffer query;
6265         TSDictInfo *dictinfo;
6266         int                     i_tableoid;
6267         int                     i_oid;
6268         int                     i_dictname;
6269         int                     i_dictnamespace;
6270         int                     i_rolname;
6271         int                     i_dicttemplate;
6272         int                     i_dictinitoption;
6273
6274         /* Before 8.3, there is no built-in text search support */
6275         if (fout->remoteVersion < 80300)
6276         {
6277                 *numTSDicts = 0;
6278                 return NULL;
6279         }
6280
6281         query = createPQExpBuffer();
6282
6283         /* Make sure we are in proper schema */
6284         selectSourceSchema(fout, "pg_catalog");
6285
6286         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6287                                           "dictnamespace, (%s dictowner) AS rolname, "
6288                                           "dicttemplate, dictinitoption "
6289                                           "FROM pg_ts_dict",
6290                                           username_subquery);
6291
6292         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6293
6294         ntups = PQntuples(res);
6295         *numTSDicts = ntups;
6296
6297         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6298
6299         i_tableoid = PQfnumber(res, "tableoid");
6300         i_oid = PQfnumber(res, "oid");
6301         i_dictname = PQfnumber(res, "dictname");
6302         i_dictnamespace = PQfnumber(res, "dictnamespace");
6303         i_rolname = PQfnumber(res, "rolname");
6304         i_dictinitoption = PQfnumber(res, "dictinitoption");
6305         i_dicttemplate = PQfnumber(res, "dicttemplate");
6306
6307         for (i = 0; i < ntups; i++)
6308         {
6309                 dictinfo[i].dobj.objType = DO_TSDICT;
6310                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6311                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6312                 AssignDumpId(&dictinfo[i].dobj);
6313                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6314                 dictinfo[i].dobj.namespace =
6315                         findNamespace(fout,
6316                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6317                                                   dictinfo[i].dobj.catId.oid);
6318                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6319                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6320                 if (PQgetisnull(res, i, i_dictinitoption))
6321                         dictinfo[i].dictinitoption = NULL;
6322                 else
6323                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6324
6325                 /* Decide whether we want to dump it */
6326                 selectDumpableObject(&(dictinfo[i].dobj));
6327         }
6328
6329         PQclear(res);
6330
6331         destroyPQExpBuffer(query);
6332
6333         return dictinfo;
6334 }
6335
6336 /*
6337  * getTSTemplates:
6338  *        read all text search templates in the system catalogs and return them
6339  *        in the TSTemplateInfo* structure
6340  *
6341  *      numTSTemplates is set to the number of templates read in
6342  */
6343 TSTemplateInfo *
6344 getTSTemplates(Archive *fout, int *numTSTemplates)
6345 {
6346         PGresult   *res;
6347         int                     ntups;
6348         int                     i;
6349         PQExpBuffer query;
6350         TSTemplateInfo *tmplinfo;
6351         int                     i_tableoid;
6352         int                     i_oid;
6353         int                     i_tmplname;
6354         int                     i_tmplnamespace;
6355         int                     i_tmplinit;
6356         int                     i_tmpllexize;
6357
6358         /* Before 8.3, there is no built-in text search support */
6359         if (fout->remoteVersion < 80300)
6360         {
6361                 *numTSTemplates = 0;
6362                 return NULL;
6363         }
6364
6365         query = createPQExpBuffer();
6366
6367         /* Make sure we are in proper schema */
6368         selectSourceSchema(fout, "pg_catalog");
6369
6370         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6371                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6372                                           "FROM pg_ts_template");
6373
6374         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6375
6376         ntups = PQntuples(res);
6377         *numTSTemplates = ntups;
6378
6379         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6380
6381         i_tableoid = PQfnumber(res, "tableoid");
6382         i_oid = PQfnumber(res, "oid");
6383         i_tmplname = PQfnumber(res, "tmplname");
6384         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6385         i_tmplinit = PQfnumber(res, "tmplinit");
6386         i_tmpllexize = PQfnumber(res, "tmpllexize");
6387
6388         for (i = 0; i < ntups; i++)
6389         {
6390                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6391                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6392                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6393                 AssignDumpId(&tmplinfo[i].dobj);
6394                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6395                 tmplinfo[i].dobj.namespace =
6396                         findNamespace(fout,
6397                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6398                                                   tmplinfo[i].dobj.catId.oid);
6399                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6400                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6401
6402                 /* Decide whether we want to dump it */
6403                 selectDumpableObject(&(tmplinfo[i].dobj));
6404         }
6405
6406         PQclear(res);
6407
6408         destroyPQExpBuffer(query);
6409
6410         return tmplinfo;
6411 }
6412
6413 /*
6414  * getTSConfigurations:
6415  *        read all text search configurations in the system catalogs and return
6416  *        them in the TSConfigInfo* structure
6417  *
6418  *      numTSConfigs is set to the number of configurations read in
6419  */
6420 TSConfigInfo *
6421 getTSConfigurations(Archive *fout, int *numTSConfigs)
6422 {
6423         PGresult   *res;
6424         int                     ntups;
6425         int                     i;
6426         PQExpBuffer query;
6427         TSConfigInfo *cfginfo;
6428         int                     i_tableoid;
6429         int                     i_oid;
6430         int                     i_cfgname;
6431         int                     i_cfgnamespace;
6432         int                     i_rolname;
6433         int                     i_cfgparser;
6434
6435         /* Before 8.3, there is no built-in text search support */
6436         if (fout->remoteVersion < 80300)
6437         {
6438                 *numTSConfigs = 0;
6439                 return NULL;
6440         }
6441
6442         query = createPQExpBuffer();
6443
6444         /* Make sure we are in proper schema */
6445         selectSourceSchema(fout, "pg_catalog");
6446
6447         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6448                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6449                                           "FROM pg_ts_config",
6450                                           username_subquery);
6451
6452         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6453
6454         ntups = PQntuples(res);
6455         *numTSConfigs = ntups;
6456
6457         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6458
6459         i_tableoid = PQfnumber(res, "tableoid");
6460         i_oid = PQfnumber(res, "oid");
6461         i_cfgname = PQfnumber(res, "cfgname");
6462         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6463         i_rolname = PQfnumber(res, "rolname");
6464         i_cfgparser = PQfnumber(res, "cfgparser");
6465
6466         for (i = 0; i < ntups; i++)
6467         {
6468                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6469                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6470                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6471                 AssignDumpId(&cfginfo[i].dobj);
6472                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6473                 cfginfo[i].dobj.namespace =
6474                         findNamespace(fout,
6475                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6476                                                   cfginfo[i].dobj.catId.oid);
6477                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6478                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6479
6480                 /* Decide whether we want to dump it */
6481                 selectDumpableObject(&(cfginfo[i].dobj));
6482         }
6483
6484         PQclear(res);
6485
6486         destroyPQExpBuffer(query);
6487
6488         return cfginfo;
6489 }
6490
6491 /*
6492  * getForeignDataWrappers:
6493  *        read all foreign-data wrappers in the system catalogs and return
6494  *        them in the FdwInfo* structure
6495  *
6496  *      numForeignDataWrappers is set to the number of fdws read in
6497  */
6498 FdwInfo *
6499 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6500 {
6501         PGresult   *res;
6502         int                     ntups;
6503         int                     i;
6504         PQExpBuffer query = createPQExpBuffer();
6505         FdwInfo    *fdwinfo;
6506         int                     i_tableoid;
6507         int                     i_oid;
6508         int                     i_fdwname;
6509         int                     i_rolname;
6510         int                     i_fdwhandler;
6511         int                     i_fdwvalidator;
6512         int                     i_fdwacl;
6513         int                     i_fdwoptions;
6514
6515         /* Before 8.4, there are no foreign-data wrappers */
6516         if (fout->remoteVersion < 80400)
6517         {
6518                 *numForeignDataWrappers = 0;
6519                 return NULL;
6520         }
6521
6522         /* Make sure we are in proper schema */
6523         selectSourceSchema(fout, "pg_catalog");
6524
6525         if (fout->remoteVersion >= 90100)
6526         {
6527                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6528                                                   "(%s fdwowner) AS rolname, "
6529                                                   "fdwhandler::pg_catalog.regproc, "
6530                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6531                                                   "array_to_string(ARRAY("
6532                                                   "SELECT quote_ident(option_name) || ' ' || "
6533                                                   "quote_literal(option_value) "
6534                                                   "FROM pg_options_to_table(fdwoptions) "
6535                                                   "ORDER BY option_name"
6536                                                   "), E',\n    ') AS fdwoptions "
6537                                                   "FROM pg_foreign_data_wrapper",
6538                                                   username_subquery);
6539         }
6540         else
6541         {
6542                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6543                                                   "(%s fdwowner) AS rolname, "
6544                                                   "'-' AS fdwhandler, "
6545                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6546                                                   "array_to_string(ARRAY("
6547                                                   "SELECT quote_ident(option_name) || ' ' || "
6548                                                   "quote_literal(option_value) "
6549                                                   "FROM pg_options_to_table(fdwoptions) "
6550                                                   "ORDER BY option_name"
6551                                                   "), E',\n    ') AS fdwoptions "
6552                                                   "FROM pg_foreign_data_wrapper",
6553                                                   username_subquery);
6554         }
6555
6556         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6557
6558         ntups = PQntuples(res);
6559         *numForeignDataWrappers = ntups;
6560
6561         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6562
6563         i_tableoid = PQfnumber(res, "tableoid");
6564         i_oid = PQfnumber(res, "oid");
6565         i_fdwname = PQfnumber(res, "fdwname");
6566         i_rolname = PQfnumber(res, "rolname");
6567         i_fdwhandler = PQfnumber(res, "fdwhandler");
6568         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6569         i_fdwacl = PQfnumber(res, "fdwacl");
6570         i_fdwoptions = PQfnumber(res, "fdwoptions");
6571
6572         for (i = 0; i < ntups; i++)
6573         {
6574                 fdwinfo[i].dobj.objType = DO_FDW;
6575                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6576                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6577                 AssignDumpId(&fdwinfo[i].dobj);
6578                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6579                 fdwinfo[i].dobj.namespace = NULL;
6580                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6581                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6582                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6583                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6584                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6585
6586                 /* Decide whether we want to dump it */
6587                 selectDumpableObject(&(fdwinfo[i].dobj));
6588         }
6589
6590         PQclear(res);
6591
6592         destroyPQExpBuffer(query);
6593
6594         return fdwinfo;
6595 }
6596
6597 /*
6598  * getForeignServers:
6599  *        read all foreign servers in the system catalogs and return
6600  *        them in the ForeignServerInfo * structure
6601  *
6602  *      numForeignServers is set to the number of servers read in
6603  */
6604 ForeignServerInfo *
6605 getForeignServers(Archive *fout, int *numForeignServers)
6606 {
6607         PGresult   *res;
6608         int                     ntups;
6609         int                     i;
6610         PQExpBuffer query = createPQExpBuffer();
6611         ForeignServerInfo *srvinfo;
6612         int                     i_tableoid;
6613         int                     i_oid;
6614         int                     i_srvname;
6615         int                     i_rolname;
6616         int                     i_srvfdw;
6617         int                     i_srvtype;
6618         int                     i_srvversion;
6619         int                     i_srvacl;
6620         int                     i_srvoptions;
6621
6622         /* Before 8.4, there are no foreign servers */
6623         if (fout->remoteVersion < 80400)
6624         {
6625                 *numForeignServers = 0;
6626                 return NULL;
6627         }
6628
6629         /* Make sure we are in proper schema */
6630         selectSourceSchema(fout,"pg_catalog");
6631
6632         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6633                                           "(%s srvowner) AS rolname, "
6634                                           "srvfdw, srvtype, srvversion, srvacl,"
6635                                           "array_to_string(ARRAY("
6636                                           "SELECT quote_ident(option_name) || ' ' || "
6637                                           "quote_literal(option_value) "
6638                                           "FROM pg_options_to_table(srvoptions) "
6639                                           "ORDER BY option_name"
6640                                           "), E',\n    ') AS srvoptions "
6641                                           "FROM pg_foreign_server",
6642                                           username_subquery);
6643
6644         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6645
6646         ntups = PQntuples(res);
6647         *numForeignServers = ntups;
6648
6649         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6650
6651         i_tableoid = PQfnumber(res, "tableoid");
6652         i_oid = PQfnumber(res, "oid");
6653         i_srvname = PQfnumber(res, "srvname");
6654         i_rolname = PQfnumber(res, "rolname");
6655         i_srvfdw = PQfnumber(res, "srvfdw");
6656         i_srvtype = PQfnumber(res, "srvtype");
6657         i_srvversion = PQfnumber(res, "srvversion");
6658         i_srvacl = PQfnumber(res, "srvacl");
6659         i_srvoptions = PQfnumber(res, "srvoptions");
6660
6661         for (i = 0; i < ntups; i++)
6662         {
6663                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6664                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6665                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6666                 AssignDumpId(&srvinfo[i].dobj);
6667                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6668                 srvinfo[i].dobj.namespace = NULL;
6669                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6670                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6671                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6672                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6673                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6674                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6675
6676                 /* Decide whether we want to dump it */
6677                 selectDumpableObject(&(srvinfo[i].dobj));
6678         }
6679
6680         PQclear(res);
6681
6682         destroyPQExpBuffer(query);
6683
6684         return srvinfo;
6685 }
6686
6687 /*
6688  * getDefaultACLs:
6689  *        read all default ACL information in the system catalogs and return
6690  *        them in the DefaultACLInfo structure
6691  *
6692  *      numDefaultACLs is set to the number of ACLs read in
6693  */
6694 DefaultACLInfo *
6695 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6696 {
6697         DefaultACLInfo *daclinfo;
6698         PQExpBuffer query;
6699         PGresult   *res;
6700         int                     i_oid;
6701         int                     i_tableoid;
6702         int                     i_defaclrole;
6703         int                     i_defaclnamespace;
6704         int                     i_defaclobjtype;
6705         int                     i_defaclacl;
6706         int                     i,
6707                                 ntups;
6708
6709         if (fout->remoteVersion < 90000)
6710         {
6711                 *numDefaultACLs = 0;
6712                 return NULL;
6713         }
6714
6715         query = createPQExpBuffer();
6716
6717         /* Make sure we are in proper schema */
6718         selectSourceSchema(fout, "pg_catalog");
6719
6720         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6721                                           "(%s defaclrole) AS defaclrole, "
6722                                           "defaclnamespace, "
6723                                           "defaclobjtype, "
6724                                           "defaclacl "
6725                                           "FROM pg_default_acl",
6726                                           username_subquery);
6727
6728         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6729
6730         ntups = PQntuples(res);
6731         *numDefaultACLs = ntups;
6732
6733         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6734
6735         i_oid = PQfnumber(res, "oid");
6736         i_tableoid = PQfnumber(res, "tableoid");
6737         i_defaclrole = PQfnumber(res, "defaclrole");
6738         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6739         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6740         i_defaclacl = PQfnumber(res, "defaclacl");
6741
6742         for (i = 0; i < ntups; i++)
6743         {
6744                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6745
6746                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6747                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6748                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6749                 AssignDumpId(&daclinfo[i].dobj);
6750                 /* cheesy ... is it worth coming up with a better object name? */
6751                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6752
6753                 if (nspid != InvalidOid)
6754                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6755                                                                                                  daclinfo[i].dobj.catId.oid);
6756                 else
6757                         daclinfo[i].dobj.namespace = NULL;
6758
6759                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6760                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6761                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6762
6763                 /* Decide whether we want to dump it */
6764                 selectDumpableDefaultACL(&(daclinfo[i]));
6765         }
6766
6767         PQclear(res);
6768
6769         destroyPQExpBuffer(query);
6770
6771         return daclinfo;
6772 }
6773
6774 /*
6775  * dumpComment --
6776  *
6777  * This routine is used to dump any comments associated with the
6778  * object handed to this routine. The routine takes a constant character
6779  * string for the target part of the comment-creation command, plus
6780  * the namespace and owner of the object (for labeling the ArchiveEntry),
6781  * plus catalog ID and subid which are the lookup key for pg_description,
6782  * plus the dump ID for the object (for setting a dependency).
6783  * If a matching pg_description entry is found, it is dumped.
6784  *
6785  * Note: although this routine takes a dumpId for dependency purposes,
6786  * that purpose is just to mark the dependency in the emitted dump file
6787  * for possible future use by pg_restore.  We do NOT use it for determining
6788  * ordering of the comment in the dump file, because this routine is called
6789  * after dependency sorting occurs.  This routine should be called just after
6790  * calling ArchiveEntry() for the specified object.
6791  */
6792 static void
6793 dumpComment(Archive *fout, const char *target,
6794                         const char *namespace, const char *owner,
6795                         CatalogId catalogId, int subid, DumpId dumpId)
6796 {
6797         CommentItem *comments;
6798         int                     ncomments;
6799
6800         /* Comments are schema not data ... except blob comments are data */
6801         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6802         {
6803                 if (dataOnly)
6804                         return;
6805         }
6806         else
6807         {
6808                 if (schemaOnly)
6809                         return;
6810         }
6811
6812         /* Search for comments associated with catalogId, using table */
6813         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6814                                                          &comments);
6815
6816         /* Is there one matching the subid? */
6817         while (ncomments > 0)
6818         {
6819                 if (comments->objsubid == subid)
6820                         break;
6821                 comments++;
6822                 ncomments--;
6823         }
6824
6825         /* If a comment exists, build COMMENT ON statement */
6826         if (ncomments > 0)
6827         {
6828                 PQExpBuffer query = createPQExpBuffer();
6829
6830                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6831                 appendStringLiteralAH(query, comments->descr, fout);
6832                 appendPQExpBuffer(query, ";\n");
6833
6834                 /*
6835                  * We mark comments as SECTION_NONE because they really belong in the
6836                  * same section as their parent, whether that is pre-data or
6837                  * post-data.
6838                  */
6839                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6840                                          target, namespace, NULL, owner,
6841                                          false, "COMMENT", SECTION_NONE,
6842                                          query->data, "", NULL,
6843                                          &(dumpId), 1,
6844                                          NULL, NULL);
6845
6846                 destroyPQExpBuffer(query);
6847         }
6848 }
6849
6850 /*
6851  * dumpTableComment --
6852  *
6853  * As above, but dump comments for both the specified table (or view)
6854  * and its columns.
6855  */
6856 static void
6857 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6858                                  const char *reltypename)
6859 {
6860         CommentItem *comments;
6861         int                     ncomments;
6862         PQExpBuffer query;
6863         PQExpBuffer target;
6864
6865         /* Comments are SCHEMA not data */
6866         if (dataOnly)
6867                 return;
6868
6869         /* Search for comments associated with relation, using table */
6870         ncomments = findComments(fout,
6871                                                          tbinfo->dobj.catId.tableoid,
6872                                                          tbinfo->dobj.catId.oid,
6873                                                          &comments);
6874
6875         /* If comments exist, build COMMENT ON statements */
6876         if (ncomments <= 0)
6877                 return;
6878
6879         query = createPQExpBuffer();
6880         target = createPQExpBuffer();
6881
6882         while (ncomments > 0)
6883         {
6884                 const char *descr = comments->descr;
6885                 int                     objsubid = comments->objsubid;
6886
6887                 if (objsubid == 0)
6888                 {
6889                         resetPQExpBuffer(target);
6890                         appendPQExpBuffer(target, "%s %s", reltypename,
6891                                                           fmtId(tbinfo->dobj.name));
6892
6893                         resetPQExpBuffer(query);
6894                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6895                         appendStringLiteralAH(query, descr, fout);
6896                         appendPQExpBuffer(query, ";\n");
6897
6898                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6899                                                  target->data,
6900                                                  tbinfo->dobj.namespace->dobj.name,
6901                                                  NULL, tbinfo->rolname,
6902                                                  false, "COMMENT", SECTION_NONE,
6903                                                  query->data, "", NULL,
6904                                                  &(tbinfo->dobj.dumpId), 1,
6905                                                  NULL, NULL);
6906                 }
6907                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6908                 {
6909                         resetPQExpBuffer(target);
6910                         appendPQExpBuffer(target, "COLUMN %s.",
6911                                                           fmtId(tbinfo->dobj.name));
6912                         appendPQExpBuffer(target, "%s",
6913                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6914
6915                         resetPQExpBuffer(query);
6916                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6917                         appendStringLiteralAH(query, descr, fout);
6918                         appendPQExpBuffer(query, ";\n");
6919
6920                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6921                                                  target->data,
6922                                                  tbinfo->dobj.namespace->dobj.name,
6923                                                  NULL, tbinfo->rolname,
6924                                                  false, "COMMENT", SECTION_NONE,
6925                                                  query->data, "", NULL,
6926                                                  &(tbinfo->dobj.dumpId), 1,
6927                                                  NULL, NULL);
6928                 }
6929
6930                 comments++;
6931                 ncomments--;
6932         }
6933
6934         destroyPQExpBuffer(query);
6935         destroyPQExpBuffer(target);
6936 }
6937
6938 /*
6939  * findComments --
6940  *
6941  * Find the comment(s), if any, associated with the given object.  All the
6942  * objsubid values associated with the given classoid/objoid are found with
6943  * one search.
6944  */
6945 static int
6946 findComments(Archive *fout, Oid classoid, Oid objoid,
6947                          CommentItem **items)
6948 {
6949         /* static storage for table of comments */
6950         static CommentItem *comments = NULL;
6951         static int      ncomments = -1;
6952
6953         CommentItem *middle = NULL;
6954         CommentItem *low;
6955         CommentItem *high;
6956         int                     nmatch;
6957
6958         /* Get comments if we didn't already */
6959         if (ncomments < 0)
6960                 ncomments = collectComments(fout, &comments);
6961
6962         /*
6963          * Pre-7.2, pg_description does not contain classoid, so collectComments
6964          * just stores a zero.  If there's a collision on object OID, well, you
6965          * get duplicate comments.
6966          */
6967         if (fout->remoteVersion < 70200)
6968                 classoid = 0;
6969
6970         /*
6971          * Do binary search to find some item matching the object.
6972          */
6973         low = &comments[0];
6974         high = &comments[ncomments - 1];
6975         while (low <= high)
6976         {
6977                 middle = low + (high - low) / 2;
6978
6979                 if (classoid < middle->classoid)
6980                         high = middle - 1;
6981                 else if (classoid > middle->classoid)
6982                         low = middle + 1;
6983                 else if (objoid < middle->objoid)
6984                         high = middle - 1;
6985                 else if (objoid > middle->objoid)
6986                         low = middle + 1;
6987                 else
6988                         break;                          /* found a match */
6989         }
6990
6991         if (low > high)                         /* no matches */
6992         {
6993                 *items = NULL;
6994                 return 0;
6995         }
6996
6997         /*
6998          * Now determine how many items match the object.  The search loop
6999          * invariant still holds: only items between low and high inclusive could
7000          * match.
7001          */
7002         nmatch = 1;
7003         while (middle > low)
7004         {
7005                 if (classoid != middle[-1].classoid ||
7006                         objoid != middle[-1].objoid)
7007                         break;
7008                 middle--;
7009                 nmatch++;
7010         }
7011
7012         *items = middle;
7013
7014         middle += nmatch;
7015         while (middle <= high)
7016         {
7017                 if (classoid != middle->classoid ||
7018                         objoid != middle->objoid)
7019                         break;
7020                 middle++;
7021                 nmatch++;
7022         }
7023
7024         return nmatch;
7025 }
7026
7027 /*
7028  * collectComments --
7029  *
7030  * Construct a table of all comments available for database objects.
7031  * We used to do per-object queries for the comments, but it's much faster
7032  * to pull them all over at once, and on most databases the memory cost
7033  * isn't high.
7034  *
7035  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7036  */
7037 static int
7038 collectComments(Archive *fout, CommentItem **items)
7039 {
7040         PGresult   *res;
7041         PQExpBuffer query;
7042         int                     i_description;
7043         int                     i_classoid;
7044         int                     i_objoid;
7045         int                     i_objsubid;
7046         int                     ntups;
7047         int                     i;
7048         CommentItem *comments;
7049
7050         /*
7051          * Note we do NOT change source schema here; preserve the caller's
7052          * setting, instead.
7053          */
7054
7055         query = createPQExpBuffer();
7056
7057         if (fout->remoteVersion >= 70300)
7058         {
7059                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7060                                                   "FROM pg_catalog.pg_description "
7061                                                   "ORDER BY classoid, objoid, objsubid");
7062         }
7063         else if (fout->remoteVersion >= 70200)
7064         {
7065                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7066                                                   "FROM pg_description "
7067                                                   "ORDER BY classoid, objoid, objsubid");
7068         }
7069         else
7070         {
7071                 /* Note: this will fail to find attribute comments in pre-7.2... */
7072                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7073                                                   "FROM pg_description "
7074                                                   "ORDER BY objoid");
7075         }
7076
7077         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7078
7079         /* Construct lookup table containing OIDs in numeric form */
7080
7081         i_description = PQfnumber(res, "description");
7082         i_classoid = PQfnumber(res, "classoid");
7083         i_objoid = PQfnumber(res, "objoid");
7084         i_objsubid = PQfnumber(res, "objsubid");
7085
7086         ntups = PQntuples(res);
7087
7088         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7089
7090         for (i = 0; i < ntups; i++)
7091         {
7092                 comments[i].descr = PQgetvalue(res, i, i_description);
7093                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7094                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7095                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7096         }
7097
7098         /* Do NOT free the PGresult since we are keeping pointers into it */
7099         destroyPQExpBuffer(query);
7100
7101         *items = comments;
7102         return ntups;
7103 }
7104
7105 /*
7106  * dumpDumpableObject
7107  *
7108  * This routine and its subsidiaries are responsible for creating
7109  * ArchiveEntries (TOC objects) for each object to be dumped.
7110  */
7111 static void
7112 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7113 {
7114
7115         bool skip = false;
7116
7117         switch (dobj->objType)
7118         {
7119                 case DO_INDEX:
7120                 case DO_TRIGGER:
7121                 case DO_CONSTRAINT:
7122                 case DO_FK_CONSTRAINT:
7123                 case DO_RULE:
7124                         skip = !(dumpSections & DUMP_POST_DATA);
7125                         break;
7126                 case DO_TABLE_DATA:
7127                         skip = !(dumpSections & DUMP_DATA);
7128                         break;
7129                 default:
7130                         skip = !(dumpSections & DUMP_PRE_DATA);
7131         }
7132
7133         if (skip)
7134                 return;
7135
7136         switch (dobj->objType)
7137         {
7138                 case DO_NAMESPACE:
7139                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7140                         break;
7141                 case DO_EXTENSION:
7142                         dumpExtension(fout, (ExtensionInfo *) dobj);
7143                         break;
7144                 case DO_TYPE:
7145                         dumpType(fout, (TypeInfo *) dobj);
7146                         break;
7147                 case DO_SHELL_TYPE:
7148                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7149                         break;
7150                 case DO_FUNC:
7151                         dumpFunc(fout, (FuncInfo *) dobj);
7152                         break;
7153                 case DO_AGG:
7154                         dumpAgg(fout, (AggInfo *) dobj);
7155                         break;
7156                 case DO_OPERATOR:
7157                         dumpOpr(fout, (OprInfo *) dobj);
7158                         break;
7159                 case DO_OPCLASS:
7160                         dumpOpclass(fout, (OpclassInfo *) dobj);
7161                         break;
7162                 case DO_OPFAMILY:
7163                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7164                         break;
7165                 case DO_COLLATION:
7166                         dumpCollation(fout, (CollInfo *) dobj);
7167                         break;
7168                 case DO_CONVERSION:
7169                         dumpConversion(fout, (ConvInfo *) dobj);
7170                         break;
7171                 case DO_TABLE:
7172                         dumpTable(fout, (TableInfo *) dobj);
7173                         break;
7174                 case DO_ATTRDEF:
7175                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7176                         break;
7177                 case DO_INDEX:
7178                         dumpIndex(fout, (IndxInfo *) dobj);
7179                         break;
7180                 case DO_RULE:
7181                         dumpRule(fout, (RuleInfo *) dobj);
7182                         break;
7183                 case DO_TRIGGER:
7184                         dumpTrigger(fout, (TriggerInfo *) dobj);
7185                         break;
7186                 case DO_CONSTRAINT:
7187                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7188                         break;
7189                 case DO_FK_CONSTRAINT:
7190                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7191                         break;
7192                 case DO_PROCLANG:
7193                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7194                         break;
7195                 case DO_CAST:
7196                         dumpCast(fout, (CastInfo *) dobj);
7197                         break;
7198                 case DO_TABLE_DATA:
7199                         dumpTableData(fout, (TableDataInfo *) dobj);
7200                         break;
7201                 case DO_DUMMY_TYPE:
7202                         /* table rowtypes and array types are never dumped separately */
7203                         break;
7204                 case DO_TSPARSER:
7205                         dumpTSParser(fout, (TSParserInfo *) dobj);
7206                         break;
7207                 case DO_TSDICT:
7208                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7209                         break;
7210                 case DO_TSTEMPLATE:
7211                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7212                         break;
7213                 case DO_TSCONFIG:
7214                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7215                         break;
7216                 case DO_FDW:
7217                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7218                         break;
7219                 case DO_FOREIGN_SERVER:
7220                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7221                         break;
7222                 case DO_DEFAULT_ACL:
7223                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7224                         break;
7225                 case DO_BLOB:
7226                         dumpBlob(fout, (BlobInfo *) dobj);
7227                         break;
7228                 case DO_BLOB_DATA:
7229                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7230                                                  dobj->name, NULL, NULL, "",
7231                                                  false, "BLOBS", SECTION_DATA,
7232                                                  "", "", NULL,
7233                                                  dobj->dependencies, dobj->nDeps,
7234                                                  dumpBlobs, NULL);
7235                         break;
7236         }
7237 }
7238
7239 /*
7240  * dumpNamespace
7241  *        writes out to fout the queries to recreate a user-defined namespace
7242  */
7243 static void
7244 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7245 {
7246         PQExpBuffer q;
7247         PQExpBuffer delq;
7248         PQExpBuffer labelq;
7249         char       *qnspname;
7250
7251         /* Skip if not to be dumped */
7252         if (!nspinfo->dobj.dump || dataOnly)
7253                 return;
7254
7255         /* don't dump dummy namespace from pre-7.3 source */
7256         if (strlen(nspinfo->dobj.name) == 0)
7257                 return;
7258
7259         q = createPQExpBuffer();
7260         delq = createPQExpBuffer();
7261         labelq = createPQExpBuffer();
7262
7263         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7264
7265         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7266
7267         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7268
7269         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7270
7271         if (binary_upgrade)
7272                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7273
7274         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7275                                  nspinfo->dobj.name,
7276                                  NULL, NULL,
7277                                  nspinfo->rolname,
7278                                  false, "SCHEMA", SECTION_PRE_DATA,
7279                                  q->data, delq->data, NULL,
7280                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7281                                  NULL, NULL);
7282
7283         /* Dump Schema Comments and Security Labels */
7284         dumpComment(fout, labelq->data,
7285                                 NULL, nspinfo->rolname,
7286                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7287         dumpSecLabel(fout, labelq->data,
7288                                  NULL, nspinfo->rolname,
7289                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7290
7291         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7292                         qnspname, NULL, nspinfo->dobj.name, NULL,
7293                         nspinfo->rolname, nspinfo->nspacl);
7294
7295         free(qnspname);
7296
7297         destroyPQExpBuffer(q);
7298         destroyPQExpBuffer(delq);
7299         destroyPQExpBuffer(labelq);
7300 }
7301
7302 /*
7303  * dumpExtension
7304  *        writes out to fout the queries to recreate an extension
7305  */
7306 static void
7307 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7308 {
7309         PQExpBuffer q;
7310         PQExpBuffer delq;
7311         PQExpBuffer labelq;
7312         char       *qextname;
7313
7314         /* Skip if not to be dumped */
7315         if (!extinfo->dobj.dump || dataOnly)
7316                 return;
7317
7318         q = createPQExpBuffer();
7319         delq = createPQExpBuffer();
7320         labelq = createPQExpBuffer();
7321
7322         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7323
7324         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7325
7326         if (!binary_upgrade)
7327         {
7328                 /*
7329                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7330                  * problem if the extension already exists in the target database;
7331                  * this is essential for installed-by-default extensions such as
7332                  * plpgsql.
7333                  *
7334                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7335                  * built-in extensions based on their OIDs; see
7336                  * selectDumpableExtension.
7337                  */
7338                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7339                                                   qextname, fmtId(extinfo->namespace));
7340         }
7341         else
7342         {
7343                 int                     i;
7344                 int                     n;
7345
7346                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7347                 appendPQExpBuffer(q,
7348                                                   "SELECT binary_upgrade.create_empty_extension(");
7349                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7350                 appendPQExpBuffer(q, ", ");
7351                 appendStringLiteralAH(q, extinfo->namespace, fout);
7352                 appendPQExpBuffer(q, ", ");
7353                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7354                 appendStringLiteralAH(q, extinfo->extversion, fout);
7355                 appendPQExpBuffer(q, ", ");
7356
7357                 /*
7358                  * Note that we're pushing extconfig (an OID array) back into
7359                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7360                  * preserved in binary upgrade.
7361                  */
7362                 if (strlen(extinfo->extconfig) > 2)
7363                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7364                 else
7365                         appendPQExpBuffer(q, "NULL");
7366                 appendPQExpBuffer(q, ", ");
7367                 if (strlen(extinfo->extcondition) > 2)
7368                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7369                 else
7370                         appendPQExpBuffer(q, "NULL");
7371                 appendPQExpBuffer(q, ", ");
7372                 appendPQExpBuffer(q, "ARRAY[");
7373                 n = 0;
7374                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7375                 {
7376                         DumpableObject *extobj;
7377
7378                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7379                         if (extobj && extobj->objType == DO_EXTENSION)
7380                         {
7381                                 if (n++ > 0)
7382                                         appendPQExpBuffer(q, ",");
7383                                 appendStringLiteralAH(q, extobj->name, fout);
7384                         }
7385                 }
7386                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7387                 appendPQExpBuffer(q, ");\n");
7388         }
7389
7390         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7391
7392         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7393                                  extinfo->dobj.name,
7394                                  NULL, NULL,
7395                                  "",
7396                                  false, "EXTENSION", SECTION_PRE_DATA,
7397                                  q->data, delq->data, NULL,
7398                                  extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7399                                  NULL, NULL);
7400
7401         /* Dump Extension Comments and Security Labels */
7402         dumpComment(fout, labelq->data,
7403                                 NULL, "",
7404                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7405         dumpSecLabel(fout, labelq->data,
7406                                  NULL, "",
7407                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7408
7409         free(qextname);
7410
7411         destroyPQExpBuffer(q);
7412         destroyPQExpBuffer(delq);
7413         destroyPQExpBuffer(labelq);
7414 }
7415
7416 /*
7417  * dumpType
7418  *        writes out to fout the queries to recreate a user-defined type
7419  */
7420 static void
7421 dumpType(Archive *fout, TypeInfo *tyinfo)
7422 {
7423         /* Skip if not to be dumped */
7424         if (!tyinfo->dobj.dump || dataOnly)
7425                 return;
7426
7427         /* Dump out in proper style */
7428         if (tyinfo->typtype == TYPTYPE_BASE)
7429                 dumpBaseType(fout, tyinfo);
7430         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7431                 dumpDomain(fout, tyinfo);
7432         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7433                 dumpCompositeType(fout, tyinfo);
7434         else if (tyinfo->typtype == TYPTYPE_ENUM)
7435                 dumpEnumType(fout, tyinfo);
7436         else if (tyinfo->typtype == TYPTYPE_RANGE)
7437                 dumpRangeType(fout, tyinfo);
7438         else
7439                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7440                                   tyinfo->dobj.name);
7441 }
7442
7443 /*
7444  * dumpEnumType
7445  *        writes out to fout the queries to recreate a user-defined enum type
7446  */
7447 static void
7448 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7449 {
7450         PQExpBuffer q = createPQExpBuffer();
7451         PQExpBuffer delq = createPQExpBuffer();
7452         PQExpBuffer labelq = createPQExpBuffer();
7453         PQExpBuffer query = createPQExpBuffer();
7454         PGresult   *res;
7455         int                     num,
7456                                 i;
7457         Oid                     enum_oid;
7458         char       *label;
7459
7460         /* Set proper schema search path */
7461         selectSourceSchema(fout, "pg_catalog");
7462
7463         if (fout->remoteVersion >= 90100)
7464                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7465                                                   "FROM pg_catalog.pg_enum "
7466                                                   "WHERE enumtypid = '%u'"
7467                                                   "ORDER BY enumsortorder",
7468                                                   tyinfo->dobj.catId.oid);
7469         else
7470                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7471                                                   "FROM pg_catalog.pg_enum "
7472                                                   "WHERE enumtypid = '%u'"
7473                                                   "ORDER BY oid",
7474                                                   tyinfo->dobj.catId.oid);
7475
7476         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7477
7478         num = PQntuples(res);
7479
7480         /*
7481          * DROP must be fully qualified in case same name appears in pg_catalog.
7482          * CASCADE shouldn't be required here as for normal types since the I/O
7483          * functions are generic and do not get dropped.
7484          */
7485         appendPQExpBuffer(delq, "DROP TYPE %s.",
7486                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7487         appendPQExpBuffer(delq, "%s;\n",
7488                                           fmtId(tyinfo->dobj.name));
7489
7490         if (binary_upgrade)
7491                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7492                                                                                                  tyinfo->dobj.catId.oid);
7493
7494         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7495                                           fmtId(tyinfo->dobj.name));
7496
7497         if (!binary_upgrade)
7498         {
7499                 /* Labels with server-assigned oids */
7500                 for (i = 0; i < num; i++)
7501                 {
7502                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7503                         if (i > 0)
7504                                 appendPQExpBuffer(q, ",");
7505                         appendPQExpBuffer(q, "\n    ");
7506                         appendStringLiteralAH(q, label, fout);
7507                 }
7508         }
7509
7510         appendPQExpBuffer(q, "\n);\n");
7511
7512         if (binary_upgrade)
7513         {
7514                 /* Labels with dump-assigned (preserved) oids */
7515                 for (i = 0; i < num; i++)
7516                 {
7517                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7518                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7519
7520                         if (i == 0)
7521                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7522                         appendPQExpBuffer(q,
7523                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7524                                                           enum_oid);
7525                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7526                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7527                         appendPQExpBuffer(q, "%s ADD VALUE ",
7528                                                           fmtId(tyinfo->dobj.name));
7529                         appendStringLiteralAH(q, label, fout);
7530                         appendPQExpBuffer(q, ";\n\n");
7531                 }
7532         }
7533
7534         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7535
7536         if (binary_upgrade)
7537                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7538
7539         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7540                                  tyinfo->dobj.name,
7541                                  tyinfo->dobj.namespace->dobj.name,
7542                                  NULL,
7543                                  tyinfo->rolname, false,
7544                                  "TYPE", SECTION_PRE_DATA,
7545                                  q->data, delq->data, NULL,
7546                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7547                                  NULL, NULL);
7548
7549         /* Dump Type Comments and Security Labels */
7550         dumpComment(fout, labelq->data,
7551                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7552                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7553         dumpSecLabel(fout, labelq->data,
7554                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7555                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7556
7557         PQclear(res);
7558         destroyPQExpBuffer(q);
7559         destroyPQExpBuffer(delq);
7560         destroyPQExpBuffer(labelq);
7561         destroyPQExpBuffer(query);
7562 }
7563
7564 /*
7565  * dumpRangeType
7566  *        writes out to fout the queries to recreate a user-defined range type
7567  */
7568 static void
7569 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7570 {
7571         PQExpBuffer q = createPQExpBuffer();
7572         PQExpBuffer delq = createPQExpBuffer();
7573         PQExpBuffer labelq = createPQExpBuffer();
7574         PQExpBuffer query = createPQExpBuffer();
7575         PGresult   *res;
7576         Oid                     collationOid;
7577         char       *procname;
7578
7579         /*
7580          * select appropriate schema to ensure names in CREATE are properly
7581          * qualified
7582          */
7583         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7584
7585         appendPQExpBuffer(query,
7586                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7587                                           "opc.opcname AS opcname, "
7588                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7589                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7590                                           "opc.opcdefault, "
7591                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7592                                           "     ELSE rngcollation END AS collation, "
7593                                           "rngcanonical, rngsubdiff "
7594                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7595                                           "     pg_catalog.pg_opclass opc "
7596                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7597                                           "rngtypid = '%u'",
7598                                           tyinfo->dobj.catId.oid);
7599
7600         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7601
7602         /*
7603          * DROP must be fully qualified in case same name appears in pg_catalog.
7604          * CASCADE shouldn't be required here as for normal types since the I/O
7605          * functions are generic and do not get dropped.
7606          */
7607         appendPQExpBuffer(delq, "DROP TYPE %s.",
7608                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7609         appendPQExpBuffer(delq, "%s;\n",
7610                                           fmtId(tyinfo->dobj.name));
7611
7612         if (binary_upgrade)
7613                 binary_upgrade_set_type_oids_by_type_oid(fout,
7614                                                                                                  q, tyinfo->dobj.catId.oid);
7615
7616         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7617                                           fmtId(tyinfo->dobj.name));
7618
7619         appendPQExpBuffer(q, "\n    subtype = %s",
7620                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7621
7622         /* print subtype_opclass only if not default for subtype */
7623         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7624         {
7625                 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7626                 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7627
7628                 /* always schema-qualify, don't try to be smart */
7629                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7630                                                   fmtId(nspname));
7631                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7632         }
7633
7634         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7635         if (OidIsValid(collationOid))
7636         {
7637                 CollInfo   *coll = findCollationByOid(collationOid);
7638
7639                 if (coll)
7640                 {
7641                         /* always schema-qualify, don't try to be smart */
7642                         appendPQExpBuffer(q, ",\n    collation = %s.",
7643                                                           fmtId(coll->dobj.namespace->dobj.name));
7644                         appendPQExpBuffer(q, "%s",
7645                                                           fmtId(coll->dobj.name));
7646                 }
7647         }
7648
7649         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7650         if (strcmp(procname, "-") != 0)
7651                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7652
7653         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7654         if (strcmp(procname, "-") != 0)
7655                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7656
7657         appendPQExpBuffer(q, "\n);\n");
7658
7659         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7660
7661         if (binary_upgrade)
7662                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7663
7664         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7665                                  tyinfo->dobj.name,
7666                                  tyinfo->dobj.namespace->dobj.name,
7667                                  NULL,
7668                                  tyinfo->rolname, false,
7669                                  "TYPE", SECTION_PRE_DATA,
7670                                  q->data, delq->data, NULL,
7671                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7672                                  NULL, NULL);
7673
7674         /* Dump Type Comments and Security Labels */
7675         dumpComment(fout, labelq->data,
7676                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7677                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7678         dumpSecLabel(fout, labelq->data,
7679                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7680                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7681
7682         PQclear(res);
7683         destroyPQExpBuffer(q);
7684         destroyPQExpBuffer(delq);
7685         destroyPQExpBuffer(labelq);
7686         destroyPQExpBuffer(query);
7687 }
7688
7689 /*
7690  * dumpBaseType
7691  *        writes out to fout the queries to recreate a user-defined base type
7692  */
7693 static void
7694 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7695 {
7696         PQExpBuffer q = createPQExpBuffer();
7697         PQExpBuffer delq = createPQExpBuffer();
7698         PQExpBuffer labelq = createPQExpBuffer();
7699         PQExpBuffer query = createPQExpBuffer();
7700         PGresult   *res;
7701         char       *typlen;
7702         char       *typinput;
7703         char       *typoutput;
7704         char       *typreceive;
7705         char       *typsend;
7706         char       *typmodin;
7707         char       *typmodout;
7708         char       *typanalyze;
7709         Oid                     typreceiveoid;
7710         Oid                     typsendoid;
7711         Oid                     typmodinoid;
7712         Oid                     typmodoutoid;
7713         Oid                     typanalyzeoid;
7714         char       *typcategory;
7715         char       *typispreferred;
7716         char       *typdelim;
7717         char       *typbyval;
7718         char       *typalign;
7719         char       *typstorage;
7720         char       *typcollatable;
7721         char       *typdefault;
7722         bool            typdefault_is_literal = false;
7723
7724         /* Set proper schema search path so regproc references list correctly */
7725         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7726
7727         /* Fetch type-specific details */
7728         if (fout->remoteVersion >= 90100)
7729         {
7730                 appendPQExpBuffer(query, "SELECT typlen, "
7731                                                   "typinput, typoutput, typreceive, typsend, "
7732                                                   "typmodin, typmodout, typanalyze, "
7733                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7734                                                   "typsend::pg_catalog.oid AS typsendoid, "
7735                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7736                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7737                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7738                                                   "typcategory, typispreferred, "
7739                                                   "typdelim, typbyval, typalign, typstorage, "
7740                                                   "(typcollation <> 0) AS typcollatable, "
7741                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7742                                                   "FROM pg_catalog.pg_type "
7743                                                   "WHERE oid = '%u'::pg_catalog.oid",
7744                                                   tyinfo->dobj.catId.oid);
7745         }
7746         else if (fout->remoteVersion >= 80400)
7747         {
7748                 appendPQExpBuffer(query, "SELECT typlen, "
7749                                                   "typinput, typoutput, typreceive, typsend, "
7750                                                   "typmodin, typmodout, typanalyze, "
7751                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7752                                                   "typsend::pg_catalog.oid AS typsendoid, "
7753                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7754                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7755                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7756                                                   "typcategory, typispreferred, "
7757                                                   "typdelim, typbyval, typalign, typstorage, "
7758                                                   "false AS typcollatable, "
7759                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7760                                                   "FROM pg_catalog.pg_type "
7761                                                   "WHERE oid = '%u'::pg_catalog.oid",
7762                                                   tyinfo->dobj.catId.oid);
7763         }
7764         else if (fout->remoteVersion >= 80300)
7765         {
7766                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7767                 appendPQExpBuffer(query, "SELECT typlen, "
7768                                                   "typinput, typoutput, typreceive, typsend, "
7769                                                   "typmodin, typmodout, typanalyze, "
7770                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7771                                                   "typsend::pg_catalog.oid AS typsendoid, "
7772                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7773                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7774                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7775                                                   "'U' AS typcategory, false AS typispreferred, "
7776                                                   "typdelim, typbyval, typalign, typstorage, "
7777                                                   "false AS typcollatable, "
7778                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7779                                                   "FROM pg_catalog.pg_type "
7780                                                   "WHERE oid = '%u'::pg_catalog.oid",
7781                                                   tyinfo->dobj.catId.oid);
7782         }
7783         else if (fout->remoteVersion >= 80000)
7784         {
7785                 appendPQExpBuffer(query, "SELECT typlen, "
7786                                                   "typinput, typoutput, typreceive, typsend, "
7787                                                   "'-' AS typmodin, '-' AS typmodout, "
7788                                                   "typanalyze, "
7789                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7790                                                   "typsend::pg_catalog.oid AS typsendoid, "
7791                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7792                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7793                                                   "'U' AS typcategory, false AS typispreferred, "
7794                                                   "typdelim, typbyval, typalign, typstorage, "
7795                                                   "false AS typcollatable, "
7796                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7797                                                   "FROM pg_catalog.pg_type "
7798                                                   "WHERE oid = '%u'::pg_catalog.oid",
7799                                                   tyinfo->dobj.catId.oid);
7800         }
7801         else if (fout->remoteVersion >= 70400)
7802         {
7803                 appendPQExpBuffer(query, "SELECT typlen, "
7804                                                   "typinput, typoutput, typreceive, typsend, "
7805                                                   "'-' AS typmodin, '-' AS typmodout, "
7806                                                   "'-' AS typanalyze, "
7807                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7808                                                   "typsend::pg_catalog.oid AS typsendoid, "
7809                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7810                                                   "0 AS typanalyzeoid, "
7811                                                   "'U' AS typcategory, false AS typispreferred, "
7812                                                   "typdelim, typbyval, typalign, typstorage, "
7813                                                   "false AS typcollatable, "
7814                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7815                                                   "FROM pg_catalog.pg_type "
7816                                                   "WHERE oid = '%u'::pg_catalog.oid",
7817                                                   tyinfo->dobj.catId.oid);
7818         }
7819         else if (fout->remoteVersion >= 70300)
7820         {
7821                 appendPQExpBuffer(query, "SELECT typlen, "
7822                                                   "typinput, typoutput, "
7823                                                   "'-' AS typreceive, '-' AS typsend, "
7824                                                   "'-' AS typmodin, '-' AS typmodout, "
7825                                                   "'-' AS typanalyze, "
7826                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7827                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7828                                                   "0 AS typanalyzeoid, "
7829                                                   "'U' AS typcategory, false AS typispreferred, "
7830                                                   "typdelim, typbyval, typalign, typstorage, "
7831                                                   "false AS typcollatable, "
7832                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7833                                                   "FROM pg_catalog.pg_type "
7834                                                   "WHERE oid = '%u'::pg_catalog.oid",
7835                                                   tyinfo->dobj.catId.oid);
7836         }
7837         else if (fout->remoteVersion >= 70200)
7838         {
7839                 /*
7840                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7841                  * ignore them because they are not right.
7842                  */
7843                 appendPQExpBuffer(query, "SELECT typlen, "
7844                                                   "typinput, typoutput, "
7845                                                   "'-' AS typreceive, '-' AS typsend, "
7846                                                   "'-' AS typmodin, '-' AS typmodout, "
7847                                                   "'-' AS typanalyze, "
7848                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7849                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7850                                                   "0 AS typanalyzeoid, "
7851                                                   "'U' AS typcategory, false AS typispreferred, "
7852                                                   "typdelim, typbyval, typalign, typstorage, "
7853                                                   "false AS typcollatable, "
7854                                                   "NULL AS typdefaultbin, typdefault "
7855                                                   "FROM pg_type "
7856                                                   "WHERE oid = '%u'::oid",
7857                                                   tyinfo->dobj.catId.oid);
7858         }
7859         else if (fout->remoteVersion >= 70100)
7860         {
7861                 /*
7862                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7863                  * representation.
7864                  */
7865                 appendPQExpBuffer(query, "SELECT typlen, "
7866                                                   "typinput, typoutput, "
7867                                                   "'-' AS typreceive, '-' AS typsend, "
7868                                                   "'-' AS typmodin, '-' AS typmodout, "
7869                                                   "'-' AS typanalyze, "
7870                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7871                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7872                                                   "0 AS typanalyzeoid, "
7873                                                   "'U' AS typcategory, false AS typispreferred, "
7874                                                   "typdelim, typbyval, typalign, typstorage, "
7875                                                   "false AS typcollatable, "
7876                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7877                                                   "FROM pg_type "
7878                                                   "WHERE oid = '%u'::oid",
7879                                                   tyinfo->dobj.catId.oid);
7880         }
7881         else
7882         {
7883                 appendPQExpBuffer(query, "SELECT typlen, "
7884                                                   "typinput, typoutput, "
7885                                                   "'-' AS typreceive, '-' AS typsend, "
7886                                                   "'-' AS typmodin, '-' AS typmodout, "
7887                                                   "'-' AS typanalyze, "
7888                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7889                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7890                                                   "0 AS typanalyzeoid, "
7891                                                   "'U' AS typcategory, false AS typispreferred, "
7892                                                   "typdelim, typbyval, typalign, "
7893                                                   "'p'::char AS typstorage, "
7894                                                   "false AS typcollatable, "
7895                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7896                                                   "FROM pg_type "
7897                                                   "WHERE oid = '%u'::oid",
7898                                                   tyinfo->dobj.catId.oid);
7899         }
7900
7901         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7902
7903         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7904         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7905         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7906         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7907         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7908         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7909         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7910         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7911         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7912         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7913         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7914         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7915         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7916         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7917         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7918         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7919         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7920         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7921         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7922         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7923         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7924                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7925         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7926         {
7927                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7928                 typdefault_is_literal = true;   /* it needs quotes */
7929         }
7930         else
7931                 typdefault = NULL;
7932
7933         /*
7934          * DROP must be fully qualified in case same name appears in pg_catalog.
7935          * The reason we include CASCADE is that the circular dependency between
7936          * the type and its I/O functions makes it impossible to drop the type any
7937          * other way.
7938          */
7939         appendPQExpBuffer(delq, "DROP TYPE %s.",
7940                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7941         appendPQExpBuffer(delq, "%s CASCADE;\n",
7942                                           fmtId(tyinfo->dobj.name));
7943
7944         /* We might already have a shell type, but setting pg_type_oid is harmless */
7945         if (binary_upgrade)
7946                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7947                                                                                                  tyinfo->dobj.catId.oid);
7948
7949         appendPQExpBuffer(q,
7950                                           "CREATE TYPE %s (\n"
7951                                           "    INTERNALLENGTH = %s",
7952                                           fmtId(tyinfo->dobj.name),
7953                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7954
7955         if (fout->remoteVersion >= 70300)
7956         {
7957                 /* regproc result is correctly quoted as of 7.3 */
7958                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
7959                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
7960                 if (OidIsValid(typreceiveoid))
7961                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
7962                 if (OidIsValid(typsendoid))
7963                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
7964                 if (OidIsValid(typmodinoid))
7965                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
7966                 if (OidIsValid(typmodoutoid))
7967                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
7968                 if (OidIsValid(typanalyzeoid))
7969                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
7970         }
7971         else
7972         {
7973                 /* regproc delivers an unquoted name before 7.3 */
7974                 /* cannot combine these because fmtId uses static result area */
7975                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
7976                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7977                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7978         }
7979
7980         if (strcmp(typcollatable, "t") == 0)
7981                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
7982
7983         if (typdefault != NULL)
7984         {
7985                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7986                 if (typdefault_is_literal)
7987                         appendStringLiteralAH(q, typdefault, fout);
7988                 else
7989                         appendPQExpBufferStr(q, typdefault);
7990         }
7991
7992         if (OidIsValid(tyinfo->typelem))
7993         {
7994                 char       *elemType;
7995
7996                 /* reselect schema in case changed by function dump */
7997                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7998                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7999                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8000                 free(elemType);
8001         }
8002
8003         if (strcmp(typcategory, "U") != 0)
8004         {
8005                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8006                 appendStringLiteralAH(q, typcategory, fout);
8007         }
8008
8009         if (strcmp(typispreferred, "t") == 0)
8010                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8011
8012         if (typdelim && strcmp(typdelim, ",") != 0)
8013         {
8014                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8015                 appendStringLiteralAH(q, typdelim, fout);
8016         }
8017
8018         if (strcmp(typalign, "c") == 0)
8019                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8020         else if (strcmp(typalign, "s") == 0)
8021                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8022         else if (strcmp(typalign, "i") == 0)
8023                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8024         else if (strcmp(typalign, "d") == 0)
8025                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8026
8027         if (strcmp(typstorage, "p") == 0)
8028                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8029         else if (strcmp(typstorage, "e") == 0)
8030                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8031         else if (strcmp(typstorage, "x") == 0)
8032                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8033         else if (strcmp(typstorage, "m") == 0)
8034                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8035
8036         if (strcmp(typbyval, "t") == 0)
8037                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8038
8039         appendPQExpBuffer(q, "\n);\n");
8040
8041         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8042
8043         if (binary_upgrade)
8044                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8045
8046         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8047                                  tyinfo->dobj.name,
8048                                  tyinfo->dobj.namespace->dobj.name,
8049                                  NULL,
8050                                  tyinfo->rolname, false,
8051                                  "TYPE", SECTION_PRE_DATA,
8052                                  q->data, delq->data, NULL,
8053                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8054                                  NULL, NULL);
8055
8056         /* Dump Type Comments and Security Labels */
8057         dumpComment(fout, labelq->data,
8058                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8059                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8060         dumpSecLabel(fout, labelq->data,
8061                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8062                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8063
8064         PQclear(res);
8065         destroyPQExpBuffer(q);
8066         destroyPQExpBuffer(delq);
8067         destroyPQExpBuffer(labelq);
8068         destroyPQExpBuffer(query);
8069 }
8070
8071 /*
8072  * dumpDomain
8073  *        writes out to fout the queries to recreate a user-defined domain
8074  */
8075 static void
8076 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8077 {
8078         PQExpBuffer q = createPQExpBuffer();
8079         PQExpBuffer delq = createPQExpBuffer();
8080         PQExpBuffer labelq = createPQExpBuffer();
8081         PQExpBuffer query = createPQExpBuffer();
8082         PGresult   *res;
8083         int                     i;
8084         char       *typnotnull;
8085         char       *typdefn;
8086         char       *typdefault;
8087         Oid                     typcollation;
8088         bool            typdefault_is_literal = false;
8089
8090         /* Set proper schema search path so type references list correctly */
8091         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8092
8093         /* Fetch domain specific details */
8094         if (fout->remoteVersion >= 90100)
8095         {
8096                 /* typcollation is new in 9.1 */
8097                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8098                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8099                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8100                                                   "t.typdefault, "
8101                                                   "CASE WHEN t.typcollation <> u.typcollation "
8102                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8103                                                   "FROM pg_catalog.pg_type t "
8104                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8105                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8106                                                   tyinfo->dobj.catId.oid);
8107         }
8108         else
8109         {
8110                 /* We assume here that remoteVersion must be at least 70300 */
8111                 appendPQExpBuffer(query, "SELECT typnotnull, "
8112                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8113                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8114                                                   "typdefault, 0 AS typcollation "
8115                                                   "FROM pg_catalog.pg_type "
8116                                                   "WHERE oid = '%u'::pg_catalog.oid",
8117                                                   tyinfo->dobj.catId.oid);
8118         }
8119
8120         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8121
8122         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8123         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8124         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8125                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8126         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8127         {
8128                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8129                 typdefault_is_literal = true;   /* it needs quotes */
8130         }
8131         else
8132                 typdefault = NULL;
8133         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8134
8135         if (binary_upgrade)
8136                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8137                                                                                                  tyinfo->dobj.catId.oid);
8138
8139         appendPQExpBuffer(q,
8140                                           "CREATE DOMAIN %s AS %s",
8141                                           fmtId(tyinfo->dobj.name),
8142                                           typdefn);
8143
8144         /* Print collation only if different from base type's collation */
8145         if (OidIsValid(typcollation))
8146         {
8147                 CollInfo   *coll;
8148
8149                 coll = findCollationByOid(typcollation);
8150                 if (coll)
8151                 {
8152                         /* always schema-qualify, don't try to be smart */
8153                         appendPQExpBuffer(q, " COLLATE %s.",
8154                                                           fmtId(coll->dobj.namespace->dobj.name));
8155                         appendPQExpBuffer(q, "%s",
8156                                                           fmtId(coll->dobj.name));
8157                 }
8158         }
8159
8160         if (typnotnull[0] == 't')
8161                 appendPQExpBuffer(q, " NOT NULL");
8162
8163         if (typdefault != NULL)
8164         {
8165                 appendPQExpBuffer(q, " DEFAULT ");
8166                 if (typdefault_is_literal)
8167                         appendStringLiteralAH(q, typdefault, fout);
8168                 else
8169                         appendPQExpBufferStr(q, typdefault);
8170         }
8171
8172         PQclear(res);
8173
8174         /*
8175          * Add any CHECK constraints for the domain
8176          */
8177         for (i = 0; i < tyinfo->nDomChecks; i++)
8178         {
8179                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8180
8181                 if (!domcheck->separate)
8182                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8183                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8184         }
8185
8186         appendPQExpBuffer(q, ";\n");
8187
8188         /*
8189          * DROP must be fully qualified in case same name appears in pg_catalog
8190          */
8191         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8192                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8193         appendPQExpBuffer(delq, "%s;\n",
8194                                           fmtId(tyinfo->dobj.name));
8195
8196         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8197
8198         if (binary_upgrade)
8199                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8200
8201         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8202                                  tyinfo->dobj.name,
8203                                  tyinfo->dobj.namespace->dobj.name,
8204                                  NULL,
8205                                  tyinfo->rolname, false,
8206                                  "DOMAIN", SECTION_PRE_DATA,
8207                                  q->data, delq->data, NULL,
8208                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8209                                  NULL, NULL);
8210
8211         /* Dump Domain Comments and Security Labels */
8212         dumpComment(fout, labelq->data,
8213                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8214                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8215         dumpSecLabel(fout, labelq->data,
8216                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8217                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8218
8219         destroyPQExpBuffer(q);
8220         destroyPQExpBuffer(delq);
8221         destroyPQExpBuffer(labelq);
8222         destroyPQExpBuffer(query);
8223 }
8224
8225 /*
8226  * dumpCompositeType
8227  *        writes out to fout the queries to recreate a user-defined stand-alone
8228  *        composite type
8229  */
8230 static void
8231 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8232 {
8233         PQExpBuffer q = createPQExpBuffer();
8234         PQExpBuffer dropped = createPQExpBuffer();
8235         PQExpBuffer delq = createPQExpBuffer();
8236         PQExpBuffer labelq = createPQExpBuffer();
8237         PQExpBuffer query = createPQExpBuffer();
8238         PGresult   *res;
8239         int                     ntups;
8240         int                     i_attname;
8241         int                     i_atttypdefn;
8242         int                     i_attlen;
8243         int                     i_attalign;
8244         int                     i_attisdropped;
8245         int                     i_attcollation;
8246         int                     i_typrelid;
8247         int                     i;
8248         int                     actual_atts;
8249
8250         /* Set proper schema search path so type references list correctly */
8251         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8252
8253         /* Fetch type specific details */
8254         if (fout->remoteVersion >= 90100)
8255         {
8256                 /*
8257                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8258                  * clauses for attributes whose collation is different from their
8259                  * type's default, we use a CASE here to suppress uninteresting
8260                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8261                  * collation does not matter for those.
8262                  */
8263                 appendPQExpBuffer(query, "SELECT a.attname, "
8264                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8265                                                   "a.attlen, a.attalign, a.attisdropped, "
8266                                                   "CASE WHEN a.attcollation <> at.typcollation "
8267                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8268                                                   "ct.typrelid "
8269                                                   "FROM pg_catalog.pg_type ct "
8270                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8271                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8272                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8273                                                   "ORDER BY a.attnum ",
8274                                                   tyinfo->dobj.catId.oid);
8275         }
8276         else
8277         {
8278                 /*
8279                  * We assume here that remoteVersion must be at least 70300.  Since
8280                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8281                  * always be false.
8282                  */
8283                 appendPQExpBuffer(query, "SELECT a.attname, "
8284                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8285                                                   "a.attlen, a.attalign, a.attisdropped, "
8286                                                   "0 AS attcollation, "
8287                                                   "ct.typrelid "
8288                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8289                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8290                                                   "AND a.attrelid = ct.typrelid "
8291                                                   "ORDER BY a.attnum ",
8292                                                   tyinfo->dobj.catId.oid);
8293         }
8294
8295         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8296
8297         ntups = PQntuples(res);
8298
8299         i_attname = PQfnumber(res, "attname");
8300         i_atttypdefn = PQfnumber(res, "atttypdefn");
8301         i_attlen = PQfnumber(res, "attlen");
8302         i_attalign = PQfnumber(res, "attalign");
8303         i_attisdropped = PQfnumber(res, "attisdropped");
8304         i_attcollation = PQfnumber(res, "attcollation");
8305         i_typrelid = PQfnumber(res, "typrelid");
8306
8307         if (binary_upgrade)
8308         {
8309                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8310
8311                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8312                                                                                                  tyinfo->dobj.catId.oid);
8313                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8314         }
8315
8316         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8317                                           fmtId(tyinfo->dobj.name));
8318
8319         actual_atts = 0;
8320         for (i = 0; i < ntups; i++)
8321         {
8322                 char       *attname;
8323                 char       *atttypdefn;
8324                 char       *attlen;
8325                 char       *attalign;
8326                 bool            attisdropped;
8327                 Oid                     attcollation;
8328
8329                 attname = PQgetvalue(res, i, i_attname);
8330                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8331                 attlen = PQgetvalue(res, i, i_attlen);
8332                 attalign = PQgetvalue(res, i, i_attalign);
8333                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8334                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8335
8336                 if (attisdropped && !binary_upgrade)
8337                         continue;
8338
8339                 /* Format properly if not first attr */
8340                 if (actual_atts++ > 0)
8341                         appendPQExpBuffer(q, ",");
8342                 appendPQExpBuffer(q, "\n\t");
8343
8344                 if (!attisdropped)
8345                 {
8346                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8347
8348                         /* Add collation if not default for the column type */
8349                         if (OidIsValid(attcollation))
8350                         {
8351                                 CollInfo   *coll;
8352
8353                                 coll = findCollationByOid(attcollation);
8354                                 if (coll)
8355                                 {
8356                                         /* always schema-qualify, don't try to be smart */
8357                                         appendPQExpBuffer(q, " COLLATE %s.",
8358                                                                           fmtId(coll->dobj.namespace->dobj.name));
8359                                         appendPQExpBuffer(q, "%s",
8360                                                                           fmtId(coll->dobj.name));
8361                                 }
8362                         }
8363                 }
8364                 else
8365                 {
8366                         /*
8367                          * This is a dropped attribute and we're in binary_upgrade mode.
8368                          * Insert a placeholder for it in the CREATE TYPE command, and set
8369                          * length and alignment with direct UPDATE to the catalogs
8370                          * afterwards. See similar code in dumpTableSchema().
8371                          */
8372                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8373
8374                         /* stash separately for insertion after the CREATE TYPE */
8375                         appendPQExpBuffer(dropped,
8376                                           "\n-- For binary upgrade, recreate dropped column.\n");
8377                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8378                                                           "SET attlen = %s, "
8379                                                           "attalign = '%s', attbyval = false\n"
8380                                                           "WHERE attname = ", attlen, attalign);
8381                         appendStringLiteralAH(dropped, attname, fout);
8382                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8383                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8384                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8385
8386                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8387                                                           fmtId(tyinfo->dobj.name));
8388                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8389                                                           fmtId(attname));
8390                 }
8391         }
8392         appendPQExpBuffer(q, "\n);\n");
8393         appendPQExpBufferStr(q, dropped->data);
8394
8395         /*
8396          * DROP must be fully qualified in case same name appears in pg_catalog
8397          */
8398         appendPQExpBuffer(delq, "DROP TYPE %s.",
8399                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8400         appendPQExpBuffer(delq, "%s;\n",
8401                                           fmtId(tyinfo->dobj.name));
8402
8403         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8404
8405         if (binary_upgrade)
8406                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8407
8408         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8409                                  tyinfo->dobj.name,
8410                                  tyinfo->dobj.namespace->dobj.name,
8411                                  NULL,
8412                                  tyinfo->rolname, false,
8413                                  "TYPE", SECTION_PRE_DATA,
8414                                  q->data, delq->data, NULL,
8415                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8416                                  NULL, NULL);
8417
8418
8419         /* Dump Type Comments and Security Labels */
8420         dumpComment(fout, labelq->data,
8421                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8422                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8423         dumpSecLabel(fout, labelq->data,
8424                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8425                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8426
8427         PQclear(res);
8428         destroyPQExpBuffer(q);
8429         destroyPQExpBuffer(dropped);
8430         destroyPQExpBuffer(delq);
8431         destroyPQExpBuffer(labelq);
8432         destroyPQExpBuffer(query);
8433
8434         /* Dump any per-column comments */
8435         dumpCompositeTypeColComments(fout, tyinfo);
8436 }
8437
8438 /*
8439  * dumpCompositeTypeColComments
8440  *        writes out to fout the queries to recreate comments on the columns of
8441  *        a user-defined stand-alone composite type
8442  */
8443 static void
8444 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8445 {
8446         CommentItem *comments;
8447         int                     ncomments;
8448         PGresult   *res;
8449         PQExpBuffer query;
8450         PQExpBuffer target;
8451         Oid                     pgClassOid;
8452         int                     i;
8453         int                     ntups;
8454         int                     i_attname;
8455         int                     i_attnum;
8456
8457         query = createPQExpBuffer();
8458
8459         /* We assume here that remoteVersion must be at least 70300 */
8460         appendPQExpBuffer(query,
8461                                           "SELECT c.tableoid, a.attname, a.attnum "
8462                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8463                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8464                                           "  AND NOT a.attisdropped "
8465                                           "ORDER BY a.attnum ",
8466                                           tyinfo->typrelid);
8467
8468         /* Fetch column attnames */
8469         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8470
8471         ntups = PQntuples(res);
8472         if (ntups < 1)
8473         {
8474                 PQclear(res);
8475                 destroyPQExpBuffer(query);
8476                 return;
8477         }
8478
8479         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8480
8481         /* Search for comments associated with type's pg_class OID */
8482         ncomments = findComments(fout,
8483                                                          pgClassOid,
8484                                                          tyinfo->typrelid,
8485                                                          &comments);
8486
8487         /* If no comments exist, we're done */
8488         if (ncomments <= 0)
8489         {
8490                 PQclear(res);
8491                 destroyPQExpBuffer(query);
8492                 return;
8493         }
8494
8495         /* Build COMMENT ON statements */
8496         target = createPQExpBuffer();
8497
8498         i_attnum = PQfnumber(res, "attnum");
8499         i_attname = PQfnumber(res, "attname");
8500         while (ncomments > 0)
8501         {
8502                 const char *attname;
8503
8504                 attname = NULL;
8505                 for (i = 0; i < ntups; i++)
8506                 {
8507                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8508                         {
8509                                 attname = PQgetvalue(res, i, i_attname);
8510                                 break;
8511                         }
8512                 }
8513                 if (attname)                    /* just in case we don't find it */
8514                 {
8515                         const char *descr = comments->descr;
8516
8517                         resetPQExpBuffer(target);
8518                         appendPQExpBuffer(target, "COLUMN %s.",
8519                                                           fmtId(tyinfo->dobj.name));
8520                         appendPQExpBuffer(target, "%s",
8521                                                           fmtId(attname));
8522
8523                         resetPQExpBuffer(query);
8524                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8525                         appendStringLiteralAH(query, descr, fout);
8526                         appendPQExpBuffer(query, ";\n");
8527
8528                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8529                                                  target->data,
8530                                                  tyinfo->dobj.namespace->dobj.name,
8531                                                  NULL, tyinfo->rolname,
8532                                                  false, "COMMENT", SECTION_NONE,
8533                                                  query->data, "", NULL,
8534                                                  &(tyinfo->dobj.dumpId), 1,
8535                                                  NULL, NULL);
8536                 }
8537
8538                 comments++;
8539                 ncomments--;
8540         }
8541
8542         PQclear(res);
8543         destroyPQExpBuffer(query);
8544         destroyPQExpBuffer(target);
8545 }
8546
8547 /*
8548  * dumpShellType
8549  *        writes out to fout the queries to create a shell type
8550  *
8551  * We dump a shell definition in advance of the I/O functions for the type.
8552  */
8553 static void
8554 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8555 {
8556         PQExpBuffer q;
8557
8558         /* Skip if not to be dumped */
8559         if (!stinfo->dobj.dump || dataOnly)
8560                 return;
8561
8562         q = createPQExpBuffer();
8563
8564         /*
8565          * Note the lack of a DROP command for the shell type; any required DROP
8566          * is driven off the base type entry, instead.  This interacts with
8567          * _printTocEntry()'s use of the presence of a DROP command to decide
8568          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8569          * the shell type's owner immediately on creation; that should happen only
8570          * after it's filled in, otherwise the backend complains.
8571          */
8572
8573         if (binary_upgrade)
8574                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8575                                                                                    stinfo->baseType->dobj.catId.oid);
8576
8577         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8578                                           fmtId(stinfo->dobj.name));
8579
8580         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8581                                  stinfo->dobj.name,
8582                                  stinfo->dobj.namespace->dobj.name,
8583                                  NULL,
8584                                  stinfo->baseType->rolname, false,
8585                                  "SHELL TYPE", SECTION_PRE_DATA,
8586                                  q->data, "", NULL,
8587                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8588                                  NULL, NULL);
8589
8590         destroyPQExpBuffer(q);
8591 }
8592
8593 /*
8594  * Determine whether we want to dump definitions for procedural languages.
8595  * Since the languages themselves don't have schemas, we can't rely on
8596  * the normal schema-based selection mechanism.  We choose to dump them
8597  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8598  * the dump flag of the PL's call handler function, but in 8.1 this will
8599  * probably always be false since call handlers are created in pg_catalog.)
8600  *
8601  * For some backwards compatibility with the older behavior, we forcibly
8602  * dump a PL if its handler function (and validator if any) are in a
8603  * dumpable namespace.  That case is not checked here.
8604  *
8605  * Also, if the PL belongs to an extension, we do not use this heuristic.
8606  * That case isn't checked here either.
8607  */
8608 static bool
8609 shouldDumpProcLangs(void)
8610 {
8611         if (!include_everything)
8612                 return false;
8613         /* And they're schema not data */
8614         if (dataOnly)
8615                 return false;
8616         return true;
8617 }
8618
8619 /*
8620  * dumpProcLang
8621  *                writes out to fout the queries to recreate a user-defined
8622  *                procedural language
8623  */
8624 static void
8625 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8626 {
8627         PQExpBuffer defqry;
8628         PQExpBuffer delqry;
8629         PQExpBuffer labelq;
8630         bool            useParams;
8631         char       *qlanname;
8632         char       *lanschema;
8633         FuncInfo   *funcInfo;
8634         FuncInfo   *inlineInfo = NULL;
8635         FuncInfo   *validatorInfo = NULL;
8636
8637         /* Skip if not to be dumped */
8638         if (!plang->dobj.dump || dataOnly)
8639                 return;
8640
8641         /*
8642          * Try to find the support function(s).  It is not an error if we don't
8643          * find them --- if the functions are in the pg_catalog schema, as is
8644          * standard in 8.1 and up, then we won't have loaded them. (In this case
8645          * we will emit a parameterless CREATE LANGUAGE command, which will
8646          * require PL template knowledge in the backend to reload.)
8647          */
8648
8649         funcInfo = findFuncByOid(plang->lanplcallfoid);
8650         if (funcInfo != NULL && !funcInfo->dobj.dump)
8651                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8652
8653         if (OidIsValid(plang->laninline))
8654         {
8655                 inlineInfo = findFuncByOid(plang->laninline);
8656                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8657                         inlineInfo = NULL;
8658         }
8659
8660         if (OidIsValid(plang->lanvalidator))
8661         {
8662                 validatorInfo = findFuncByOid(plang->lanvalidator);
8663                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8664                         validatorInfo = NULL;
8665         }
8666
8667         /*
8668          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8669          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8670          * dump it.
8671          *
8672          * However, for a language that belongs to an extension, we must not use
8673          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8674          * told to (via dobj.dump).  Generally the support functions will belong
8675          * to the same extension and so have the same dump flags ... if they
8676          * don't, this might not work terribly nicely.
8677          */
8678         useParams = (funcInfo != NULL &&
8679                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8680                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8681
8682         if (!plang->dobj.ext_member)
8683         {
8684                 if (!useParams && !shouldDumpProcLangs())
8685                         return;
8686         }
8687
8688         defqry = createPQExpBuffer();
8689         delqry = createPQExpBuffer();
8690         labelq = createPQExpBuffer();
8691
8692         qlanname = pg_strdup(fmtId(plang->dobj.name));
8693
8694         /*
8695          * If dumping a HANDLER clause, treat the language as being in the handler
8696          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8697          * it doesn't really have a schema.
8698          */
8699         if (useParams)
8700                 lanschema = funcInfo->dobj.namespace->dobj.name;
8701         else
8702                 lanschema = NULL;
8703
8704         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8705                                           qlanname);
8706
8707         if (useParams)
8708         {
8709                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8710                                                   plang->lanpltrusted ? "TRUSTED " : "",
8711                                                   qlanname);
8712                 appendPQExpBuffer(defqry, " HANDLER %s",
8713                                                   fmtId(funcInfo->dobj.name));
8714                 if (OidIsValid(plang->laninline))
8715                 {
8716                         appendPQExpBuffer(defqry, " INLINE ");
8717                         /* Cope with possibility that inline is in different schema */
8718                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8719                                 appendPQExpBuffer(defqry, "%s.",
8720                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8721                         appendPQExpBuffer(defqry, "%s",
8722                                                           fmtId(inlineInfo->dobj.name));
8723                 }
8724                 if (OidIsValid(plang->lanvalidator))
8725                 {
8726                         appendPQExpBuffer(defqry, " VALIDATOR ");
8727                         /* Cope with possibility that validator is in different schema */
8728                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8729                                 appendPQExpBuffer(defqry, "%s.",
8730                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8731                         appendPQExpBuffer(defqry, "%s",
8732                                                           fmtId(validatorInfo->dobj.name));
8733                 }
8734         }
8735         else
8736         {
8737                 /*
8738                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8739                  * command will not fail if the language is preinstalled in the target
8740                  * database.  We restrict the use of REPLACE to this case so as to
8741                  * eliminate the risk of replacing a language with incompatible
8742                  * parameter settings: this command will only succeed at all if there
8743                  * is a pg_pltemplate entry, and if there is one, the existing entry
8744                  * must match it too.
8745                  */
8746                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8747                                                   qlanname);
8748         }
8749         appendPQExpBuffer(defqry, ";\n");
8750
8751         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8752
8753         if (binary_upgrade)
8754                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8755
8756         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8757                                  plang->dobj.name,
8758                                  lanschema, NULL, plang->lanowner,
8759                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8760                                  defqry->data, delqry->data, NULL,
8761                                  plang->dobj.dependencies, plang->dobj.nDeps,
8762                                  NULL, NULL);
8763
8764         /* Dump Proc Lang Comments and Security Labels */
8765         dumpComment(fout, labelq->data,
8766                                 NULL, "",
8767                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8768         dumpSecLabel(fout, labelq->data,
8769                                  NULL, "",
8770                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8771
8772         if (plang->lanpltrusted)
8773                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8774                                 qlanname, NULL, plang->dobj.name,
8775                                 lanschema,
8776                                 plang->lanowner, plang->lanacl);
8777
8778         free(qlanname);
8779
8780         destroyPQExpBuffer(defqry);
8781         destroyPQExpBuffer(delqry);
8782         destroyPQExpBuffer(labelq);
8783 }
8784
8785 /*
8786  * format_function_arguments: generate function name and argument list
8787  *
8788  * This is used when we can rely on pg_get_function_arguments to format
8789  * the argument list.
8790  */
8791 static char *
8792 format_function_arguments(FuncInfo *finfo, char *funcargs)
8793 {
8794         PQExpBufferData fn;
8795
8796         initPQExpBuffer(&fn);
8797         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8798         return fn.data;
8799 }
8800
8801 /*
8802  * format_function_arguments_old: generate function name and argument list
8803  *
8804  * The argument type names are qualified if needed.  The function name
8805  * is never qualified.
8806  *
8807  * This is used only with pre-8.4 servers, so we aren't expecting to see
8808  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8809  *
8810  * Any or all of allargtypes, argmodes, argnames may be NULL.
8811  */
8812 static char *
8813 format_function_arguments_old(Archive *fout,
8814                                                           FuncInfo *finfo, int nallargs,
8815                                                           char **allargtypes,
8816                                                           char **argmodes,
8817                                                           char **argnames)
8818 {
8819         PQExpBufferData fn;
8820         int                     j;
8821
8822         initPQExpBuffer(&fn);
8823         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8824         for (j = 0; j < nallargs; j++)
8825         {
8826                 Oid                     typid;
8827                 char       *typname;
8828                 const char *argmode;
8829                 const char *argname;
8830
8831                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8832                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8833
8834                 if (argmodes)
8835                 {
8836                         switch (argmodes[j][0])
8837                         {
8838                                 case PROARGMODE_IN:
8839                                         argmode = "";
8840                                         break;
8841                                 case PROARGMODE_OUT:
8842                                         argmode = "OUT ";
8843                                         break;
8844                                 case PROARGMODE_INOUT:
8845                                         argmode = "INOUT ";
8846                                         break;
8847                                 default:
8848                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8849                                         argmode = "";
8850                                         break;
8851                         }
8852                 }
8853                 else
8854                         argmode = "";
8855
8856                 argname = argnames ? argnames[j] : (char *) NULL;
8857                 if (argname && argname[0] == '\0')
8858                         argname = NULL;
8859
8860                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8861                                                   (j > 0) ? ", " : "",
8862                                                   argmode,
8863                                                   argname ? fmtId(argname) : "",
8864                                                   argname ? " " : "",
8865                                                   typname);
8866                 free(typname);
8867         }
8868         appendPQExpBuffer(&fn, ")");
8869         return fn.data;
8870 }
8871
8872 /*
8873  * format_function_signature: generate function name and argument list
8874  *
8875  * This is like format_function_arguments_old except that only a minimal
8876  * list of input argument types is generated; this is sufficient to
8877  * reference the function, but not to define it.
8878  *
8879  * If honor_quotes is false then the function name is never quoted.
8880  * This is appropriate for use in TOC tags, but not in SQL commands.
8881  */
8882 static char *
8883 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8884 {
8885         PQExpBufferData fn;
8886         int                     j;
8887
8888         initPQExpBuffer(&fn);
8889         if (honor_quotes)
8890                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8891         else
8892                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8893         for (j = 0; j < finfo->nargs; j++)
8894         {
8895                 char       *typname;
8896
8897                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8898                                                                            zeroAsOpaque);
8899
8900                 appendPQExpBuffer(&fn, "%s%s",
8901                                                   (j > 0) ? ", " : "",
8902                                                   typname);
8903                 free(typname);
8904         }
8905         appendPQExpBuffer(&fn, ")");
8906         return fn.data;
8907 }
8908
8909
8910 /*
8911  * dumpFunc:
8912  *        dump out one function
8913  */
8914 static void
8915 dumpFunc(Archive *fout, FuncInfo *finfo)
8916 {
8917         PQExpBuffer query;
8918         PQExpBuffer q;
8919         PQExpBuffer delqry;
8920         PQExpBuffer labelq;
8921         PQExpBuffer asPart;
8922         PGresult   *res;
8923         char       *funcsig;            /* identity signature */
8924         char       *funcfullsig;        /* full signature */
8925         char       *funcsig_tag;
8926         char       *proretset;
8927         char       *prosrc;
8928         char       *probin;
8929         char       *funcargs;
8930         char       *funciargs;
8931         char       *funcresult;
8932         char       *proallargtypes;
8933         char       *proargmodes;
8934         char       *proargnames;
8935         char       *proiswindow;
8936         char       *provolatile;
8937         char       *proisstrict;
8938         char       *prosecdef;
8939         char       *proleakproof;
8940         char       *proconfig;
8941         char       *procost;
8942         char       *prorows;
8943         char       *lanname;
8944         char       *rettypename;
8945         int                     nallargs;
8946         char      **allargtypes = NULL;
8947         char      **argmodes = NULL;
8948         char      **argnames = NULL;
8949         char      **configitems = NULL;
8950         int                     nconfigitems = 0;
8951         int                     i;
8952
8953         /* Skip if not to be dumped */
8954         if (!finfo->dobj.dump || dataOnly)
8955                 return;
8956
8957         query = createPQExpBuffer();
8958         q = createPQExpBuffer();
8959         delqry = createPQExpBuffer();
8960         labelq = createPQExpBuffer();
8961         asPart = createPQExpBuffer();
8962
8963         /* Set proper schema search path so type references list correctly */
8964         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8965
8966         /* Fetch function-specific details */
8967         if (fout->remoteVersion >= 90200)
8968         {
8969                 /*
8970                  * proleakproof was added at v9.2
8971                  */
8972                 appendPQExpBuffer(query,
8973                                                   "SELECT proretset, prosrc, probin, "
8974                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8975                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8976                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8977                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8978                                                   "proleakproof, proconfig, procost, prorows, "
8979                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8980                                                   "FROM pg_catalog.pg_proc "
8981                                                   "WHERE oid = '%u'::pg_catalog.oid",
8982                                                   finfo->dobj.catId.oid);
8983         }
8984         else if (fout->remoteVersion >= 80400)
8985         {
8986                 /*
8987                  * In 8.4 and up we rely on pg_get_function_arguments and
8988                  * pg_get_function_result instead of examining proallargtypes etc.
8989                  */
8990                 appendPQExpBuffer(query,
8991                                                   "SELECT proretset, prosrc, probin, "
8992                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8993                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8994                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8995                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8996                                                   "false AS proleakproof, "
8997                                                   " proconfig, procost, prorows, "
8998                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8999                                                   "FROM pg_catalog.pg_proc "
9000                                                   "WHERE oid = '%u'::pg_catalog.oid",
9001                                                   finfo->dobj.catId.oid);
9002         }
9003         else if (fout->remoteVersion >= 80300)
9004         {
9005                 appendPQExpBuffer(query,
9006                                                   "SELECT proretset, prosrc, probin, "
9007                                                   "proallargtypes, proargmodes, proargnames, "
9008                                                   "false AS proiswindow, "
9009                                                   "provolatile, proisstrict, prosecdef, "
9010                                                   "false AS proleakproof, "
9011                                                   "proconfig, procost, prorows, "
9012                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9013                                                   "FROM pg_catalog.pg_proc "
9014                                                   "WHERE oid = '%u'::pg_catalog.oid",
9015                                                   finfo->dobj.catId.oid);
9016         }
9017         else if (fout->remoteVersion >= 80100)
9018         {
9019                 appendPQExpBuffer(query,
9020                                                   "SELECT proretset, prosrc, probin, "
9021                                                   "proallargtypes, proargmodes, proargnames, "
9022                                                   "false AS proiswindow, "
9023                                                   "provolatile, proisstrict, prosecdef, "
9024                                                   "false AS proleakproof, "
9025                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9026                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9027                                                   "FROM pg_catalog.pg_proc "
9028                                                   "WHERE oid = '%u'::pg_catalog.oid",
9029                                                   finfo->dobj.catId.oid);
9030         }
9031         else if (fout->remoteVersion >= 80000)
9032         {
9033                 appendPQExpBuffer(query,
9034                                                   "SELECT proretset, prosrc, probin, "
9035                                                   "null AS proallargtypes, "
9036                                                   "null AS proargmodes, "
9037                                                   "proargnames, "
9038                                                   "false AS proiswindow, "
9039                                                   "provolatile, proisstrict, prosecdef, "
9040                                                   "false AS proleakproof, "
9041                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9042                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9043                                                   "FROM pg_catalog.pg_proc "
9044                                                   "WHERE oid = '%u'::pg_catalog.oid",
9045                                                   finfo->dobj.catId.oid);
9046         }
9047         else if (fout->remoteVersion >= 70300)
9048         {
9049                 appendPQExpBuffer(query,
9050                                                   "SELECT proretset, prosrc, probin, "
9051                                                   "null AS proallargtypes, "
9052                                                   "null AS proargmodes, "
9053                                                   "null AS proargnames, "
9054                                                   "false AS proiswindow, "
9055                                                   "provolatile, proisstrict, prosecdef, "
9056                                                   "false AS proleakproof, "
9057                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9058                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9059                                                   "FROM pg_catalog.pg_proc "
9060                                                   "WHERE oid = '%u'::pg_catalog.oid",
9061                                                   finfo->dobj.catId.oid);
9062         }
9063         else if (fout->remoteVersion >= 70100)
9064         {
9065                 appendPQExpBuffer(query,
9066                                                   "SELECT proretset, prosrc, probin, "
9067                                                   "null AS proallargtypes, "
9068                                                   "null AS proargmodes, "
9069                                                   "null AS proargnames, "
9070                                                   "false AS proiswindow, "
9071                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9072                                                   "proisstrict, "
9073                                                   "false AS prosecdef, "
9074                                                   "false AS proleakproof, "
9075                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9076                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9077                                                   "FROM pg_proc "
9078                                                   "WHERE oid = '%u'::oid",
9079                                                   finfo->dobj.catId.oid);
9080         }
9081         else
9082         {
9083                 appendPQExpBuffer(query,
9084                                                   "SELECT proretset, prosrc, probin, "
9085                                                   "null AS proallargtypes, "
9086                                                   "null AS proargmodes, "
9087                                                   "null AS proargnames, "
9088                                                   "false AS proiswindow, "
9089                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9090                                                   "false AS proisstrict, "
9091                                                   "false AS prosecdef, "
9092                                                   "false AS proleakproof, "
9093                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9094                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9095                                                   "FROM pg_proc "
9096                                                   "WHERE oid = '%u'::oid",
9097                                                   finfo->dobj.catId.oid);
9098         }
9099
9100         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9101
9102         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9103         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9104         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9105         if (fout->remoteVersion >= 80400)
9106         {
9107                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9108                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9109                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9110                 proallargtypes = proargmodes = proargnames = NULL;
9111         }
9112         else
9113         {
9114                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9115                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9116                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9117                 funcargs = funciargs = funcresult = NULL;
9118         }
9119         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9120         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9121         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9122         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9123         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9124         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9125         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9126         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9127         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9128
9129         /*
9130          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9131          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9132          * versions would set it to "-".  There are no known cases in which prosrc
9133          * is unused, so the tests below for "-" are probably useless.
9134          */
9135         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9136         {
9137                 appendPQExpBuffer(asPart, "AS ");
9138                 appendStringLiteralAH(asPart, probin, fout);
9139                 if (strcmp(prosrc, "-") != 0)
9140                 {
9141                         appendPQExpBuffer(asPart, ", ");
9142
9143                         /*
9144                          * where we have bin, use dollar quoting if allowed and src
9145                          * contains quote or backslash; else use regular quoting.
9146                          */
9147                         if (disable_dollar_quoting ||
9148                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9149                                 appendStringLiteralAH(asPart, prosrc, fout);
9150                         else
9151                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9152                 }
9153         }
9154         else
9155         {
9156                 if (strcmp(prosrc, "-") != 0)
9157                 {
9158                         appendPQExpBuffer(asPart, "AS ");
9159                         /* with no bin, dollar quote src unconditionally if allowed */
9160                         if (disable_dollar_quoting)
9161                                 appendStringLiteralAH(asPart, prosrc, fout);
9162                         else
9163                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9164                 }
9165         }
9166
9167         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9168
9169         if (proallargtypes && *proallargtypes)
9170         {
9171                 int                     nitems = 0;
9172
9173                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9174                         nitems < finfo->nargs)
9175                 {
9176                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9177                         if (allargtypes)
9178                                 free(allargtypes);
9179                         allargtypes = NULL;
9180                 }
9181                 else
9182                         nallargs = nitems;
9183         }
9184
9185         if (proargmodes && *proargmodes)
9186         {
9187                 int                     nitems = 0;
9188
9189                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9190                         nitems != nallargs)
9191                 {
9192                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9193                         if (argmodes)
9194                                 free(argmodes);
9195                         argmodes = NULL;
9196                 }
9197         }
9198
9199         if (proargnames && *proargnames)
9200         {
9201                 int                     nitems = 0;
9202
9203                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9204                         nitems != nallargs)
9205                 {
9206                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9207                         if (argnames)
9208                                 free(argnames);
9209                         argnames = NULL;
9210                 }
9211         }
9212
9213         if (proconfig && *proconfig)
9214         {
9215                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9216                 {
9217                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9218                         if (configitems)
9219                                 free(configitems);
9220                         configitems = NULL;
9221                         nconfigitems = 0;
9222                 }
9223         }
9224
9225         if (funcargs)
9226         {
9227                 /* 8.4 or later; we rely on server-side code for most of the work */
9228                 funcfullsig = format_function_arguments(finfo, funcargs);
9229                 funcsig = format_function_arguments(finfo, funciargs);
9230         }
9231         else
9232         {
9233                 /* pre-8.4, do it ourselves */
9234                 funcsig = format_function_arguments_old(fout,
9235                                                                                                 finfo, nallargs, allargtypes,
9236                                                                                                 argmodes, argnames);
9237                 funcfullsig = funcsig;
9238         }
9239
9240         funcsig_tag = format_function_signature(fout, finfo, false);
9241
9242         /*
9243          * DROP must be fully qualified in case same name appears in pg_catalog
9244          */
9245         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9246                                           fmtId(finfo->dobj.namespace->dobj.name),
9247                                           funcsig);
9248
9249         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9250         if (funcresult)
9251                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9252         else
9253         {
9254                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9255                                                                                    zeroAsOpaque);
9256                 appendPQExpBuffer(q, "RETURNS %s%s",
9257                                                   (proretset[0] == 't') ? "SETOF " : "",
9258                                                   rettypename);
9259                 free(rettypename);
9260         }
9261
9262         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9263
9264         if (proiswindow[0] == 't')
9265                 appendPQExpBuffer(q, " WINDOW");
9266
9267         if (provolatile[0] != PROVOLATILE_VOLATILE)
9268         {
9269                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9270                         appendPQExpBuffer(q, " IMMUTABLE");
9271                 else if (provolatile[0] == PROVOLATILE_STABLE)
9272                         appendPQExpBuffer(q, " STABLE");
9273                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9274                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9275                                                   finfo->dobj.name);
9276         }
9277
9278         if (proisstrict[0] == 't')
9279                 appendPQExpBuffer(q, " STRICT");
9280
9281         if (prosecdef[0] == 't')
9282                 appendPQExpBuffer(q, " SECURITY DEFINER");
9283
9284         if (proleakproof[0] == 't')
9285                 appendPQExpBuffer(q, " LEAKPROOF");
9286
9287         /*
9288          * COST and ROWS are emitted only if present and not default, so as not to
9289          * break backwards-compatibility of the dump without need.      Keep this code
9290          * in sync with the defaults in functioncmds.c.
9291          */
9292         if (strcmp(procost, "0") != 0)
9293         {
9294                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9295                 {
9296                         /* default cost is 1 */
9297                         if (strcmp(procost, "1") != 0)
9298                                 appendPQExpBuffer(q, " COST %s", procost);
9299                 }
9300                 else
9301                 {
9302                         /* default cost is 100 */
9303                         if (strcmp(procost, "100") != 0)
9304                                 appendPQExpBuffer(q, " COST %s", procost);
9305                 }
9306         }
9307         if (proretset[0] == 't' &&
9308                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9309                 appendPQExpBuffer(q, " ROWS %s", prorows);
9310
9311         for (i = 0; i < nconfigitems; i++)
9312         {
9313                 /* we feel free to scribble on configitems[] here */
9314                 char       *configitem = configitems[i];
9315                 char       *pos;
9316
9317                 pos = strchr(configitem, '=');
9318                 if (pos == NULL)
9319                         continue;
9320                 *pos++ = '\0';
9321                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9322
9323                 /*
9324                  * Some GUC variable names are 'LIST' type and hence must not be
9325                  * quoted.
9326                  */
9327                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9328                         || pg_strcasecmp(configitem, "search_path") == 0)
9329                         appendPQExpBuffer(q, "%s", pos);
9330                 else
9331                         appendStringLiteralAH(q, pos, fout);
9332         }
9333
9334         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9335
9336         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9337
9338         if (binary_upgrade)
9339                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9340
9341         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9342                                  funcsig_tag,
9343                                  finfo->dobj.namespace->dobj.name,
9344                                  NULL,
9345                                  finfo->rolname, false,
9346                                  "FUNCTION", SECTION_PRE_DATA,
9347                                  q->data, delqry->data, NULL,
9348                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
9349                                  NULL, NULL);
9350
9351         /* Dump Function Comments and Security Labels */
9352         dumpComment(fout, labelq->data,
9353                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9354                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9355         dumpSecLabel(fout, labelq->data,
9356                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9357                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9358
9359         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9360                         funcsig, NULL, funcsig_tag,
9361                         finfo->dobj.namespace->dobj.name,
9362                         finfo->rolname, finfo->proacl);
9363
9364         PQclear(res);
9365
9366         destroyPQExpBuffer(query);
9367         destroyPQExpBuffer(q);
9368         destroyPQExpBuffer(delqry);
9369         destroyPQExpBuffer(labelq);
9370         destroyPQExpBuffer(asPart);
9371         free(funcsig);
9372         free(funcsig_tag);
9373         if (allargtypes)
9374                 free(allargtypes);
9375         if (argmodes)
9376                 free(argmodes);
9377         if (argnames)
9378                 free(argnames);
9379         if (configitems)
9380                 free(configitems);
9381 }
9382
9383
9384 /*
9385  * Dump a user-defined cast
9386  */
9387 static void
9388 dumpCast(Archive *fout, CastInfo *cast)
9389 {
9390         PQExpBuffer defqry;
9391         PQExpBuffer delqry;
9392         PQExpBuffer labelq;
9393         FuncInfo   *funcInfo = NULL;
9394
9395         /* Skip if not to be dumped */
9396         if (!cast->dobj.dump || dataOnly)
9397                 return;
9398
9399         /* Cannot dump if we don't have the cast function's info */
9400         if (OidIsValid(cast->castfunc))
9401         {
9402                 funcInfo = findFuncByOid(cast->castfunc);
9403                 if (funcInfo == NULL)
9404                         return;
9405         }
9406
9407         /*
9408          * As per discussion we dump casts if one or more of the underlying
9409          * objects (the conversion function and the two data types) are not
9410          * builtin AND if all of the non-builtin objects are included in the dump.
9411          * Builtin meaning, the namespace name does not start with "pg_".
9412          *
9413          * However, for a cast that belongs to an extension, we must not use this
9414          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9415          */
9416         if (!cast->dobj.ext_member)
9417         {
9418                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9419                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9420
9421                 if (sourceInfo == NULL || targetInfo == NULL)
9422                         return;
9423
9424                 /*
9425                  * Skip this cast if all objects are from pg_
9426                  */
9427                 if ((funcInfo == NULL ||
9428                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9429                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9430                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9431                         return;
9432
9433                 /*
9434                  * Skip cast if function isn't from pg_ and is not to be dumped.
9435                  */
9436                 if (funcInfo &&
9437                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9438                         !funcInfo->dobj.dump)
9439                         return;
9440
9441                 /*
9442                  * Same for the source type
9443                  */
9444                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9445                         !sourceInfo->dobj.dump)
9446                         return;
9447
9448                 /*
9449                  * and the target type.
9450                  */
9451                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9452                         !targetInfo->dobj.dump)
9453                         return;
9454         }
9455
9456         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9457         selectSourceSchema(fout, "pg_catalog");
9458
9459         defqry = createPQExpBuffer();
9460         delqry = createPQExpBuffer();
9461         labelq = createPQExpBuffer();
9462
9463         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9464                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9465                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9466
9467         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9468                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9469                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9470
9471         switch (cast->castmethod)
9472         {
9473                 case COERCION_METHOD_BINARY:
9474                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9475                         break;
9476                 case COERCION_METHOD_INOUT:
9477                         appendPQExpBuffer(defqry, "WITH INOUT");
9478                         break;
9479                 case COERCION_METHOD_FUNCTION:
9480                 {
9481                         char   *fsig = format_function_signature(fout, funcInfo, true);
9482
9483                         /*
9484                          * Always qualify the function name, in case it is not in
9485                          * pg_catalog schema (format_function_signature won't qualify it).
9486                          */
9487                         appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9488                                                           fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9489                         free(fsig);
9490                         break;
9491                 }
9492                 default:
9493                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9494         }
9495
9496         if (cast->castcontext == 'a')
9497                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9498         else if (cast->castcontext == 'i')
9499                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9500         appendPQExpBuffer(defqry, ";\n");
9501
9502         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9503                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9504                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9505
9506         if (binary_upgrade)
9507                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9508
9509         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9510                                  labelq->data,
9511                                  "pg_catalog", NULL, "",
9512                                  false, "CAST", SECTION_PRE_DATA,
9513                                  defqry->data, delqry->data, NULL,
9514                                  cast->dobj.dependencies, cast->dobj.nDeps,
9515                                  NULL, NULL);
9516
9517         /* Dump Cast Comments */
9518         dumpComment(fout, labelq->data,
9519                                 NULL, "",
9520                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9521
9522         destroyPQExpBuffer(defqry);
9523         destroyPQExpBuffer(delqry);
9524         destroyPQExpBuffer(labelq);
9525 }
9526
9527 /*
9528  * dumpOpr
9529  *        write out a single operator definition
9530  */
9531 static void
9532 dumpOpr(Archive *fout, OprInfo *oprinfo)
9533 {
9534         PQExpBuffer query;
9535         PQExpBuffer q;
9536         PQExpBuffer delq;
9537         PQExpBuffer labelq;
9538         PQExpBuffer oprid;
9539         PQExpBuffer details;
9540         const char *name;
9541         PGresult   *res;
9542         int                     i_oprkind;
9543         int                     i_oprcode;
9544         int                     i_oprleft;
9545         int                     i_oprright;
9546         int                     i_oprcom;
9547         int                     i_oprnegate;
9548         int                     i_oprrest;
9549         int                     i_oprjoin;
9550         int                     i_oprcanmerge;
9551         int                     i_oprcanhash;
9552         char       *oprkind;
9553         char       *oprcode;
9554         char       *oprleft;
9555         char       *oprright;
9556         char       *oprcom;
9557         char       *oprnegate;
9558         char       *oprrest;
9559         char       *oprjoin;
9560         char       *oprcanmerge;
9561         char       *oprcanhash;
9562
9563         /* Skip if not to be dumped */
9564         if (!oprinfo->dobj.dump || dataOnly)
9565                 return;
9566
9567         /*
9568          * some operators are invalid because they were the result of user
9569          * defining operators before commutators exist
9570          */
9571         if (!OidIsValid(oprinfo->oprcode))
9572                 return;
9573
9574         query = createPQExpBuffer();
9575         q = createPQExpBuffer();
9576         delq = createPQExpBuffer();
9577         labelq = createPQExpBuffer();
9578         oprid = createPQExpBuffer();
9579         details = createPQExpBuffer();
9580
9581         /* Make sure we are in proper schema so regoperator works correctly */
9582         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9583
9584         if (fout->remoteVersion >= 80300)
9585         {
9586                 appendPQExpBuffer(query, "SELECT oprkind, "
9587                                                   "oprcode::pg_catalog.regprocedure, "
9588                                                   "oprleft::pg_catalog.regtype, "
9589                                                   "oprright::pg_catalog.regtype, "
9590                                                   "oprcom::pg_catalog.regoperator, "
9591                                                   "oprnegate::pg_catalog.regoperator, "
9592                                                   "oprrest::pg_catalog.regprocedure, "
9593                                                   "oprjoin::pg_catalog.regprocedure, "
9594                                                   "oprcanmerge, oprcanhash "
9595                                                   "FROM pg_catalog.pg_operator "
9596                                                   "WHERE oid = '%u'::pg_catalog.oid",
9597                                                   oprinfo->dobj.catId.oid);
9598         }
9599         else if (fout->remoteVersion >= 70300)
9600         {
9601                 appendPQExpBuffer(query, "SELECT oprkind, "
9602                                                   "oprcode::pg_catalog.regprocedure, "
9603                                                   "oprleft::pg_catalog.regtype, "
9604                                                   "oprright::pg_catalog.regtype, "
9605                                                   "oprcom::pg_catalog.regoperator, "
9606                                                   "oprnegate::pg_catalog.regoperator, "
9607                                                   "oprrest::pg_catalog.regprocedure, "
9608                                                   "oprjoin::pg_catalog.regprocedure, "
9609                                                   "(oprlsortop != 0) AS oprcanmerge, "
9610                                                   "oprcanhash "
9611                                                   "FROM pg_catalog.pg_operator "
9612                                                   "WHERE oid = '%u'::pg_catalog.oid",
9613                                                   oprinfo->dobj.catId.oid);
9614         }
9615         else if (fout->remoteVersion >= 70100)
9616         {
9617                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9618                                                   "CASE WHEN oprleft = 0 THEN '-' "
9619                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9620                                                   "CASE WHEN oprright = 0 THEN '-' "
9621                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9622                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9623                                                   "(oprlsortop != 0) AS oprcanmerge, "
9624                                                   "oprcanhash "
9625                                                   "FROM pg_operator "
9626                                                   "WHERE oid = '%u'::oid",
9627                                                   oprinfo->dobj.catId.oid);
9628         }
9629         else
9630         {
9631                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9632                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9633                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9634                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9635                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9636                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9637                                                   "(oprlsortop != 0) AS oprcanmerge, "
9638                                                   "oprcanhash "
9639                                                   "FROM pg_operator "
9640                                                   "WHERE oid = '%u'::oid",
9641                                                   oprinfo->dobj.catId.oid);
9642         }
9643
9644         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9645
9646         i_oprkind = PQfnumber(res, "oprkind");
9647         i_oprcode = PQfnumber(res, "oprcode");
9648         i_oprleft = PQfnumber(res, "oprleft");
9649         i_oprright = PQfnumber(res, "oprright");
9650         i_oprcom = PQfnumber(res, "oprcom");
9651         i_oprnegate = PQfnumber(res, "oprnegate");
9652         i_oprrest = PQfnumber(res, "oprrest");
9653         i_oprjoin = PQfnumber(res, "oprjoin");
9654         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9655         i_oprcanhash = PQfnumber(res, "oprcanhash");
9656
9657         oprkind = PQgetvalue(res, 0, i_oprkind);
9658         oprcode = PQgetvalue(res, 0, i_oprcode);
9659         oprleft = PQgetvalue(res, 0, i_oprleft);
9660         oprright = PQgetvalue(res, 0, i_oprright);
9661         oprcom = PQgetvalue(res, 0, i_oprcom);
9662         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9663         oprrest = PQgetvalue(res, 0, i_oprrest);
9664         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9665         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9666         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9667
9668         appendPQExpBuffer(details, "    PROCEDURE = %s",
9669                                           convertRegProcReference(fout, oprcode));
9670
9671         appendPQExpBuffer(oprid, "%s (",
9672                                           oprinfo->dobj.name);
9673
9674         /*
9675          * right unary means there's a left arg and left unary means there's a
9676          * right arg
9677          */
9678         if (strcmp(oprkind, "r") == 0 ||
9679                 strcmp(oprkind, "b") == 0)
9680         {
9681                 if (fout->remoteVersion >= 70100)
9682                         name = oprleft;
9683                 else
9684                         name = fmtId(oprleft);
9685                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9686                 appendPQExpBuffer(oprid, "%s", name);
9687         }
9688         else
9689                 appendPQExpBuffer(oprid, "NONE");
9690
9691         if (strcmp(oprkind, "l") == 0 ||
9692                 strcmp(oprkind, "b") == 0)
9693         {
9694                 if (fout->remoteVersion >= 70100)
9695                         name = oprright;
9696                 else
9697                         name = fmtId(oprright);
9698                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9699                 appendPQExpBuffer(oprid, ", %s)", name);
9700         }
9701         else
9702                 appendPQExpBuffer(oprid, ", NONE)");
9703
9704         name = convertOperatorReference(fout, oprcom);
9705         if (name)
9706                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9707
9708         name = convertOperatorReference(fout, oprnegate);
9709         if (name)
9710                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9711
9712         if (strcmp(oprcanmerge, "t") == 0)
9713                 appendPQExpBuffer(details, ",\n    MERGES");
9714
9715         if (strcmp(oprcanhash, "t") == 0)
9716                 appendPQExpBuffer(details, ",\n    HASHES");
9717
9718         name = convertRegProcReference(fout, oprrest);
9719         if (name)
9720                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9721
9722         name = convertRegProcReference(fout, oprjoin);
9723         if (name)
9724                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9725
9726         /*
9727          * DROP must be fully qualified in case same name appears in pg_catalog
9728          */
9729         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9730                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9731                                           oprid->data);
9732
9733         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9734                                           oprinfo->dobj.name, details->data);
9735
9736         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9737
9738         if (binary_upgrade)
9739                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9740
9741         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9742                                  oprinfo->dobj.name,
9743                                  oprinfo->dobj.namespace->dobj.name,
9744                                  NULL,
9745                                  oprinfo->rolname,
9746                                  false, "OPERATOR", SECTION_PRE_DATA,
9747                                  q->data, delq->data, NULL,
9748                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9749                                  NULL, NULL);
9750
9751         /* Dump Operator Comments */
9752         dumpComment(fout, labelq->data,
9753                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9754                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9755
9756         PQclear(res);
9757
9758         destroyPQExpBuffer(query);
9759         destroyPQExpBuffer(q);
9760         destroyPQExpBuffer(delq);
9761         destroyPQExpBuffer(labelq);
9762         destroyPQExpBuffer(oprid);
9763         destroyPQExpBuffer(details);
9764 }
9765
9766 /*
9767  * Convert a function reference obtained from pg_operator
9768  *
9769  * Returns what to print, or NULL if function references is InvalidOid
9770  *
9771  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9772  * argument-types part.  In prior versions, the input is a REGPROC display.
9773  */
9774 static const char *
9775 convertRegProcReference(Archive *fout, const char *proc)
9776 {
9777         /* In all cases "-" means a null reference */
9778         if (strcmp(proc, "-") == 0)
9779                 return NULL;
9780
9781         if (fout->remoteVersion >= 70300)
9782         {
9783                 char       *name;
9784                 char       *paren;
9785                 bool            inquote;
9786
9787                 name = pg_strdup(proc);
9788                 /* find non-double-quoted left paren */
9789                 inquote = false;
9790                 for (paren = name; *paren; paren++)
9791                 {
9792                         if (*paren == '(' && !inquote)
9793                         {
9794                                 *paren = '\0';
9795                                 break;
9796                         }
9797                         if (*paren == '"')
9798                                 inquote = !inquote;
9799                 }
9800                 return name;
9801         }
9802
9803         /* REGPROC before 7.3 does not quote its result */
9804         return fmtId(proc);
9805 }
9806
9807 /*
9808  * Convert an operator cross-reference obtained from pg_operator
9809  *
9810  * Returns what to print, or NULL to print nothing
9811  *
9812  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9813  * argument-types part, and add OPERATOR() decoration if the name is
9814  * schema-qualified.  In older versions, the input is just a numeric OID,
9815  * which we search our operator list for.
9816  */
9817 static const char *
9818 convertOperatorReference(Archive *fout, const char *opr)
9819 {
9820         OprInfo    *oprInfo;
9821
9822         /* In all cases "0" means a null reference */
9823         if (strcmp(opr, "0") == 0)
9824                 return NULL;
9825
9826         if (fout->remoteVersion >= 70300)
9827         {
9828                 char       *name;
9829                 char       *oname;
9830                 char       *ptr;
9831                 bool            inquote;
9832                 bool            sawdot;
9833
9834                 name = pg_strdup(opr);
9835                 /* find non-double-quoted left paren, and check for non-quoted dot */
9836                 inquote = false;
9837                 sawdot = false;
9838                 for (ptr = name; *ptr; ptr++)
9839                 {
9840                         if (*ptr == '"')
9841                                 inquote = !inquote;
9842                         else if (*ptr == '.' && !inquote)
9843                                 sawdot = true;
9844                         else if (*ptr == '(' && !inquote)
9845                         {
9846                                 *ptr = '\0';
9847                                 break;
9848                         }
9849                 }
9850                 /* If not schema-qualified, don't need to add OPERATOR() */
9851                 if (!sawdot)
9852                         return name;
9853                 oname = pg_malloc(strlen(name) + 11);
9854                 sprintf(oname, "OPERATOR(%s)", name);
9855                 free(name);
9856                 return oname;
9857         }
9858
9859         oprInfo = findOprByOid(atooid(opr));
9860         if (oprInfo == NULL)
9861         {
9862                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9863                                   opr);
9864                 return NULL;
9865         }
9866         return oprInfo->dobj.name;
9867 }
9868
9869 /*
9870  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9871  *
9872  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9873  * argument lists of these functions are predetermined.  Note that the
9874  * caller should ensure we are in the proper schema, because the results
9875  * are search path dependent!
9876  */
9877 static const char *
9878 convertTSFunction(Archive *fout, Oid funcOid)
9879 {
9880         char       *result;
9881         char            query[128];
9882         PGresult   *res;
9883
9884         snprintf(query, sizeof(query),
9885                          "SELECT '%u'::pg_catalog.regproc", funcOid);
9886         res = ExecuteSqlQueryForSingleRow(fout, query);
9887
9888         result = pg_strdup(PQgetvalue(res, 0, 0));
9889
9890         PQclear(res);
9891
9892         return result;
9893 }
9894
9895
9896 /*
9897  * dumpOpclass
9898  *        write out a single operator class definition
9899  */
9900 static void
9901 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9902 {
9903         PQExpBuffer query;
9904         PQExpBuffer q;
9905         PQExpBuffer delq;
9906         PQExpBuffer labelq;
9907         PGresult   *res;
9908         int                     ntups;
9909         int                     i_opcintype;
9910         int                     i_opckeytype;
9911         int                     i_opcdefault;
9912         int                     i_opcfamily;
9913         int                     i_opcfamilyname;
9914         int                     i_opcfamilynsp;
9915         int                     i_amname;
9916         int                     i_amopstrategy;
9917         int                     i_amopreqcheck;
9918         int                     i_amopopr;
9919         int                     i_sortfamily;
9920         int                     i_sortfamilynsp;
9921         int                     i_amprocnum;
9922         int                     i_amproc;
9923         int                     i_amproclefttype;
9924         int                     i_amprocrighttype;
9925         char       *opcintype;
9926         char       *opckeytype;
9927         char       *opcdefault;
9928         char       *opcfamily;
9929         char       *opcfamilyname;
9930         char       *opcfamilynsp;
9931         char       *amname;
9932         char       *amopstrategy;
9933         char       *amopreqcheck;
9934         char       *amopopr;
9935         char       *sortfamily;
9936         char       *sortfamilynsp;
9937         char       *amprocnum;
9938         char       *amproc;
9939         char       *amproclefttype;
9940         char       *amprocrighttype;
9941         bool            needComma;
9942         int                     i;
9943
9944         /* Skip if not to be dumped */
9945         if (!opcinfo->dobj.dump || dataOnly)
9946                 return;
9947
9948         /*
9949          * XXX currently we do not implement dumping of operator classes from
9950          * pre-7.3 databases.  This could be done but it seems not worth the
9951          * trouble.
9952          */
9953         if (fout->remoteVersion < 70300)
9954                 return;
9955
9956         query = createPQExpBuffer();
9957         q = createPQExpBuffer();
9958         delq = createPQExpBuffer();
9959         labelq = createPQExpBuffer();
9960
9961         /* Make sure we are in proper schema so regoperator works correctly */
9962         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9963
9964         /* Get additional fields from the pg_opclass row */
9965         if (fout->remoteVersion >= 80300)
9966         {
9967                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9968                                                   "opckeytype::pg_catalog.regtype, "
9969                                                   "opcdefault, opcfamily, "
9970                                                   "opfname AS opcfamilyname, "
9971                                                   "nspname AS opcfamilynsp, "
9972                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9973                                                   "FROM pg_catalog.pg_opclass c "
9974                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9975                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9976                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
9977                                                   opcinfo->dobj.catId.oid);
9978         }
9979         else
9980         {
9981                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9982                                                   "opckeytype::pg_catalog.regtype, "
9983                                                   "opcdefault, NULL AS opcfamily, "
9984                                                   "NULL AS opcfamilyname, "
9985                                                   "NULL AS opcfamilynsp, "
9986                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9987                                                   "FROM pg_catalog.pg_opclass "
9988                                                   "WHERE oid = '%u'::pg_catalog.oid",
9989                                                   opcinfo->dobj.catId.oid);
9990         }
9991
9992         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9993
9994         i_opcintype = PQfnumber(res, "opcintype");
9995         i_opckeytype = PQfnumber(res, "opckeytype");
9996         i_opcdefault = PQfnumber(res, "opcdefault");
9997         i_opcfamily = PQfnumber(res, "opcfamily");
9998         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9999         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10000         i_amname = PQfnumber(res, "amname");
10001
10002         opcintype = PQgetvalue(res, 0, i_opcintype);
10003         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10004         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10005         /* opcfamily will still be needed after we PQclear res */
10006         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10007         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10008         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10009         /* amname will still be needed after we PQclear res */
10010         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10011
10012         /*
10013          * DROP must be fully qualified in case same name appears in pg_catalog
10014          */
10015         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10016                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10017         appendPQExpBuffer(delq, ".%s",
10018                                           fmtId(opcinfo->dobj.name));
10019         appendPQExpBuffer(delq, " USING %s;\n",
10020                                           fmtId(amname));
10021
10022         /* Build the fixed portion of the CREATE command */
10023         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10024                                           fmtId(opcinfo->dobj.name));
10025         if (strcmp(opcdefault, "t") == 0)
10026                 appendPQExpBuffer(q, "DEFAULT ");
10027         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10028                                           opcintype,
10029                                           fmtId(amname));
10030         if (strlen(opcfamilyname) > 0 &&
10031                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10032                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10033         {
10034                 appendPQExpBuffer(q, " FAMILY ");
10035                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10036                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10037                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10038         }
10039         appendPQExpBuffer(q, " AS\n    ");
10040
10041         needComma = false;
10042
10043         if (strcmp(opckeytype, "-") != 0)
10044         {
10045                 appendPQExpBuffer(q, "STORAGE %s",
10046                                                   opckeytype);
10047                 needComma = true;
10048         }
10049
10050         PQclear(res);
10051
10052         /*
10053          * Now fetch and print the OPERATOR entries (pg_amop rows).
10054          *
10055          * Print only those opfamily members that are tied to the opclass by
10056          * pg_depend entries.
10057          *
10058          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10059          * older server's opclass in which it is used.  This is to avoid
10060          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10061          * older server and then reload into that old version.  This can go away
10062          * once 8.3 is so old as to not be of interest to anyone.
10063          */
10064         resetPQExpBuffer(query);
10065
10066         if (fout->remoteVersion >= 90100)
10067         {
10068                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10069                                                   "amopopr::pg_catalog.regoperator, "
10070                                                   "opfname AS sortfamily, "
10071                                                   "nspname AS sortfamilynsp "
10072                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10073                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10074                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10075                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10076                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10077                                                   "AND refobjid = '%u'::pg_catalog.oid "
10078                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10079                                                   "ORDER BY amopstrategy",
10080                                                   opcinfo->dobj.catId.oid,
10081                                                   opcfamily);
10082         }
10083         else if (fout->remoteVersion >= 80400)
10084         {
10085                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10086                                                   "amopopr::pg_catalog.regoperator, "
10087                                                   "NULL AS sortfamily, "
10088                                                   "NULL AS sortfamilynsp "
10089                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10090                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10091                                                   "AND refobjid = '%u'::pg_catalog.oid "
10092                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10093                                                   "AND objid = ao.oid "
10094                                                   "ORDER BY amopstrategy",
10095                                                   opcinfo->dobj.catId.oid);
10096         }
10097         else if (fout->remoteVersion >= 80300)
10098         {
10099                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10100                                                   "amopopr::pg_catalog.regoperator, "
10101                                                   "NULL AS sortfamily, "
10102                                                   "NULL AS sortfamilynsp "
10103                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10104                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10105                                                   "AND refobjid = '%u'::pg_catalog.oid "
10106                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10107                                                   "AND objid = ao.oid "
10108                                                   "ORDER BY amopstrategy",
10109                                                   opcinfo->dobj.catId.oid);
10110         }
10111         else
10112         {
10113                 /*
10114                  * Here, we print all entries since there are no opfamilies and hence
10115                  * no loose operators to worry about.
10116                  */
10117                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10118                                                   "amopopr::pg_catalog.regoperator, "
10119                                                   "NULL AS sortfamily, "
10120                                                   "NULL AS sortfamilynsp "
10121                                                   "FROM pg_catalog.pg_amop "
10122                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10123                                                   "ORDER BY amopstrategy",
10124                                                   opcinfo->dobj.catId.oid);
10125         }
10126
10127         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10128
10129         ntups = PQntuples(res);
10130
10131         i_amopstrategy = PQfnumber(res, "amopstrategy");
10132         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10133         i_amopopr = PQfnumber(res, "amopopr");
10134         i_sortfamily = PQfnumber(res, "sortfamily");
10135         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10136
10137         for (i = 0; i < ntups; i++)
10138         {
10139                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10140                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10141                 amopopr = PQgetvalue(res, i, i_amopopr);
10142                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10143                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10144
10145                 if (needComma)
10146                         appendPQExpBuffer(q, " ,\n    ");
10147
10148                 appendPQExpBuffer(q, "OPERATOR %s %s",
10149                                                   amopstrategy, amopopr);
10150
10151                 if (strlen(sortfamily) > 0)
10152                 {
10153                         appendPQExpBuffer(q, " FOR ORDER BY ");
10154                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10155                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10156                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10157                 }
10158
10159                 if (strcmp(amopreqcheck, "t") == 0)
10160                         appendPQExpBuffer(q, " RECHECK");
10161
10162                 needComma = true;
10163         }
10164
10165         PQclear(res);
10166
10167         /*
10168          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10169          *
10170          * Print only those opfamily members that are tied to the opclass by
10171          * pg_depend entries.
10172          *
10173          * We print the amproclefttype/amprocrighttype even though in most cases
10174          * the backend could deduce the right values, because of the corner case
10175          * of a btree sort support function for a cross-type comparison.  That's
10176          * only allowed in 9.2 and later, but for simplicity print them in all
10177          * versions that have the columns.
10178          */
10179         resetPQExpBuffer(query);
10180
10181         if (fout->remoteVersion >= 80300)
10182         {
10183                 appendPQExpBuffer(query, "SELECT amprocnum, "
10184                                                   "amproc::pg_catalog.regprocedure, "
10185                                                   "amproclefttype::pg_catalog.regtype, "
10186                                                   "amprocrighttype::pg_catalog.regtype "
10187                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10188                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10189                                                   "AND refobjid = '%u'::pg_catalog.oid "
10190                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10191                                                   "AND objid = ap.oid "
10192                                                   "ORDER BY amprocnum",
10193                                                   opcinfo->dobj.catId.oid);
10194         }
10195         else
10196         {
10197                 appendPQExpBuffer(query, "SELECT amprocnum, "
10198                                                   "amproc::pg_catalog.regprocedure, "
10199                                                   "'' AS amproclefttype, "
10200                                                   "'' AS amprocrighttype "
10201                                                   "FROM pg_catalog.pg_amproc "
10202                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10203                                                   "ORDER BY amprocnum",
10204                                                   opcinfo->dobj.catId.oid);
10205         }
10206
10207         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10208
10209         ntups = PQntuples(res);
10210
10211         i_amprocnum = PQfnumber(res, "amprocnum");
10212         i_amproc = PQfnumber(res, "amproc");
10213         i_amproclefttype = PQfnumber(res, "amproclefttype");
10214         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10215
10216         for (i = 0; i < ntups; i++)
10217         {
10218                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10219                 amproc = PQgetvalue(res, i, i_amproc);
10220                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10221                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10222
10223                 if (needComma)
10224                         appendPQExpBuffer(q, " ,\n    ");
10225
10226                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10227
10228                 if (*amproclefttype && *amprocrighttype)
10229                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10230
10231                 appendPQExpBuffer(q, " %s", amproc);
10232
10233                 needComma = true;
10234         }
10235
10236         PQclear(res);
10237
10238         appendPQExpBuffer(q, ";\n");
10239
10240         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10241                                           fmtId(opcinfo->dobj.name));
10242         appendPQExpBuffer(labelq, " USING %s",
10243                                           fmtId(amname));
10244
10245         if (binary_upgrade)
10246                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10247
10248         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10249                                  opcinfo->dobj.name,
10250                                  opcinfo->dobj.namespace->dobj.name,
10251                                  NULL,
10252                                  opcinfo->rolname,
10253                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10254                                  q->data, delq->data, NULL,
10255                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10256                                  NULL, NULL);
10257
10258         /* Dump Operator Class Comments */
10259         dumpComment(fout, labelq->data,
10260                                 NULL, opcinfo->rolname,
10261                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10262
10263         free(amname);
10264         destroyPQExpBuffer(query);
10265         destroyPQExpBuffer(q);
10266         destroyPQExpBuffer(delq);
10267         destroyPQExpBuffer(labelq);
10268 }
10269
10270 /*
10271  * dumpOpfamily
10272  *        write out a single operator family definition
10273  *
10274  * Note: this also dumps any "loose" operator members that aren't bound to a
10275  * specific opclass within the opfamily.
10276  */
10277 static void
10278 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10279 {
10280         PQExpBuffer query;
10281         PQExpBuffer q;
10282         PQExpBuffer delq;
10283         PQExpBuffer labelq;
10284         PGresult   *res;
10285         PGresult   *res_ops;
10286         PGresult   *res_procs;
10287         int                     ntups;
10288         int                     i_amname;
10289         int                     i_amopstrategy;
10290         int                     i_amopreqcheck;
10291         int                     i_amopopr;
10292         int                     i_sortfamily;
10293         int                     i_sortfamilynsp;
10294         int                     i_amprocnum;
10295         int                     i_amproc;
10296         int                     i_amproclefttype;
10297         int                     i_amprocrighttype;
10298         char       *amname;
10299         char       *amopstrategy;
10300         char       *amopreqcheck;
10301         char       *amopopr;
10302         char       *sortfamily;
10303         char       *sortfamilynsp;
10304         char       *amprocnum;
10305         char       *amproc;
10306         char       *amproclefttype;
10307         char       *amprocrighttype;
10308         bool            needComma;
10309         int                     i;
10310
10311         /* Skip if not to be dumped */
10312         if (!opfinfo->dobj.dump || dataOnly)
10313                 return;
10314
10315         /*
10316          * We want to dump the opfamily only if (1) it contains "loose" operators
10317          * or functions, or (2) it contains an opclass with a different name or
10318          * owner.  Otherwise it's sufficient to let it be created during creation
10319          * of the contained opclass, and not dumping it improves portability of
10320          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10321          * that first.
10322          */
10323
10324         query = createPQExpBuffer();
10325         q = createPQExpBuffer();
10326         delq = createPQExpBuffer();
10327         labelq = createPQExpBuffer();
10328
10329         /* Make sure we are in proper schema so regoperator works correctly */
10330         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10331
10332         /*
10333          * Fetch only those opfamily members that are tied directly to the
10334          * opfamily by pg_depend entries.
10335          *
10336          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10337          * older server's opclass in which it is used.  This is to avoid
10338          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10339          * older server and then reload into that old version.  This can go away
10340          * once 8.3 is so old as to not be of interest to anyone.
10341          */
10342         if (fout->remoteVersion >= 90100)
10343         {
10344                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10345                                                   "amopopr::pg_catalog.regoperator, "
10346                                                   "opfname AS sortfamily, "
10347                                                   "nspname AS sortfamilynsp "
10348                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10349                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10350                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10351                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10352                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10353                                                   "AND refobjid = '%u'::pg_catalog.oid "
10354                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10355                                                   "ORDER BY amopstrategy",
10356                                                   opfinfo->dobj.catId.oid,
10357                                                   opfinfo->dobj.catId.oid);
10358         }
10359         else if (fout->remoteVersion >= 80400)
10360         {
10361                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10362                                                   "amopopr::pg_catalog.regoperator, "
10363                                                   "NULL AS sortfamily, "
10364                                                   "NULL AS sortfamilynsp "
10365                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10366                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10367                                                   "AND refobjid = '%u'::pg_catalog.oid "
10368                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10369                                                   "AND objid = ao.oid "
10370                                                   "ORDER BY amopstrategy",
10371                                                   opfinfo->dobj.catId.oid);
10372         }
10373         else
10374         {
10375                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10376                                                   "amopopr::pg_catalog.regoperator, "
10377                                                   "NULL AS sortfamily, "
10378                                                   "NULL AS sortfamilynsp "
10379                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10380                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10381                                                   "AND refobjid = '%u'::pg_catalog.oid "
10382                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10383                                                   "AND objid = ao.oid "
10384                                                   "ORDER BY amopstrategy",
10385                                                   opfinfo->dobj.catId.oid);
10386         }
10387
10388         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10389
10390         resetPQExpBuffer(query);
10391
10392         appendPQExpBuffer(query, "SELECT amprocnum, "
10393                                           "amproc::pg_catalog.regprocedure, "
10394                                           "amproclefttype::pg_catalog.regtype, "
10395                                           "amprocrighttype::pg_catalog.regtype "
10396                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10397                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10398                                           "AND refobjid = '%u'::pg_catalog.oid "
10399                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10400                                           "AND objid = ap.oid "
10401                                           "ORDER BY amprocnum",
10402                                           opfinfo->dobj.catId.oid);
10403
10404         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10405
10406         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10407         {
10408                 /* No loose members, so check contained opclasses */
10409                 resetPQExpBuffer(query);
10410
10411                 appendPQExpBuffer(query, "SELECT 1 "
10412                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10413                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10414                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10415                                                   "AND refobjid = f.oid "
10416                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10417                                                   "AND objid = c.oid "
10418                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10419                                                   "LIMIT 1",
10420                                                   opfinfo->dobj.catId.oid);
10421
10422                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10423
10424                 if (PQntuples(res) == 0)
10425                 {
10426                         /* no need to dump it, so bail out */
10427                         PQclear(res);
10428                         PQclear(res_ops);
10429                         PQclear(res_procs);
10430                         destroyPQExpBuffer(query);
10431                         destroyPQExpBuffer(q);
10432                         destroyPQExpBuffer(delq);
10433                         destroyPQExpBuffer(labelq);
10434                         return;
10435                 }
10436
10437                 PQclear(res);
10438         }
10439
10440         /* Get additional fields from the pg_opfamily row */
10441         resetPQExpBuffer(query);
10442
10443         appendPQExpBuffer(query, "SELECT "
10444          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10445                                           "FROM pg_catalog.pg_opfamily "
10446                                           "WHERE oid = '%u'::pg_catalog.oid",
10447                                           opfinfo->dobj.catId.oid);
10448
10449         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10450
10451         i_amname = PQfnumber(res, "amname");
10452
10453         /* amname will still be needed after we PQclear res */
10454         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10455
10456         /*
10457          * DROP must be fully qualified in case same name appears in pg_catalog
10458          */
10459         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10460                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10461         appendPQExpBuffer(delq, ".%s",
10462                                           fmtId(opfinfo->dobj.name));
10463         appendPQExpBuffer(delq, " USING %s;\n",
10464                                           fmtId(amname));
10465
10466         /* Build the fixed portion of the CREATE command */
10467         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10468                                           fmtId(opfinfo->dobj.name));
10469         appendPQExpBuffer(q, " USING %s;\n",
10470                                           fmtId(amname));
10471
10472         PQclear(res);
10473
10474         /* Do we need an ALTER to add loose members? */
10475         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10476         {
10477                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10478                                                   fmtId(opfinfo->dobj.name));
10479                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10480                                                   fmtId(amname));
10481
10482                 needComma = false;
10483
10484                 /*
10485                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10486                  */
10487                 ntups = PQntuples(res_ops);
10488
10489                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10490                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10491                 i_amopopr = PQfnumber(res_ops, "amopopr");
10492                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10493                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10494
10495                 for (i = 0; i < ntups; i++)
10496                 {
10497                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10498                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10499                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10500                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10501                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10502
10503                         if (needComma)
10504                                 appendPQExpBuffer(q, " ,\n    ");
10505
10506                         appendPQExpBuffer(q, "OPERATOR %s %s",
10507                                                           amopstrategy, amopopr);
10508
10509                         if (strlen(sortfamily) > 0)
10510                         {
10511                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10512                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10513                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10514                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10515                         }
10516
10517                         if (strcmp(amopreqcheck, "t") == 0)
10518                                 appendPQExpBuffer(q, " RECHECK");
10519
10520                         needComma = true;
10521                 }
10522
10523                 /*
10524                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10525                  */
10526                 ntups = PQntuples(res_procs);
10527
10528                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10529                 i_amproc = PQfnumber(res_procs, "amproc");
10530                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10531                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10532
10533                 for (i = 0; i < ntups; i++)
10534                 {
10535                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10536                         amproc = PQgetvalue(res_procs, i, i_amproc);
10537                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10538                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10539
10540                         if (needComma)
10541                                 appendPQExpBuffer(q, " ,\n    ");
10542
10543                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10544                                                           amprocnum, amproclefttype, amprocrighttype,
10545                                                           amproc);
10546
10547                         needComma = true;
10548                 }
10549
10550                 appendPQExpBuffer(q, ";\n");
10551         }
10552
10553         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10554                                           fmtId(opfinfo->dobj.name));
10555         appendPQExpBuffer(labelq, " USING %s",
10556                                           fmtId(amname));
10557
10558         if (binary_upgrade)
10559                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10560
10561         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10562                                  opfinfo->dobj.name,
10563                                  opfinfo->dobj.namespace->dobj.name,
10564                                  NULL,
10565                                  opfinfo->rolname,
10566                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10567                                  q->data, delq->data, NULL,
10568                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10569                                  NULL, NULL);
10570
10571         /* Dump Operator Family Comments */
10572         dumpComment(fout, labelq->data,
10573                                 NULL, opfinfo->rolname,
10574                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10575
10576         free(amname);
10577         PQclear(res_ops);
10578         PQclear(res_procs);
10579         destroyPQExpBuffer(query);
10580         destroyPQExpBuffer(q);
10581         destroyPQExpBuffer(delq);
10582         destroyPQExpBuffer(labelq);
10583 }
10584
10585 /*
10586  * dumpCollation
10587  *        write out a single collation definition
10588  */
10589 static void
10590 dumpCollation(Archive *fout, CollInfo *collinfo)
10591 {
10592         PQExpBuffer query;
10593         PQExpBuffer q;
10594         PQExpBuffer delq;
10595         PQExpBuffer labelq;
10596         PGresult   *res;
10597         int                     i_collcollate;
10598         int                     i_collctype;
10599         const char *collcollate;
10600         const char *collctype;
10601
10602         /* Skip if not to be dumped */
10603         if (!collinfo->dobj.dump || dataOnly)
10604                 return;
10605
10606         query = createPQExpBuffer();
10607         q = createPQExpBuffer();
10608         delq = createPQExpBuffer();
10609         labelq = createPQExpBuffer();
10610
10611         /* Make sure we are in proper schema */
10612         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10613
10614         /* Get conversion-specific details */
10615         appendPQExpBuffer(query, "SELECT "
10616                                           "collcollate, "
10617                                           "collctype "
10618                                           "FROM pg_catalog.pg_collation c "
10619                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10620                                           collinfo->dobj.catId.oid);
10621
10622         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10623
10624         i_collcollate = PQfnumber(res, "collcollate");
10625         i_collctype = PQfnumber(res, "collctype");
10626
10627         collcollate = PQgetvalue(res, 0, i_collcollate);
10628         collctype = PQgetvalue(res, 0, i_collctype);
10629
10630         /*
10631          * DROP must be fully qualified in case same name appears in pg_catalog
10632          */
10633         appendPQExpBuffer(delq, "DROP COLLATION %s",
10634                                           fmtId(collinfo->dobj.namespace->dobj.name));
10635         appendPQExpBuffer(delq, ".%s;\n",
10636                                           fmtId(collinfo->dobj.name));
10637
10638         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10639                                           fmtId(collinfo->dobj.name));
10640         appendStringLiteralAH(q, collcollate, fout);
10641         appendPQExpBuffer(q, ", lc_ctype = ");
10642         appendStringLiteralAH(q, collctype, fout);
10643         appendPQExpBuffer(q, ");\n");
10644
10645         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10646
10647         if (binary_upgrade)
10648                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10649
10650         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10651                                  collinfo->dobj.name,
10652                                  collinfo->dobj.namespace->dobj.name,
10653                                  NULL,
10654                                  collinfo->rolname,
10655                                  false, "COLLATION", SECTION_PRE_DATA,
10656                                  q->data, delq->data, NULL,
10657                                  collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10658                                  NULL, NULL);
10659
10660         /* Dump Collation Comments */
10661         dumpComment(fout, labelq->data,
10662                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10663                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10664
10665         PQclear(res);
10666
10667         destroyPQExpBuffer(query);
10668         destroyPQExpBuffer(q);
10669         destroyPQExpBuffer(delq);
10670         destroyPQExpBuffer(labelq);
10671 }
10672
10673 /*
10674  * dumpConversion
10675  *        write out a single conversion definition
10676  */
10677 static void
10678 dumpConversion(Archive *fout, ConvInfo *convinfo)
10679 {
10680         PQExpBuffer query;
10681         PQExpBuffer q;
10682         PQExpBuffer delq;
10683         PQExpBuffer labelq;
10684         PGresult   *res;
10685         int                     i_conforencoding;
10686         int                     i_contoencoding;
10687         int                     i_conproc;
10688         int                     i_condefault;
10689         const char *conforencoding;
10690         const char *contoencoding;
10691         const char *conproc;
10692         bool            condefault;
10693
10694         /* Skip if not to be dumped */
10695         if (!convinfo->dobj.dump || dataOnly)
10696                 return;
10697
10698         query = createPQExpBuffer();
10699         q = createPQExpBuffer();
10700         delq = createPQExpBuffer();
10701         labelq = createPQExpBuffer();
10702
10703         /* Make sure we are in proper schema */
10704         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10705
10706         /* Get conversion-specific details */
10707         appendPQExpBuffer(query, "SELECT "
10708                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10709                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10710                                           "conproc, condefault "
10711                                           "FROM pg_catalog.pg_conversion c "
10712                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10713                                           convinfo->dobj.catId.oid);
10714
10715         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10716
10717         i_conforencoding = PQfnumber(res, "conforencoding");
10718         i_contoencoding = PQfnumber(res, "contoencoding");
10719         i_conproc = PQfnumber(res, "conproc");
10720         i_condefault = PQfnumber(res, "condefault");
10721
10722         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10723         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10724         conproc = PQgetvalue(res, 0, i_conproc);
10725         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10726
10727         /*
10728          * DROP must be fully qualified in case same name appears in pg_catalog
10729          */
10730         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10731                                           fmtId(convinfo->dobj.namespace->dobj.name));
10732         appendPQExpBuffer(delq, ".%s;\n",
10733                                           fmtId(convinfo->dobj.name));
10734
10735         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10736                                           (condefault) ? "DEFAULT " : "",
10737                                           fmtId(convinfo->dobj.name));
10738         appendStringLiteralAH(q, conforencoding, fout);
10739         appendPQExpBuffer(q, " TO ");
10740         appendStringLiteralAH(q, contoencoding, fout);
10741         /* regproc is automatically quoted in 7.3 and above */
10742         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10743
10744         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10745
10746         if (binary_upgrade)
10747                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10748
10749         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10750                                  convinfo->dobj.name,
10751                                  convinfo->dobj.namespace->dobj.name,
10752                                  NULL,
10753                                  convinfo->rolname,
10754                                  false, "CONVERSION", SECTION_PRE_DATA,
10755                                  q->data, delq->data, NULL,
10756                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10757                                  NULL, NULL);
10758
10759         /* Dump Conversion Comments */
10760         dumpComment(fout, labelq->data,
10761                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10762                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10763
10764         PQclear(res);
10765
10766         destroyPQExpBuffer(query);
10767         destroyPQExpBuffer(q);
10768         destroyPQExpBuffer(delq);
10769         destroyPQExpBuffer(labelq);
10770 }
10771
10772 /*
10773  * format_aggregate_signature: generate aggregate name and argument list
10774  *
10775  * The argument type names are qualified if needed.  The aggregate name
10776  * is never qualified.
10777  */
10778 static char *
10779 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10780 {
10781         PQExpBufferData buf;
10782         int                     j;
10783
10784         initPQExpBuffer(&buf);
10785         if (honor_quotes)
10786                 appendPQExpBuffer(&buf, "%s",
10787                                                   fmtId(agginfo->aggfn.dobj.name));
10788         else
10789                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10790
10791         if (agginfo->aggfn.nargs == 0)
10792                 appendPQExpBuffer(&buf, "(*)");
10793         else
10794         {
10795                 appendPQExpBuffer(&buf, "(");
10796                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10797                 {
10798                         char       *typname;
10799
10800                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10801                                                                                    zeroAsOpaque);
10802
10803                         appendPQExpBuffer(&buf, "%s%s",
10804                                                           (j > 0) ? ", " : "",
10805                                                           typname);
10806                         free(typname);
10807                 }
10808                 appendPQExpBuffer(&buf, ")");
10809         }
10810         return buf.data;
10811 }
10812
10813 /*
10814  * dumpAgg
10815  *        write out a single aggregate definition
10816  */
10817 static void
10818 dumpAgg(Archive *fout, AggInfo *agginfo)
10819 {
10820         PQExpBuffer query;
10821         PQExpBuffer q;
10822         PQExpBuffer delq;
10823         PQExpBuffer labelq;
10824         PQExpBuffer details;
10825         char       *aggsig;
10826         char       *aggsig_tag;
10827         PGresult   *res;
10828         int                     i_aggtransfn;
10829         int                     i_aggfinalfn;
10830         int                     i_aggsortop;
10831         int                     i_aggtranstype;
10832         int                     i_agginitval;
10833         int                     i_convertok;
10834         const char *aggtransfn;
10835         const char *aggfinalfn;
10836         const char *aggsortop;
10837         const char *aggtranstype;
10838         const char *agginitval;
10839         bool            convertok;
10840
10841         /* Skip if not to be dumped */
10842         if (!agginfo->aggfn.dobj.dump || dataOnly)
10843                 return;
10844
10845         query = createPQExpBuffer();
10846         q = createPQExpBuffer();
10847         delq = createPQExpBuffer();
10848         labelq = createPQExpBuffer();
10849         details = createPQExpBuffer();
10850
10851         /* Make sure we are in proper schema */
10852         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10853
10854         /* Get aggregate-specific details */
10855         if (fout->remoteVersion >= 80100)
10856         {
10857                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10858                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10859                                                   "aggsortop::pg_catalog.regoperator, "
10860                                                   "agginitval, "
10861                                                   "'t'::boolean AS convertok "
10862                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10863                                                   "WHERE a.aggfnoid = p.oid "
10864                                                   "AND p.oid = '%u'::pg_catalog.oid",
10865                                                   agginfo->aggfn.dobj.catId.oid);
10866         }
10867         else if (fout->remoteVersion >= 70300)
10868         {
10869                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10870                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10871                                                   "0 AS aggsortop, "
10872                                                   "agginitval, "
10873                                                   "'t'::boolean AS convertok "
10874                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10875                                                   "WHERE a.aggfnoid = p.oid "
10876                                                   "AND p.oid = '%u'::pg_catalog.oid",
10877                                                   agginfo->aggfn.dobj.catId.oid);
10878         }
10879         else if (fout->remoteVersion >= 70100)
10880         {
10881                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10882                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
10883                                                   "0 AS aggsortop, "
10884                                                   "agginitval, "
10885                                                   "'t'::boolean AS convertok "
10886                                                   "FROM pg_aggregate "
10887                                                   "WHERE oid = '%u'::oid",
10888                                                   agginfo->aggfn.dobj.catId.oid);
10889         }
10890         else
10891         {
10892                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10893                                                   "aggfinalfn, "
10894                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10895                                                   "0 AS aggsortop, "
10896                                                   "agginitval1 AS agginitval, "
10897                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10898                                                   "FROM pg_aggregate "
10899                                                   "WHERE oid = '%u'::oid",
10900                                                   agginfo->aggfn.dobj.catId.oid);
10901         }
10902
10903         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10904
10905         i_aggtransfn = PQfnumber(res, "aggtransfn");
10906         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10907         i_aggsortop = PQfnumber(res, "aggsortop");
10908         i_aggtranstype = PQfnumber(res, "aggtranstype");
10909         i_agginitval = PQfnumber(res, "agginitval");
10910         i_convertok = PQfnumber(res, "convertok");
10911
10912         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10913         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10914         aggsortop = PQgetvalue(res, 0, i_aggsortop);
10915         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10916         agginitval = PQgetvalue(res, 0, i_agginitval);
10917         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10918
10919         aggsig = format_aggregate_signature(agginfo, fout, true);
10920         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10921
10922         if (!convertok)
10923         {
10924                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10925                                   aggsig);
10926                 return;
10927         }
10928
10929         if (fout->remoteVersion >= 70300)
10930         {
10931                 /* If using 7.3's regproc or regtype, data is already quoted */
10932                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10933                                                   aggtransfn,
10934                                                   aggtranstype);
10935         }
10936         else if (fout->remoteVersion >= 70100)
10937         {
10938                 /* format_type quotes, regproc does not */
10939                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10940                                                   fmtId(aggtransfn),
10941                                                   aggtranstype);
10942         }
10943         else
10944         {
10945                 /* need quotes all around */
10946                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
10947                                                   fmtId(aggtransfn));
10948                 appendPQExpBuffer(details, "    STYPE = %s",
10949                                                   fmtId(aggtranstype));
10950         }
10951
10952         if (!PQgetisnull(res, 0, i_agginitval))
10953         {
10954                 appendPQExpBuffer(details, ",\n    INITCOND = ");
10955                 appendStringLiteralAH(details, agginitval, fout);
10956         }
10957
10958         if (strcmp(aggfinalfn, "-") != 0)
10959         {
10960                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
10961                                                   aggfinalfn);
10962         }
10963
10964         aggsortop = convertOperatorReference(fout, aggsortop);
10965         if (aggsortop)
10966         {
10967                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
10968                                                   aggsortop);
10969         }
10970
10971         /*
10972          * DROP must be fully qualified in case same name appears in pg_catalog
10973          */
10974         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10975                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10976                                           aggsig);
10977
10978         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10979                                           aggsig, details->data);
10980
10981         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10982
10983         if (binary_upgrade)
10984                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10985
10986         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10987                                  aggsig_tag,
10988                                  agginfo->aggfn.dobj.namespace->dobj.name,
10989                                  NULL,
10990                                  agginfo->aggfn.rolname,
10991                                  false, "AGGREGATE", SECTION_PRE_DATA,
10992                                  q->data, delq->data, NULL,
10993                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10994                                  NULL, NULL);
10995
10996         /* Dump Aggregate Comments */
10997         dumpComment(fout, labelq->data,
10998                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10999                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11000         dumpSecLabel(fout, labelq->data,
11001                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11002                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11003
11004         /*
11005          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11006          * command look like a function's GRANT; in particular this affects the
11007          * syntax for zero-argument aggregates.
11008          */
11009         free(aggsig);
11010         free(aggsig_tag);
11011
11012         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11013         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11014
11015         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11016                         "FUNCTION",
11017                         aggsig, NULL, aggsig_tag,
11018                         agginfo->aggfn.dobj.namespace->dobj.name,
11019                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11020
11021         free(aggsig);
11022         free(aggsig_tag);
11023
11024         PQclear(res);
11025
11026         destroyPQExpBuffer(query);
11027         destroyPQExpBuffer(q);
11028         destroyPQExpBuffer(delq);
11029         destroyPQExpBuffer(labelq);
11030         destroyPQExpBuffer(details);
11031 }
11032
11033 /*
11034  * dumpTSParser
11035  *        write out a single text search parser
11036  */
11037 static void
11038 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11039 {
11040         PQExpBuffer q;
11041         PQExpBuffer delq;
11042         PQExpBuffer labelq;
11043
11044         /* Skip if not to be dumped */
11045         if (!prsinfo->dobj.dump || dataOnly)
11046                 return;
11047
11048         q = createPQExpBuffer();
11049         delq = createPQExpBuffer();
11050         labelq = createPQExpBuffer();
11051
11052         /* Make sure we are in proper schema */
11053         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11054
11055         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11056                                           fmtId(prsinfo->dobj.name));
11057
11058         appendPQExpBuffer(q, "    START = %s,\n",
11059                                           convertTSFunction(fout, prsinfo->prsstart));
11060         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11061                                           convertTSFunction(fout, prsinfo->prstoken));
11062         appendPQExpBuffer(q, "    END = %s,\n",
11063                                           convertTSFunction(fout, prsinfo->prsend));
11064         if (prsinfo->prsheadline != InvalidOid)
11065                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11066                                                   convertTSFunction(fout, prsinfo->prsheadline));
11067         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11068                                           convertTSFunction(fout, prsinfo->prslextype));
11069
11070         /*
11071          * DROP must be fully qualified in case same name appears in pg_catalog
11072          */
11073         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11074                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11075         appendPQExpBuffer(delq, ".%s;\n",
11076                                           fmtId(prsinfo->dobj.name));
11077
11078         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11079                                           fmtId(prsinfo->dobj.name));
11080
11081         if (binary_upgrade)
11082                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11083
11084         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11085                                  prsinfo->dobj.name,
11086                                  prsinfo->dobj.namespace->dobj.name,
11087                                  NULL,
11088                                  "",
11089                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11090                                  q->data, delq->data, NULL,
11091                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11092                                  NULL, NULL);
11093
11094         /* Dump Parser Comments */
11095         dumpComment(fout, labelq->data,
11096                                 NULL, "",
11097                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11098
11099         destroyPQExpBuffer(q);
11100         destroyPQExpBuffer(delq);
11101         destroyPQExpBuffer(labelq);
11102 }
11103
11104 /*
11105  * dumpTSDictionary
11106  *        write out a single text search dictionary
11107  */
11108 static void
11109 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11110 {
11111         PQExpBuffer q;
11112         PQExpBuffer delq;
11113         PQExpBuffer labelq;
11114         PQExpBuffer query;
11115         PGresult   *res;
11116         char       *nspname;
11117         char       *tmplname;
11118
11119         /* Skip if not to be dumped */
11120         if (!dictinfo->dobj.dump || dataOnly)
11121                 return;
11122
11123         q = createPQExpBuffer();
11124         delq = createPQExpBuffer();
11125         labelq = createPQExpBuffer();
11126         query = createPQExpBuffer();
11127
11128         /* Fetch name and namespace of the dictionary's template */
11129         selectSourceSchema(fout, "pg_catalog");
11130         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11131                                           "FROM pg_ts_template p, pg_namespace n "
11132                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11133                                           dictinfo->dicttemplate);
11134         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11135         nspname = PQgetvalue(res, 0, 0);
11136         tmplname = PQgetvalue(res, 0, 1);
11137
11138         /* Make sure we are in proper schema */
11139         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11140
11141         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11142                                           fmtId(dictinfo->dobj.name));
11143
11144         appendPQExpBuffer(q, "    TEMPLATE = ");
11145         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11146                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11147         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11148
11149         PQclear(res);
11150
11151         /* the dictinitoption can be dumped straight into the command */
11152         if (dictinfo->dictinitoption)
11153                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11154
11155         appendPQExpBuffer(q, " );\n");
11156
11157         /*
11158          * DROP must be fully qualified in case same name appears in pg_catalog
11159          */
11160         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11161                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11162         appendPQExpBuffer(delq, ".%s;\n",
11163                                           fmtId(dictinfo->dobj.name));
11164
11165         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11166                                           fmtId(dictinfo->dobj.name));
11167
11168         if (binary_upgrade)
11169                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11170
11171         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11172                                  dictinfo->dobj.name,
11173                                  dictinfo->dobj.namespace->dobj.name,
11174                                  NULL,
11175                                  dictinfo->rolname,
11176                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11177                                  q->data, delq->data, NULL,
11178                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11179                                  NULL, NULL);
11180
11181         /* Dump Dictionary Comments */
11182         dumpComment(fout, labelq->data,
11183                                 NULL, dictinfo->rolname,
11184                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11185
11186         destroyPQExpBuffer(q);
11187         destroyPQExpBuffer(delq);
11188         destroyPQExpBuffer(labelq);
11189         destroyPQExpBuffer(query);
11190 }
11191
11192 /*
11193  * dumpTSTemplate
11194  *        write out a single text search template
11195  */
11196 static void
11197 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11198 {
11199         PQExpBuffer q;
11200         PQExpBuffer delq;
11201         PQExpBuffer labelq;
11202
11203         /* Skip if not to be dumped */
11204         if (!tmplinfo->dobj.dump || dataOnly)
11205                 return;
11206
11207         q = createPQExpBuffer();
11208         delq = createPQExpBuffer();
11209         labelq = createPQExpBuffer();
11210
11211         /* Make sure we are in proper schema */
11212         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11213
11214         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11215                                           fmtId(tmplinfo->dobj.name));
11216
11217         if (tmplinfo->tmplinit != InvalidOid)
11218                 appendPQExpBuffer(q, "    INIT = %s,\n",
11219                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11220         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11221                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11222
11223         /*
11224          * DROP must be fully qualified in case same name appears in pg_catalog
11225          */
11226         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11227                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11228         appendPQExpBuffer(delq, ".%s;\n",
11229                                           fmtId(tmplinfo->dobj.name));
11230
11231         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11232                                           fmtId(tmplinfo->dobj.name));
11233
11234         if (binary_upgrade)
11235                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11236
11237         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11238                                  tmplinfo->dobj.name,
11239                                  tmplinfo->dobj.namespace->dobj.name,
11240                                  NULL,
11241                                  "",
11242                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11243                                  q->data, delq->data, NULL,
11244                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11245                                  NULL, NULL);
11246
11247         /* Dump Template Comments */
11248         dumpComment(fout, labelq->data,
11249                                 NULL, "",
11250                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11251
11252         destroyPQExpBuffer(q);
11253         destroyPQExpBuffer(delq);
11254         destroyPQExpBuffer(labelq);
11255 }
11256
11257 /*
11258  * dumpTSConfig
11259  *        write out a single text search configuration
11260  */
11261 static void
11262 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11263 {
11264         PQExpBuffer q;
11265         PQExpBuffer delq;
11266         PQExpBuffer labelq;
11267         PQExpBuffer query;
11268         PGresult   *res;
11269         char       *nspname;
11270         char       *prsname;
11271         int                     ntups,
11272                                 i;
11273         int                     i_tokenname;
11274         int                     i_dictname;
11275
11276         /* Skip if not to be dumped */
11277         if (!cfginfo->dobj.dump || dataOnly)
11278                 return;
11279
11280         q = createPQExpBuffer();
11281         delq = createPQExpBuffer();
11282         labelq = createPQExpBuffer();
11283         query = createPQExpBuffer();
11284
11285         /* Fetch name and namespace of the config's parser */
11286         selectSourceSchema(fout, "pg_catalog");
11287         appendPQExpBuffer(query, "SELECT nspname, prsname "
11288                                           "FROM pg_ts_parser p, pg_namespace n "
11289                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11290                                           cfginfo->cfgparser);
11291         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11292         nspname = PQgetvalue(res, 0, 0);
11293         prsname = PQgetvalue(res, 0, 1);
11294
11295         /* Make sure we are in proper schema */
11296         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11297
11298         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11299                                           fmtId(cfginfo->dobj.name));
11300
11301         appendPQExpBuffer(q, "    PARSER = ");
11302         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11303                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11304         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11305
11306         PQclear(res);
11307
11308         resetPQExpBuffer(query);
11309         appendPQExpBuffer(query,
11310                                           "SELECT \n"
11311                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11312                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11313                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11314                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11315                                           "WHERE m.mapcfg = '%u' \n"
11316                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11317                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11318
11319         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11320         ntups = PQntuples(res);
11321
11322         i_tokenname = PQfnumber(res, "tokenname");
11323         i_dictname = PQfnumber(res, "dictname");
11324
11325         for (i = 0; i < ntups; i++)
11326         {
11327                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11328                 char       *dictname = PQgetvalue(res, i, i_dictname);
11329
11330                 if (i == 0 ||
11331                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11332                 {
11333                         /* starting a new token type, so start a new command */
11334                         if (i > 0)
11335                                 appendPQExpBuffer(q, ";\n");
11336                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11337                                                           fmtId(cfginfo->dobj.name));
11338                         /* tokenname needs quoting, dictname does NOT */
11339                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11340                                                           fmtId(tokenname), dictname);
11341                 }
11342                 else
11343                         appendPQExpBuffer(q, ", %s", dictname);
11344         }
11345
11346         if (ntups > 0)
11347                 appendPQExpBuffer(q, ";\n");
11348
11349         PQclear(res);
11350
11351         /*
11352          * DROP must be fully qualified in case same name appears in pg_catalog
11353          */
11354         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11355                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11356         appendPQExpBuffer(delq, ".%s;\n",
11357                                           fmtId(cfginfo->dobj.name));
11358
11359         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11360                                           fmtId(cfginfo->dobj.name));
11361
11362         if (binary_upgrade)
11363                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11364
11365         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11366                                  cfginfo->dobj.name,
11367                                  cfginfo->dobj.namespace->dobj.name,
11368                                  NULL,
11369                                  cfginfo->rolname,
11370                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11371                                  q->data, delq->data, NULL,
11372                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11373                                  NULL, NULL);
11374
11375         /* Dump Configuration Comments */
11376         dumpComment(fout, labelq->data,
11377                                 NULL, cfginfo->rolname,
11378                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11379
11380         destroyPQExpBuffer(q);
11381         destroyPQExpBuffer(delq);
11382         destroyPQExpBuffer(labelq);
11383         destroyPQExpBuffer(query);
11384 }
11385
11386 /*
11387  * dumpForeignDataWrapper
11388  *        write out a single foreign-data wrapper definition
11389  */
11390 static void
11391 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11392 {
11393         PQExpBuffer q;
11394         PQExpBuffer delq;
11395         PQExpBuffer labelq;
11396         char       *qfdwname;
11397
11398         /* Skip if not to be dumped */
11399         if (!fdwinfo->dobj.dump || dataOnly)
11400                 return;
11401
11402         /*
11403          * FDWs that belong to an extension are dumped based on their "dump"
11404          * field. Otherwise omit them if we are only dumping some specific object.
11405          */
11406         if (!fdwinfo->dobj.ext_member)
11407                 if (!include_everything)
11408                         return;
11409
11410         q = createPQExpBuffer();
11411         delq = createPQExpBuffer();
11412         labelq = createPQExpBuffer();
11413
11414         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11415
11416         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11417                                           qfdwname);
11418
11419         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11420                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11421
11422         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11423                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11424
11425         if (strlen(fdwinfo->fdwoptions) > 0)
11426                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11427
11428         appendPQExpBuffer(q, ";\n");
11429
11430         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11431                                           qfdwname);
11432
11433         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11434                                           qfdwname);
11435
11436         if (binary_upgrade)
11437                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11438
11439         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11440                                  fdwinfo->dobj.name,
11441                                  NULL,
11442                                  NULL,
11443                                  fdwinfo->rolname,
11444                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11445                                  q->data, delq->data, NULL,
11446                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11447                                  NULL, NULL);
11448
11449         /* Handle the ACL */
11450         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11451                         "FOREIGN DATA WRAPPER",
11452                         qfdwname, NULL, fdwinfo->dobj.name,
11453                         NULL, fdwinfo->rolname,
11454                         fdwinfo->fdwacl);
11455
11456         /* Dump Foreign Data Wrapper Comments */
11457         dumpComment(fout, labelq->data,
11458                                 NULL, fdwinfo->rolname,
11459                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11460
11461         free(qfdwname);
11462
11463         destroyPQExpBuffer(q);
11464         destroyPQExpBuffer(delq);
11465         destroyPQExpBuffer(labelq);
11466 }
11467
11468 /*
11469  * dumpForeignServer
11470  *        write out a foreign server definition
11471  */
11472 static void
11473 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11474 {
11475         PQExpBuffer q;
11476         PQExpBuffer delq;
11477         PQExpBuffer labelq;
11478         PQExpBuffer query;
11479         PGresult   *res;
11480         char       *qsrvname;
11481         char       *fdwname;
11482
11483         /* Skip if not to be dumped */
11484         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11485                 return;
11486
11487         q = createPQExpBuffer();
11488         delq = createPQExpBuffer();
11489         labelq = createPQExpBuffer();
11490         query = createPQExpBuffer();
11491
11492         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11493
11494         /* look up the foreign-data wrapper */
11495         selectSourceSchema(fout, "pg_catalog");
11496         appendPQExpBuffer(query, "SELECT fdwname "
11497                                           "FROM pg_foreign_data_wrapper w "
11498                                           "WHERE w.oid = '%u'",
11499                                           srvinfo->srvfdw);
11500         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11501         fdwname = PQgetvalue(res, 0, 0);
11502
11503         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11504         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11505         {
11506                 appendPQExpBuffer(q, " TYPE ");
11507                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11508         }
11509         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11510         {
11511                 appendPQExpBuffer(q, " VERSION ");
11512                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11513         }
11514
11515         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11516         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11517
11518         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11519                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11520
11521         appendPQExpBuffer(q, ";\n");
11522
11523         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11524                                           qsrvname);
11525
11526         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11527
11528         if (binary_upgrade)
11529                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11530
11531         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11532                                  srvinfo->dobj.name,
11533                                  NULL,
11534                                  NULL,
11535                                  srvinfo->rolname,
11536                                  false, "SERVER", SECTION_PRE_DATA,
11537                                  q->data, delq->data, NULL,
11538                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11539                                  NULL, NULL);
11540
11541         /* Handle the ACL */
11542         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11543                         "FOREIGN SERVER",
11544                         qsrvname, NULL, srvinfo->dobj.name,
11545                         NULL, srvinfo->rolname,
11546                         srvinfo->srvacl);
11547
11548         /* Dump user mappings */
11549         dumpUserMappings(fout,
11550                                          srvinfo->dobj.name, NULL,
11551                                          srvinfo->rolname,
11552                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11553
11554         /* Dump Foreign Server Comments */
11555         dumpComment(fout, labelq->data,
11556                                 NULL, srvinfo->rolname,
11557                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11558
11559         free(qsrvname);
11560
11561         destroyPQExpBuffer(q);
11562         destroyPQExpBuffer(delq);
11563         destroyPQExpBuffer(labelq);
11564 }
11565
11566 /*
11567  * dumpUserMappings
11568  *
11569  * This routine is used to dump any user mappings associated with the
11570  * server handed to this routine. Should be called after ArchiveEntry()
11571  * for the server.
11572  */
11573 static void
11574 dumpUserMappings(Archive *fout,
11575                                  const char *servername, const char *namespace,
11576                                  const char *owner,
11577                                  CatalogId catalogId, DumpId dumpId)
11578 {
11579         PQExpBuffer q;
11580         PQExpBuffer delq;
11581         PQExpBuffer query;
11582         PQExpBuffer tag;
11583         PGresult   *res;
11584         int                     ntups;
11585         int                     i_usename;
11586         int                     i_umoptions;
11587         int                     i;
11588
11589         q = createPQExpBuffer();
11590         tag = createPQExpBuffer();
11591         delq = createPQExpBuffer();
11592         query = createPQExpBuffer();
11593
11594         /*
11595          * We read from the publicly accessible view pg_user_mappings, so as not
11596          * to fail if run by a non-superuser.  Note that the view will show
11597          * umoptions as null if the user hasn't got privileges for the associated
11598          * server; this means that pg_dump will dump such a mapping, but with no
11599          * OPTIONS clause.      A possible alternative is to skip such mappings
11600          * altogether, but it's not clear that that's an improvement.
11601          */
11602         selectSourceSchema(fout, "pg_catalog");
11603
11604         appendPQExpBuffer(query,
11605                                           "SELECT usename, "
11606                                           "array_to_string(ARRAY("
11607                                           "SELECT quote_ident(option_name) || ' ' || "
11608                                           "quote_literal(option_value) "
11609                                           "FROM pg_options_to_table(umoptions) "
11610                                           "ORDER BY option_name"
11611                                           "), E',\n    ') AS umoptions "
11612                                           "FROM pg_user_mappings "
11613                                           "WHERE srvid = '%u' "
11614                                           "ORDER BY usename",
11615                                           catalogId.oid);
11616
11617         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11618
11619         ntups = PQntuples(res);
11620         i_usename = PQfnumber(res, "usename");
11621         i_umoptions = PQfnumber(res, "umoptions");
11622
11623         for (i = 0; i < ntups; i++)
11624         {
11625                 char       *usename;
11626                 char       *umoptions;
11627
11628                 usename = PQgetvalue(res, i, i_usename);
11629                 umoptions = PQgetvalue(res, i, i_umoptions);
11630
11631                 resetPQExpBuffer(q);
11632                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11633                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11634
11635                 if (umoptions && strlen(umoptions) > 0)
11636                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11637
11638                 appendPQExpBuffer(q, ";\n");
11639
11640                 resetPQExpBuffer(delq);
11641                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11642                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11643
11644                 resetPQExpBuffer(tag);
11645                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11646                                                   usename, servername);
11647
11648                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11649                                          tag->data,
11650                                          namespace,
11651                                          NULL,
11652                                          owner, false,
11653                                          "USER MAPPING", SECTION_PRE_DATA,
11654                                          q->data, delq->data, NULL,
11655                                          &dumpId, 1,
11656                                          NULL, NULL);
11657         }
11658
11659         PQclear(res);
11660
11661         destroyPQExpBuffer(query);
11662         destroyPQExpBuffer(delq);
11663         destroyPQExpBuffer(q);
11664 }
11665
11666 /*
11667  * Write out default privileges information
11668  */
11669 static void
11670 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11671 {
11672         PQExpBuffer q;
11673         PQExpBuffer tag;
11674         const char *type;
11675
11676         /* Skip if not to be dumped */
11677         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11678                 return;
11679
11680         q = createPQExpBuffer();
11681         tag = createPQExpBuffer();
11682
11683         switch (daclinfo->defaclobjtype)
11684         {
11685                 case DEFACLOBJ_RELATION:
11686                         type = "TABLES";
11687                         break;
11688                 case DEFACLOBJ_SEQUENCE:
11689                         type = "SEQUENCES";
11690                         break;
11691                 case DEFACLOBJ_FUNCTION:
11692                         type = "FUNCTIONS";
11693                         break;
11694                 default:
11695                         /* shouldn't get here */
11696                         exit_horribly(NULL,
11697                                                   "unknown object type (%d) in default privileges\n",
11698                                                   (int) daclinfo->defaclobjtype);
11699                         type = "";                      /* keep compiler quiet */
11700         }
11701
11702         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11703
11704         /* build the actual command(s) for this tuple */
11705         if (!buildDefaultACLCommands(type,
11706                                                                  daclinfo->dobj.namespace != NULL ?
11707                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11708                                                                  daclinfo->defaclacl,
11709                                                                  daclinfo->defaclrole,
11710                                                                  fout->remoteVersion,
11711                                                                  q))
11712                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11713                                           daclinfo->defaclacl);
11714
11715         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11716                                  tag->data,
11717            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11718                                  NULL,
11719                                  daclinfo->defaclrole,
11720                                  false, "DEFAULT ACL", SECTION_NONE,
11721                                  q->data, "", NULL,
11722                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11723                                  NULL, NULL);
11724
11725         destroyPQExpBuffer(tag);
11726         destroyPQExpBuffer(q);
11727 }
11728
11729 /*----------
11730  * Write out grant/revoke information
11731  *
11732  * 'objCatId' is the catalog ID of the underlying object.
11733  * 'objDumpId' is the dump ID of the underlying object.
11734  * 'type' must be one of
11735  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11736  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11737  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11738  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11739  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11740  * 'nspname' is the namespace the object is in (NULL if none).
11741  * 'owner' is the owner, NULL if there is no owner (for languages).
11742  * 'acls' is the string read out of the fooacl system catalog field;
11743  *              it will be parsed here.
11744  *----------
11745  */
11746 static void
11747 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11748                 const char *type, const char *name, const char *subname,
11749                 const char *tag, const char *nspname, const char *owner,
11750                 const char *acls)
11751 {
11752         PQExpBuffer sql;
11753
11754         /* Do nothing if ACL dump is not enabled */
11755         if (aclsSkip)
11756                 return;
11757
11758         /* --data-only skips ACLs *except* BLOB ACLs */
11759         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11760                 return;
11761
11762         sql = createPQExpBuffer();
11763
11764         if (!buildACLCommands(name, subname, type, acls, owner,
11765                                                   "", fout->remoteVersion, sql))
11766                 exit_horribly(NULL,
11767                                           "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11768                                           acls, name, type);
11769
11770         if (sql->len > 0)
11771                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11772                                          tag, nspname,
11773                                          NULL,
11774                                          owner ? owner : "",
11775                                          false, "ACL", SECTION_NONE,
11776                                          sql->data, "", NULL,
11777                                          &(objDumpId), 1,
11778                                          NULL, NULL);
11779
11780         destroyPQExpBuffer(sql);
11781 }
11782
11783 /*
11784  * dumpSecLabel
11785  *
11786  * This routine is used to dump any security labels associated with the
11787  * object handed to this routine. The routine takes a constant character
11788  * string for the target part of the security-label command, plus
11789  * the namespace and owner of the object (for labeling the ArchiveEntry),
11790  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11791  * plus the dump ID for the object (for setting a dependency).
11792  * If a matching pg_seclabel entry is found, it is dumped.
11793  *
11794  * Note: although this routine takes a dumpId for dependency purposes,
11795  * that purpose is just to mark the dependency in the emitted dump file
11796  * for possible future use by pg_restore.  We do NOT use it for determining
11797  * ordering of the label in the dump file, because this routine is called
11798  * after dependency sorting occurs.  This routine should be called just after
11799  * calling ArchiveEntry() for the specified object.
11800  */
11801 static void
11802 dumpSecLabel(Archive *fout, const char *target,
11803                          const char *namespace, const char *owner,
11804                          CatalogId catalogId, int subid, DumpId dumpId)
11805 {
11806         SecLabelItem *labels;
11807         int                     nlabels;
11808         int                     i;
11809         PQExpBuffer query;
11810
11811         /* do nothing, if --no-security-labels is supplied */
11812         if (no_security_labels)
11813                 return;
11814
11815         /* Comments are schema not data ... except blob comments are data */
11816         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11817         {
11818                 if (dataOnly)
11819                         return;
11820         }
11821         else
11822         {
11823                 if (schemaOnly)
11824                         return;
11825         }
11826
11827         /* Search for security labels associated with catalogId, using table */
11828         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11829
11830         query = createPQExpBuffer();
11831
11832         for (i = 0; i < nlabels; i++)
11833         {
11834                 /*
11835                  * Ignore label entries for which the subid doesn't match.
11836                  */
11837                 if (labels[i].objsubid != subid)
11838                         continue;
11839
11840                 appendPQExpBuffer(query,
11841                                                   "SECURITY LABEL FOR %s ON %s IS ",
11842                                                   fmtId(labels[i].provider), target);
11843                 appendStringLiteralAH(query, labels[i].label, fout);
11844                 appendPQExpBuffer(query, ";\n");
11845         }
11846
11847         if (query->len > 0)
11848         {
11849                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11850                                          target, namespace, NULL, owner,
11851                                          false, "SECURITY LABEL", SECTION_NONE,
11852                                          query->data, "", NULL,
11853                                          &(dumpId), 1,
11854                                          NULL, NULL);
11855         }
11856         destroyPQExpBuffer(query);
11857 }
11858
11859 /*
11860  * dumpTableSecLabel
11861  *
11862  * As above, but dump security label for both the specified table (or view)
11863  * and its columns.
11864  */
11865 static void
11866 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11867 {
11868         SecLabelItem *labels;
11869         int                     nlabels;
11870         int                     i;
11871         PQExpBuffer query;
11872         PQExpBuffer target;
11873
11874         /* do nothing, if --no-security-labels is supplied */
11875         if (no_security_labels)
11876                 return;
11877
11878         /* SecLabel are SCHEMA not data */
11879         if (dataOnly)
11880                 return;
11881
11882         /* Search for comments associated with relation, using table */
11883         nlabels = findSecLabels(fout,
11884                                                         tbinfo->dobj.catId.tableoid,
11885                                                         tbinfo->dobj.catId.oid,
11886                                                         &labels);
11887
11888         /* If security labels exist, build SECURITY LABEL statements */
11889         if (nlabels <= 0)
11890                 return;
11891
11892         query = createPQExpBuffer();
11893         target = createPQExpBuffer();
11894
11895         for (i = 0; i < nlabels; i++)
11896         {
11897                 const char *colname;
11898                 const char *provider = labels[i].provider;
11899                 const char *label = labels[i].label;
11900                 int                     objsubid = labels[i].objsubid;
11901
11902                 resetPQExpBuffer(target);
11903                 if (objsubid == 0)
11904                 {
11905                         appendPQExpBuffer(target, "%s %s", reltypename,
11906                                                           fmtId(tbinfo->dobj.name));
11907                 }
11908                 else
11909                 {
11910                         colname = getAttrName(objsubid, tbinfo);
11911                         /* first fmtId result must be consumed before calling it again */
11912                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11913                         appendPQExpBuffer(target, ".%s", fmtId(colname));
11914                 }
11915                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11916                                                   fmtId(provider), target->data);
11917                 appendStringLiteralAH(query, label, fout);
11918                 appendPQExpBuffer(query, ";\n");
11919         }
11920         if (query->len > 0)
11921         {
11922                 resetPQExpBuffer(target);
11923                 appendPQExpBuffer(target, "%s %s", reltypename,
11924                                                   fmtId(tbinfo->dobj.name));
11925                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11926                                          target->data,
11927                                          tbinfo->dobj.namespace->dobj.name,
11928                                          NULL, tbinfo->rolname,
11929                                          false, "SECURITY LABEL", SECTION_NONE,
11930                                          query->data, "", NULL,
11931                                          &(tbinfo->dobj.dumpId), 1,
11932                                          NULL, NULL);
11933         }
11934         destroyPQExpBuffer(query);
11935         destroyPQExpBuffer(target);
11936 }
11937
11938 /*
11939  * findSecLabels
11940  *
11941  * Find the security label(s), if any, associated with the given object.
11942  * All the objsubid values associated with the given classoid/objoid are
11943  * found with one search.
11944  */
11945 static int
11946 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11947 {
11948         /* static storage for table of security labels */
11949         static SecLabelItem *labels = NULL;
11950         static int      nlabels = -1;
11951
11952         SecLabelItem *middle = NULL;
11953         SecLabelItem *low;
11954         SecLabelItem *high;
11955         int                     nmatch;
11956
11957         /* Get security labels if we didn't already */
11958         if (nlabels < 0)
11959                 nlabels = collectSecLabels(fout, &labels);
11960
11961         if (nlabels <= 0)                       /* no labels, so no match is possible */
11962         {
11963                 *items = NULL;
11964                 return 0;
11965         }
11966
11967         /*
11968          * Do binary search to find some item matching the object.
11969          */
11970         low = &labels[0];
11971         high = &labels[nlabels - 1];
11972         while (low <= high)
11973         {
11974                 middle = low + (high - low) / 2;
11975
11976                 if (classoid < middle->classoid)
11977                         high = middle - 1;
11978                 else if (classoid > middle->classoid)
11979                         low = middle + 1;
11980                 else if (objoid < middle->objoid)
11981                         high = middle - 1;
11982                 else if (objoid > middle->objoid)
11983                         low = middle + 1;
11984                 else
11985                         break;                          /* found a match */
11986         }
11987
11988         if (low > high)                         /* no matches */
11989         {
11990                 *items = NULL;
11991                 return 0;
11992         }
11993
11994         /*
11995          * Now determine how many items match the object.  The search loop
11996          * invariant still holds: only items between low and high inclusive could
11997          * match.
11998          */
11999         nmatch = 1;
12000         while (middle > low)
12001         {
12002                 if (classoid != middle[-1].classoid ||
12003                         objoid != middle[-1].objoid)
12004                         break;
12005                 middle--;
12006                 nmatch++;
12007         }
12008
12009         *items = middle;
12010
12011         middle += nmatch;
12012         while (middle <= high)
12013         {
12014                 if (classoid != middle->classoid ||
12015                         objoid != middle->objoid)
12016                         break;
12017                 middle++;
12018                 nmatch++;
12019         }
12020
12021         return nmatch;
12022 }
12023
12024 /*
12025  * collectSecLabels
12026  *
12027  * Construct a table of all security labels available for database objects.
12028  * It's much faster to pull them all at once.
12029  *
12030  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12031  */
12032 static int
12033 collectSecLabels(Archive *fout, SecLabelItem **items)
12034 {
12035         PGresult   *res;
12036         PQExpBuffer query;
12037         int                     i_label;
12038         int                     i_provider;
12039         int                     i_classoid;
12040         int                     i_objoid;
12041         int                     i_objsubid;
12042         int                     ntups;
12043         int                     i;
12044         SecLabelItem *labels;
12045
12046         query = createPQExpBuffer();
12047
12048         appendPQExpBuffer(query,
12049                                           "SELECT label, provider, classoid, objoid, objsubid "
12050                                           "FROM pg_catalog.pg_seclabel "
12051                                           "ORDER BY classoid, objoid, objsubid");
12052
12053         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12054
12055         /* Construct lookup table containing OIDs in numeric form */
12056         i_label = PQfnumber(res, "label");
12057         i_provider = PQfnumber(res, "provider");
12058         i_classoid = PQfnumber(res, "classoid");
12059         i_objoid = PQfnumber(res, "objoid");
12060         i_objsubid = PQfnumber(res, "objsubid");
12061
12062         ntups = PQntuples(res);
12063
12064         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12065
12066         for (i = 0; i < ntups; i++)
12067         {
12068                 labels[i].label = PQgetvalue(res, i, i_label);
12069                 labels[i].provider = PQgetvalue(res, i, i_provider);
12070                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12071                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12072                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12073         }
12074
12075         /* Do NOT free the PGresult since we are keeping pointers into it */
12076         destroyPQExpBuffer(query);
12077
12078         *items = labels;
12079         return ntups;
12080 }
12081
12082 /*
12083  * dumpTable
12084  *        write out to fout the declarations (not data) of a user-defined table
12085  */
12086 static void
12087 dumpTable(Archive *fout, TableInfo *tbinfo)
12088 {
12089         if (tbinfo->dobj.dump)
12090         {
12091                 char       *namecopy;
12092
12093                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12094                         dumpSequence(fout, tbinfo);
12095                 else if (!dataOnly)
12096                         dumpTableSchema(fout, tbinfo);
12097
12098                 /* Handle the ACL here */
12099                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12100                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12101                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12102                                 "TABLE",
12103                                 namecopy, NULL, tbinfo->dobj.name,
12104                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12105                                 tbinfo->relacl);
12106
12107                 /*
12108                  * Handle column ACLs, if any.  Note: we pull these with a separate
12109                  * query rather than trying to fetch them during getTableAttrs, so
12110                  * that we won't miss ACLs on system columns.
12111                  */
12112                 if (fout->remoteVersion >= 80400)
12113                 {
12114                         PQExpBuffer query = createPQExpBuffer();
12115                         PGresult   *res;
12116                         int                     i;
12117
12118                         appendPQExpBuffer(query,
12119                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12120                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12121                                                           "ORDER BY attnum",
12122                                                           tbinfo->dobj.catId.oid);
12123                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12124
12125                         for (i = 0; i < PQntuples(res); i++)
12126                         {
12127                                 char       *attname = PQgetvalue(res, i, 0);
12128                                 char       *attacl = PQgetvalue(res, i, 1);
12129                                 char       *attnamecopy;
12130                                 char       *acltag;
12131
12132                                 attnamecopy = pg_strdup(fmtId(attname));
12133                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12134                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12135                                 /* Column's GRANT type is always TABLE */
12136                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12137                                                 namecopy, attnamecopy, acltag,
12138                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12139                                                 attacl);
12140                                 free(attnamecopy);
12141                                 free(acltag);
12142                         }
12143                         PQclear(res);
12144                         destroyPQExpBuffer(query);
12145                 }
12146
12147                 free(namecopy);
12148         }
12149 }
12150
12151 /*
12152  * dumpTableSchema
12153  *        write the declaration (not data) of one user-defined table or view
12154  */
12155 static void
12156 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12157 {
12158         PQExpBuffer query = createPQExpBuffer();
12159         PQExpBuffer q = createPQExpBuffer();
12160         PQExpBuffer delq = createPQExpBuffer();
12161         PQExpBuffer labelq = createPQExpBuffer();
12162         PGresult   *res;
12163         int                     numParents;
12164         TableInfo **parents;
12165         int                     actual_atts;    /* number of attrs in this CREATE statment */
12166         const char *reltypename;
12167         char       *storage;
12168         char       *srvname;
12169         char       *ftoptions;
12170         int                     j,
12171                                 k;
12172
12173         /* Make sure we are in proper schema */
12174         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12175
12176         if (binary_upgrade)
12177                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12178                                                                                                 tbinfo->dobj.catId.oid);
12179
12180         /* Is it a table or a view? */
12181         if (tbinfo->relkind == RELKIND_VIEW)
12182         {
12183                 char       *viewdef;
12184
12185                 reltypename = "VIEW";
12186
12187                 /* Fetch the view definition */
12188                 if (fout->remoteVersion >= 70300)
12189                 {
12190                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12191                         appendPQExpBuffer(query,
12192                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12193                                                           tbinfo->dobj.catId.oid);
12194                 }
12195                 else
12196                 {
12197                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12198                                                           "FROM pg_views WHERE viewname = ");
12199                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12200                         appendPQExpBuffer(query, ";");
12201                 }
12202
12203                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12204
12205                 if (PQntuples(res) != 1)
12206                 {
12207                         if (PQntuples(res) < 1)
12208                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12209                                                   tbinfo->dobj.name);
12210                         else
12211                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12212                                                   tbinfo->dobj.name);
12213                 }
12214
12215                 viewdef = PQgetvalue(res, 0, 0);
12216
12217                 if (strlen(viewdef) == 0)
12218                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12219                                                   tbinfo->dobj.name);
12220
12221                 /*
12222                  * DROP must be fully qualified in case same name appears in
12223                  * pg_catalog
12224                  */
12225                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12226                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12227                 appendPQExpBuffer(delq, "%s;\n",
12228                                                   fmtId(tbinfo->dobj.name));
12229
12230                 if (binary_upgrade)
12231                         binary_upgrade_set_pg_class_oids(fout, q,
12232                                                                                          tbinfo->dobj.catId.oid, false);
12233
12234                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12235                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12236                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12237                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12238
12239                 appendPQExpBuffer(labelq, "VIEW %s",
12240                                                   fmtId(tbinfo->dobj.name));
12241
12242                 PQclear(res);
12243         }
12244         else
12245         {
12246                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12247                 {
12248                         int                     i_srvname;
12249                         int                     i_ftoptions;
12250
12251                         reltypename = "FOREIGN TABLE";
12252
12253                         /* retrieve name of foreign server and generic options */
12254                         appendPQExpBuffer(query,
12255                                                           "SELECT fs.srvname, "
12256                                                           "pg_catalog.array_to_string(ARRAY("
12257                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12258                                                           "' ' || pg_catalog.quote_literal(option_value) "
12259                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
12260                                                           "ORDER BY option_name"
12261                                                           "), E',\n    ') AS ftoptions "
12262                                                           "FROM pg_catalog.pg_foreign_table ft "
12263                                                           "JOIN pg_catalog.pg_foreign_server fs "
12264                                                           "ON (fs.oid = ft.ftserver) "
12265                                                           "WHERE ft.ftrelid = '%u'",
12266                                                           tbinfo->dobj.catId.oid);
12267                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12268                         i_srvname = PQfnumber(res, "srvname");
12269                         i_ftoptions = PQfnumber(res, "ftoptions");
12270                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12271                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12272                         PQclear(res);
12273                 }
12274                 else
12275                 {
12276                         reltypename = "TABLE";
12277                         srvname = NULL;
12278                         ftoptions = NULL;
12279                 }
12280                 numParents = tbinfo->numParents;
12281                 parents = tbinfo->parents;
12282
12283                 /*
12284                  * DROP must be fully qualified in case same name appears in
12285                  * pg_catalog
12286                  */
12287                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12288                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12289                 appendPQExpBuffer(delq, "%s;\n",
12290                                                   fmtId(tbinfo->dobj.name));
12291
12292                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12293                                                   fmtId(tbinfo->dobj.name));
12294
12295                 if (binary_upgrade)
12296                         binary_upgrade_set_pg_class_oids(fout, q,
12297                                                                                          tbinfo->dobj.catId.oid, false);
12298
12299                 appendPQExpBuffer(q, "CREATE %s%s %s",
12300                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12301                                                   "UNLOGGED " : "",
12302                                                   reltypename,
12303                                                   fmtId(tbinfo->dobj.name));
12304
12305                 /*
12306                  * Attach to type, if reloftype; except in case of a binary upgrade,
12307                  * we dump the table normally and attach it to the type afterward.
12308                  */
12309                 if (tbinfo->reloftype && !binary_upgrade)
12310                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12311
12312                 /* Dump the attributes */
12313                 actual_atts = 0;
12314                 for (j = 0; j < tbinfo->numatts; j++)
12315                 {
12316                         /*
12317                          * Normally, dump if it's locally defined in this table, and not
12318                          * dropped.  But for binary upgrade, we'll dump all the columns,
12319                          * and then fix up the dropped and nonlocal cases below.
12320                          */
12321                         if (shouldPrintColumn(tbinfo, j))
12322                         {
12323                                 /*
12324                                  * Default value --- suppress if to be printed separately.
12325                                  */
12326                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12327                                                                                    !tbinfo->attrdefs[j]->separate);
12328
12329                                 /*
12330                                  * Not Null constraint --- suppress if inherited, except in
12331                                  * binary-upgrade case where that won't work.
12332                                  */
12333                                 bool            has_notnull = (tbinfo->notnull[j] &&
12334                                                                                    (!tbinfo->inhNotNull[j] ||
12335                                                                                         binary_upgrade));
12336
12337                                 /* Skip column if fully defined by reloftype */
12338                                 if (tbinfo->reloftype &&
12339                                         !has_default && !has_notnull && !binary_upgrade)
12340                                         continue;
12341
12342                                 /* Format properly if not first attr */
12343                                 if (actual_atts == 0)
12344                                         appendPQExpBuffer(q, " (");
12345                                 else
12346                                         appendPQExpBuffer(q, ",");
12347                                 appendPQExpBuffer(q, "\n    ");
12348                                 actual_atts++;
12349
12350                                 /* Attribute name */
12351                                 appendPQExpBuffer(q, "%s ",
12352                                                                   fmtId(tbinfo->attnames[j]));
12353
12354                                 if (tbinfo->attisdropped[j])
12355                                 {
12356                                         /*
12357                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12358                                          * so we will not have gotten a valid type name; insert
12359                                          * INTEGER as a stopgap.  We'll clean things up later.
12360                                          */
12361                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12362                                         /* Skip all the rest, too */
12363                                         continue;
12364                                 }
12365
12366                                 /* Attribute type */
12367                                 if (tbinfo->reloftype && !binary_upgrade)
12368                                 {
12369                                         appendPQExpBuffer(q, "WITH OPTIONS");
12370                                 }
12371                                 else if (fout->remoteVersion >= 70100)
12372                                 {
12373                                         appendPQExpBuffer(q, "%s",
12374                                                                           tbinfo->atttypnames[j]);
12375                                 }
12376                                 else
12377                                 {
12378                                         /* If no format_type, fake it */
12379                                         appendPQExpBuffer(q, "%s",
12380                                                                           myFormatType(tbinfo->atttypnames[j],
12381                                                                                                    tbinfo->atttypmod[j]));
12382                                 }
12383
12384                                 /* Add collation if not default for the type */
12385                                 if (OidIsValid(tbinfo->attcollation[j]))
12386                                 {
12387                                         CollInfo   *coll;
12388
12389                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12390                                         if (coll)
12391                                         {
12392                                                 /* always schema-qualify, don't try to be smart */
12393                                                 appendPQExpBuffer(q, " COLLATE %s.",
12394                                                                          fmtId(coll->dobj.namespace->dobj.name));
12395                                                 appendPQExpBuffer(q, "%s",
12396                                                                                   fmtId(coll->dobj.name));
12397                                         }
12398                                 }
12399
12400                                 if (has_default)
12401                                         appendPQExpBuffer(q, " DEFAULT %s",
12402                                                                           tbinfo->attrdefs[j]->adef_expr);
12403
12404                                 if (has_notnull)
12405                                         appendPQExpBuffer(q, " NOT NULL");
12406                         }
12407                 }
12408
12409                 /*
12410                  * Add non-inherited CHECK constraints, if any.
12411                  */
12412                 for (j = 0; j < tbinfo->ncheck; j++)
12413                 {
12414                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12415
12416                         if (constr->separate || !constr->conislocal)
12417                                 continue;
12418
12419                         if (actual_atts == 0)
12420                                 appendPQExpBuffer(q, " (\n    ");
12421                         else
12422                                 appendPQExpBuffer(q, ",\n    ");
12423
12424                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12425                                                           fmtId(constr->dobj.name));
12426                         appendPQExpBuffer(q, "%s", constr->condef);
12427
12428                         actual_atts++;
12429                 }
12430
12431                 if (actual_atts)
12432                         appendPQExpBuffer(q, "\n)");
12433                 else if (!(tbinfo->reloftype && !binary_upgrade))
12434                 {
12435                         /*
12436                          * We must have a parenthesized attribute list, even though empty,
12437                          * when not using the OF TYPE syntax.
12438                          */
12439                         appendPQExpBuffer(q, " (\n)");
12440                 }
12441
12442                 if (numParents > 0 && !binary_upgrade)
12443                 {
12444                         appendPQExpBuffer(q, "\nINHERITS (");
12445                         for (k = 0; k < numParents; k++)
12446                         {
12447                                 TableInfo  *parentRel = parents[k];
12448
12449                                 if (k > 0)
12450                                         appendPQExpBuffer(q, ", ");
12451                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12452                                         appendPQExpBuffer(q, "%s.",
12453                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12454                                 appendPQExpBuffer(q, "%s",
12455                                                                   fmtId(parentRel->dobj.name));
12456                         }
12457                         appendPQExpBuffer(q, ")");
12458                 }
12459
12460                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12461                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12462
12463                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12464                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12465                 {
12466                         bool            addcomma = false;
12467
12468                         appendPQExpBuffer(q, "\nWITH (");
12469                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12470                         {
12471                                 addcomma = true;
12472                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12473                         }
12474                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12475                         {
12476                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12477                                                                   tbinfo->toast_reloptions);
12478                         }
12479                         appendPQExpBuffer(q, ")");
12480                 }
12481
12482                 /* Dump generic options if any */
12483                 if (ftoptions && ftoptions[0])
12484                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12485
12486                 appendPQExpBuffer(q, ";\n");
12487
12488                 /*
12489                  * To create binary-compatible heap files, we have to ensure the same
12490                  * physical column order, including dropped columns, as in the
12491                  * original.  Therefore, we create dropped columns above and drop them
12492                  * here, also updating their attlen/attalign values so that the
12493                  * dropped column can be skipped properly.      (We do not bother with
12494                  * restoring the original attbyval setting.)  Also, inheritance
12495                  * relationships are set up by doing ALTER INHERIT rather than using
12496                  * an INHERITS clause --- the latter would possibly mess up the column
12497                  * order.  That also means we have to take care about setting
12498                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12499                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12500                  */
12501                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12502                 {
12503                         for (j = 0; j < tbinfo->numatts; j++)
12504                         {
12505                                 if (tbinfo->attisdropped[j])
12506                                 {
12507                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12508                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12509                                                                           "SET attlen = %d, "
12510                                                                           "attalign = '%c', attbyval = false\n"
12511                                                                           "WHERE attname = ",
12512                                                                           tbinfo->attlen[j],
12513                                                                           tbinfo->attalign[j]);
12514                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12515                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12516                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12517                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12518
12519                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12520                                                                           fmtId(tbinfo->dobj.name));
12521                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12522                                                                           fmtId(tbinfo->attnames[j]));
12523                                 }
12524                                 else if (!tbinfo->attislocal[j])
12525                                 {
12526                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12527                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12528                                                                           "SET attislocal = false\n"
12529                                                                           "WHERE attname = ");
12530                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12531                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12532                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12533                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12534                                 }
12535                         }
12536
12537                         for (k = 0; k < tbinfo->ncheck; k++)
12538                         {
12539                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12540
12541                                 if (constr->separate || constr->conislocal)
12542                                         continue;
12543
12544                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12545                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12546                                                                   fmtId(tbinfo->dobj.name));
12547                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12548                                                                   fmtId(constr->dobj.name));
12549                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12550                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12551                                                                   "SET conislocal = false\n"
12552                                                                   "WHERE contype = 'c' AND conname = ");
12553                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12554                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12555                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12556                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12557                         }
12558
12559                         if (numParents > 0)
12560                         {
12561                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12562                                 for (k = 0; k < numParents; k++)
12563                                 {
12564                                         TableInfo  *parentRel = parents[k];
12565
12566                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12567                                                                           fmtId(tbinfo->dobj.name));
12568                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12569                                                 appendPQExpBuffer(q, "%s.",
12570                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12571                                         appendPQExpBuffer(q, "%s;\n",
12572                                                                           fmtId(parentRel->dobj.name));
12573                                 }
12574                         }
12575
12576                         if (tbinfo->reloftype)
12577                         {
12578                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12579                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12580                                                                   fmtId(tbinfo->dobj.name),
12581                                                                   tbinfo->reloftype);
12582                         }
12583
12584                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12585                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12586                                                           "SET relfrozenxid = '%u'\n"
12587                                                           "WHERE oid = ",
12588                                                           tbinfo->frozenxid);
12589                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12590                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12591
12592                         if (tbinfo->toast_oid)
12593                         {
12594                                 /* We preserve the toast oids, so we can use it during restore */
12595                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12596                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12597                                                                   "SET relfrozenxid = '%u'\n"
12598                                                                   "WHERE oid = '%u';\n",
12599                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12600                         }
12601                 }
12602
12603                 /*
12604                  * Dump additional per-column properties that we can't handle in the
12605                  * main CREATE TABLE command.
12606                  */
12607                 for (j = 0; j < tbinfo->numatts; j++)
12608                 {
12609                         /* None of this applies to dropped columns */
12610                         if (tbinfo->attisdropped[j])
12611                                 continue;
12612
12613                         /*
12614                          * If we didn't dump the column definition explicitly above, and
12615                          * it is NOT NULL and did not inherit that property from a parent,
12616                          * we have to mark it separately.
12617                          */
12618                         if (!shouldPrintColumn(tbinfo, j) &&
12619                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12620                         {
12621                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12622                                                                   fmtId(tbinfo->dobj.name));
12623                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12624                                                                   fmtId(tbinfo->attnames[j]));
12625                         }
12626
12627                         /*
12628                          * Dump per-column statistics information. We only issue an ALTER
12629                          * TABLE statement if the attstattarget entry for this column is
12630                          * non-negative (i.e. it's not the default value)
12631                          */
12632                         if (tbinfo->attstattarget[j] >= 0)
12633                         {
12634                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12635                                                                   fmtId(tbinfo->dobj.name));
12636                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12637                                                                   fmtId(tbinfo->attnames[j]));
12638                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12639                                                                   tbinfo->attstattarget[j]);
12640                         }
12641
12642                         /*
12643                          * Dump per-column storage information.  The statement is only
12644                          * dumped if the storage has been changed from the type's default.
12645                          */
12646                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12647                         {
12648                                 switch (tbinfo->attstorage[j])
12649                                 {
12650                                         case 'p':
12651                                                 storage = "PLAIN";
12652                                                 break;
12653                                         case 'e':
12654                                                 storage = "EXTERNAL";
12655                                                 break;
12656                                         case 'm':
12657                                                 storage = "MAIN";
12658                                                 break;
12659                                         case 'x':
12660                                                 storage = "EXTENDED";
12661                                                 break;
12662                                         default:
12663                                                 storage = NULL;
12664                                 }
12665
12666                                 /*
12667                                  * Only dump the statement if it's a storage type we recognize
12668                                  */
12669                                 if (storage != NULL)
12670                                 {
12671                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12672                                                                           fmtId(tbinfo->dobj.name));
12673                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12674                                                                           fmtId(tbinfo->attnames[j]));
12675                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12676                                                                           storage);
12677                                 }
12678                         }
12679
12680                         /*
12681                          * Dump per-column attributes.
12682                          */
12683                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12684                         {
12685                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12686                                                                   fmtId(tbinfo->dobj.name));
12687                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12688                                                                   fmtId(tbinfo->attnames[j]));
12689                                 appendPQExpBuffer(q, "SET (%s);\n",
12690                                                                   tbinfo->attoptions[j]);
12691                         }
12692
12693                         /*
12694                          * Dump per-column fdw options.
12695                          */
12696                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12697                                 tbinfo->attfdwoptions[j] &&
12698                                 tbinfo->attfdwoptions[j][0] != '\0')
12699                         {
12700                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12701                                                                   fmtId(tbinfo->dobj.name));
12702                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12703                                                                   fmtId(tbinfo->attnames[j]));
12704                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12705                                                                   tbinfo->attfdwoptions[j]);
12706                         }
12707                 }
12708         }
12709
12710         if (binary_upgrade)
12711                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12712
12713         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12714                                  tbinfo->dobj.name,
12715                                  tbinfo->dobj.namespace->dobj.name,
12716                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12717                                  tbinfo->rolname,
12718                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12719                                  reltypename, SECTION_PRE_DATA,
12720                                  q->data, delq->data, NULL,
12721                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12722                                  NULL, NULL);
12723
12724
12725         /* Dump Table Comments */
12726         dumpTableComment(fout, tbinfo, reltypename);
12727
12728         /* Dump Table Security Labels */
12729         dumpTableSecLabel(fout, tbinfo, reltypename);
12730
12731         /* Dump comments on inlined table constraints */
12732         for (j = 0; j < tbinfo->ncheck; j++)
12733         {
12734                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12735
12736                 if (constr->separate || !constr->conislocal)
12737                         continue;
12738
12739                 dumpTableConstraintComment(fout, constr);
12740         }
12741
12742         destroyPQExpBuffer(query);
12743         destroyPQExpBuffer(q);
12744         destroyPQExpBuffer(delq);
12745         destroyPQExpBuffer(labelq);
12746 }
12747
12748 /*
12749  * dumpAttrDef --- dump an attribute's default-value declaration
12750  */
12751 static void
12752 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12753 {
12754         TableInfo  *tbinfo = adinfo->adtable;
12755         int                     adnum = adinfo->adnum;
12756         PQExpBuffer q;
12757         PQExpBuffer delq;
12758
12759         /* Skip if table definition not to be dumped */
12760         if (!tbinfo->dobj.dump || dataOnly)
12761                 return;
12762
12763         /* Skip if not "separate"; it was dumped in the table's definition */
12764         if (!adinfo->separate)
12765                 return;
12766
12767         q = createPQExpBuffer();
12768         delq = createPQExpBuffer();
12769
12770         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12771                                           fmtId(tbinfo->dobj.name));
12772         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12773                                           fmtId(tbinfo->attnames[adnum - 1]),
12774                                           adinfo->adef_expr);
12775
12776         /*
12777          * DROP must be fully qualified in case same name appears in pg_catalog
12778          */
12779         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12780                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12781         appendPQExpBuffer(delq, "%s ",
12782                                           fmtId(tbinfo->dobj.name));
12783         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12784                                           fmtId(tbinfo->attnames[adnum - 1]));
12785
12786         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12787                                  tbinfo->attnames[adnum - 1],
12788                                  tbinfo->dobj.namespace->dobj.name,
12789                                  NULL,
12790                                  tbinfo->rolname,
12791                                  false, "DEFAULT", SECTION_PRE_DATA,
12792                                  q->data, delq->data, NULL,
12793                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12794                                  NULL, NULL);
12795
12796         destroyPQExpBuffer(q);
12797         destroyPQExpBuffer(delq);
12798 }
12799
12800 /*
12801  * getAttrName: extract the correct name for an attribute
12802  *
12803  * The array tblInfo->attnames[] only provides names of user attributes;
12804  * if a system attribute number is supplied, we have to fake it.
12805  * We also do a little bit of bounds checking for safety's sake.
12806  */
12807 static const char *
12808 getAttrName(int attrnum, TableInfo *tblInfo)
12809 {
12810         if (attrnum > 0 && attrnum <= tblInfo->numatts)
12811                 return tblInfo->attnames[attrnum - 1];
12812         switch (attrnum)
12813         {
12814                 case SelfItemPointerAttributeNumber:
12815                         return "ctid";
12816                 case ObjectIdAttributeNumber:
12817                         return "oid";
12818                 case MinTransactionIdAttributeNumber:
12819                         return "xmin";
12820                 case MinCommandIdAttributeNumber:
12821                         return "cmin";
12822                 case MaxTransactionIdAttributeNumber:
12823                         return "xmax";
12824                 case MaxCommandIdAttributeNumber:
12825                         return "cmax";
12826                 case TableOidAttributeNumber:
12827                         return "tableoid";
12828         }
12829         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12830                                   attrnum, tblInfo->dobj.name);
12831         return NULL;                            /* keep compiler quiet */
12832 }
12833
12834 /*
12835  * dumpIndex
12836  *        write out to fout a user-defined index
12837  */
12838 static void
12839 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12840 {
12841         TableInfo  *tbinfo = indxinfo->indextable;
12842         PQExpBuffer q;
12843         PQExpBuffer delq;
12844         PQExpBuffer labelq;
12845
12846         if (dataOnly)
12847                 return;
12848
12849         q = createPQExpBuffer();
12850         delq = createPQExpBuffer();
12851         labelq = createPQExpBuffer();
12852
12853         appendPQExpBuffer(labelq, "INDEX %s",
12854                                           fmtId(indxinfo->dobj.name));
12855
12856         /*
12857          * If there's an associated constraint, don't dump the index per se, but
12858          * do dump any comment for it.  (This is safe because dependency ordering
12859          * will have ensured the constraint is emitted first.)
12860          */
12861         if (indxinfo->indexconstraint == 0)
12862         {
12863                 if (binary_upgrade)
12864                         binary_upgrade_set_pg_class_oids(fout, q,
12865                                                                                          indxinfo->dobj.catId.oid, true);
12866
12867                 /* Plain secondary index */
12868                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12869
12870                 /* If the index is clustered, we need to record that. */
12871                 if (indxinfo->indisclustered)
12872                 {
12873                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12874                                                           fmtId(tbinfo->dobj.name));
12875                         appendPQExpBuffer(q, " ON %s;\n",
12876                                                           fmtId(indxinfo->dobj.name));
12877                 }
12878
12879                 /*
12880                  * DROP must be fully qualified in case same name appears in
12881                  * pg_catalog
12882                  */
12883                 appendPQExpBuffer(delq, "DROP INDEX %s.",
12884                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12885                 appendPQExpBuffer(delq, "%s;\n",
12886                                                   fmtId(indxinfo->dobj.name));
12887
12888                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12889                                          indxinfo->dobj.name,
12890                                          tbinfo->dobj.namespace->dobj.name,
12891                                          indxinfo->tablespace,
12892                                          tbinfo->rolname, false,
12893                                          "INDEX", SECTION_POST_DATA,
12894                                          q->data, delq->data, NULL,
12895                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12896                                          NULL, NULL);
12897         }
12898
12899         /* Dump Index Comments */
12900         dumpComment(fout, labelq->data,
12901                                 tbinfo->dobj.namespace->dobj.name,
12902                                 tbinfo->rolname,
12903                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12904
12905         destroyPQExpBuffer(q);
12906         destroyPQExpBuffer(delq);
12907         destroyPQExpBuffer(labelq);
12908 }
12909
12910 /*
12911  * dumpConstraint
12912  *        write out to fout a user-defined constraint
12913  */
12914 static void
12915 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12916 {
12917         TableInfo  *tbinfo = coninfo->contable;
12918         PQExpBuffer q;
12919         PQExpBuffer delq;
12920
12921         /* Skip if not to be dumped */
12922         if (!coninfo->dobj.dump || dataOnly)
12923                 return;
12924
12925         q = createPQExpBuffer();
12926         delq = createPQExpBuffer();
12927
12928         if (coninfo->contype == 'p' ||
12929                 coninfo->contype == 'u' ||
12930                 coninfo->contype == 'x')
12931         {
12932                 /* Index-related constraint */
12933                 IndxInfo   *indxinfo;
12934                 int                     k;
12935
12936                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12937
12938                 if (indxinfo == NULL)
12939                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12940                                                   coninfo->dobj.name);
12941
12942                 if (binary_upgrade)
12943                         binary_upgrade_set_pg_class_oids(fout, q,
12944                                                                                          indxinfo->dobj.catId.oid, true);
12945
12946                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12947                                                   fmtId(tbinfo->dobj.name));
12948                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
12949                                                   fmtId(coninfo->dobj.name));
12950
12951                 if (coninfo->condef)
12952                 {
12953                         /* pg_get_constraintdef should have provided everything */
12954                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12955                 }
12956                 else
12957                 {
12958                         appendPQExpBuffer(q, "%s (",
12959                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12960                         for (k = 0; k < indxinfo->indnkeys; k++)
12961                         {
12962                                 int                     indkey = (int) indxinfo->indkeys[k];
12963                                 const char *attname;
12964
12965                                 if (indkey == InvalidAttrNumber)
12966                                         break;
12967                                 attname = getAttrName(indkey, tbinfo);
12968
12969                                 appendPQExpBuffer(q, "%s%s",
12970                                                                   (k == 0) ? "" : ", ",
12971                                                                   fmtId(attname));
12972                         }
12973
12974                         appendPQExpBuffer(q, ")");
12975
12976                         if (indxinfo->options && strlen(indxinfo->options) > 0)
12977                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12978
12979                         if (coninfo->condeferrable)
12980                         {
12981                                 appendPQExpBuffer(q, " DEFERRABLE");
12982                                 if (coninfo->condeferred)
12983                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
12984                         }
12985
12986                         appendPQExpBuffer(q, ";\n");
12987                 }
12988
12989                 /* If the index is clustered, we need to record that. */
12990                 if (indxinfo->indisclustered)
12991                 {
12992                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12993                                                           fmtId(tbinfo->dobj.name));
12994                         appendPQExpBuffer(q, " ON %s;\n",
12995                                                           fmtId(indxinfo->dobj.name));
12996                 }
12997
12998                 /*
12999                  * DROP must be fully qualified in case same name appears in
13000                  * pg_catalog
13001                  */
13002                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13003                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13004                 appendPQExpBuffer(delq, "%s ",
13005                                                   fmtId(tbinfo->dobj.name));
13006                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13007                                                   fmtId(coninfo->dobj.name));
13008
13009                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13010                                          coninfo->dobj.name,
13011                                          tbinfo->dobj.namespace->dobj.name,
13012                                          indxinfo->tablespace,
13013                                          tbinfo->rolname, false,
13014                                          "CONSTRAINT", SECTION_POST_DATA,
13015                                          q->data, delq->data, NULL,
13016                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13017                                          NULL, NULL);
13018         }
13019         else if (coninfo->contype == 'f')
13020         {
13021                 /*
13022                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13023                  * current table data is not processed
13024                  */
13025                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13026                                                   fmtId(tbinfo->dobj.name));
13027                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13028                                                   fmtId(coninfo->dobj.name),
13029                                                   coninfo->condef);
13030
13031                 /*
13032                  * DROP must be fully qualified in case same name appears in
13033                  * pg_catalog
13034                  */
13035                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13036                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13037                 appendPQExpBuffer(delq, "%s ",
13038                                                   fmtId(tbinfo->dobj.name));
13039                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13040                                                   fmtId(coninfo->dobj.name));
13041
13042                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13043                                          coninfo->dobj.name,
13044                                          tbinfo->dobj.namespace->dobj.name,
13045                                          NULL,
13046                                          tbinfo->rolname, false,
13047                                          "FK CONSTRAINT", SECTION_POST_DATA,
13048                                          q->data, delq->data, NULL,
13049                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13050                                          NULL, NULL);
13051         }
13052         else if (coninfo->contype == 'c' && tbinfo)
13053         {
13054                 /* CHECK constraint on a table */
13055
13056                 /* Ignore if not to be dumped separately */
13057                 if (coninfo->separate)
13058                 {
13059                         /* add ONLY if we do not want it to propagate to children */
13060                         appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13061                                                          coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13062                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13063                                                           fmtId(coninfo->dobj.name),
13064                                                           coninfo->condef);
13065
13066                         /*
13067                          * DROP must be fully qualified in case same name appears in
13068                          * pg_catalog
13069                          */
13070                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13071                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13072                         appendPQExpBuffer(delq, "%s ",
13073                                                           fmtId(tbinfo->dobj.name));
13074                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13075                                                           fmtId(coninfo->dobj.name));
13076
13077                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13078                                                  coninfo->dobj.name,
13079                                                  tbinfo->dobj.namespace->dobj.name,
13080                                                  NULL,
13081                                                  tbinfo->rolname, false,
13082                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13083                                                  q->data, delq->data, NULL,
13084                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13085                                                  NULL, NULL);
13086                 }
13087         }
13088         else if (coninfo->contype == 'c' && tbinfo == NULL)
13089         {
13090                 /* CHECK constraint on a domain */
13091                 TypeInfo   *tyinfo = coninfo->condomain;
13092
13093                 /* Ignore if not to be dumped separately */
13094                 if (coninfo->separate)
13095                 {
13096                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13097                                                           fmtId(tyinfo->dobj.name));
13098                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13099                                                           fmtId(coninfo->dobj.name),
13100                                                           coninfo->condef);
13101
13102                         /*
13103                          * DROP must be fully qualified in case same name appears in
13104                          * pg_catalog
13105                          */
13106                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13107                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13108                         appendPQExpBuffer(delq, "%s ",
13109                                                           fmtId(tyinfo->dobj.name));
13110                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13111                                                           fmtId(coninfo->dobj.name));
13112
13113                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13114                                                  coninfo->dobj.name,
13115                                                  tyinfo->dobj.namespace->dobj.name,
13116                                                  NULL,
13117                                                  tyinfo->rolname, false,
13118                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13119                                                  q->data, delq->data, NULL,
13120                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13121                                                  NULL, NULL);
13122                 }
13123         }
13124         else
13125         {
13126                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13127                                           coninfo->contype);
13128         }
13129
13130         /* Dump Constraint Comments --- only works for table constraints */
13131         if (tbinfo && coninfo->separate)
13132                 dumpTableConstraintComment(fout, coninfo);
13133
13134         destroyPQExpBuffer(q);
13135         destroyPQExpBuffer(delq);
13136 }
13137
13138 /*
13139  * dumpTableConstraintComment --- dump a constraint's comment if any
13140  *
13141  * This is split out because we need the function in two different places
13142  * depending on whether the constraint is dumped as part of CREATE TABLE
13143  * or as a separate ALTER command.
13144  */
13145 static void
13146 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13147 {
13148         TableInfo  *tbinfo = coninfo->contable;
13149         PQExpBuffer labelq = createPQExpBuffer();
13150
13151         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13152                                           fmtId(coninfo->dobj.name));
13153         appendPQExpBuffer(labelq, "ON %s",
13154                                           fmtId(tbinfo->dobj.name));
13155         dumpComment(fout, labelq->data,
13156                                 tbinfo->dobj.namespace->dobj.name,
13157                                 tbinfo->rolname,
13158                                 coninfo->dobj.catId, 0,
13159                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13160
13161         destroyPQExpBuffer(labelq);
13162 }
13163
13164 /*
13165  * findLastBuiltInOid -
13166  * find the last built in oid
13167  *
13168  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13169  * pg_database entry for the current database
13170  */
13171 static Oid
13172 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13173 {
13174         PGresult   *res;
13175         Oid                     last_oid;
13176         PQExpBuffer query = createPQExpBuffer();
13177
13178         resetPQExpBuffer(query);
13179         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13180         appendStringLiteralAH(query, dbname, fout);
13181
13182         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13183         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13184         PQclear(res);
13185         destroyPQExpBuffer(query);
13186         return last_oid;
13187 }
13188
13189 /*
13190  * findLastBuiltInOid -
13191  * find the last built in oid
13192  *
13193  * For 7.0, we do this by assuming that the last thing that initdb does is to
13194  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13195  * initdb won't be changing anymore, it'll do.
13196  */
13197 static Oid
13198 findLastBuiltinOid_V70(Archive *fout)
13199 {
13200         PGresult   *res;
13201         int                     last_oid;
13202
13203         res = ExecuteSqlQueryForSingleRow(fout,
13204                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13205         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13206         PQclear(res);
13207         return last_oid;
13208 }
13209
13210 static void
13211 dumpSequence(Archive *fout, TableInfo *tbinfo)
13212 {
13213         PGresult   *res;
13214         char       *startv,
13215                            *last,
13216                            *incby,
13217                            *maxv = NULL,
13218                            *minv = NULL,
13219                            *cache;
13220         char            bufm[100],
13221                                 bufx[100];
13222         bool            cycled,
13223                                 called;
13224         PQExpBuffer query = createPQExpBuffer();
13225         PQExpBuffer delqry = createPQExpBuffer();
13226         PQExpBuffer labelq = createPQExpBuffer();
13227
13228         /* Make sure we are in proper schema */
13229         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13230
13231         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13232         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13233
13234         if (fout->remoteVersion >= 80400)
13235         {
13236                 appendPQExpBuffer(query,
13237                                                   "SELECT sequence_name, "
13238                                                   "start_value, last_value, increment_by, "
13239                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13240                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13241                                                   "     ELSE max_value "
13242                                                   "END AS max_value, "
13243                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13244                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13245                                                   "     ELSE min_value "
13246                                                   "END AS min_value, "
13247                                                   "cache_value, is_cycled, is_called from %s",
13248                                                   bufx, bufm,
13249                                                   fmtId(tbinfo->dobj.name));
13250         }
13251         else
13252         {
13253                 appendPQExpBuffer(query,
13254                                                   "SELECT sequence_name, "
13255                                                   "0 AS start_value, last_value, increment_by, "
13256                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13257                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13258                                                   "     ELSE max_value "
13259                                                   "END AS max_value, "
13260                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13261                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13262                                                   "     ELSE min_value "
13263                                                   "END AS min_value, "
13264                                                   "cache_value, is_cycled, is_called from %s",
13265                                                   bufx, bufm,
13266                                                   fmtId(tbinfo->dobj.name));
13267         }
13268
13269         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13270
13271         if (PQntuples(res) != 1)
13272         {
13273                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13274                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13275                                                                  PQntuples(res)),
13276                                   tbinfo->dobj.name, PQntuples(res));
13277                 exit_nicely(1);
13278         }
13279
13280         /* Disable this check: it fails if sequence has been renamed */
13281 #ifdef NOT_USED
13282         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13283         {
13284                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13285                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13286                 exit_nicely(1);
13287         }
13288 #endif
13289
13290         startv = PQgetvalue(res, 0, 1);
13291         last = PQgetvalue(res, 0, 2);
13292         incby = PQgetvalue(res, 0, 3);
13293         if (!PQgetisnull(res, 0, 4))
13294                 maxv = PQgetvalue(res, 0, 4);
13295         if (!PQgetisnull(res, 0, 5))
13296                 minv = PQgetvalue(res, 0, 5);
13297         cache = PQgetvalue(res, 0, 6);
13298         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13299         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13300
13301         /*
13302          * The logic we use for restoring sequences is as follows:
13303          *
13304          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13305          * last_val for start if called is false, else use min_val for start_val).
13306          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13307          * BY command for it.
13308          *
13309          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13310          */
13311         if (!dataOnly)
13312         {
13313                 /*
13314                  * DROP must be fully qualified in case same name appears in
13315                  * pg_catalog
13316                  */
13317                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13318                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13319                 appendPQExpBuffer(delqry, "%s;\n",
13320                                                   fmtId(tbinfo->dobj.name));
13321
13322                 resetPQExpBuffer(query);
13323
13324                 if (binary_upgrade)
13325                 {
13326                         binary_upgrade_set_pg_class_oids(fout, query,
13327                                                                                          tbinfo->dobj.catId.oid, false);
13328                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13329                                                                                                         tbinfo->dobj.catId.oid);
13330                 }
13331
13332                 appendPQExpBuffer(query,
13333                                                   "CREATE SEQUENCE %s\n",
13334                                                   fmtId(tbinfo->dobj.name));
13335
13336                 if (fout->remoteVersion >= 80400)
13337                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13338                 else
13339                 {
13340                         /*
13341                          * Versions before 8.4 did not remember the true start value.  If
13342                          * is_called is false then the sequence has never been incremented
13343                          * so we can use last_val.      Otherwise punt and let it default.
13344                          */
13345                         if (!called)
13346                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13347                 }
13348
13349                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13350
13351                 if (minv)
13352                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13353                 else
13354                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13355
13356                 if (maxv)
13357                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13358                 else
13359                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13360
13361                 appendPQExpBuffer(query,
13362                                                   "    CACHE %s%s",
13363                                                   cache, (cycled ? "\n    CYCLE" : ""));
13364
13365                 appendPQExpBuffer(query, ";\n");
13366
13367                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13368
13369                 /* binary_upgrade:      no need to clear TOAST table oid */
13370
13371                 if (binary_upgrade)
13372                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13373                                                                                         labelq->data);
13374
13375                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13376                                          tbinfo->dobj.name,
13377                                          tbinfo->dobj.namespace->dobj.name,
13378                                          NULL,
13379                                          tbinfo->rolname,
13380                                          false, "SEQUENCE", SECTION_PRE_DATA,
13381                                          query->data, delqry->data, NULL,
13382                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13383                                          NULL, NULL);
13384
13385                 /*
13386                  * If the sequence is owned by a table column, emit the ALTER for it
13387                  * as a separate TOC entry immediately following the sequence's own
13388                  * entry.  It's OK to do this rather than using full sorting logic,
13389                  * because the dependency that tells us it's owned will have forced
13390                  * the table to be created first.  We can't just include the ALTER in
13391                  * the TOC entry because it will fail if we haven't reassigned the
13392                  * sequence owner to match the table's owner.
13393                  *
13394                  * We need not schema-qualify the table reference because both
13395                  * sequence and table must be in the same schema.
13396                  */
13397                 if (OidIsValid(tbinfo->owning_tab))
13398                 {
13399                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13400
13401                         if (owning_tab && owning_tab->dobj.dump)
13402                         {
13403                                 resetPQExpBuffer(query);
13404                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13405                                                                   fmtId(tbinfo->dobj.name));
13406                                 appendPQExpBuffer(query, " OWNED BY %s",
13407                                                                   fmtId(owning_tab->dobj.name));
13408                                 appendPQExpBuffer(query, ".%s;\n",
13409                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13410
13411                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13412                                                          tbinfo->dobj.name,
13413                                                          tbinfo->dobj.namespace->dobj.name,
13414                                                          NULL,
13415                                                          tbinfo->rolname,
13416                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13417                                                          query->data, "", NULL,
13418                                                          &(tbinfo->dobj.dumpId), 1,
13419                                                          NULL, NULL);
13420                         }
13421                 }
13422
13423                 /* Dump Sequence Comments and Security Labels */
13424                 dumpComment(fout, labelq->data,
13425                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13426                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13427                 dumpSecLabel(fout, labelq->data,
13428                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13429                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13430         }
13431
13432         if (!schemaOnly)
13433         {
13434                 resetPQExpBuffer(query);
13435                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13436                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13437                 appendPQExpBuffer(query, ", %s, %s);\n",
13438                                                   last, (called ? "true" : "false"));
13439
13440                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13441                                          tbinfo->dobj.name,
13442                                          tbinfo->dobj.namespace->dobj.name,
13443                                          NULL,
13444                                          tbinfo->rolname,
13445                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13446                                          query->data, "", NULL,
13447                                          &(tbinfo->dobj.dumpId), 1,
13448                                          NULL, NULL);
13449         }
13450
13451         PQclear(res);
13452
13453         destroyPQExpBuffer(query);
13454         destroyPQExpBuffer(delqry);
13455         destroyPQExpBuffer(labelq);
13456 }
13457
13458 static void
13459 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13460 {
13461         TableInfo  *tbinfo = tginfo->tgtable;
13462         PQExpBuffer query;
13463         PQExpBuffer delqry;
13464         PQExpBuffer labelq;
13465         char       *tgargs;
13466         size_t          lentgargs;
13467         const char *p;
13468         int                     findx;
13469
13470         if (dataOnly)
13471                 return;
13472
13473         query = createPQExpBuffer();
13474         delqry = createPQExpBuffer();
13475         labelq = createPQExpBuffer();
13476
13477         /*
13478          * DROP must be fully qualified in case same name appears in pg_catalog
13479          */
13480         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13481                                           fmtId(tginfo->dobj.name));
13482         appendPQExpBuffer(delqry, "ON %s.",
13483                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13484         appendPQExpBuffer(delqry, "%s;\n",
13485                                           fmtId(tbinfo->dobj.name));
13486
13487         if (tginfo->tgdef)
13488         {
13489                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13490         }
13491         else
13492         {
13493                 if (tginfo->tgisconstraint)
13494                 {
13495                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13496                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13497                 }
13498                 else
13499                 {
13500                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13501                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13502                 }
13503                 appendPQExpBuffer(query, "\n    ");
13504
13505                 /* Trigger type */
13506                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13507                         appendPQExpBuffer(query, "BEFORE");
13508                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13509                         appendPQExpBuffer(query, "AFTER");
13510                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13511                         appendPQExpBuffer(query, "INSTEAD OF");
13512                 else
13513                 {
13514                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13515                         exit_nicely(1);
13516                 }
13517
13518                 findx = 0;
13519                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13520                 {
13521                         appendPQExpBuffer(query, " INSERT");
13522                         findx++;
13523                 }
13524                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13525                 {
13526                         if (findx > 0)
13527                                 appendPQExpBuffer(query, " OR DELETE");
13528                         else
13529                                 appendPQExpBuffer(query, " DELETE");
13530                         findx++;
13531                 }
13532                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13533                 {
13534                         if (findx > 0)
13535                                 appendPQExpBuffer(query, " OR UPDATE");
13536                         else
13537                                 appendPQExpBuffer(query, " UPDATE");
13538                         findx++;
13539                 }
13540                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13541                 {
13542                         if (findx > 0)
13543                                 appendPQExpBuffer(query, " OR TRUNCATE");
13544                         else
13545                                 appendPQExpBuffer(query, " TRUNCATE");
13546                         findx++;
13547                 }
13548                 appendPQExpBuffer(query, " ON %s\n",
13549                                                   fmtId(tbinfo->dobj.name));
13550
13551                 if (tginfo->tgisconstraint)
13552                 {
13553                         if (OidIsValid(tginfo->tgconstrrelid))
13554                         {
13555                                 /* If we are using regclass, name is already quoted */
13556                                 if (fout->remoteVersion >= 70300)
13557                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13558                                                                           tginfo->tgconstrrelname);
13559                                 else
13560                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13561                                                                           fmtId(tginfo->tgconstrrelname));
13562                         }
13563                         if (!tginfo->tgdeferrable)
13564                                 appendPQExpBuffer(query, "NOT ");
13565                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13566                         if (tginfo->tginitdeferred)
13567                                 appendPQExpBuffer(query, "DEFERRED\n");
13568                         else
13569                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13570                 }
13571
13572                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13573                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13574                 else
13575                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13576
13577                 /* In 7.3, result of regproc is already quoted */
13578                 if (fout->remoteVersion >= 70300)
13579                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13580                                                           tginfo->tgfname);
13581                 else
13582                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13583                                                           fmtId(tginfo->tgfname));
13584
13585                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13586                                                                                   &lentgargs);
13587                 p = tgargs;
13588                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13589                 {
13590                         /* find the embedded null that terminates this trigger argument */
13591                         size_t          tlen = strlen(p);
13592
13593                         if (p + tlen >= tgargs + lentgargs)
13594                         {
13595                                 /* hm, not found before end of bytea value... */
13596                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13597                                                   tginfo->tgargs,
13598                                                   tginfo->dobj.name,
13599                                                   tbinfo->dobj.name);
13600                                 exit_nicely(1);
13601                         }
13602
13603                         if (findx > 0)
13604                                 appendPQExpBuffer(query, ", ");
13605                         appendStringLiteralAH(query, p, fout);
13606                         p += tlen + 1;
13607                 }
13608                 free(tgargs);
13609                 appendPQExpBuffer(query, ");\n");
13610         }
13611
13612         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13613         {
13614                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13615                                                   fmtId(tbinfo->dobj.name));
13616                 switch (tginfo->tgenabled)
13617                 {
13618                         case 'D':
13619                         case 'f':
13620                                 appendPQExpBuffer(query, "DISABLE");
13621                                 break;
13622                         case 'A':
13623                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13624                                 break;
13625                         case 'R':
13626                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13627                                 break;
13628                         default:
13629                                 appendPQExpBuffer(query, "ENABLE");
13630                                 break;
13631                 }
13632                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13633                                                   fmtId(tginfo->dobj.name));
13634         }
13635
13636         appendPQExpBuffer(labelq, "TRIGGER %s ",
13637                                           fmtId(tginfo->dobj.name));
13638         appendPQExpBuffer(labelq, "ON %s",
13639                                           fmtId(tbinfo->dobj.name));
13640
13641         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13642                                  tginfo->dobj.name,
13643                                  tbinfo->dobj.namespace->dobj.name,
13644                                  NULL,
13645                                  tbinfo->rolname, false,
13646                                  "TRIGGER", SECTION_POST_DATA,
13647                                  query->data, delqry->data, NULL,
13648                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13649                                  NULL, NULL);
13650
13651         dumpComment(fout, labelq->data,
13652                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13653                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13654
13655         destroyPQExpBuffer(query);
13656         destroyPQExpBuffer(delqry);
13657         destroyPQExpBuffer(labelq);
13658 }
13659
13660 /*
13661  * dumpRule
13662  *              Dump a rule
13663  */
13664 static void
13665 dumpRule(Archive *fout, RuleInfo *rinfo)
13666 {
13667         TableInfo  *tbinfo = rinfo->ruletable;
13668         PQExpBuffer query;
13669         PQExpBuffer cmd;
13670         PQExpBuffer delcmd;
13671         PQExpBuffer labelq;
13672         PGresult   *res;
13673
13674         /* Skip if not to be dumped */
13675         if (!rinfo->dobj.dump || dataOnly)
13676                 return;
13677
13678         /*
13679          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13680          * we do not want to dump it as a separate object.
13681          */
13682         if (!rinfo->separate)
13683                 return;
13684
13685         /*
13686          * Make sure we are in proper schema.
13687          */
13688         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13689
13690         query = createPQExpBuffer();
13691         cmd = createPQExpBuffer();
13692         delcmd = createPQExpBuffer();
13693         labelq = createPQExpBuffer();
13694
13695         if (fout->remoteVersion >= 70300)
13696         {
13697                 appendPQExpBuffer(query,
13698                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13699                                                   rinfo->dobj.catId.oid);
13700         }
13701         else
13702         {
13703                 /* Rule name was unique before 7.3 ... */
13704                 appendPQExpBuffer(query,
13705                                                   "SELECT pg_get_ruledef('%s') AS definition",
13706                                                   rinfo->dobj.name);
13707         }
13708
13709         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13710
13711         if (PQntuples(res) != 1)
13712         {
13713                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13714                                   rinfo->dobj.name, tbinfo->dobj.name);
13715                 exit_nicely(1);
13716         }
13717
13718         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13719
13720         /*
13721          * Add the command to alter the rules replication firing semantics if it
13722          * differs from the default.
13723          */
13724         if (rinfo->ev_enabled != 'O')
13725         {
13726                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13727                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13728                 appendPQExpBuffer(cmd, "%s ",
13729                                                   fmtId(tbinfo->dobj.name));
13730                 switch (rinfo->ev_enabled)
13731                 {
13732                         case 'A':
13733                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13734                                                                   fmtId(rinfo->dobj.name));
13735                                 break;
13736                         case 'R':
13737                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13738                                                                   fmtId(rinfo->dobj.name));
13739                                 break;
13740                         case 'D':
13741                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13742                                                                   fmtId(rinfo->dobj.name));
13743                                 break;
13744                 }
13745         }
13746
13747         /*
13748          * DROP must be fully qualified in case same name appears in pg_catalog
13749          */
13750         appendPQExpBuffer(delcmd, "DROP RULE %s ",
13751                                           fmtId(rinfo->dobj.name));
13752         appendPQExpBuffer(delcmd, "ON %s.",
13753                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13754         appendPQExpBuffer(delcmd, "%s;\n",
13755                                           fmtId(tbinfo->dobj.name));
13756
13757         appendPQExpBuffer(labelq, "RULE %s",
13758                                           fmtId(rinfo->dobj.name));
13759         appendPQExpBuffer(labelq, " ON %s",
13760                                           fmtId(tbinfo->dobj.name));
13761
13762         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13763                                  rinfo->dobj.name,
13764                                  tbinfo->dobj.namespace->dobj.name,
13765                                  NULL,
13766                                  tbinfo->rolname, false,
13767                                  "RULE", SECTION_POST_DATA,
13768                                  cmd->data, delcmd->data, NULL,
13769                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13770                                  NULL, NULL);
13771
13772         /* Dump rule comments */
13773         dumpComment(fout, labelq->data,
13774                                 tbinfo->dobj.namespace->dobj.name,
13775                                 tbinfo->rolname,
13776                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13777
13778         PQclear(res);
13779
13780         destroyPQExpBuffer(query);
13781         destroyPQExpBuffer(cmd);
13782         destroyPQExpBuffer(delcmd);
13783         destroyPQExpBuffer(labelq);
13784 }
13785
13786 /*
13787  * getExtensionMembership --- obtain extension membership data
13788  */
13789 void
13790 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13791                                            int numExtensions)
13792 {
13793         PQExpBuffer query;
13794         PGresult   *res;
13795         int                     ntups,
13796                                 i;
13797         int                     i_classid,
13798                                 i_objid,
13799                                 i_refclassid,
13800                                 i_refobjid;
13801         DumpableObject *dobj,
13802                            *refdobj;
13803
13804         /* Nothing to do if no extensions */
13805         if (numExtensions == 0)
13806                 return;
13807
13808         /* Make sure we are in proper schema */
13809         selectSourceSchema(fout, "pg_catalog");
13810
13811         query = createPQExpBuffer();
13812
13813         /* refclassid constraint is redundant but may speed the search */
13814         appendPQExpBuffer(query, "SELECT "
13815                                           "classid, objid, refclassid, refobjid "
13816                                           "FROM pg_depend "
13817                                           "WHERE refclassid = 'pg_extension'::regclass "
13818                                           "AND deptype = 'e' "
13819                                           "ORDER BY 3,4");
13820
13821         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13822
13823         ntups = PQntuples(res);
13824
13825         i_classid = PQfnumber(res, "classid");
13826         i_objid = PQfnumber(res, "objid");
13827         i_refclassid = PQfnumber(res, "refclassid");
13828         i_refobjid = PQfnumber(res, "refobjid");
13829
13830         /*
13831          * Since we ordered the SELECT by referenced ID, we can expect that
13832          * multiple entries for the same extension will appear together; this
13833          * saves on searches.
13834          */
13835         refdobj = NULL;
13836
13837         for (i = 0; i < ntups; i++)
13838         {
13839                 CatalogId       objId;
13840                 CatalogId       refobjId;
13841
13842                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13843                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13844                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13845                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13846
13847                 if (refdobj == NULL ||
13848                         refdobj->catId.tableoid != refobjId.tableoid ||
13849                         refdobj->catId.oid != refobjId.oid)
13850                         refdobj = findObjectByCatalogId(refobjId);
13851
13852                 /*
13853                  * Failure to find objects mentioned in pg_depend is not unexpected,
13854                  * since for example we don't collect info about TOAST tables.
13855                  */
13856                 if (refdobj == NULL)
13857                 {
13858 #ifdef NOT_USED
13859                         fprintf(stderr, "no referenced object %u %u\n",
13860                                         refobjId.tableoid, refobjId.oid);
13861 #endif
13862                         continue;
13863                 }
13864
13865                 dobj = findObjectByCatalogId(objId);
13866
13867                 if (dobj == NULL)
13868                 {
13869 #ifdef NOT_USED
13870                         fprintf(stderr, "no referencing object %u %u\n",
13871                                         objId.tableoid, objId.oid);
13872 #endif
13873                         continue;
13874                 }
13875
13876                 /* Record dependency so that getDependencies needn't repeat this */
13877                 addObjectDependency(dobj, refdobj->dumpId);
13878
13879                 dobj->ext_member = true;
13880
13881                 /*
13882                  * Normally, mark the member object as not to be dumped.  But in
13883                  * binary upgrades, we still dump the members individually, since the
13884                  * idea is to exactly reproduce the database contents rather than
13885                  * replace the extension contents with something different.
13886                  */
13887                 if (!binary_upgrade)
13888                         dobj->dump = false;
13889                 else
13890                         dobj->dump = refdobj->dump;
13891         }
13892
13893         PQclear(res);
13894
13895         /*
13896          * Now identify extension configuration tables and create TableDataInfo
13897          * objects for them, ensuring their data will be dumped even though the
13898          * tables themselves won't be.
13899          *
13900          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13901          * user data in a configuration table is treated like schema data. This
13902          * seems appropriate since system data in a config table would get
13903          * reloaded by CREATE EXTENSION.
13904          */
13905         for (i = 0; i < numExtensions; i++)
13906         {
13907                 ExtensionInfo *curext = &(extinfo[i]);
13908                 char       *extconfig = curext->extconfig;
13909                 char       *extcondition = curext->extcondition;
13910                 char      **extconfigarray = NULL;
13911                 char      **extconditionarray = NULL;
13912                 int                     nconfigitems;
13913                 int                     nconditionitems;
13914
13915                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13916                 if (!curext->dobj.dump)
13917                         continue;
13918
13919                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13920                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13921                         nconfigitems == nconditionitems)
13922                 {
13923                         int                     j;
13924
13925                         for (j = 0; j < nconfigitems; j++)
13926                         {
13927                                 TableInfo  *configtbl;
13928
13929                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
13930                                 if (configtbl == NULL)
13931                                         continue;
13932
13933                                 /*
13934                                  * Note: config tables are dumped without OIDs regardless
13935                                  * of the --oids setting.  This is because row filtering
13936                                  * conditions aren't compatible with dumping OIDs.
13937                                  */
13938                                 makeTableDataInfo(configtbl, false);
13939                                 if (configtbl->dataObj != NULL)
13940                                 {
13941                                         if (strlen(extconditionarray[j]) > 0)
13942                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13943                                 }
13944                         }
13945                 }
13946                 if (extconfigarray)
13947                         free(extconfigarray);
13948                 if (extconditionarray)
13949                         free(extconditionarray);
13950         }
13951
13952         destroyPQExpBuffer(query);
13953 }
13954
13955 /*
13956  * getDependencies --- obtain available dependency data
13957  */
13958 static void
13959 getDependencies(Archive *fout)
13960 {
13961         PQExpBuffer query;
13962         PGresult   *res;
13963         int                     ntups,
13964                                 i;
13965         int                     i_classid,
13966                                 i_objid,
13967                                 i_refclassid,
13968                                 i_refobjid,
13969                                 i_deptype;
13970         DumpableObject *dobj,
13971                            *refdobj;
13972
13973         /* No dependency info available before 7.3 */
13974         if (fout->remoteVersion < 70300)
13975                 return;
13976
13977         if (g_verbose)
13978                 write_msg(NULL, "reading dependency data\n");
13979
13980         /* Make sure we are in proper schema */
13981         selectSourceSchema(fout, "pg_catalog");
13982
13983         query = createPQExpBuffer();
13984
13985         /*
13986          * PIN dependencies aren't interesting, and EXTENSION dependencies were
13987          * already processed by getExtensionMembership.
13988          */
13989         appendPQExpBuffer(query, "SELECT "
13990                                           "classid, objid, refclassid, refobjid, deptype "
13991                                           "FROM pg_depend "
13992                                           "WHERE deptype != 'p' AND deptype != 'e' "
13993                                           "ORDER BY 1,2");
13994
13995         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13996
13997         ntups = PQntuples(res);
13998
13999         i_classid = PQfnumber(res, "classid");
14000         i_objid = PQfnumber(res, "objid");
14001         i_refclassid = PQfnumber(res, "refclassid");
14002         i_refobjid = PQfnumber(res, "refobjid");
14003         i_deptype = PQfnumber(res, "deptype");
14004
14005         /*
14006          * Since we ordered the SELECT by referencing ID, we can expect that
14007          * multiple entries for the same object will appear together; this saves
14008          * on searches.
14009          */
14010         dobj = NULL;
14011
14012         for (i = 0; i < ntups; i++)
14013         {
14014                 CatalogId       objId;
14015                 CatalogId       refobjId;
14016                 char            deptype;
14017
14018                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14019                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14020                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14021                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14022                 deptype = *(PQgetvalue(res, i, i_deptype));
14023
14024                 if (dobj == NULL ||
14025                         dobj->catId.tableoid != objId.tableoid ||
14026                         dobj->catId.oid != objId.oid)
14027                         dobj = findObjectByCatalogId(objId);
14028
14029                 /*
14030                  * Failure to find objects mentioned in pg_depend is not unexpected,
14031                  * since for example we don't collect info about TOAST tables.
14032                  */
14033                 if (dobj == NULL)
14034                 {
14035 #ifdef NOT_USED
14036                         fprintf(stderr, "no referencing object %u %u\n",
14037                                         objId.tableoid, objId.oid);
14038 #endif
14039                         continue;
14040                 }
14041
14042                 refdobj = findObjectByCatalogId(refobjId);
14043
14044                 if (refdobj == NULL)
14045                 {
14046 #ifdef NOT_USED
14047                         fprintf(stderr, "no referenced object %u %u\n",
14048                                         refobjId.tableoid, refobjId.oid);
14049 #endif
14050                         continue;
14051                 }
14052
14053                 /*
14054                  * Ordinarily, table rowtypes have implicit dependencies on their
14055                  * tables.      However, for a composite type the implicit dependency goes
14056                  * the other way in pg_depend; which is the right thing for DROP but
14057                  * it doesn't produce the dependency ordering we need. So in that one
14058                  * case, we reverse the direction of the dependency.
14059                  */
14060                 if (deptype == 'i' &&
14061                         dobj->objType == DO_TABLE &&
14062                         refdobj->objType == DO_TYPE)
14063                         addObjectDependency(refdobj, dobj->dumpId);
14064                 else
14065                         /* normal case */
14066                         addObjectDependency(dobj, refdobj->dumpId);
14067         }
14068
14069         PQclear(res);
14070
14071         destroyPQExpBuffer(query);
14072 }
14073
14074
14075 /*
14076  * selectSourceSchema - make the specified schema the active search path
14077  * in the source database.
14078  *
14079  * NB: pg_catalog is explicitly searched after the specified schema;
14080  * so user names are only qualified if they are cross-schema references,
14081  * and system names are only qualified if they conflict with a user name
14082  * in the current schema.
14083  *
14084  * Whenever the selected schema is not pg_catalog, be careful to qualify
14085  * references to system catalogs and types in our emitted commands!
14086  */
14087 static void
14088 selectSourceSchema(Archive *fout, const char *schemaName)
14089 {
14090         static char *curSchemaName = NULL;
14091         PQExpBuffer query;
14092
14093         /* Not relevant if fetching from pre-7.3 DB */
14094         if (fout->remoteVersion < 70300)
14095                 return;
14096         /* Ignore null schema names */
14097         if (schemaName == NULL || *schemaName == '\0')
14098                 return;
14099         /* Optimize away repeated selection of same schema */
14100         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14101                 return;
14102
14103         query = createPQExpBuffer();
14104         appendPQExpBuffer(query, "SET search_path = %s",
14105                                           fmtId(schemaName));
14106         if (strcmp(schemaName, "pg_catalog") != 0)
14107                 appendPQExpBuffer(query, ", pg_catalog");
14108
14109         ExecuteSqlStatement(fout, query->data);
14110
14111         destroyPQExpBuffer(query);
14112         if (curSchemaName)
14113                 free(curSchemaName);
14114         curSchemaName = pg_strdup(schemaName);
14115 }
14116
14117 /*
14118  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14119  * given type name.
14120  *
14121  * NB: in 7.3 and up the result may depend on the currently-selected
14122  * schema; this is why we don't try to cache the names.
14123  */
14124 static char *
14125 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14126 {
14127         char       *result;
14128         PQExpBuffer query;
14129         PGresult   *res;
14130
14131         if (oid == 0)
14132         {
14133                 if ((opts & zeroAsOpaque) != 0)
14134                         return pg_strdup(g_opaque_type);
14135                 else if ((opts & zeroAsAny) != 0)
14136                         return pg_strdup("'any'");
14137                 else if ((opts & zeroAsStar) != 0)
14138                         return pg_strdup("*");
14139                 else if ((opts & zeroAsNone) != 0)
14140                         return pg_strdup("NONE");
14141         }
14142
14143         query = createPQExpBuffer();
14144         if (fout->remoteVersion >= 70300)
14145         {
14146                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14147                                                   oid);
14148         }
14149         else if (fout->remoteVersion >= 70100)
14150         {
14151                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14152                                                   oid);
14153         }
14154         else
14155         {
14156                 appendPQExpBuffer(query, "SELECT typname "
14157                                                   "FROM pg_type "
14158                                                   "WHERE oid = '%u'::oid",
14159                                                   oid);
14160         }
14161
14162         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14163
14164         if (fout->remoteVersion >= 70100)
14165         {
14166                 /* already quoted */
14167                 result = pg_strdup(PQgetvalue(res, 0, 0));
14168         }
14169         else
14170         {
14171                 /* may need to quote it */
14172                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14173         }
14174
14175         PQclear(res);
14176         destroyPQExpBuffer(query);
14177
14178         return result;
14179 }
14180
14181 /*
14182  * myFormatType --- local implementation of format_type for use with 7.0.
14183  */
14184 static char *
14185 myFormatType(const char *typname, int32 typmod)
14186 {
14187         char       *result;
14188         bool            isarray = false;
14189         PQExpBuffer buf = createPQExpBuffer();
14190
14191         /* Handle array types */
14192         if (typname[0] == '_')
14193         {
14194                 isarray = true;
14195                 typname++;
14196         }
14197
14198         /* Show lengths on bpchar and varchar */
14199         if (strcmp(typname, "bpchar") == 0)
14200         {
14201                 int                     len = (typmod - VARHDRSZ);
14202
14203                 appendPQExpBuffer(buf, "character");
14204                 if (len > 1)
14205                         appendPQExpBuffer(buf, "(%d)",
14206                                                           typmod - VARHDRSZ);
14207         }
14208         else if (strcmp(typname, "varchar") == 0)
14209         {
14210                 appendPQExpBuffer(buf, "character varying");
14211                 if (typmod != -1)
14212                         appendPQExpBuffer(buf, "(%d)",
14213                                                           typmod - VARHDRSZ);
14214         }
14215         else if (strcmp(typname, "numeric") == 0)
14216         {
14217                 appendPQExpBuffer(buf, "numeric");
14218                 if (typmod != -1)
14219                 {
14220                         int32           tmp_typmod;
14221                         int                     precision;
14222                         int                     scale;
14223
14224                         tmp_typmod = typmod - VARHDRSZ;
14225                         precision = (tmp_typmod >> 16) & 0xffff;
14226                         scale = tmp_typmod & 0xffff;
14227                         appendPQExpBuffer(buf, "(%d,%d)",
14228                                                           precision, scale);
14229                 }
14230         }
14231
14232         /*
14233          * char is an internal single-byte data type; Let's make sure we force it
14234          * through with quotes. - thomas 1998-12-13
14235          */
14236         else if (strcmp(typname, "char") == 0)
14237                 appendPQExpBuffer(buf, "\"char\"");
14238         else
14239                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14240
14241         /* Append array qualifier for array types */
14242         if (isarray)
14243                 appendPQExpBuffer(buf, "[]");
14244
14245         result = pg_strdup(buf->data);
14246         destroyPQExpBuffer(buf);
14247
14248         return result;
14249 }
14250
14251 /*
14252  * fmtQualifiedId - convert a qualified name to the proper format for
14253  * the source database.
14254  *
14255  * Like fmtId, use the result before calling again.
14256  */
14257 static const char *
14258 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14259 {
14260         static PQExpBuffer id_return = NULL;
14261
14262         if (id_return)                          /* first time through? */
14263                 resetPQExpBuffer(id_return);
14264         else
14265                 id_return = createPQExpBuffer();
14266
14267         /* Suppress schema name if fetching from pre-7.3 DB */
14268         if (fout->remoteVersion >= 70300 && schema && *schema)
14269         {
14270                 appendPQExpBuffer(id_return, "%s.",
14271                                                   fmtId(schema));
14272         }
14273         appendPQExpBuffer(id_return, "%s",
14274                                           fmtId(id));
14275
14276         return id_return->data;
14277 }
14278
14279 /*
14280  * Return a column list clause for the given relation.
14281  *
14282  * Special case: if there are no undropped columns in the relation, return
14283  * "", not an invalid "()" column list.
14284  */
14285 static const char *
14286 fmtCopyColumnList(const TableInfo *ti)
14287 {
14288         static PQExpBuffer q = NULL;
14289         int                     numatts = ti->numatts;
14290         char      **attnames = ti->attnames;
14291         bool       *attisdropped = ti->attisdropped;
14292         bool            needComma;
14293         int                     i;
14294
14295         if (q)                                          /* first time through? */
14296                 resetPQExpBuffer(q);
14297         else
14298                 q = createPQExpBuffer();
14299
14300         appendPQExpBuffer(q, "(");
14301         needComma = false;
14302         for (i = 0; i < numatts; i++)
14303         {
14304                 if (attisdropped[i])
14305                         continue;
14306                 if (needComma)
14307                         appendPQExpBuffer(q, ", ");
14308                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14309                 needComma = true;
14310         }
14311
14312         if (!needComma)
14313                 return "";                              /* no undropped columns */
14314
14315         appendPQExpBuffer(q, ")");
14316         return q->data;
14317 }
14318
14319 /*
14320  * Execute an SQL query and verify that we got exactly one row back.
14321  */
14322 static PGresult *
14323 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14324 {
14325         PGresult   *res;
14326         int                     ntups;
14327
14328         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14329
14330         /* Expecting a single result only */
14331         ntups = PQntuples(res);
14332         if (ntups != 1)
14333                 exit_horribly(NULL,
14334                                           ngettext("query returned %d row instead of one: %s\n",
14335                                                            "query returned %d rows instead of one: %s\n",
14336                                                                  ntups),
14337                                           ntups, query);
14338
14339         return res;
14340 }