]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
f968496aaa67af5160daa8a06782678edd447192
[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 PGconn     *g_conn;                             /* the database connection */
90
91 /* various user-settable parameters */
92 bool            schemaOnly;
93 bool            dataOnly;
94 int         dumpSections; /* bitmask of chosen sections */
95 bool            aclsSkip;
96 const char *lockWaitTimeout;
97
98 /* subquery used to convert user ID (eg, datdba) to user name */
99 static const char *username_subquery;
100
101 /* obsolete as of 7.3: */
102 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
103
104 /*
105  * Object inclusion/exclusion lists
106  *
107  * The string lists record the patterns given by command-line switches,
108  * which we then convert to lists of OIDs of matching objects.
109  */
110 static SimpleStringList schema_include_patterns = {NULL, NULL};
111 static SimpleOidList schema_include_oids = {NULL, NULL};
112 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
113 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114
115 static SimpleStringList table_include_patterns = {NULL, NULL};
116 static SimpleOidList table_include_oids = {NULL, NULL};
117 static SimpleStringList table_exclude_patterns = {NULL, NULL};
118 static SimpleOidList table_exclude_oids = {NULL, NULL};
119 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
120 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
121
122 /* default, if no "inclusion" switches appear, is to dump everything */
123 static bool include_everything = true;
124
125 char            g_opaque_type[10];      /* name for the opaque type */
126
127 /* placeholders for the delimiters for comments */
128 char            g_comment_start[10];
129 char            g_comment_end[10];
130
131 static const CatalogId nilCatalogId = {0, 0};
132
133 /* these are to avoid passing around info for findNamespace() */
134 static NamespaceInfo *g_namespaces;
135 static int      g_numNamespaces;
136
137 /* flags for various command-line long options */
138 static int      binary_upgrade = 0;
139 static int      disable_dollar_quoting = 0;
140 static int      dump_inserts = 0;
141 static int      column_inserts = 0;
142 static int      no_security_labels = 0;
143 static int      no_unlogged_table_data = 0;
144 static int      serializable_deferrable = 0;
145
146
147 static void help(const char *progname);
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
260 int
261 main(int argc, char **argv)
262 {
263         int                     c;
264         const char *filename = NULL;
265         const char *format = "p";
266         const char *dbname = NULL;
267         const char *pghost = NULL;
268         const char *pgport = NULL;
269         const char *username = NULL;
270         const char *dumpencoding = NULL;
271         bool            oids = false;
272         TableInfo  *tblinfo;
273         int                     numTables;
274         DumpableObject **dobjs;
275         int                     numObjs;
276         int                     i;
277         enum trivalue prompt_password = TRI_DEFAULT;
278         int                     compressLevel = -1;
279         int                     plainText = 0;
280         int                     outputClean = 0;
281         int                     outputCreateDB = 0;
282         bool            outputBlobs = false;
283         int                     outputNoOwner = 0;
284         char       *outputSuperuser = NULL;
285         char       *use_role = NULL;
286         int                     my_version;
287         int                     optindex;
288         RestoreOptions *ropt;
289         ArchiveFormat archiveFormat = archUnknown;
290         ArchiveMode archiveMode;
291         Archive    *fout;                               /* the script file */
292
293         static int      disable_triggers = 0;
294         static int      outputNoTablespaces = 0;
295         static int      use_setsessauth = 0;
296
297         static struct option long_options[] = {
298                 {"data-only", no_argument, NULL, 'a'},
299                 {"blobs", no_argument, NULL, 'b'},
300                 {"clean", no_argument, NULL, 'c'},
301                 {"create", no_argument, NULL, 'C'},
302                 {"file", required_argument, NULL, 'f'},
303                 {"format", required_argument, NULL, 'F'},
304                 {"host", required_argument, NULL, 'h'},
305                 {"ignore-version", no_argument, NULL, 'i'},
306                 {"no-reconnect", no_argument, NULL, 'R'},
307                 {"oids", no_argument, NULL, 'o'},
308                 {"no-owner", no_argument, NULL, 'O'},
309                 {"port", required_argument, NULL, 'p'},
310                 {"schema", required_argument, NULL, 'n'},
311                 {"exclude-schema", required_argument, NULL, 'N'},
312                 {"schema-only", no_argument, NULL, 's'},
313                 {"superuser", required_argument, NULL, 'S'},
314                 {"table", required_argument, NULL, 't'},
315                 {"exclude-table", required_argument, NULL, 'T'},
316                 {"no-password", no_argument, NULL, 'w'},
317                 {"password", no_argument, NULL, 'W'},
318                 {"username", required_argument, NULL, 'U'},
319                 {"verbose", no_argument, NULL, 'v'},
320                 {"no-privileges", no_argument, NULL, 'x'},
321                 {"no-acl", no_argument, NULL, 'x'},
322                 {"compress", required_argument, NULL, 'Z'},
323                 {"encoding", required_argument, NULL, 'E'},
324                 {"help", no_argument, NULL, '?'},
325                 {"version", no_argument, NULL, 'V'},
326
327                 /*
328                  * the following options don't have an equivalent short option letter
329                  */
330                 {"attribute-inserts", no_argument, &column_inserts, 1},
331                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
332                 {"column-inserts", no_argument, &column_inserts, 1},
333                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
334                 {"disable-triggers", no_argument, &disable_triggers, 1},
335                 {"exclude-table-data", required_argument, NULL, 4},
336                 {"inserts", no_argument, &dump_inserts, 1},
337                 {"lock-wait-timeout", required_argument, NULL, 2},
338                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
339                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
340                 {"role", required_argument, NULL, 3},
341                 {"section", required_argument, NULL, 5},
342                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
343                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
344                 {"no-security-labels", no_argument, &no_security_labels, 1},
345                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
346
347                 {NULL, 0, NULL, 0}
348         };
349
350         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
351
352         g_verbose = false;
353
354         strcpy(g_comment_start, "-- ");
355         g_comment_end[0] = '\0';
356         strcpy(g_opaque_type, "opaque");
357
358         dataOnly = schemaOnly = false;
359         dumpSections = DUMP_UNSECTIONED;
360         lockWaitTimeout = NULL;
361
362         progname = get_progname(argv[0]);
363
364         /* Set default options based on progname */
365         if (strcmp(progname, "pg_backup") == 0)
366                 format = "c";
367
368         if (argc > 1)
369         {
370                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
371                 {
372                         help(progname);
373                         exit(0);
374                 }
375                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
376                 {
377                         puts("pg_dump (PostgreSQL) " PG_VERSION);
378                         exit(0);
379                 }
380         }
381
382         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
383                                                         long_options, &optindex)) != -1)
384         {
385                 switch (c)
386                 {
387                         case 'a':                       /* Dump data only */
388                                 dataOnly = true;
389                                 break;
390
391                         case 'b':                       /* Dump blobs */
392                                 outputBlobs = true;
393                                 break;
394
395                         case 'c':                       /* clean (i.e., drop) schema prior to create */
396                                 outputClean = 1;
397                                 break;
398
399                         case 'C':                       /* Create DB */
400                                 outputCreateDB = 1;
401                                 break;
402
403                         case 'E':                       /* Dump encoding */
404                                 dumpencoding = optarg;
405                                 break;
406
407                         case 'f':
408                                 filename = optarg;
409                                 break;
410
411                         case 'F':
412                                 format = optarg;
413                                 break;
414
415                         case 'h':                       /* server host */
416                                 pghost = optarg;
417                                 break;
418
419                         case 'i':
420                                 /* ignored, deprecated option */
421                                 break;
422
423                         case 'n':                       /* include schema(s) */
424                                 simple_string_list_append(&schema_include_patterns, optarg);
425                                 include_everything = false;
426                                 break;
427
428                         case 'N':                       /* exclude schema(s) */
429                                 simple_string_list_append(&schema_exclude_patterns, optarg);
430                                 break;
431
432                         case 'o':                       /* Dump oids */
433                                 oids = true;
434                                 break;
435
436                         case 'O':                       /* Don't reconnect to match owner */
437                                 outputNoOwner = 1;
438                                 break;
439
440                         case 'p':                       /* server port */
441                                 pgport = optarg;
442                                 break;
443
444                         case 'R':
445                                 /* no-op, still accepted for backwards compatibility */
446                                 break;
447
448                         case 's':                       /* dump schema only */
449                                 schemaOnly = true;
450                                 break;
451
452                         case 'S':                       /* Username for superuser in plain text output */
453                                 outputSuperuser = pg_strdup(optarg);
454                                 break;
455
456                         case 't':                       /* include table(s) */
457                                 simple_string_list_append(&table_include_patterns, optarg);
458                                 include_everything = false;
459                                 break;
460
461                         case 'T':                       /* exclude table(s) */
462                                 simple_string_list_append(&table_exclude_patterns, optarg);
463                                 break;
464
465                         case 'U':
466                                 username = optarg;
467                                 break;
468
469                         case 'v':                       /* verbose */
470                                 g_verbose = true;
471                                 break;
472
473                         case 'w':
474                                 prompt_password = TRI_NO;
475                                 break;
476
477                         case 'W':
478                                 prompt_password = TRI_YES;
479                                 break;
480
481                         case 'x':                       /* skip ACL dump */
482                                 aclsSkip = true;
483                                 break;
484
485                         case 'Z':                       /* Compression Level */
486                                 compressLevel = atoi(optarg);
487                                 break;
488
489                         case 0:
490                                 /* This covers the long options. */
491                                 break;
492
493                         case 2:                         /* lock-wait-timeout */
494                                 lockWaitTimeout = optarg;
495                                 break;
496
497                         case 3:                         /* SET ROLE */
498                                 use_role = optarg;
499                                 break;
500
501                         case 4:                 /* exclude table(s) data */
502                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
503                                 break;
504
505                         case 5:                         /* section */
506                                 set_section(optarg, &dumpSections);
507                                 break;
508
509                         default:
510                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
511                                 exit(1);
512                 }
513         }
514
515         /* Get database name from command line */
516         if (optind < argc)
517                 dbname = argv[optind++];
518
519         /* Complain if any arguments remain */
520         if (optind < argc)
521         {
522                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
523                                 progname, argv[optind]);
524                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
525                                 progname);
526                 exit(1);
527         }
528
529         /* --column-inserts implies --inserts */
530         if (column_inserts)
531                 dump_inserts = 1;
532
533         if (dataOnly && schemaOnly)
534         {
535                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
536                 exit(1);
537         }
538
539         if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
540         {
541                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
542                 exit(1);
543         }
544
545         if (dataOnly)
546                 dumpSections = DUMP_DATA;
547         else if (schemaOnly)
548                 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
549         else if ( dumpSections != DUMP_UNSECTIONED)
550         {
551                 dataOnly = dumpSections == DUMP_DATA;
552                 schemaOnly = !(dumpSections & DUMP_DATA);
553         }
554
555         if (dataOnly && outputClean)
556         {
557                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
558                 exit(1);
559         }
560
561         if (dump_inserts && oids)
562         {
563                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
564                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
565                 exit(1);
566         }
567
568         /* Identify archive format to emit */
569         archiveFormat = parseArchiveFormat(format, &archiveMode);
570
571         /* archiveFormat specific setup */
572         if (archiveFormat == archNull)
573                 plainText = 1;
574
575         /* Custom and directory formats are compressed by default, others not */
576         if (compressLevel == -1)
577         {
578                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
579                         compressLevel = Z_DEFAULT_COMPRESSION;
580                 else
581                         compressLevel = 0;
582         }
583
584         /* Open the output file */
585         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
586
587         if (fout == NULL)
588         {
589                 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
590                 exit(1);
591         }
592
593         /* Let the archiver know how noisy to be */
594         fout->verbose = g_verbose;
595
596         my_version = parse_version(PG_VERSION);
597         if (my_version < 0)
598         {
599                 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
600                 exit(1);
601         }
602
603         /*
604          * We allow the server to be back to 7.0, and up to any minor release of
605          * our own major version.  (See also version check in pg_dumpall.c.)
606          */
607         fout->minRemoteVersion = 70000;
608         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
609
610         /*
611          * Open the database using the Archiver, so it knows about it. Errors mean
612          * death.
613          */
614         g_conn = ConnectDatabase(fout, dbname, pghost, pgport,
615                                                          username, prompt_password);
616
617         setup_connection(fout, dumpencoding, use_role);
618
619         /*
620          * Disable security label support if server version < v9.1.x (prevents
621          * access to nonexistent pg_seclabel catalog)
622          */
623         if (fout->remoteVersion < 90100)
624                 no_security_labels = 1;
625
626         /*
627          * Start transaction-snapshot mode transaction to dump consistent data.
628          */
629         ExecuteSqlStatement(fout, "BEGIN");
630         if (fout->remoteVersion >= 90100)
631         {
632                 if (serializable_deferrable)
633                         ExecuteSqlStatement(fout,
634                                                                 "SET TRANSACTION ISOLATION LEVEL "
635                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
636                 else
637                         ExecuteSqlStatement(fout,
638                                                                 "SET TRANSACTION ISOLATION LEVEL "
639                                                                 "REPEATABLE READ");
640         }
641         else
642                 ExecuteSqlStatement(fout,
643                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
644
645         /* Select the appropriate subquery to convert user IDs to names */
646         if (fout->remoteVersion >= 80100)
647                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
648         else if (fout->remoteVersion >= 70300)
649                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
650         else
651                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
652
653         /* Find the last built-in OID, if needed */
654         if (fout->remoteVersion < 70300)
655         {
656                 if (fout->remoteVersion >= 70100)
657                         g_last_builtin_oid = findLastBuiltinOid_V71(fout, PQdb(g_conn));
658                 else
659                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
660                 if (g_verbose)
661                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
662         }
663
664         /* Expand schema selection patterns into OID lists */
665         if (schema_include_patterns.head != NULL)
666         {
667                 expand_schema_name_patterns(fout, &schema_include_patterns,
668                                                                         &schema_include_oids);
669                 if (schema_include_oids.head == NULL)
670                 {
671                         write_msg(NULL, "No matching schemas were found\n");
672                         exit_nicely();
673                 }
674         }
675         expand_schema_name_patterns(fout, &schema_exclude_patterns,
676                                                                 &schema_exclude_oids);
677         /* non-matching exclusion patterns aren't an error */
678
679         /* Expand table selection patterns into OID lists */
680         if (table_include_patterns.head != NULL)
681         {
682                 expand_table_name_patterns(fout, &table_include_patterns,
683                                                                    &table_include_oids);
684                 if (table_include_oids.head == NULL)
685                 {
686                         write_msg(NULL, "No matching tables were found\n");
687                         exit_nicely();
688                 }
689         }
690         expand_table_name_patterns(fout, &table_exclude_patterns,
691                                                            &table_exclude_oids);
692
693         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
694                                                            &tabledata_exclude_oids);
695
696         /* non-matching exclusion patterns aren't an error */
697
698         /*
699          * Dumping blobs is now default unless we saw an inclusion switch or -s
700          * ... but even if we did see one of these, -b turns it back on.
701          */
702         if (include_everything && !schemaOnly)
703                 outputBlobs = true;
704
705         /*
706          * Now scan the database and create DumpableObject structs for all the
707          * objects we intend to dump.
708          */
709         tblinfo = getSchemaData(fout, &numTables);
710
711         if (fout->remoteVersion < 80400)
712                 guessConstraintInheritance(tblinfo, numTables);
713
714         if (!schemaOnly)
715         {
716                 getTableData(tblinfo, numTables, oids);
717                 if (dataOnly)
718                         getTableDataFKConstraints();
719         }
720
721         if (outputBlobs)
722                 getBlobs(fout);
723
724         /*
725          * Collect dependency data to assist in ordering the objects.
726          */
727         getDependencies(fout);
728
729         /*
730          * Sort the objects into a safe dump order (no forward references).
731          *
732          * In 7.3 or later, we can rely on dependency information to help us
733          * determine a safe order, so the initial sort is mostly for cosmetic
734          * purposes: we sort by name to ensure that logically identical schemas
735          * will dump identically.  Before 7.3 we don't have dependencies and we
736          * use OID ordering as an (unreliable) guide to creation order.
737          */
738         getDumpableObjects(&dobjs, &numObjs);
739
740         if (fout->remoteVersion >= 70300)
741                 sortDumpableObjectsByTypeName(dobjs, numObjs);
742         else
743                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
744
745         sortDumpableObjects(dobjs, numObjs);
746
747         /*
748          * Create archive TOC entries for all the objects to be dumped, in a safe
749          * order.
750          */
751
752         /* First the special ENCODING and STDSTRINGS entries. */
753         dumpEncoding(fout);
754         dumpStdStrings(fout);
755
756         /* The database item is always next, unless we don't want it at all */
757         if (include_everything && !dataOnly)
758                 dumpDatabase(fout);
759
760         /* Now the rearrangeable objects. */
761         for (i = 0; i < numObjs; i++)
762                 dumpDumpableObject(fout, dobjs[i]);
763
764         /*
765          * And finally we can do the actual output.
766          */
767         if (plainText)
768         {
769                 ropt = NewRestoreOptions();
770                 ropt->filename = filename;
771                 ropt->dropSchema = outputClean;
772                 ropt->aclsSkip = aclsSkip;
773                 ropt->superuser = outputSuperuser;
774                 ropt->createDB = outputCreateDB;
775                 ropt->noOwner = outputNoOwner;
776                 ropt->noTablespace = outputNoTablespaces;
777                 ropt->disable_triggers = disable_triggers;
778                 ropt->use_setsessauth = use_setsessauth;
779                 ropt->dataOnly = dataOnly;
780
781                 if (compressLevel == -1)
782                         ropt->compression = 0;
783                 else
784                         ropt->compression = compressLevel;
785
786                 ropt->suppressDumpWarnings = true;              /* We've already shown them */
787
788                 RestoreArchive(fout, ropt);
789         }
790
791         CloseArchive(fout);
792
793         PQfinish(g_conn);
794
795         exit(0);
796 }
797
798
799 static void
800 help(const char *progname)
801 {
802         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
803         printf(_("Usage:\n"));
804         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
805
806         printf(_("\nGeneral options:\n"));
807         printf(_("  -f, --file=FILENAME         output file or directory name\n"));
808         printf(_("  -F, --format=c|d|t|p        output file format (custom, directory, tar,\n"
809                          "                              plain text (default))\n"));
810         printf(_("  -v, --verbose               verbose mode\n"));
811         printf(_("  -Z, --compress=0-9          compression level for compressed formats\n"));
812         printf(_("  --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
813         printf(_("  --help                      show this help, then exit\n"));
814         printf(_("  --version                   output version information, then exit\n"));
815
816         printf(_("\nOptions controlling the output content:\n"));
817         printf(_("  -a, --data-only             dump only the data, not the schema\n"));
818         printf(_("  -b, --blobs                 include large objects in dump\n"));
819         printf(_("  -c, --clean                 clean (drop) database objects before recreating\n"));
820         printf(_("  -C, --create                include commands to create database in dump\n"));
821         printf(_("  -E, --encoding=ENCODING     dump the data in encoding ENCODING\n"));
822         printf(_("  -n, --schema=SCHEMA         dump the named schema(s) only\n"));
823         printf(_("  -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
824         printf(_("  -o, --oids                  include OIDs in dump\n"));
825         printf(_("  -O, --no-owner              skip restoration of object ownership in\n"
826                          "                              plain-text format\n"));
827         printf(_("  -s, --schema-only           dump only the schema, no data\n"));
828         printf(_("  -S, --superuser=NAME        superuser user name to use in plain-text format\n"));
829         printf(_("  -t, --table=TABLE           dump the named table(s) only\n"));
830         printf(_("  -T, --exclude-table=TABLE   do NOT dump the named table(s)\n"));
831         printf(_("  -x, --no-privileges         do not dump privileges (grant/revoke)\n"));
832         printf(_("  --binary-upgrade            for use by upgrade utilities only\n"));
833         printf(_("  --column-inserts            dump data as INSERT commands with column names\n"));
834         printf(_("  --disable-dollar-quoting    disable dollar quoting, use SQL standard quoting\n"));
835         printf(_("  --disable-triggers          disable triggers during data-only restore\n"));
836         printf(_("  --exclude-table-data=TABLE  do NOT dump data for the named table(s)\n"));
837         printf(_("  --inserts                   dump data as INSERT commands, rather than COPY\n"));
838         printf(_("  --no-security-labels        do not dump security label assignments\n"));
839         printf(_("  --no-tablespaces            do not dump tablespace assignments\n"));
840         printf(_("  --no-unlogged-table-data    do not dump unlogged table data\n"));
841         printf(_("  --quote-all-identifiers     quote all identifiers, even if not key words\n"));
842         printf(_("  --section=SECTION           dump named section (pre-data, data or post-data)\n"));
843         printf(_("  --serializable-deferrable   wait until the dump can run without anomalies\n"));
844         printf(_("  --use-set-session-authorization\n"
845                          "                              use SET SESSION AUTHORIZATION commands instead of\n"
846         "                              ALTER OWNER commands to set ownership\n"));
847
848         printf(_("\nConnection options:\n"));
849         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
850         printf(_("  -p, --port=PORT          database server port number\n"));
851         printf(_("  -U, --username=NAME      connect as specified database user\n"));
852         printf(_("  -w, --no-password        never prompt for password\n"));
853         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
854         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
855
856         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
857                          "variable value is used.\n\n"));
858         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
859 }
860
861 void
862 exit_nicely(void)
863 {
864         PQfinish(g_conn);
865         if (g_verbose)
866                 write_msg(NULL, "*** aborted because of error\n");
867         exit(1);
868 }
869
870 static void
871 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
872 {
873         const char *std_strings;
874
875         /* Set the client encoding if requested */
876         if (dumpencoding)
877         {
878                 if (PQsetClientEncoding(g_conn, dumpencoding) < 0)
879                 {
880                         write_msg(NULL, "invalid client encoding \"%s\" specified\n",
881                                           dumpencoding);
882                         exit(1);
883                 }
884         }
885
886         /*
887          * Get the active encoding and the standard_conforming_strings setting, so
888          * we know how to escape strings.
889          */
890         AH->encoding = PQclientEncoding(g_conn);
891
892         std_strings = PQparameterStatus(g_conn, "standard_conforming_strings");
893         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
894
895         /* Set the role if requested */
896         if (use_role && AH->remoteVersion >= 80100)
897         {
898                 PQExpBuffer query = createPQExpBuffer();
899
900                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
901                 ExecuteSqlStatement(AH, query->data);
902                 destroyPQExpBuffer(query);
903         }
904
905         /* Set the datestyle to ISO to ensure the dump's portability */
906         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
907
908         /* Likewise, avoid using sql_standard intervalstyle */
909         if (AH->remoteVersion >= 80400)
910                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
911
912         /*
913          * If supported, set extra_float_digits so that we can dump float data
914          * exactly (given correctly implemented float I/O code, anyway)
915          */
916         if (AH->remoteVersion >= 90000)
917                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
918         else if (AH->remoteVersion >= 70400)
919                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
920
921         /*
922          * If synchronized scanning is supported, disable it, to prevent
923          * unpredictable changes in row ordering across a dump and reload.
924          */
925         if (AH->remoteVersion >= 80300)
926                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
927
928         /*
929          * Disable timeouts if supported.
930          */
931         if (AH->remoteVersion >= 70300)
932                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
933
934         /*
935          * Quote all identifiers, if requested.
936          */
937         if (quote_all_identifiers && AH->remoteVersion >= 90100)
938                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
939 }
940
941 static ArchiveFormat
942 parseArchiveFormat(const char *format, ArchiveMode *mode)
943 {
944         ArchiveFormat archiveFormat;
945
946         *mode = archModeWrite;
947
948         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
949         {
950                 /* This is used by pg_dumpall, and is not documented */
951                 archiveFormat = archNull;
952                 *mode = archModeAppend;
953         }
954         else if (pg_strcasecmp(format, "c") == 0)
955                 archiveFormat = archCustom;
956         else if (pg_strcasecmp(format, "custom") == 0)
957                 archiveFormat = archCustom;
958         else if (pg_strcasecmp(format, "d") == 0)
959                 archiveFormat = archDirectory;
960         else if (pg_strcasecmp(format, "directory") == 0)
961                 archiveFormat = archDirectory;
962         else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
963
964                 /*
965                  * Dump files into the current directory; for demonstration only, not
966                  * documented.
967                  */
968                 archiveFormat = archFiles;
969         else if (pg_strcasecmp(format, "p") == 0)
970                 archiveFormat = archNull;
971         else if (pg_strcasecmp(format, "plain") == 0)
972                 archiveFormat = archNull;
973         else if (pg_strcasecmp(format, "t") == 0)
974                 archiveFormat = archTar;
975         else if (pg_strcasecmp(format, "tar") == 0)
976                 archiveFormat = archTar;
977         else
978         {
979                 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
980                 exit(1);
981         }
982         return archiveFormat;
983 }
984
985 /*
986  * Find the OIDs of all schemas matching the given list of patterns,
987  * and append them to the given OID list.
988  */
989 static void
990 expand_schema_name_patterns(Archive *fout,
991                                                         SimpleStringList *patterns,
992                                                         SimpleOidList *oids)
993 {
994         PQExpBuffer query;
995         PGresult   *res;
996         SimpleStringListCell *cell;
997         int                     i;
998
999         if (patterns->head == NULL)
1000                 return;                                 /* nothing to do */
1001
1002         if (fout->remoteVersion < 70300)
1003         {
1004                 write_msg(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1005                 exit_nicely();
1006         }
1007
1008         query = createPQExpBuffer();
1009
1010         /*
1011          * We use UNION ALL rather than UNION; this might sometimes result in
1012          * duplicate entries in the OID list, but we don't care.
1013          */
1014
1015         for (cell = patterns->head; cell; cell = cell->next)
1016         {
1017                 if (cell != patterns->head)
1018                         appendPQExpBuffer(query, "UNION ALL\n");
1019                 appendPQExpBuffer(query,
1020                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1021                 processSQLNamePattern(g_conn, query, cell->val, false, false,
1022                                                           NULL, "n.nspname", NULL,
1023                                                           NULL);
1024         }
1025
1026         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1027
1028         for (i = 0; i < PQntuples(res); i++)
1029         {
1030                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1031         }
1032
1033         PQclear(res);
1034         destroyPQExpBuffer(query);
1035 }
1036
1037 /*
1038  * Find the OIDs of all tables matching the given list of patterns,
1039  * and append them to the given OID list.
1040  */
1041 static void
1042 expand_table_name_patterns(Archive *fout,
1043                                                    SimpleStringList *patterns, SimpleOidList *oids)
1044 {
1045         PQExpBuffer query;
1046         PGresult   *res;
1047         SimpleStringListCell *cell;
1048         int                     i;
1049
1050         if (patterns->head == NULL)
1051                 return;                                 /* nothing to do */
1052
1053         query = createPQExpBuffer();
1054
1055         /*
1056          * We use UNION ALL rather than UNION; this might sometimes result in
1057          * duplicate entries in the OID list, but we don't care.
1058          */
1059
1060         for (cell = patterns->head; cell; cell = cell->next)
1061         {
1062                 if (cell != patterns->head)
1063                         appendPQExpBuffer(query, "UNION ALL\n");
1064                 appendPQExpBuffer(query,
1065                                                   "SELECT c.oid"
1066                                                   "\nFROM pg_catalog.pg_class c"
1067                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1068                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1069                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1070                                                   RELKIND_FOREIGN_TABLE);
1071                 processSQLNamePattern(g_conn, query, cell->val, true, false,
1072                                                           "n.nspname", "c.relname", NULL,
1073                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1074         }
1075
1076         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1077
1078         for (i = 0; i < PQntuples(res); i++)
1079         {
1080                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1081         }
1082
1083         PQclear(res);
1084         destroyPQExpBuffer(query);
1085 }
1086
1087 /*
1088  * selectDumpableNamespace: policy-setting subroutine
1089  *              Mark a namespace as to be dumped or not
1090  */
1091 static void
1092 selectDumpableNamespace(NamespaceInfo *nsinfo)
1093 {
1094         /*
1095          * If specific tables are being dumped, do not dump any complete
1096          * namespaces. If specific namespaces are being dumped, dump just those
1097          * namespaces. Otherwise, dump all non-system namespaces.
1098          */
1099         if (table_include_oids.head != NULL)
1100                 nsinfo->dobj.dump = false;
1101         else if (schema_include_oids.head != NULL)
1102                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1103                                                                                                    nsinfo->dobj.catId.oid);
1104         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1105                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1106                 nsinfo->dobj.dump = false;
1107         else
1108                 nsinfo->dobj.dump = true;
1109
1110         /*
1111          * In any case, a namespace can be excluded by an exclusion switch
1112          */
1113         if (nsinfo->dobj.dump &&
1114                 simple_oid_list_member(&schema_exclude_oids,
1115                                                            nsinfo->dobj.catId.oid))
1116                 nsinfo->dobj.dump = false;
1117 }
1118
1119 /*
1120  * selectDumpableTable: policy-setting subroutine
1121  *              Mark a table as to be dumped or not
1122  */
1123 static void
1124 selectDumpableTable(TableInfo *tbinfo)
1125 {
1126         /*
1127          * If specific tables are being dumped, dump just those tables; else, dump
1128          * according to the parent namespace's dump flag.
1129          */
1130         if (table_include_oids.head != NULL)
1131                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1132                                                                                                    tbinfo->dobj.catId.oid);
1133         else
1134                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1135
1136         /*
1137          * In any case, a table can be excluded by an exclusion switch
1138          */
1139         if (tbinfo->dobj.dump &&
1140                 simple_oid_list_member(&table_exclude_oids,
1141                                                            tbinfo->dobj.catId.oid))
1142                 tbinfo->dobj.dump = false;
1143 }
1144
1145 /*
1146  * selectDumpableType: policy-setting subroutine
1147  *              Mark a type as to be dumped or not
1148  *
1149  * If it's a table's rowtype or an autogenerated array type, we also apply a
1150  * special type code to facilitate sorting into the desired order.      (We don't
1151  * want to consider those to be ordinary types because that would bring tables
1152  * up into the datatype part of the dump order.)  We still set the object's
1153  * dump flag; that's not going to cause the dummy type to be dumped, but we
1154  * need it so that casts involving such types will be dumped correctly -- see
1155  * dumpCast.  This means the flag should be set the same as for the underlying
1156  * object (the table or base type).
1157  */
1158 static void
1159 selectDumpableType(TypeInfo *tyinfo)
1160 {
1161         /* skip complex types, except for standalone composite types */
1162         if (OidIsValid(tyinfo->typrelid) &&
1163                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1164         {
1165                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1166
1167                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1168                 if (tytable != NULL)
1169                         tyinfo->dobj.dump = tytable->dobj.dump;
1170                 else
1171                         tyinfo->dobj.dump = false;
1172                 return;
1173         }
1174
1175         /* skip auto-generated array types */
1176         if (tyinfo->isArray)
1177         {
1178                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1179                 /*
1180                  * Fall through to set the dump flag; we assume that the subsequent
1181                  * rules will do the same thing as they would for the array's base
1182                  * type.  (We cannot reliably look up the base type here, since
1183                  * getTypes may not have processed it yet.)
1184                  */
1185         }
1186
1187         /* dump only types in dumpable namespaces */
1188         if (!tyinfo->dobj.namespace->dobj.dump)
1189                 tyinfo->dobj.dump = false;
1190
1191         /* skip undefined placeholder types */
1192         else if (!tyinfo->isDefined)
1193                 tyinfo->dobj.dump = false;
1194
1195         else
1196                 tyinfo->dobj.dump = true;
1197 }
1198
1199 /*
1200  * selectDumpableDefaultACL: policy-setting subroutine
1201  *              Mark a default ACL as to be dumped or not
1202  *
1203  * For per-schema default ACLs, dump if the schema is to be dumped.
1204  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1205  * and aclsSkip are checked separately.
1206  */
1207 static void
1208 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1209 {
1210         if (dinfo->dobj.namespace)
1211                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1212         else
1213                 dinfo->dobj.dump = include_everything;
1214 }
1215
1216 /*
1217  * selectDumpableExtension: policy-setting subroutine
1218  *              Mark an extension as to be dumped or not
1219  *
1220  * Normally, we dump all extensions, or none of them if include_everything
1221  * is false (i.e., a --schema or --table switch was given).  However, in
1222  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1223  * assume those will already be installed in the target database.  We identify
1224  * such extensions by their having OIDs in the range reserved for initdb.
1225  */
1226 static void
1227 selectDumpableExtension(ExtensionInfo *extinfo)
1228 {
1229         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1230                 extinfo->dobj.dump = false;
1231         else
1232                 extinfo->dobj.dump = include_everything;
1233 }
1234
1235 /*
1236  * selectDumpableObject: policy-setting subroutine
1237  *              Mark a generic dumpable object as to be dumped or not
1238  *
1239  * Use this only for object types without a special-case routine above.
1240  */
1241 static void
1242 selectDumpableObject(DumpableObject *dobj)
1243 {
1244         /*
1245          * Default policy is to dump if parent namespace is dumpable, or always
1246          * for non-namespace-associated items.
1247          */
1248         if (dobj->namespace)
1249                 dobj->dump = dobj->namespace->dobj.dump;
1250         else
1251                 dobj->dump = true;
1252 }
1253
1254 /*
1255  *      Dump a table's contents for loading using the COPY command
1256  *      - this routine is called by the Archiver when it wants the table
1257  *        to be dumped.
1258  */
1259
1260 static int
1261 dumpTableData_copy(Archive *fout, void *dcontext)
1262 {
1263         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1264         TableInfo  *tbinfo = tdinfo->tdtable;
1265         const char *classname = tbinfo->dobj.name;
1266         const bool      hasoids = tbinfo->hasoids;
1267         const bool      oids = tdinfo->oids;
1268         PQExpBuffer q = createPQExpBuffer();
1269         PGresult   *res;
1270         int                     ret;
1271         char       *copybuf;
1272         const char *column_list;
1273
1274         if (g_verbose)
1275                 write_msg(NULL, "dumping contents of table %s\n", classname);
1276
1277         /*
1278          * Make sure we are in proper schema.  We will qualify the table name
1279          * below anyway (in case its name conflicts with a pg_catalog table); but
1280          * this ensures reproducible results in case the table contains regproc,
1281          * regclass, etc columns.
1282          */
1283         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1284
1285         /*
1286          * If possible, specify the column list explicitly so that we have no
1287          * possibility of retrieving data in the wrong column order.  (The default
1288          * column ordering of COPY will not be what we want in certain corner
1289          * cases involving ADD COLUMN and inheritance.)
1290          */
1291         if (fout->remoteVersion >= 70300)
1292                 column_list = fmtCopyColumnList(tbinfo);
1293         else
1294                 column_list = "";               /* can't select columns in COPY */
1295
1296         if (oids && hasoids)
1297         {
1298                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1299                                                   fmtQualifiedId(fout,
1300                                                                                  tbinfo->dobj.namespace->dobj.name,
1301                                                                                  classname),
1302                                                   column_list);
1303         }
1304         else if (tdinfo->filtercond)
1305         {
1306                 /* Note: this syntax is only supported in 8.2 and up */
1307                 appendPQExpBufferStr(q, "COPY (SELECT ");
1308                 /* klugery to get rid of parens in column list */
1309                 if (strlen(column_list) > 2)
1310                 {
1311                         appendPQExpBufferStr(q, column_list + 1);
1312                         q->data[q->len - 1] = ' ';
1313                 }
1314                 else
1315                         appendPQExpBufferStr(q, "* ");
1316                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1317                                                   fmtQualifiedId(fout,
1318                                                                                  tbinfo->dobj.namespace->dobj.name,
1319                                                                                  classname),
1320                                                   tdinfo->filtercond);
1321         }
1322         else
1323         {
1324                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1325                                                   fmtQualifiedId(fout,
1326                                                                                  tbinfo->dobj.namespace->dobj.name,
1327                                                                                  classname),
1328                                                   column_list);
1329         }
1330         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1331         PQclear(res);
1332
1333         for (;;)
1334         {
1335                 ret = PQgetCopyData(g_conn, &copybuf, 0);
1336
1337                 if (ret < 0)
1338                         break;                          /* done or error */
1339
1340                 if (copybuf)
1341                 {
1342                         WriteData(fout, copybuf, ret);
1343                         PQfreemem(copybuf);
1344                 }
1345
1346                 /* ----------
1347                  * THROTTLE:
1348                  *
1349                  * There was considerable discussion in late July, 2000 regarding
1350                  * slowing down pg_dump when backing up large tables. Users with both
1351                  * slow & fast (multi-processor) machines experienced performance
1352                  * degradation when doing a backup.
1353                  *
1354                  * Initial attempts based on sleeping for a number of ms for each ms
1355                  * of work were deemed too complex, then a simple 'sleep in each loop'
1356                  * implementation was suggested. The latter failed because the loop
1357                  * was too tight. Finally, the following was implemented:
1358                  *
1359                  * If throttle is non-zero, then
1360                  *              See how long since the last sleep.
1361                  *              Work out how long to sleep (based on ratio).
1362                  *              If sleep is more than 100ms, then
1363                  *                      sleep
1364                  *                      reset timer
1365                  *              EndIf
1366                  * EndIf
1367                  *
1368                  * where the throttle value was the number of ms to sleep per ms of
1369                  * work. The calculation was done in each loop.
1370                  *
1371                  * Most of the hard work is done in the backend, and this solution
1372                  * still did not work particularly well: on slow machines, the ratio
1373                  * was 50:1, and on medium paced machines, 1:1, and on fast
1374                  * multi-processor machines, it had little or no effect, for reasons
1375                  * that were unclear.
1376                  *
1377                  * Further discussion ensued, and the proposal was dropped.
1378                  *
1379                  * For those people who want this feature, it can be implemented using
1380                  * gettimeofday in each loop, calculating the time since last sleep,
1381                  * multiplying that by the sleep ratio, then if the result is more
1382                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1383                  * function to sleep for a subsecond period ie.
1384                  *
1385                  * select(0, NULL, NULL, NULL, &tvi);
1386                  *
1387                  * This will return after the interval specified in the structure tvi.
1388                  * Finally, call gettimeofday again to save the 'last sleep time'.
1389                  * ----------
1390                  */
1391         }
1392         archprintf(fout, "\\.\n\n\n");
1393
1394         if (ret == -2)
1395         {
1396                 /* copy data transfer failed */
1397                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1398                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1399                 write_msg(NULL, "The command was: %s\n", q->data);
1400                 exit_nicely();
1401         }
1402
1403         /* Check command status and return to normal libpq state */
1404         res = PQgetResult(g_conn);
1405         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1406         {
1407                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1408                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1409                 write_msg(NULL, "The command was: %s\n", q->data);
1410                 exit_nicely();
1411         }
1412         PQclear(res);
1413
1414         destroyPQExpBuffer(q);
1415         return 1;
1416 }
1417
1418 /*
1419  * Dump table data using INSERT commands.
1420  *
1421  * Caution: when we restore from an archive file direct to database, the
1422  * INSERT commands emitted by this function have to be parsed by
1423  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1424  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1425  */
1426 static int
1427 dumpTableData_insert(Archive *fout, void *dcontext)
1428 {
1429         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1430         TableInfo  *tbinfo = tdinfo->tdtable;
1431         const char *classname = tbinfo->dobj.name;
1432         PQExpBuffer q = createPQExpBuffer();
1433         PGresult   *res;
1434         int                     tuple;
1435         int                     nfields;
1436         int                     field;
1437
1438         /*
1439          * Make sure we are in proper schema.  We will qualify the table name
1440          * below anyway (in case its name conflicts with a pg_catalog table); but
1441          * this ensures reproducible results in case the table contains regproc,
1442          * regclass, etc columns.
1443          */
1444         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1445
1446         if (fout->remoteVersion >= 70100)
1447         {
1448                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1449                                                   "SELECT * FROM ONLY %s",
1450                                                   fmtQualifiedId(fout,
1451                                                                                  tbinfo->dobj.namespace->dobj.name,
1452                                                                                  classname));
1453         }
1454         else
1455         {
1456                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1457                                                   "SELECT * FROM %s",
1458                                                   fmtQualifiedId(fout,
1459                                                                                  tbinfo->dobj.namespace->dobj.name,
1460                                                                                  classname));
1461         }
1462         if (tdinfo->filtercond)
1463                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1464
1465         ExecuteSqlStatement(fout, q->data);
1466
1467         while (1)
1468         {
1469                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1470                                                           PGRES_TUPLES_OK);
1471                 nfields = PQnfields(res);
1472                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1473                 {
1474                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1475                         if (nfields == 0)
1476                         {
1477                                 /* corner case for zero-column table */
1478                                 archprintf(fout, "DEFAULT VALUES;\n");
1479                                 continue;
1480                         }
1481                         if (column_inserts)
1482                         {
1483                                 resetPQExpBuffer(q);
1484                                 appendPQExpBuffer(q, "(");
1485                                 for (field = 0; field < nfields; field++)
1486                                 {
1487                                         if (field > 0)
1488                                                 appendPQExpBuffer(q, ", ");
1489                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1490                                 }
1491                                 appendPQExpBuffer(q, ") ");
1492                                 archputs(q->data, fout);
1493                         }
1494                         archprintf(fout, "VALUES (");
1495                         for (field = 0; field < nfields; field++)
1496                         {
1497                                 if (field > 0)
1498                                         archprintf(fout, ", ");
1499                                 if (PQgetisnull(res, tuple, field))
1500                                 {
1501                                         archprintf(fout, "NULL");
1502                                         continue;
1503                                 }
1504
1505                                 /* XXX This code is partially duplicated in ruleutils.c */
1506                                 switch (PQftype(res, field))
1507                                 {
1508                                         case INT2OID:
1509                                         case INT4OID:
1510                                         case INT8OID:
1511                                         case OIDOID:
1512                                         case FLOAT4OID:
1513                                         case FLOAT8OID:
1514                                         case NUMERICOID:
1515                                                 {
1516                                                         /*
1517                                                          * These types are printed without quotes unless
1518                                                          * they contain values that aren't accepted by the
1519                                                          * scanner unquoted (e.g., 'NaN').      Note that
1520                                                          * strtod() and friends might accept NaN, so we
1521                                                          * can't use that to test.
1522                                                          *
1523                                                          * In reality we only need to defend against
1524                                                          * infinity and NaN, so we need not get too crazy
1525                                                          * about pattern matching here.
1526                                                          */
1527                                                         const char *s = PQgetvalue(res, tuple, field);
1528
1529                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1530                                                                 archprintf(fout, "%s", s);
1531                                                         else
1532                                                                 archprintf(fout, "'%s'", s);
1533                                                 }
1534                                                 break;
1535
1536                                         case BITOID:
1537                                         case VARBITOID:
1538                                                 archprintf(fout, "B'%s'",
1539                                                                    PQgetvalue(res, tuple, field));
1540                                                 break;
1541
1542                                         case BOOLOID:
1543                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1544                                                         archprintf(fout, "true");
1545                                                 else
1546                                                         archprintf(fout, "false");
1547                                                 break;
1548
1549                                         default:
1550                                                 /* All other types are printed as string literals. */
1551                                                 resetPQExpBuffer(q);
1552                                                 appendStringLiteralAH(q,
1553                                                                                           PQgetvalue(res, tuple, field),
1554                                                                                           fout);
1555                                                 archputs(q->data, fout);
1556                                                 break;
1557                                 }
1558                         }
1559                         archprintf(fout, ");\n");
1560                 }
1561
1562                 if (PQntuples(res) <= 0)
1563                 {
1564                         PQclear(res);
1565                         break;
1566                 }
1567                 PQclear(res);
1568         }
1569
1570         archprintf(fout, "\n\n");
1571
1572         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1573
1574         destroyPQExpBuffer(q);
1575         return 1;
1576 }
1577
1578
1579 /*
1580  * dumpTableData -
1581  *        dump the contents of a single table
1582  *
1583  * Actually, this just makes an ArchiveEntry for the table contents.
1584  */
1585 static void
1586 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1587 {
1588         TableInfo  *tbinfo = tdinfo->tdtable;
1589         PQExpBuffer copyBuf = createPQExpBuffer();
1590         DataDumperPtr dumpFn;
1591         char       *copyStmt;
1592
1593         if (!dump_inserts)
1594         {
1595                 /* Dump/restore using COPY */
1596                 dumpFn = dumpTableData_copy;
1597                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1598                 appendPQExpBuffer(copyBuf, "COPY %s ",
1599                                                   fmtId(tbinfo->dobj.name));
1600                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1601                                                   fmtCopyColumnList(tbinfo),
1602                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1603                 copyStmt = copyBuf->data;
1604         }
1605         else
1606         {
1607                 /* Restore using INSERT */
1608                 dumpFn = dumpTableData_insert;
1609                 copyStmt = NULL;
1610         }
1611
1612         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1613                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1614                                  NULL, tbinfo->rolname,
1615                                  false, "TABLE DATA", SECTION_DATA,
1616                                  "", "", copyStmt,
1617                                  tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1618                                  dumpFn, tdinfo);
1619
1620         destroyPQExpBuffer(copyBuf);
1621 }
1622
1623 /*
1624  * getTableData -
1625  *        set up dumpable objects representing the contents of tables
1626  */
1627 static void
1628 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1629 {
1630         int                     i;
1631
1632         for (i = 0; i < numTables; i++)
1633         {
1634                 if (tblinfo[i].dobj.dump)
1635                         makeTableDataInfo(&(tblinfo[i]), oids);
1636         }
1637 }
1638
1639 /*
1640  * Make a dumpable object for the data of this specific table
1641  *
1642  * Note: we make a TableDataInfo if and only if we are going to dump the
1643  * table data; the "dump" flag in such objects isn't used.
1644  */
1645 static void
1646 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1647 {
1648         TableDataInfo *tdinfo;
1649
1650         /*
1651          * Nothing to do if we already decided to dump the table.  This will
1652          * happen for "config" tables.
1653          */
1654         if (tbinfo->dataObj != NULL)
1655                 return;
1656
1657         /* Skip VIEWs (no data to dump) */
1658         if (tbinfo->relkind == RELKIND_VIEW)
1659                 return;
1660         /* Skip SEQUENCEs (handled elsewhere) */
1661         if (tbinfo->relkind == RELKIND_SEQUENCE)
1662                 return;
1663         /* Skip FOREIGN TABLEs (no data to dump) */
1664         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1665                 return;
1666
1667         /* Don't dump data in unlogged tables, if so requested */
1668         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1669                 no_unlogged_table_data)
1670                 return;
1671
1672         /* Check that the data is not explicitly excluded */
1673         if (simple_oid_list_member(&tabledata_exclude_oids,
1674                                                            tbinfo->dobj.catId.oid))
1675                 return;
1676
1677         /* OK, let's dump it */
1678         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1679
1680         tdinfo->dobj.objType = DO_TABLE_DATA;
1681
1682         /*
1683          * Note: use tableoid 0 so that this object won't be mistaken for
1684          * something that pg_depend entries apply to.
1685          */
1686         tdinfo->dobj.catId.tableoid = 0;
1687         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1688         AssignDumpId(&tdinfo->dobj);
1689         tdinfo->dobj.name = tbinfo->dobj.name;
1690         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1691         tdinfo->tdtable = tbinfo;
1692         tdinfo->oids = oids;
1693         tdinfo->filtercond = NULL;      /* might get set later */
1694         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1695
1696         tbinfo->dataObj = tdinfo;
1697 }
1698
1699 /*
1700  * getTableDataFKConstraints -
1701  *        add dump-order dependencies reflecting foreign key constraints
1702  *
1703  * This code is executed only in a data-only dump --- in schema+data dumps
1704  * we handle foreign key issues by not creating the FK constraints until
1705  * after the data is loaded.  In a data-only dump, however, we want to
1706  * order the table data objects in such a way that a table's referenced
1707  * tables are restored first.  (In the presence of circular references or
1708  * self-references this may be impossible; we'll detect and complain about
1709  * that during the dependency sorting step.)
1710  */
1711 static void
1712 getTableDataFKConstraints(void)
1713 {
1714         DumpableObject **dobjs;
1715         int                     numObjs;
1716         int                     i;
1717
1718         /* Search through all the dumpable objects for FK constraints */
1719         getDumpableObjects(&dobjs, &numObjs);
1720         for (i = 0; i < numObjs; i++)
1721         {
1722                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1723                 {
1724                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1725                         TableInfo  *ftable;
1726
1727                         /* Not interesting unless both tables are to be dumped */
1728                         if (cinfo->contable == NULL ||
1729                                 cinfo->contable->dataObj == NULL)
1730                                 continue;
1731                         ftable = findTableByOid(cinfo->confrelid);
1732                         if (ftable == NULL ||
1733                                 ftable->dataObj == NULL)
1734                                 continue;
1735
1736                         /*
1737                          * Okay, make referencing table's TABLE_DATA object depend on the
1738                          * referenced table's TABLE_DATA object.
1739                          */
1740                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1741                                                                 ftable->dataObj->dobj.dumpId);
1742                 }
1743         }
1744         free(dobjs);
1745 }
1746
1747
1748 /*
1749  * guessConstraintInheritance:
1750  *      In pre-8.4 databases, we can't tell for certain which constraints
1751  *      are inherited.  We assume a CHECK constraint is inherited if its name
1752  *      matches the name of any constraint in the parent.  Originally this code
1753  *      tried to compare the expression texts, but that can fail for various
1754  *      reasons --- for example, if the parent and child tables are in different
1755  *      schemas, reverse-listing of function calls may produce different text
1756  *      (schema-qualified or not) depending on search path.
1757  *
1758  *      In 8.4 and up we can rely on the conislocal field to decide which
1759  *      constraints must be dumped; much safer.
1760  *
1761  *      This function assumes all conislocal flags were initialized to TRUE.
1762  *      It clears the flag on anything that seems to be inherited.
1763  */
1764 static void
1765 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1766 {
1767         int                     i,
1768                                 j,
1769                                 k;
1770
1771         for (i = 0; i < numTables; i++)
1772         {
1773                 TableInfo  *tbinfo = &(tblinfo[i]);
1774                 int                     numParents;
1775                 TableInfo **parents;
1776                 TableInfo  *parent;
1777
1778                 /* Sequences and views never have parents */
1779                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1780                         tbinfo->relkind == RELKIND_VIEW)
1781                         continue;
1782
1783                 /* Don't bother computing anything for non-target tables, either */
1784                 if (!tbinfo->dobj.dump)
1785                         continue;
1786
1787                 numParents = tbinfo->numParents;
1788                 parents = tbinfo->parents;
1789
1790                 if (numParents == 0)
1791                         continue;                       /* nothing to see here, move along */
1792
1793                 /* scan for inherited CHECK constraints */
1794                 for (j = 0; j < tbinfo->ncheck; j++)
1795                 {
1796                         ConstraintInfo *constr;
1797
1798                         constr = &(tbinfo->checkexprs[j]);
1799
1800                         for (k = 0; k < numParents; k++)
1801                         {
1802                                 int                     l;
1803
1804                                 parent = parents[k];
1805                                 for (l = 0; l < parent->ncheck; l++)
1806                                 {
1807                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1808
1809                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1810                                         {
1811                                                 constr->conislocal = false;
1812                                                 break;
1813                                         }
1814                                 }
1815                                 if (!constr->conislocal)
1816                                         break;
1817                         }
1818                 }
1819         }
1820 }
1821
1822
1823 /*
1824  * dumpDatabase:
1825  *      dump the database definition
1826  */
1827 static void
1828 dumpDatabase(Archive *fout)
1829 {
1830         PQExpBuffer dbQry = createPQExpBuffer();
1831         PQExpBuffer delQry = createPQExpBuffer();
1832         PQExpBuffer creaQry = createPQExpBuffer();
1833         PGresult   *res;
1834         int                     ntups;
1835         int                     i_tableoid,
1836                                 i_oid,
1837                                 i_dba,
1838                                 i_encoding,
1839                                 i_collate,
1840                                 i_ctype,
1841                                 i_frozenxid,
1842                                 i_tablespace;
1843         CatalogId       dbCatId;
1844         DumpId          dbDumpId;
1845         const char *datname,
1846                            *dba,
1847                            *encoding,
1848                            *collate,
1849                            *ctype,
1850                            *tablespace;
1851         uint32          frozenxid;
1852
1853         datname = PQdb(g_conn);
1854
1855         if (g_verbose)
1856                 write_msg(NULL, "saving database definition\n");
1857
1858         /* Make sure we are in proper schema */
1859         selectSourceSchema(fout, "pg_catalog");
1860
1861         /* Get the database owner and parameters from pg_database */
1862         if (fout->remoteVersion >= 80400)
1863         {
1864                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1865                                                   "(%s datdba) AS dba, "
1866                                                   "pg_encoding_to_char(encoding) AS encoding, "
1867                                                   "datcollate, datctype, datfrozenxid, "
1868                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1869                                           "shobj_description(oid, 'pg_database') AS description "
1870
1871                                                   "FROM pg_database "
1872                                                   "WHERE datname = ",
1873                                                   username_subquery);
1874                 appendStringLiteralAH(dbQry, datname, fout);
1875         }
1876         else if (fout->remoteVersion >= 80200)
1877         {
1878                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1879                                                   "(%s datdba) AS dba, "
1880                                                   "pg_encoding_to_char(encoding) AS encoding, "
1881                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1882                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1883                                           "shobj_description(oid, 'pg_database') AS description "
1884
1885                                                   "FROM pg_database "
1886                                                   "WHERE datname = ",
1887                                                   username_subquery);
1888                 appendStringLiteralAH(dbQry, datname, fout);
1889         }
1890         else if (fout->remoteVersion >= 80000)
1891         {
1892                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1893                                                   "(%s datdba) AS dba, "
1894                                                   "pg_encoding_to_char(encoding) AS encoding, "
1895                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1896                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1897                                                   "FROM pg_database "
1898                                                   "WHERE datname = ",
1899                                                   username_subquery);
1900                 appendStringLiteralAH(dbQry, datname, fout);
1901         }
1902         else if (fout->remoteVersion >= 70100)
1903         {
1904                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1905                                                   "(%s datdba) AS dba, "
1906                                                   "pg_encoding_to_char(encoding) AS encoding, "
1907                                                   "NULL AS datcollate, NULL AS datctype, "
1908                                                   "0 AS datfrozenxid, "
1909                                                   "NULL AS tablespace "
1910                                                   "FROM pg_database "
1911                                                   "WHERE datname = ",
1912                                                   username_subquery);
1913                 appendStringLiteralAH(dbQry, datname, fout);
1914         }
1915         else
1916         {
1917                 appendPQExpBuffer(dbQry, "SELECT "
1918                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1919                                                   "oid, "
1920                                                   "(%s datdba) AS dba, "
1921                                                   "pg_encoding_to_char(encoding) AS encoding, "
1922                                                   "NULL AS datcollate, NULL AS datctype, "
1923                                                   "0 AS datfrozenxid, "
1924                                                   "NULL AS tablespace "
1925                                                   "FROM pg_database "
1926                                                   "WHERE datname = ",
1927                                                   username_subquery);
1928                 appendStringLiteralAH(dbQry, datname, fout);
1929         }
1930
1931         res = ExecuteSqlQuery(fout, dbQry->data, PGRES_TUPLES_OK);
1932
1933         ntups = PQntuples(res);
1934
1935         if (ntups <= 0)
1936         {
1937                 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1938                                   datname);
1939                 exit_nicely();
1940         }
1941
1942         if (ntups != 1)
1943         {
1944                 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1945                                   ntups, datname);
1946                 exit_nicely();
1947         }
1948
1949         i_tableoid = PQfnumber(res, "tableoid");
1950         i_oid = PQfnumber(res, "oid");
1951         i_dba = PQfnumber(res, "dba");
1952         i_encoding = PQfnumber(res, "encoding");
1953         i_collate = PQfnumber(res, "datcollate");
1954         i_ctype = PQfnumber(res, "datctype");
1955         i_frozenxid = PQfnumber(res, "datfrozenxid");
1956         i_tablespace = PQfnumber(res, "tablespace");
1957
1958         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1959         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1960         dba = PQgetvalue(res, 0, i_dba);
1961         encoding = PQgetvalue(res, 0, i_encoding);
1962         collate = PQgetvalue(res, 0, i_collate);
1963         ctype = PQgetvalue(res, 0, i_ctype);
1964         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1965         tablespace = PQgetvalue(res, 0, i_tablespace);
1966
1967         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1968                                           fmtId(datname));
1969         if (strlen(encoding) > 0)
1970         {
1971                 appendPQExpBuffer(creaQry, " ENCODING = ");
1972                 appendStringLiteralAH(creaQry, encoding, fout);
1973         }
1974         if (strlen(collate) > 0)
1975         {
1976                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1977                 appendStringLiteralAH(creaQry, collate, fout);
1978         }
1979         if (strlen(ctype) > 0)
1980         {
1981                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1982                 appendStringLiteralAH(creaQry, ctype, fout);
1983         }
1984         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1985                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1986                                                   fmtId(tablespace));
1987         appendPQExpBuffer(creaQry, ";\n");
1988
1989         if (binary_upgrade)
1990         {
1991                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1992                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1993                                                   "SET datfrozenxid = '%u'\n"
1994                                                   "WHERE        datname = ",
1995                                                   frozenxid);
1996                 appendStringLiteralAH(creaQry, datname, fout);
1997                 appendPQExpBuffer(creaQry, ";\n");
1998
1999         }
2000
2001         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2002                                           fmtId(datname));
2003
2004         dbDumpId = createDumpId();
2005
2006         ArchiveEntry(fout,
2007                                  dbCatId,               /* catalog ID */
2008                                  dbDumpId,              /* dump ID */
2009                                  datname,               /* Name */
2010                                  NULL,                  /* Namespace */
2011                                  NULL,                  /* Tablespace */
2012                                  dba,                   /* Owner */
2013                                  false,                 /* with oids */
2014                                  "DATABASE",    /* Desc */
2015                                  SECTION_PRE_DATA,              /* Section */
2016                                  creaQry->data, /* Create */
2017                                  delQry->data,  /* Del */
2018                                  NULL,                  /* Copy */
2019                                  NULL,                  /* Deps */
2020                                  0,                             /* # Deps */
2021                                  NULL,                  /* Dumper */
2022                                  NULL);                 /* Dumper Arg */
2023
2024         /*
2025          * pg_largeobject and pg_largeobject_metadata come from the old system
2026          * intact, so set their relfrozenxids.
2027          */
2028         if (binary_upgrade)
2029         {
2030                 PGresult   *lo_res;
2031                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2032                 PQExpBuffer loOutQry = createPQExpBuffer();
2033                 int                     i_relfrozenxid;
2034
2035                 /*
2036                  * pg_largeobject
2037                  */
2038                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2039                                                   "FROM pg_catalog.pg_class\n"
2040                                                   "WHERE oid = %u;\n",
2041                                                   LargeObjectRelationId);
2042
2043                 lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
2044
2045                 if (PQntuples(lo_res) != 1)
2046                 {
2047                         write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
2048                         exit_nicely();
2049                 }
2050
2051                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2052
2053                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2054                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2055                                                   "SET relfrozenxid = '%u'\n"
2056                                                   "WHERE oid = %u;\n",
2057                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2058                                                   LargeObjectRelationId);
2059                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2060                                          "pg_largeobject", NULL, NULL, "",
2061                                          false, "pg_largeobject", SECTION_PRE_DATA,
2062                                          loOutQry->data, "", NULL,
2063                                          NULL, 0,
2064                                          NULL, NULL);
2065
2066                 PQclear(lo_res);
2067
2068                 /*
2069                  * pg_largeobject_metadata
2070                  */
2071                 if (fout->remoteVersion >= 90000)
2072                 {
2073                         resetPQExpBuffer(loFrozenQry);
2074                         resetPQExpBuffer(loOutQry);
2075
2076                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2077                                                           "FROM pg_catalog.pg_class\n"
2078                                                           "WHERE oid = %u;\n",
2079                                                           LargeObjectMetadataRelationId);
2080
2081                         lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
2082
2083                         if (PQntuples(lo_res) != 1)
2084                         {
2085                                 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject_metadata.relfrozenxid\n");
2086                                 exit_nicely();
2087                         }
2088
2089                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2090
2091                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2092                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2093                                                           "SET relfrozenxid = '%u'\n"
2094                                                           "WHERE oid = %u;\n",
2095                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2096                                                           LargeObjectMetadataRelationId);
2097                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2098                                                  "pg_largeobject_metadata", NULL, NULL, "",
2099                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2100                                                  loOutQry->data, "", NULL,
2101                                                  NULL, 0,
2102                                                  NULL, NULL);
2103
2104                         PQclear(lo_res);
2105                 }
2106
2107                 destroyPQExpBuffer(loFrozenQry);
2108                 destroyPQExpBuffer(loOutQry);
2109         }
2110
2111         /* Dump DB comment if any */
2112         if (fout->remoteVersion >= 80200)
2113         {
2114                 /*
2115                  * 8.2 keeps comments on shared objects in a shared table, so we
2116                  * cannot use the dumpComment used for other database objects.
2117                  */
2118                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2119
2120                 if (comment && strlen(comment))
2121                 {
2122                         resetPQExpBuffer(dbQry);
2123
2124                         /*
2125                          * Generates warning when loaded into a differently-named
2126                          * database.
2127                          */
2128                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2129                         appendStringLiteralAH(dbQry, comment, fout);
2130                         appendPQExpBuffer(dbQry, ";\n");
2131
2132                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2133                                                  dba, false, "COMMENT", SECTION_NONE,
2134                                                  dbQry->data, "", NULL,
2135                                                  &dbDumpId, 1, NULL, NULL);
2136                 }
2137         }
2138         else
2139         {
2140                 resetPQExpBuffer(dbQry);
2141                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2142                 dumpComment(fout, dbQry->data, NULL, "",
2143                                         dbCatId, 0, dbDumpId);
2144         }
2145
2146         PQclear(res);
2147
2148         /* Dump shared security label. */
2149         if (!no_security_labels && fout->remoteVersion >= 90200)
2150         {
2151                 PQExpBuffer seclabelQry = createPQExpBuffer();
2152
2153                 buildShSecLabelQuery(g_conn, "pg_database", dbCatId.oid, seclabelQry);
2154                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2155                 resetPQExpBuffer(seclabelQry);
2156                 emitShSecLabels(g_conn, res, seclabelQry, "DATABASE", datname);
2157                 if (strlen(seclabelQry->data))
2158                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2159                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2160                                                  seclabelQry->data, "", NULL,
2161                                                  &dbDumpId, 1, NULL, NULL);
2162                 destroyPQExpBuffer(seclabelQry);
2163         }
2164
2165         destroyPQExpBuffer(dbQry);
2166         destroyPQExpBuffer(delQry);
2167         destroyPQExpBuffer(creaQry);
2168 }
2169
2170
2171 /*
2172  * dumpEncoding: put the correct encoding into the archive
2173  */
2174 static void
2175 dumpEncoding(Archive *AH)
2176 {
2177         const char *encname = pg_encoding_to_char(AH->encoding);
2178         PQExpBuffer qry = createPQExpBuffer();
2179
2180         if (g_verbose)
2181                 write_msg(NULL, "saving encoding = %s\n", encname);
2182
2183         appendPQExpBuffer(qry, "SET client_encoding = ");
2184         appendStringLiteralAH(qry, encname, AH);
2185         appendPQExpBuffer(qry, ";\n");
2186
2187         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2188                                  "ENCODING", NULL, NULL, "",
2189                                  false, "ENCODING", SECTION_PRE_DATA,
2190                                  qry->data, "", NULL,
2191                                  NULL, 0,
2192                                  NULL, NULL);
2193
2194         destroyPQExpBuffer(qry);
2195 }
2196
2197
2198 /*
2199  * dumpStdStrings: put the correct escape string behavior into the archive
2200  */
2201 static void
2202 dumpStdStrings(Archive *AH)
2203 {
2204         const char *stdstrings = AH->std_strings ? "on" : "off";
2205         PQExpBuffer qry = createPQExpBuffer();
2206
2207         if (g_verbose)
2208                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2209                                   stdstrings);
2210
2211         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2212                                           stdstrings);
2213
2214         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2215                                  "STDSTRINGS", NULL, NULL, "",
2216                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2217                                  qry->data, "", NULL,
2218                                  NULL, 0,
2219                                  NULL, NULL);
2220
2221         destroyPQExpBuffer(qry);
2222 }
2223
2224
2225 /*
2226  * getBlobs:
2227  *      Collect schema-level data about large objects
2228  */
2229 static void
2230 getBlobs(Archive *fout)
2231 {
2232         PQExpBuffer blobQry = createPQExpBuffer();
2233         BlobInfo   *binfo;
2234         DumpableObject *bdata;
2235         PGresult   *res;
2236         int                     ntups;
2237         int                     i;
2238
2239         /* Verbose message */
2240         if (g_verbose)
2241                 write_msg(NULL, "reading large objects\n");
2242
2243         /* Make sure we are in proper schema */
2244         selectSourceSchema(fout, "pg_catalog");
2245
2246         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2247         if (fout->remoteVersion >= 90000)
2248                 appendPQExpBuffer(blobQry,
2249                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2250                                                   " FROM pg_largeobject_metadata",
2251                                                   username_subquery);
2252         else if (fout->remoteVersion >= 70100)
2253                 appendPQExpBuffer(blobQry,
2254                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2255                                                   " FROM pg_largeobject");
2256         else
2257                 appendPQExpBuffer(blobQry,
2258                                                   "SELECT oid, NULL::oid, NULL::oid"
2259                                                   " FROM pg_class WHERE relkind = 'l'");
2260
2261         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2262
2263         ntups = PQntuples(res);
2264         if (ntups > 0)
2265         {
2266                 /*
2267                  * Each large object has its own BLOB archive entry.
2268                  */
2269                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2270
2271                 for (i = 0; i < ntups; i++)
2272                 {
2273                         binfo[i].dobj.objType = DO_BLOB;
2274                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2275                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2276                         AssignDumpId(&binfo[i].dobj);
2277
2278                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2279                         if (!PQgetisnull(res, i, 1))
2280                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2281                         else
2282                                 binfo[i].rolname = "";
2283                         if (!PQgetisnull(res, i, 2))
2284                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2285                         else
2286                                 binfo[i].blobacl = NULL;
2287                 }
2288
2289                 /*
2290                  * If we have any large objects, a "BLOBS" archive entry is needed.
2291                  * This is just a placeholder for sorting; it carries no data now.
2292                  */
2293                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2294                 bdata->objType = DO_BLOB_DATA;
2295                 bdata->catId = nilCatalogId;
2296                 AssignDumpId(bdata);
2297                 bdata->name = pg_strdup("BLOBS");
2298         }
2299
2300         PQclear(res);
2301         destroyPQExpBuffer(blobQry);
2302 }
2303
2304 /*
2305  * dumpBlob
2306  *
2307  * dump the definition (metadata) of the given large object
2308  */
2309 static void
2310 dumpBlob(Archive *fout, BlobInfo *binfo)
2311 {
2312         PQExpBuffer cquery = createPQExpBuffer();
2313         PQExpBuffer dquery = createPQExpBuffer();
2314
2315         appendPQExpBuffer(cquery,
2316                                           "SELECT pg_catalog.lo_create('%s');\n",
2317                                           binfo->dobj.name);
2318
2319         appendPQExpBuffer(dquery,
2320                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2321                                           binfo->dobj.name);
2322
2323         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2324                                  binfo->dobj.name,
2325                                  NULL, NULL,
2326                                  binfo->rolname, false,
2327                                  "BLOB", SECTION_PRE_DATA,
2328                                  cquery->data, dquery->data, NULL,
2329                                  binfo->dobj.dependencies, binfo->dobj.nDeps,
2330                                  NULL, NULL);
2331
2332         /* set up tag for comment and/or ACL */
2333         resetPQExpBuffer(cquery);
2334         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2335
2336         /* Dump comment if any */
2337         dumpComment(fout, cquery->data,
2338                                 NULL, binfo->rolname,
2339                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2340
2341         /* Dump security label if any */
2342         dumpSecLabel(fout, cquery->data,
2343                                  NULL, binfo->rolname,
2344                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2345
2346         /* Dump ACL if any */
2347         if (binfo->blobacl)
2348                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2349                                 binfo->dobj.name, NULL, cquery->data,
2350                                 NULL, binfo->rolname, binfo->blobacl);
2351
2352         destroyPQExpBuffer(cquery);
2353         destroyPQExpBuffer(dquery);
2354 }
2355
2356 /*
2357  * dumpBlobs:
2358  *      dump the data contents of all large objects
2359  */
2360 static int
2361 dumpBlobs(Archive *fout, void *arg)
2362 {
2363         const char *blobQry;
2364         const char *blobFetchQry;
2365         PGresult   *res;
2366         char            buf[LOBBUFSIZE];
2367         int                     ntups;
2368         int                     i;
2369         int                     cnt;
2370
2371         if (g_verbose)
2372                 write_msg(NULL, "saving large objects\n");
2373
2374         /* Make sure we are in proper schema */
2375         selectSourceSchema(fout, "pg_catalog");
2376
2377         /*
2378          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2379          * the already-in-memory dumpable objects instead...
2380          */
2381         if (fout->remoteVersion >= 90000)
2382                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2383         else if (fout->remoteVersion >= 70100)
2384                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2385         else
2386                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2387
2388         ExecuteSqlStatement(fout, blobQry);
2389
2390         /* Command to fetch from cursor */
2391         blobFetchQry = "FETCH 1000 IN bloboid";
2392
2393         do
2394         {
2395                 /* Do a fetch */
2396                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2397
2398                 /* Process the tuples, if any */
2399                 ntups = PQntuples(res);
2400                 for (i = 0; i < ntups; i++)
2401                 {
2402                         Oid                     blobOid;
2403                         int                     loFd;
2404
2405                         blobOid = atooid(PQgetvalue(res, i, 0));
2406                         /* Open the BLOB */
2407                         loFd = lo_open(g_conn, blobOid, INV_READ);
2408                         if (loFd == -1)
2409                         {
2410                                 write_msg(NULL, "could not open large object %u: %s",
2411                                                   blobOid, PQerrorMessage(g_conn));
2412                                 exit_nicely();
2413                         }
2414
2415                         StartBlob(fout, blobOid);
2416
2417                         /* Now read it in chunks, sending data to archive */
2418                         do
2419                         {
2420                                 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2421                                 if (cnt < 0)
2422                                 {
2423                                         write_msg(NULL, "error reading large object %u: %s",
2424                                                           blobOid, PQerrorMessage(g_conn));
2425                                         exit_nicely();
2426                                 }
2427
2428                                 WriteData(fout, buf, cnt);
2429                         } while (cnt > 0);
2430
2431                         lo_close(g_conn, loFd);
2432
2433                         EndBlob(fout, blobOid);
2434                 }
2435
2436                 PQclear(res);
2437         } while (ntups > 0);
2438
2439         PQclear(res);
2440
2441         return 1;
2442 }
2443
2444 static void
2445 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2446                                                                                  PQExpBuffer upgrade_buffer,
2447                                                                                  Oid pg_type_oid)
2448 {
2449         PQExpBuffer upgrade_query = createPQExpBuffer();
2450         int                     ntups;
2451         PGresult   *upgrade_res;
2452         Oid                     pg_type_array_oid;
2453
2454         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2455         appendPQExpBuffer(upgrade_buffer,
2456          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2457                                           pg_type_oid);
2458
2459         /* we only support old >= 8.3 for binary upgrades */
2460         appendPQExpBuffer(upgrade_query,
2461                                           "SELECT typarray "
2462                                           "FROM pg_catalog.pg_type "
2463                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2464                                           pg_type_oid);
2465
2466         upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2467
2468         /* Expecting a single result only */
2469         ntups = PQntuples(upgrade_res);
2470         if (ntups != 1)
2471         {
2472                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2473                                                            "query returned %d rows instead of one: %s\n",
2474                                                                  ntups),
2475                                   ntups, upgrade_query->data);
2476                 exit_nicely();
2477         }
2478
2479         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2480
2481         if (OidIsValid(pg_type_array_oid))
2482         {
2483                 appendPQExpBuffer(upgrade_buffer,
2484                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2485                 appendPQExpBuffer(upgrade_buffer,
2486                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2487                                                   pg_type_array_oid);
2488         }
2489
2490         PQclear(upgrade_res);
2491         destroyPQExpBuffer(upgrade_query);
2492 }
2493
2494 static bool
2495 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2496                                                                                 PQExpBuffer upgrade_buffer,
2497                                                                                 Oid pg_rel_oid)
2498 {
2499         PQExpBuffer upgrade_query = createPQExpBuffer();
2500         int                     ntups;
2501         PGresult   *upgrade_res;
2502         Oid                     pg_type_oid;
2503         bool            toast_set = false;
2504
2505         /* we only support old >= 8.3 for binary upgrades */
2506         appendPQExpBuffer(upgrade_query,
2507                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2508                                           "FROM pg_catalog.pg_class c "
2509                                           "LEFT JOIN pg_catalog.pg_class t ON "
2510                                           "  (c.reltoastrelid = t.oid) "
2511                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2512                                           pg_rel_oid);
2513
2514         upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2515
2516         /* Expecting a single result only */
2517         ntups = PQntuples(upgrade_res);
2518         if (ntups != 1)
2519         {
2520                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2521                                                            "query returned %d rows instead of one: %s\n",
2522                                                                  ntups),
2523                                   ntups, upgrade_query->data);
2524                 exit_nicely();
2525         }
2526
2527         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2528
2529         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2530                                                                                          pg_type_oid);
2531
2532         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2533         {
2534                 /* Toast tables do not have pg_type array rows */
2535                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2536                                                                                         PQfnumber(upgrade_res, "trel")));
2537
2538                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2539                 appendPQExpBuffer(upgrade_buffer,
2540                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2541                                                   pg_type_toast_oid);
2542
2543                 toast_set = true;
2544         }
2545
2546         PQclear(upgrade_res);
2547         destroyPQExpBuffer(upgrade_query);
2548
2549         return toast_set;
2550 }
2551
2552 static void
2553 binary_upgrade_set_pg_class_oids(Archive *fout,
2554                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2555                                                                  bool is_index)
2556 {
2557         PQExpBuffer upgrade_query = createPQExpBuffer();
2558         int                     ntups;
2559         PGresult   *upgrade_res;
2560         Oid                     pg_class_reltoastrelid;
2561         Oid                     pg_class_reltoastidxid;
2562
2563         appendPQExpBuffer(upgrade_query,
2564                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2565                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2566                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2567                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2568                                           pg_class_oid);
2569
2570         upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2571
2572         /* Expecting a single result only */
2573         ntups = PQntuples(upgrade_res);
2574         if (ntups != 1)
2575         {
2576                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2577                                                            "query returned %d rows instead of one: %s\n",
2578                                                                  ntups),
2579                                   ntups, upgrade_query->data);
2580                 exit_nicely();
2581         }
2582
2583         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2584         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2585
2586         appendPQExpBuffer(upgrade_buffer,
2587                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2588
2589         if (!is_index)
2590         {
2591                 appendPQExpBuffer(upgrade_buffer,
2592                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2593                                                   pg_class_oid);
2594                 /* only tables have toast tables, not indexes */
2595                 if (OidIsValid(pg_class_reltoastrelid))
2596                 {
2597                         /*
2598                          * One complexity is that the table definition might not require
2599                          * the creation of a TOAST table, and the TOAST table might have
2600                          * been created long after table creation, when the table was
2601                          * loaded with wide data.  By setting the TOAST oid we force
2602                          * creation of the TOAST heap and TOAST index by the backend so we
2603                          * can cleanly copy the files during binary upgrade.
2604                          */
2605
2606                         appendPQExpBuffer(upgrade_buffer,
2607                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2608                                                           pg_class_reltoastrelid);
2609
2610                         /* every toast table has an index */
2611                         appendPQExpBuffer(upgrade_buffer,
2612                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2613                                                           pg_class_reltoastidxid);
2614                 }
2615         }
2616         else
2617                 appendPQExpBuffer(upgrade_buffer,
2618                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2619                                                   pg_class_oid);
2620
2621         appendPQExpBuffer(upgrade_buffer, "\n");
2622
2623         PQclear(upgrade_res);
2624         destroyPQExpBuffer(upgrade_query);
2625 }
2626
2627 /*
2628  * If the DumpableObject is a member of an extension, add a suitable
2629  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2630  */
2631 static void
2632 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2633                                                                 DumpableObject *dobj,
2634                                                                 const char *objlabel)
2635 {
2636         DumpableObject *extobj = NULL;
2637         int                     i;
2638
2639         if (!dobj->ext_member)
2640                 return;
2641
2642         /*
2643          * Find the parent extension.  We could avoid this search if we wanted to
2644          * add a link field to DumpableObject, but the space costs of that would
2645          * be considerable.  We assume that member objects could only have a
2646          * direct dependency on their own extension, not any others.
2647          */
2648         for (i = 0; i < dobj->nDeps; i++)
2649         {
2650                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2651                 if (extobj && extobj->objType == DO_EXTENSION)
2652                         break;
2653                 extobj = NULL;
2654         }
2655         if (extobj == NULL)
2656         {
2657                 write_msg(NULL, "could not find parent extension for %s", objlabel);
2658                 exit_nicely();
2659         }
2660
2661         appendPQExpBuffer(upgrade_buffer,
2662           "\n-- For binary upgrade, handle extension membership the hard way\n");
2663         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2664                                           fmtId(extobj->name),
2665                                           objlabel);
2666 }
2667
2668 /*
2669  * getNamespaces:
2670  *        read all namespaces in the system catalogs and return them in the
2671  * NamespaceInfo* structure
2672  *
2673  *      numNamespaces is set to the number of namespaces read in
2674  */
2675 NamespaceInfo *
2676 getNamespaces(Archive *fout, int *numNamespaces)
2677 {
2678         PGresult   *res;
2679         int                     ntups;
2680         int                     i;
2681         PQExpBuffer query;
2682         NamespaceInfo *nsinfo;
2683         int                     i_tableoid;
2684         int                     i_oid;
2685         int                     i_nspname;
2686         int                     i_rolname;
2687         int                     i_nspacl;
2688
2689         /*
2690          * Before 7.3, there are no real namespaces; create two dummy entries, one
2691          * for user stuff and one for system stuff.
2692          */
2693         if (fout->remoteVersion < 70300)
2694         {
2695                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2696
2697                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2698                 nsinfo[0].dobj.catId.tableoid = 0;
2699                 nsinfo[0].dobj.catId.oid = 0;
2700                 AssignDumpId(&nsinfo[0].dobj);
2701                 nsinfo[0].dobj.name = pg_strdup("public");
2702                 nsinfo[0].rolname = pg_strdup("");
2703                 nsinfo[0].nspacl = pg_strdup("");
2704
2705                 selectDumpableNamespace(&nsinfo[0]);
2706
2707                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2708                 nsinfo[1].dobj.catId.tableoid = 0;
2709                 nsinfo[1].dobj.catId.oid = 1;
2710                 AssignDumpId(&nsinfo[1].dobj);
2711                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2712                 nsinfo[1].rolname = pg_strdup("");
2713                 nsinfo[1].nspacl = pg_strdup("");
2714
2715                 selectDumpableNamespace(&nsinfo[1]);
2716
2717                 g_namespaces = nsinfo;
2718                 g_numNamespaces = *numNamespaces = 2;
2719
2720                 return nsinfo;
2721         }
2722
2723         query = createPQExpBuffer();
2724
2725         /* Make sure we are in proper schema */
2726         selectSourceSchema(fout, "pg_catalog");
2727
2728         /*
2729          * we fetch all namespaces including system ones, so that every object we
2730          * read in can be linked to a containing namespace.
2731          */
2732         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2733                                           "(%s nspowner) AS rolname, "
2734                                           "nspacl FROM pg_namespace",
2735                                           username_subquery);
2736
2737         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2738
2739         ntups = PQntuples(res);
2740
2741         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2742
2743         i_tableoid = PQfnumber(res, "tableoid");
2744         i_oid = PQfnumber(res, "oid");
2745         i_nspname = PQfnumber(res, "nspname");
2746         i_rolname = PQfnumber(res, "rolname");
2747         i_nspacl = PQfnumber(res, "nspacl");
2748
2749         for (i = 0; i < ntups; i++)
2750         {
2751                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2752                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2753                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2754                 AssignDumpId(&nsinfo[i].dobj);
2755                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2756                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2757                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2758
2759                 /* Decide whether to dump this namespace */
2760                 selectDumpableNamespace(&nsinfo[i]);
2761
2762                 if (strlen(nsinfo[i].rolname) == 0)
2763                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2764                                           nsinfo[i].dobj.name);
2765         }
2766
2767         PQclear(res);
2768         destroyPQExpBuffer(query);
2769
2770         g_namespaces = nsinfo;
2771         g_numNamespaces = *numNamespaces = ntups;
2772
2773         return nsinfo;
2774 }
2775
2776 /*
2777  * findNamespace:
2778  *              given a namespace OID and an object OID, look up the info read by
2779  *              getNamespaces
2780  *
2781  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2782  * a system object or not.      In 7.3 and later there is no guessing.
2783  */
2784 static NamespaceInfo *
2785 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2786 {
2787         int                     i;
2788
2789         if (fout->remoteVersion >= 70300)
2790         {
2791                 for (i = 0; i < g_numNamespaces; i++)
2792                 {
2793                         NamespaceInfo *nsinfo = &g_namespaces[i];
2794
2795                         if (nsoid == nsinfo->dobj.catId.oid)
2796                                 return nsinfo;
2797                 }
2798                 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2799                 exit_nicely();
2800         }
2801         else
2802         {
2803                 /* This code depends on the layout set up by getNamespaces. */
2804                 if (objoid > g_last_builtin_oid)
2805                         i = 0;                          /* user object */
2806                 else
2807                         i = 1;                          /* system object */
2808                 return &g_namespaces[i];
2809         }
2810
2811         return NULL;                            /* keep compiler quiet */
2812 }
2813
2814 /*
2815  * getExtensions:
2816  *        read all extensions in the system catalogs and return them in the
2817  * ExtensionInfo* structure
2818  *
2819  *      numExtensions is set to the number of extensions read in
2820  */
2821 ExtensionInfo *
2822 getExtensions(Archive *fout, int *numExtensions)
2823 {
2824         PGresult   *res;
2825         int                     ntups;
2826         int                     i;
2827         PQExpBuffer query;
2828         ExtensionInfo *extinfo;
2829         int                     i_tableoid;
2830         int                     i_oid;
2831         int                     i_extname;
2832         int                     i_nspname;
2833         int                     i_extrelocatable;
2834         int                     i_extversion;
2835         int                     i_extconfig;
2836         int                     i_extcondition;
2837
2838         /*
2839          * Before 9.1, there are no extensions.
2840          */
2841         if (fout->remoteVersion < 90100)
2842         {
2843                 *numExtensions = 0;
2844                 return NULL;
2845         }
2846
2847         query = createPQExpBuffer();
2848
2849         /* Make sure we are in proper schema */
2850         selectSourceSchema(fout, "pg_catalog");
2851
2852         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2853                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2854                                           "FROM pg_extension x "
2855                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2856
2857         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2858
2859         ntups = PQntuples(res);
2860
2861         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2862
2863         i_tableoid = PQfnumber(res, "tableoid");
2864         i_oid = PQfnumber(res, "oid");
2865         i_extname = PQfnumber(res, "extname");
2866         i_nspname = PQfnumber(res, "nspname");
2867         i_extrelocatable = PQfnumber(res, "extrelocatable");
2868         i_extversion = PQfnumber(res, "extversion");
2869         i_extconfig = PQfnumber(res, "extconfig");
2870         i_extcondition = PQfnumber(res, "extcondition");
2871
2872         for (i = 0; i < ntups; i++)
2873         {
2874                 extinfo[i].dobj.objType = DO_EXTENSION;
2875                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2876                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2877                 AssignDumpId(&extinfo[i].dobj);
2878                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2879                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2880                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2881                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2882                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2883                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2884
2885                 /* Decide whether we want to dump it */
2886                 selectDumpableExtension(&(extinfo[i]));
2887         }
2888
2889         PQclear(res);
2890         destroyPQExpBuffer(query);
2891
2892         *numExtensions = ntups;
2893
2894         return extinfo;
2895 }
2896
2897 /*
2898  * getTypes:
2899  *        read all types in the system catalogs and return them in the
2900  * TypeInfo* structure
2901  *
2902  *      numTypes is set to the number of types read in
2903  *
2904  * NB: this must run after getFuncs() because we assume we can do
2905  * findFuncByOid().
2906  */
2907 TypeInfo *
2908 getTypes(Archive *fout, int *numTypes)
2909 {
2910         PGresult   *res;
2911         int                     ntups;
2912         int                     i;
2913         PQExpBuffer query = createPQExpBuffer();
2914         TypeInfo   *tyinfo;
2915         ShellTypeInfo *stinfo;
2916         int                     i_tableoid;
2917         int                     i_oid;
2918         int                     i_typname;
2919         int                     i_typnamespace;
2920         int                     i_rolname;
2921         int                     i_typinput;
2922         int                     i_typoutput;
2923         int                     i_typelem;
2924         int                     i_typrelid;
2925         int                     i_typrelkind;
2926         int                     i_typtype;
2927         int                     i_typisdefined;
2928         int                     i_isarray;
2929
2930         /*
2931          * we include even the built-in types because those may be used as array
2932          * elements by user-defined types
2933          *
2934          * we filter out the built-in types when we dump out the types
2935          *
2936          * same approach for undefined (shell) types and array types
2937          *
2938          * Note: as of 8.3 we can reliably detect whether a type is an
2939          * auto-generated array type by checking the element type's typarray.
2940          * (Before that the test is capable of generating false positives.) We
2941          * still check for name beginning with '_', though, so as to avoid the
2942          * cost of the subselect probe for all standard types.  This would have to
2943          * be revisited if the backend ever allows renaming of array types.
2944          */
2945
2946         /* Make sure we are in proper schema */
2947         selectSourceSchema(fout, "pg_catalog");
2948
2949         if (fout->remoteVersion >= 80300)
2950         {
2951                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2952                                                   "typnamespace, "
2953                                                   "(%s typowner) AS rolname, "
2954                                                   "typinput::oid AS typinput, "
2955                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2956                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2957                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2958                                                   "typtype, typisdefined, "
2959                                                   "typname[0] = '_' AND typelem != 0 AND "
2960                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2961                                                   "FROM pg_type",
2962                                                   username_subquery);
2963         }
2964         else if (fout->remoteVersion >= 70300)
2965         {
2966                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2967                                                   "typnamespace, "
2968                                                   "(%s typowner) AS rolname, "
2969                                                   "typinput::oid AS typinput, "
2970                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2971                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2972                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2973                                                   "typtype, typisdefined, "
2974                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2975                                                   "FROM pg_type",
2976                                                   username_subquery);
2977         }
2978         else if (fout->remoteVersion >= 70100)
2979         {
2980                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2981                                                   "0::oid AS typnamespace, "
2982                                                   "(%s typowner) AS rolname, "
2983                                                   "typinput::oid AS typinput, "
2984                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2985                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2986                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2987                                                   "typtype, typisdefined, "
2988                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2989                                                   "FROM pg_type",
2990                                                   username_subquery);
2991         }
2992         else
2993         {
2994                 appendPQExpBuffer(query, "SELECT "
2995                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2996                                                   "oid, typname, "
2997                                                   "0::oid AS typnamespace, "
2998                                                   "(%s typowner) AS rolname, "
2999                                                   "typinput::oid AS typinput, "
3000                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3001                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3002                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3003                                                   "typtype, typisdefined, "
3004                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3005                                                   "FROM pg_type",
3006                                                   username_subquery);
3007         }
3008
3009         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3010
3011         ntups = PQntuples(res);
3012
3013         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3014
3015         i_tableoid = PQfnumber(res, "tableoid");
3016         i_oid = PQfnumber(res, "oid");
3017         i_typname = PQfnumber(res, "typname");
3018         i_typnamespace = PQfnumber(res, "typnamespace");
3019         i_rolname = PQfnumber(res, "rolname");
3020         i_typinput = PQfnumber(res, "typinput");
3021         i_typoutput = PQfnumber(res, "typoutput");
3022         i_typelem = PQfnumber(res, "typelem");
3023         i_typrelid = PQfnumber(res, "typrelid");
3024         i_typrelkind = PQfnumber(res, "typrelkind");
3025         i_typtype = PQfnumber(res, "typtype");
3026         i_typisdefined = PQfnumber(res, "typisdefined");
3027         i_isarray = PQfnumber(res, "isarray");
3028
3029         for (i = 0; i < ntups; i++)
3030         {
3031                 tyinfo[i].dobj.objType = DO_TYPE;
3032                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3033                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3034                 AssignDumpId(&tyinfo[i].dobj);
3035                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3036                 tyinfo[i].dobj.namespace =
3037                         findNamespace(fout,
3038                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
3039                                                   tyinfo[i].dobj.catId.oid);
3040                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3041                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3042                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3043                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3044                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3045                 tyinfo[i].shellType = NULL;
3046
3047                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3048                         tyinfo[i].isDefined = true;
3049                 else
3050                         tyinfo[i].isDefined = false;
3051
3052                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3053                         tyinfo[i].isArray = true;
3054                 else
3055                         tyinfo[i].isArray = false;
3056
3057                 /* Decide whether we want to dump it */
3058                 selectDumpableType(&tyinfo[i]);
3059
3060                 /*
3061                  * If it's a domain, fetch info about its constraints, if any
3062                  */
3063                 tyinfo[i].nDomChecks = 0;
3064                 tyinfo[i].domChecks = NULL;
3065                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3066                         getDomainConstraints(fout, &(tyinfo[i]));
3067
3068                 /*
3069                  * If it's a base type, make a DumpableObject representing a shell
3070                  * definition of the type.      We will need to dump that ahead of the I/O
3071                  * functions for the type.  Similarly, range types need a shell
3072                  * definition in case they have a canonicalize function.
3073                  *
3074                  * Note: the shell type doesn't have a catId.  You might think it
3075                  * should copy the base type's catId, but then it might capture the
3076                  * pg_depend entries for the type, which we don't want.
3077                  */
3078                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3079                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
3080                 {
3081                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3082                         stinfo->dobj.objType = DO_SHELL_TYPE;
3083                         stinfo->dobj.catId = nilCatalogId;
3084                         AssignDumpId(&stinfo->dobj);
3085                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3086                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3087                         stinfo->baseType = &(tyinfo[i]);
3088                         tyinfo[i].shellType = stinfo;
3089
3090                         /*
3091                          * Initially mark the shell type as not to be dumped.  We'll only
3092                          * dump it if the I/O or canonicalize functions need to be dumped;
3093                          * this is taken care of while sorting dependencies.
3094                          */
3095                         stinfo->dobj.dump = false;
3096
3097                         /*
3098                          * However, if dumping from pre-7.3, there will be no dependency
3099                          * info so we have to fake it here.  We only need to worry about
3100                          * typinput and typoutput since the other functions only exist
3101                          * post-7.3.
3102                          */
3103                         if (fout->remoteVersion < 70300)
3104                         {
3105                                 Oid                     typinput;
3106                                 Oid                     typoutput;
3107                                 FuncInfo   *funcInfo;
3108
3109                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3110                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3111
3112                                 funcInfo = findFuncByOid(typinput);
3113                                 if (funcInfo && funcInfo->dobj.dump)
3114                                 {
3115                                         /* base type depends on function */
3116                                         addObjectDependency(&tyinfo[i].dobj,
3117                                                                                 funcInfo->dobj.dumpId);
3118                                         /* function depends on shell type */
3119                                         addObjectDependency(&funcInfo->dobj,
3120                                                                                 stinfo->dobj.dumpId);
3121                                         /* mark shell type as to be dumped */
3122                                         stinfo->dobj.dump = true;
3123                                 }
3124
3125                                 funcInfo = findFuncByOid(typoutput);
3126                                 if (funcInfo && funcInfo->dobj.dump)
3127                                 {
3128                                         /* base type depends on function */
3129                                         addObjectDependency(&tyinfo[i].dobj,
3130                                                                                 funcInfo->dobj.dumpId);
3131                                         /* function depends on shell type */
3132                                         addObjectDependency(&funcInfo->dobj,
3133                                                                                 stinfo->dobj.dumpId);
3134                                         /* mark shell type as to be dumped */
3135                                         stinfo->dobj.dump = true;
3136                                 }
3137                         }
3138                 }
3139
3140                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3141                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3142                                           tyinfo[i].dobj.name);
3143         }
3144
3145         *numTypes = ntups;
3146
3147         PQclear(res);
3148
3149         destroyPQExpBuffer(query);
3150
3151         return tyinfo;
3152 }
3153
3154 /*
3155  * getOperators:
3156  *        read all operators in the system catalogs and return them in the
3157  * OprInfo* structure
3158  *
3159  *      numOprs is set to the number of operators read in
3160  */
3161 OprInfo *
3162 getOperators(Archive *fout, int *numOprs)
3163 {
3164         PGresult   *res;
3165         int                     ntups;
3166         int                     i;
3167         PQExpBuffer query = createPQExpBuffer();
3168         OprInfo    *oprinfo;
3169         int                     i_tableoid;
3170         int                     i_oid;
3171         int                     i_oprname;
3172         int                     i_oprnamespace;
3173         int                     i_rolname;
3174         int                     i_oprkind;
3175         int                     i_oprcode;
3176
3177         /*
3178          * find all operators, including builtin operators; we filter out
3179          * system-defined operators at dump-out time.
3180          */
3181
3182         /* Make sure we are in proper schema */
3183         selectSourceSchema(fout, "pg_catalog");
3184
3185         if (fout->remoteVersion >= 70300)
3186         {
3187                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3188                                                   "oprnamespace, "
3189                                                   "(%s oprowner) AS rolname, "
3190                                                   "oprkind, "
3191                                                   "oprcode::oid AS oprcode "
3192                                                   "FROM pg_operator",
3193                                                   username_subquery);
3194         }
3195         else if (fout->remoteVersion >= 70100)
3196         {
3197                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3198                                                   "0::oid AS oprnamespace, "
3199                                                   "(%s oprowner) AS rolname, "
3200                                                   "oprkind, "
3201                                                   "oprcode::oid AS oprcode "
3202                                                   "FROM pg_operator",
3203                                                   username_subquery);
3204         }
3205         else
3206         {
3207                 appendPQExpBuffer(query, "SELECT "
3208                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3209                                                   "oid, oprname, "
3210                                                   "0::oid AS oprnamespace, "
3211                                                   "(%s oprowner) AS rolname, "
3212                                                   "oprkind, "
3213                                                   "oprcode::oid AS oprcode "
3214                                                   "FROM pg_operator",
3215                                                   username_subquery);
3216         }
3217
3218         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3219
3220         ntups = PQntuples(res);
3221         *numOprs = ntups;
3222
3223         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3224
3225         i_tableoid = PQfnumber(res, "tableoid");
3226         i_oid = PQfnumber(res, "oid");
3227         i_oprname = PQfnumber(res, "oprname");
3228         i_oprnamespace = PQfnumber(res, "oprnamespace");
3229         i_rolname = PQfnumber(res, "rolname");
3230         i_oprkind = PQfnumber(res, "oprkind");
3231         i_oprcode = PQfnumber(res, "oprcode");
3232
3233         for (i = 0; i < ntups; i++)
3234         {
3235                 oprinfo[i].dobj.objType = DO_OPERATOR;
3236                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3237                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3238                 AssignDumpId(&oprinfo[i].dobj);
3239                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3240                 oprinfo[i].dobj.namespace =
3241                         findNamespace(fout,
3242                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3243                                                   oprinfo[i].dobj.catId.oid);
3244                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3245                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3246                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3247
3248                 /* Decide whether we want to dump it */
3249                 selectDumpableObject(&(oprinfo[i].dobj));
3250
3251                 if (strlen(oprinfo[i].rolname) == 0)
3252                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3253                                           oprinfo[i].dobj.name);
3254         }
3255
3256         PQclear(res);
3257
3258         destroyPQExpBuffer(query);
3259
3260         return oprinfo;
3261 }
3262
3263 /*
3264  * getCollations:
3265  *        read all collations in the system catalogs and return them in the
3266  * CollInfo* structure
3267  *
3268  *      numCollations is set to the number of collations read in
3269  */
3270 CollInfo *
3271 getCollations(Archive *fout, int *numCollations)
3272 {
3273         PGresult   *res;
3274         int                     ntups;
3275         int                     i;
3276         PQExpBuffer query = createPQExpBuffer();
3277         CollInfo   *collinfo;
3278         int                     i_tableoid;
3279         int                     i_oid;
3280         int                     i_collname;
3281         int                     i_collnamespace;
3282         int                     i_rolname;
3283
3284         /* Collations didn't exist pre-9.1 */
3285         if (fout->remoteVersion < 90100)
3286         {
3287                 *numCollations = 0;
3288                 return NULL;
3289         }
3290
3291         /*
3292          * find all collations, including builtin collations; we filter out
3293          * system-defined collations at dump-out time.
3294          */
3295
3296         /* Make sure we are in proper schema */
3297         selectSourceSchema(fout, "pg_catalog");
3298
3299         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3300                                           "collnamespace, "
3301                                           "(%s collowner) AS rolname "
3302                                           "FROM pg_collation",
3303                                           username_subquery);
3304
3305         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3306
3307         ntups = PQntuples(res);
3308         *numCollations = ntups;
3309
3310         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3311
3312         i_tableoid = PQfnumber(res, "tableoid");
3313         i_oid = PQfnumber(res, "oid");
3314         i_collname = PQfnumber(res, "collname");
3315         i_collnamespace = PQfnumber(res, "collnamespace");
3316         i_rolname = PQfnumber(res, "rolname");
3317
3318         for (i = 0; i < ntups; i++)
3319         {
3320                 collinfo[i].dobj.objType = DO_COLLATION;
3321                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3322                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3323                 AssignDumpId(&collinfo[i].dobj);
3324                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3325                 collinfo[i].dobj.namespace =
3326                         findNamespace(fout,
3327                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3328                                                   collinfo[i].dobj.catId.oid);
3329                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3330
3331                 /* Decide whether we want to dump it */
3332                 selectDumpableObject(&(collinfo[i].dobj));
3333         }
3334
3335         PQclear(res);
3336
3337         destroyPQExpBuffer(query);
3338
3339         return collinfo;
3340 }
3341
3342 /*
3343  * getConversions:
3344  *        read all conversions in the system catalogs and return them in the
3345  * ConvInfo* structure
3346  *
3347  *      numConversions is set to the number of conversions read in
3348  */
3349 ConvInfo *
3350 getConversions(Archive *fout, int *numConversions)
3351 {
3352         PGresult   *res;
3353         int                     ntups;
3354         int                     i;
3355         PQExpBuffer query = createPQExpBuffer();
3356         ConvInfo   *convinfo;
3357         int                     i_tableoid;
3358         int                     i_oid;
3359         int                     i_conname;
3360         int                     i_connamespace;
3361         int                     i_rolname;
3362
3363         /* Conversions didn't exist pre-7.3 */
3364         if (fout->remoteVersion < 70300)
3365         {
3366                 *numConversions = 0;
3367                 return NULL;
3368         }
3369
3370         /*
3371          * find all conversions, including builtin conversions; we filter out
3372          * system-defined conversions at dump-out time.
3373          */
3374
3375         /* Make sure we are in proper schema */
3376         selectSourceSchema(fout, "pg_catalog");
3377
3378         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3379                                           "connamespace, "
3380                                           "(%s conowner) AS rolname "
3381                                           "FROM pg_conversion",
3382                                           username_subquery);
3383
3384         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3385
3386         ntups = PQntuples(res);
3387         *numConversions = ntups;
3388
3389         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3390
3391         i_tableoid = PQfnumber(res, "tableoid");
3392         i_oid = PQfnumber(res, "oid");
3393         i_conname = PQfnumber(res, "conname");
3394         i_connamespace = PQfnumber(res, "connamespace");
3395         i_rolname = PQfnumber(res, "rolname");
3396
3397         for (i = 0; i < ntups; i++)
3398         {
3399                 convinfo[i].dobj.objType = DO_CONVERSION;
3400                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3401                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3402                 AssignDumpId(&convinfo[i].dobj);
3403                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3404                 convinfo[i].dobj.namespace =
3405                         findNamespace(fout,
3406                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3407                                                   convinfo[i].dobj.catId.oid);
3408                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3409
3410                 /* Decide whether we want to dump it */
3411                 selectDumpableObject(&(convinfo[i].dobj));
3412         }
3413
3414         PQclear(res);
3415
3416         destroyPQExpBuffer(query);
3417
3418         return convinfo;
3419 }
3420
3421 /*
3422  * getOpclasses:
3423  *        read all opclasses in the system catalogs and return them in the
3424  * OpclassInfo* structure
3425  *
3426  *      numOpclasses is set to the number of opclasses read in
3427  */
3428 OpclassInfo *
3429 getOpclasses(Archive *fout, int *numOpclasses)
3430 {
3431         PGresult   *res;
3432         int                     ntups;
3433         int                     i;
3434         PQExpBuffer query = createPQExpBuffer();
3435         OpclassInfo *opcinfo;
3436         int                     i_tableoid;
3437         int                     i_oid;
3438         int                     i_opcname;
3439         int                     i_opcnamespace;
3440         int                     i_rolname;
3441
3442         /*
3443          * find all opclasses, including builtin opclasses; we filter out
3444          * system-defined opclasses at dump-out time.
3445          */
3446
3447         /* Make sure we are in proper schema */
3448         selectSourceSchema(fout, "pg_catalog");
3449
3450         if (fout->remoteVersion >= 70300)
3451         {
3452                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3453                                                   "opcnamespace, "
3454                                                   "(%s opcowner) AS rolname "
3455                                                   "FROM pg_opclass",
3456                                                   username_subquery);
3457         }
3458         else if (fout->remoteVersion >= 70100)
3459         {
3460                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3461                                                   "0::oid AS opcnamespace, "
3462                                                   "''::name AS rolname "
3463                                                   "FROM pg_opclass");
3464         }
3465         else
3466         {
3467                 appendPQExpBuffer(query, "SELECT "
3468                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3469                                                   "oid, opcname, "
3470                                                   "0::oid AS opcnamespace, "
3471                                                   "''::name AS rolname "
3472                                                   "FROM pg_opclass");
3473         }
3474
3475         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3476
3477         ntups = PQntuples(res);
3478         *numOpclasses = ntups;
3479
3480         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3481
3482         i_tableoid = PQfnumber(res, "tableoid");
3483         i_oid = PQfnumber(res, "oid");
3484         i_opcname = PQfnumber(res, "opcname");
3485         i_opcnamespace = PQfnumber(res, "opcnamespace");
3486         i_rolname = PQfnumber(res, "rolname");
3487
3488         for (i = 0; i < ntups; i++)
3489         {
3490                 opcinfo[i].dobj.objType = DO_OPCLASS;
3491                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3492                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3493                 AssignDumpId(&opcinfo[i].dobj);
3494                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3495                 opcinfo[i].dobj.namespace =
3496                         findNamespace(fout,
3497                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3498                                                   opcinfo[i].dobj.catId.oid);
3499                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3500
3501                 /* Decide whether we want to dump it */
3502                 selectDumpableObject(&(opcinfo[i].dobj));
3503
3504                 if (fout->remoteVersion >= 70300)
3505                 {
3506                         if (strlen(opcinfo[i].rolname) == 0)
3507                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3508                                                   opcinfo[i].dobj.name);
3509                 }
3510         }
3511
3512         PQclear(res);
3513
3514         destroyPQExpBuffer(query);
3515
3516         return opcinfo;
3517 }
3518
3519 /*
3520  * getOpfamilies:
3521  *        read all opfamilies in the system catalogs and return them in the
3522  * OpfamilyInfo* structure
3523  *
3524  *      numOpfamilies is set to the number of opfamilies read in
3525  */
3526 OpfamilyInfo *
3527 getOpfamilies(Archive *fout, int *numOpfamilies)
3528 {
3529         PGresult   *res;
3530         int                     ntups;
3531         int                     i;
3532         PQExpBuffer query;
3533         OpfamilyInfo *opfinfo;
3534         int                     i_tableoid;
3535         int                     i_oid;
3536         int                     i_opfname;
3537         int                     i_opfnamespace;
3538         int                     i_rolname;
3539
3540         /* Before 8.3, there is no separate concept of opfamilies */
3541         if (fout->remoteVersion < 80300)
3542         {
3543                 *numOpfamilies = 0;
3544                 return NULL;
3545         }
3546
3547         query = createPQExpBuffer();
3548
3549         /*
3550          * find all opfamilies, including builtin opfamilies; we filter out
3551          * system-defined opfamilies at dump-out time.
3552          */
3553
3554         /* Make sure we are in proper schema */
3555         selectSourceSchema(fout, "pg_catalog");
3556
3557         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3558                                           "opfnamespace, "
3559                                           "(%s opfowner) AS rolname "
3560                                           "FROM pg_opfamily",
3561                                           username_subquery);
3562
3563         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3564
3565         ntups = PQntuples(res);
3566         *numOpfamilies = ntups;
3567
3568         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3569
3570         i_tableoid = PQfnumber(res, "tableoid");
3571         i_oid = PQfnumber(res, "oid");
3572         i_opfname = PQfnumber(res, "opfname");
3573         i_opfnamespace = PQfnumber(res, "opfnamespace");
3574         i_rolname = PQfnumber(res, "rolname");
3575
3576         for (i = 0; i < ntups; i++)
3577         {
3578                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3579                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3580                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3581                 AssignDumpId(&opfinfo[i].dobj);
3582                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3583                 opfinfo[i].dobj.namespace =
3584                         findNamespace(fout,
3585                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3586                                                   opfinfo[i].dobj.catId.oid);
3587                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3588
3589                 /* Decide whether we want to dump it */
3590                 selectDumpableObject(&(opfinfo[i].dobj));
3591
3592                 if (fout->remoteVersion >= 70300)
3593                 {
3594                         if (strlen(opfinfo[i].rolname) == 0)
3595                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3596                                                   opfinfo[i].dobj.name);
3597                 }
3598         }
3599
3600         PQclear(res);
3601
3602         destroyPQExpBuffer(query);
3603
3604         return opfinfo;
3605 }
3606
3607 /*
3608  * getAggregates:
3609  *        read all the user-defined aggregates in the system catalogs and
3610  * return them in the AggInfo* structure
3611  *
3612  * numAggs is set to the number of aggregates read in
3613  */
3614 AggInfo *
3615 getAggregates(Archive *fout, int *numAggs)
3616 {
3617         PGresult   *res;
3618         int                     ntups;
3619         int                     i;
3620         PQExpBuffer query = createPQExpBuffer();
3621         AggInfo    *agginfo;
3622         int                     i_tableoid;
3623         int                     i_oid;
3624         int                     i_aggname;
3625         int                     i_aggnamespace;
3626         int                     i_pronargs;
3627         int                     i_proargtypes;
3628         int                     i_rolname;
3629         int                     i_aggacl;
3630
3631         /* Make sure we are in proper schema */
3632         selectSourceSchema(fout, "pg_catalog");
3633
3634         /*
3635          * Find all user-defined aggregates.  See comment in getFuncs() for the
3636          * rationale behind the filtering logic.
3637          */
3638
3639         if (fout->remoteVersion >= 80200)
3640         {
3641                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3642                                                   "pronamespace AS aggnamespace, "
3643                                                   "pronargs, proargtypes, "
3644                                                   "(%s proowner) AS rolname, "
3645                                                   "proacl AS aggacl "
3646                                                   "FROM pg_proc p "
3647                                                   "WHERE proisagg AND ("
3648                                                   "pronamespace != "
3649                                                   "(SELECT oid FROM pg_namespace "
3650                                                   "WHERE nspname = 'pg_catalog')",
3651                                                   username_subquery);
3652                 if (binary_upgrade && fout->remoteVersion >= 90100)
3653                         appendPQExpBuffer(query,
3654                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3655                                                           "classid = 'pg_proc'::regclass AND "
3656                                                           "objid = p.oid AND "
3657                                                           "refclassid = 'pg_extension'::regclass AND "
3658                                                           "deptype = 'e')");
3659                 appendPQExpBuffer(query, ")");
3660         }
3661         else if (fout->remoteVersion >= 70300)
3662         {
3663                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3664                                                   "pronamespace AS aggnamespace, "
3665                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3666                                                   "proargtypes, "
3667                                                   "(%s proowner) AS rolname, "
3668                                                   "proacl AS aggacl "
3669                                                   "FROM pg_proc "
3670                                                   "WHERE proisagg "
3671                                                   "AND pronamespace != "
3672                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3673                                                   username_subquery);
3674         }
3675         else if (fout->remoteVersion >= 70100)
3676         {
3677                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3678                                                   "0::oid AS aggnamespace, "
3679                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3680                                                   "aggbasetype AS proargtypes, "
3681                                                   "(%s aggowner) AS rolname, "
3682                                                   "'{=X}' AS aggacl "
3683                                                   "FROM pg_aggregate "
3684                                                   "where oid > '%u'::oid",
3685                                                   username_subquery,
3686                                                   g_last_builtin_oid);
3687         }
3688         else
3689         {
3690                 appendPQExpBuffer(query, "SELECT "
3691                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3692                                                   "oid, aggname, "
3693                                                   "0::oid AS aggnamespace, "
3694                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3695                                                   "aggbasetype AS proargtypes, "
3696                                                   "(%s aggowner) AS rolname, "
3697                                                   "'{=X}' AS aggacl "
3698                                                   "FROM pg_aggregate "
3699                                                   "where oid > '%u'::oid",
3700                                                   username_subquery,
3701                                                   g_last_builtin_oid);
3702         }
3703
3704         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3705
3706         ntups = PQntuples(res);
3707         *numAggs = ntups;
3708
3709         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3710
3711         i_tableoid = PQfnumber(res, "tableoid");
3712         i_oid = PQfnumber(res, "oid");
3713         i_aggname = PQfnumber(res, "aggname");
3714         i_aggnamespace = PQfnumber(res, "aggnamespace");
3715         i_pronargs = PQfnumber(res, "pronargs");
3716         i_proargtypes = PQfnumber(res, "proargtypes");
3717         i_rolname = PQfnumber(res, "rolname");
3718         i_aggacl = PQfnumber(res, "aggacl");
3719
3720         for (i = 0; i < ntups; i++)
3721         {
3722                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3723                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3724                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3725                 AssignDumpId(&agginfo[i].aggfn.dobj);
3726                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3727                 agginfo[i].aggfn.dobj.namespace =
3728                         findNamespace(fout,
3729                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3730                                                   agginfo[i].aggfn.dobj.catId.oid);
3731                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3732                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3733                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3734                                           agginfo[i].aggfn.dobj.name);
3735                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3736                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3737                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3738                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3739                 if (agginfo[i].aggfn.nargs == 0)
3740                         agginfo[i].aggfn.argtypes = NULL;
3741                 else
3742                 {
3743                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3744                         if (fout->remoteVersion >= 70300)
3745                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3746                                                           agginfo[i].aggfn.argtypes,
3747                                                           agginfo[i].aggfn.nargs);
3748                         else
3749                                 /* it's just aggbasetype */
3750                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3751                 }
3752
3753                 /* Decide whether we want to dump it */
3754                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3755         }
3756
3757         PQclear(res);
3758
3759         destroyPQExpBuffer(query);
3760
3761         return agginfo;
3762 }
3763
3764 /*
3765  * getFuncs:
3766  *        read all the user-defined functions in the system catalogs and
3767  * return them in the FuncInfo* structure
3768  *
3769  * numFuncs is set to the number of functions read in
3770  */
3771 FuncInfo *
3772 getFuncs(Archive *fout, int *numFuncs)
3773 {
3774         PGresult   *res;
3775         int                     ntups;
3776         int                     i;
3777         PQExpBuffer query = createPQExpBuffer();
3778         FuncInfo   *finfo;
3779         int                     i_tableoid;
3780         int                     i_oid;
3781         int                     i_proname;
3782         int                     i_pronamespace;
3783         int                     i_rolname;
3784         int                     i_prolang;
3785         int                     i_pronargs;
3786         int                     i_proargtypes;
3787         int                     i_prorettype;
3788         int                     i_proacl;
3789
3790         /* Make sure we are in proper schema */
3791         selectSourceSchema(fout, "pg_catalog");
3792
3793         /*
3794          * Find all user-defined functions.  Normally we can exclude functions in
3795          * pg_catalog, which is worth doing since there are several thousand of
3796          * 'em.  However, there are some extensions that create functions in
3797          * pg_catalog.  In normal dumps we can still ignore those --- but in
3798          * binary-upgrade mode, we must dump the member objects of the extension,
3799          * so be sure to fetch any such functions.
3800          *
3801          * Also, in 9.2 and up, exclude functions that are internally dependent on
3802          * something else, since presumably those will be created as a result of
3803          * creating the something else.  This currently only acts to suppress
3804          * constructor functions for range types.  Note that this is OK only
3805          * because the constructors don't have any dependencies the range type
3806          * doesn't have; otherwise we might not get creation ordering correct.
3807          */
3808
3809         if (fout->remoteVersion >= 70300)
3810         {
3811                 appendPQExpBuffer(query,
3812                                                   "SELECT tableoid, oid, proname, prolang, "
3813                                                   "pronargs, proargtypes, prorettype, proacl, "
3814                                                   "pronamespace, "
3815                                                   "(%s proowner) AS rolname "
3816                                                   "FROM pg_proc p "
3817                                                   "WHERE NOT proisagg AND ("
3818                                                   "pronamespace != "
3819                                                   "(SELECT oid FROM pg_namespace "
3820                                                   "WHERE nspname = 'pg_catalog')",
3821                                                   username_subquery);
3822                 if (fout->remoteVersion >= 90200)
3823                         appendPQExpBuffer(query,
3824                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3825                                                           "WHERE classid = 'pg_proc'::regclass AND "
3826                                                           "objid = p.oid AND deptype = 'i')");
3827                 if (binary_upgrade && fout->remoteVersion >= 90100)
3828                         appendPQExpBuffer(query,
3829                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3830                                                           "classid = 'pg_proc'::regclass AND "
3831                                                           "objid = p.oid AND "
3832                                                           "refclassid = 'pg_extension'::regclass AND "
3833                                                           "deptype = 'e')");
3834                 appendPQExpBuffer(query, ")");
3835         }
3836         else if (fout->remoteVersion >= 70100)
3837         {
3838                 appendPQExpBuffer(query,
3839                                                   "SELECT tableoid, oid, proname, prolang, "
3840                                                   "pronargs, proargtypes, prorettype, "
3841                                                   "'{=X}' AS proacl, "
3842                                                   "0::oid AS pronamespace, "
3843                                                   "(%s proowner) AS rolname "
3844                                                   "FROM pg_proc "
3845                                                   "WHERE pg_proc.oid > '%u'::oid",
3846                                                   username_subquery,
3847                                                   g_last_builtin_oid);
3848         }
3849         else
3850         {
3851                 appendPQExpBuffer(query,
3852                                                   "SELECT "
3853                                                   "(SELECT oid FROM pg_class "
3854                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3855                                                   "oid, proname, prolang, "
3856                                                   "pronargs, proargtypes, prorettype, "
3857                                                   "'{=X}' AS proacl, "
3858                                                   "0::oid AS pronamespace, "
3859                                                   "(%s proowner) AS rolname "
3860                                                   "FROM pg_proc "
3861                                                   "where pg_proc.oid > '%u'::oid",
3862                                                   username_subquery,
3863                                                   g_last_builtin_oid);
3864         }
3865
3866         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3867
3868         ntups = PQntuples(res);
3869
3870         *numFuncs = ntups;
3871
3872         finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3873
3874         i_tableoid = PQfnumber(res, "tableoid");
3875         i_oid = PQfnumber(res, "oid");
3876         i_proname = PQfnumber(res, "proname");
3877         i_pronamespace = PQfnumber(res, "pronamespace");
3878         i_rolname = PQfnumber(res, "rolname");
3879         i_prolang = PQfnumber(res, "prolang");
3880         i_pronargs = PQfnumber(res, "pronargs");
3881         i_proargtypes = PQfnumber(res, "proargtypes");
3882         i_prorettype = PQfnumber(res, "prorettype");
3883         i_proacl = PQfnumber(res, "proacl");
3884
3885         for (i = 0; i < ntups; i++)
3886         {
3887                 finfo[i].dobj.objType = DO_FUNC;
3888                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3889                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3890                 AssignDumpId(&finfo[i].dobj);
3891                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3892                 finfo[i].dobj.namespace =
3893                         findNamespace(fout,
3894                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3895                                                   finfo[i].dobj.catId.oid);
3896                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3897                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3898                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3899                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3900                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3901                 if (finfo[i].nargs == 0)
3902                         finfo[i].argtypes = NULL;
3903                 else
3904                 {
3905                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3906                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3907                                                   finfo[i].argtypes, finfo[i].nargs);
3908                 }
3909
3910                 /* Decide whether we want to dump it */
3911                 selectDumpableObject(&(finfo[i].dobj));
3912
3913                 if (strlen(finfo[i].rolname) == 0)
3914                         write_msg(NULL,
3915                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3916                                           finfo[i].dobj.name);
3917         }
3918
3919         PQclear(res);
3920
3921         destroyPQExpBuffer(query);
3922
3923         return finfo;
3924 }
3925
3926 /*
3927  * getTables
3928  *        read all the user-defined tables (no indexes, no catalogs)
3929  * in the system catalogs return them in the TableInfo* structure
3930  *
3931  * numTables is set to the number of tables read in
3932  */
3933 TableInfo *
3934 getTables(Archive *fout, int *numTables)
3935 {
3936         PGresult   *res;
3937         int                     ntups;
3938         int                     i;
3939         PQExpBuffer query = createPQExpBuffer();
3940         TableInfo  *tblinfo;
3941         int                     i_reltableoid;
3942         int                     i_reloid;
3943         int                     i_relname;
3944         int                     i_relnamespace;
3945         int                     i_relkind;
3946         int                     i_relacl;
3947         int                     i_rolname;
3948         int                     i_relchecks;
3949         int                     i_relhastriggers;
3950         int                     i_relhasindex;
3951         int                     i_relhasrules;
3952         int                     i_relhasoids;
3953         int                     i_relfrozenxid;
3954         int                     i_toastoid;
3955         int                     i_toastfrozenxid;
3956         int                     i_relpersistence;
3957         int                     i_owning_tab;
3958         int                     i_owning_col;
3959         int                     i_reltablespace;
3960         int                     i_reloptions;
3961         int                     i_toastreloptions;
3962         int                     i_reloftype;
3963
3964         /* Make sure we are in proper schema */
3965         selectSourceSchema(fout, "pg_catalog");
3966
3967         /*
3968          * Find all the tables (including views and sequences).
3969          *
3970          * We include system catalogs, so that we can work if a user table is
3971          * defined to inherit from a system catalog (pretty weird, but...)
3972          *
3973          * We ignore tables that are not type 'r' (ordinary relation), 'S'
3974          * (sequence), 'v' (view), or 'c' (composite type).
3975          *
3976          * Composite-type table entries won't be dumped as such, but we have to
3977          * make a DumpableObject for them so that we can track dependencies of the
3978          * composite type (pg_depend entries for columns of the composite type
3979          * link to the pg_class entry not the pg_type entry).
3980          *
3981          * Note: in this phase we should collect only a minimal amount of
3982          * information about each table, basically just enough to decide if it is
3983          * interesting. We must fetch all tables in this phase because otherwise
3984          * we cannot correctly identify inherited columns, owned sequences, etc.
3985          */
3986
3987         if (fout->remoteVersion >= 90100)
3988         {
3989                 /*
3990                  * Left join to pick up dependency info linking sequences to their
3991                  * owning column, if any (note this dependency is AUTO as of 8.2)
3992                  */
3993                 appendPQExpBuffer(query,
3994                                                   "SELECT c.tableoid, c.oid, c.relname, "
3995                                                   "c.relacl, c.relkind, c.relnamespace, "
3996                                                   "(%s c.relowner) AS rolname, "
3997                                                   "c.relchecks, c.relhastriggers, "
3998                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3999                                                   "c.relfrozenxid, tc.oid AS toid, "
4000                                                   "tc.relfrozenxid AS tfrozenxid, "
4001                                                   "c.relpersistence, "
4002                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4003                                                   "d.refobjid AS owning_tab, "
4004                                                   "d.refobjsubid AS owning_col, "
4005                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4006                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4007                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4008                                                   "FROM pg_class c "
4009                                                   "LEFT JOIN pg_depend d ON "
4010                                                   "(c.relkind = '%c' AND "
4011                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4012                                                   "d.objsubid = 0 AND "
4013                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4014                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4015                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
4016                                                   "ORDER BY c.oid",
4017                                                   username_subquery,
4018                                                   RELKIND_SEQUENCE,
4019                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4020                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4021                                                   RELKIND_FOREIGN_TABLE);
4022         }
4023         else if (fout->remoteVersion >= 90000)
4024         {
4025                 /*
4026                  * Left join to pick up dependency info linking sequences to their
4027                  * owning column, if any (note this dependency is AUTO as of 8.2)
4028                  */
4029                 appendPQExpBuffer(query,
4030                                                   "SELECT c.tableoid, c.oid, c.relname, "
4031                                                   "c.relacl, c.relkind, c.relnamespace, "
4032                                                   "(%s c.relowner) AS rolname, "
4033                                                   "c.relchecks, c.relhastriggers, "
4034                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4035                                                   "c.relfrozenxid, tc.oid AS toid, "
4036                                                   "tc.relfrozenxid AS tfrozenxid, "
4037                                                   "'p' AS relpersistence, "
4038                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4039                                                   "d.refobjid AS owning_tab, "
4040                                                   "d.refobjsubid AS owning_col, "
4041                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4042                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4043                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4044                                                   "FROM pg_class c "
4045                                                   "LEFT JOIN pg_depend d ON "
4046                                                   "(c.relkind = '%c' AND "
4047                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4048                                                   "d.objsubid = 0 AND "
4049                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4050                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4051                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4052                                                   "ORDER BY c.oid",
4053                                                   username_subquery,
4054                                                   RELKIND_SEQUENCE,
4055                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4056                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4057         }
4058         else if (fout->remoteVersion >= 80400)
4059         {
4060                 /*
4061                  * Left join to pick up dependency info linking sequences to their
4062                  * owning column, if any (note this dependency is AUTO as of 8.2)
4063                  */
4064                 appendPQExpBuffer(query,
4065                                                   "SELECT c.tableoid, c.oid, c.relname, "
4066                                                   "c.relacl, c.relkind, c.relnamespace, "
4067                                                   "(%s c.relowner) AS rolname, "
4068                                                   "c.relchecks, c.relhastriggers, "
4069                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4070                                                   "c.relfrozenxid, tc.oid AS toid, "
4071                                                   "tc.relfrozenxid AS tfrozenxid, "
4072                                                   "'p' AS relpersistence, "
4073                                                   "NULL AS reloftype, "
4074                                                   "d.refobjid AS owning_tab, "
4075                                                   "d.refobjsubid AS owning_col, "
4076                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4077                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4078                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4079                                                   "FROM pg_class c "
4080                                                   "LEFT JOIN pg_depend d ON "
4081                                                   "(c.relkind = '%c' AND "
4082                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4083                                                   "d.objsubid = 0 AND "
4084                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4085                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4086                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4087                                                   "ORDER BY c.oid",
4088                                                   username_subquery,
4089                                                   RELKIND_SEQUENCE,
4090                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4091                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4092         }
4093         else if (fout->remoteVersion >= 80200)
4094         {
4095                 /*
4096                  * Left join to pick up dependency info linking sequences to their
4097                  * owning column, if any (note this dependency is AUTO as of 8.2)
4098                  */
4099                 appendPQExpBuffer(query,
4100                                                   "SELECT c.tableoid, c.oid, c.relname, "
4101                                                   "c.relacl, c.relkind, c.relnamespace, "
4102                                                   "(%s c.relowner) AS rolname, "
4103                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4104                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4105                                                   "c.relfrozenxid, tc.oid AS toid, "
4106                                                   "tc.relfrozenxid AS tfrozenxid, "
4107                                                   "'p' AS relpersistence, "
4108                                                   "NULL AS reloftype, "
4109                                                   "d.refobjid AS owning_tab, "
4110                                                   "d.refobjsubid AS owning_col, "
4111                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4112                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4113                                                   "NULL AS toast_reloptions "
4114                                                   "FROM pg_class c "
4115                                                   "LEFT JOIN pg_depend d ON "
4116                                                   "(c.relkind = '%c' AND "
4117                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4118                                                   "d.objsubid = 0 AND "
4119                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4120                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4121                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4122                                                   "ORDER BY c.oid",
4123                                                   username_subquery,
4124                                                   RELKIND_SEQUENCE,
4125                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4126                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4127         }
4128         else if (fout->remoteVersion >= 80000)
4129         {
4130                 /*
4131                  * Left join to pick up dependency info linking sequences to their
4132                  * owning column, if any
4133                  */
4134                 appendPQExpBuffer(query,
4135                                                   "SELECT c.tableoid, c.oid, relname, "
4136                                                   "relacl, relkind, relnamespace, "
4137                                                   "(%s relowner) AS rolname, "
4138                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4139                                                   "relhasindex, relhasrules, relhasoids, "
4140                                                   "0 AS relfrozenxid, "
4141                                                   "0 AS toid, "
4142                                                   "0 AS tfrozenxid, "
4143                                                   "'p' AS relpersistence, "
4144                                                   "NULL AS reloftype, "
4145                                                   "d.refobjid AS owning_tab, "
4146                                                   "d.refobjsubid AS owning_col, "
4147                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4148                                                   "NULL AS reloptions, "
4149                                                   "NULL AS toast_reloptions "
4150                                                   "FROM pg_class c "
4151                                                   "LEFT JOIN pg_depend d ON "
4152                                                   "(c.relkind = '%c' AND "
4153                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4154                                                   "d.objsubid = 0 AND "
4155                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4156                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4157                                                   "ORDER BY c.oid",
4158                                                   username_subquery,
4159                                                   RELKIND_SEQUENCE,
4160                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4161                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4162         }
4163         else if (fout->remoteVersion >= 70300)
4164         {
4165                 /*
4166                  * Left join to pick up dependency info linking sequences to their
4167                  * owning column, if any
4168                  */
4169                 appendPQExpBuffer(query,
4170                                                   "SELECT c.tableoid, c.oid, relname, "
4171                                                   "relacl, relkind, relnamespace, "
4172                                                   "(%s relowner) AS rolname, "
4173                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4174                                                   "relhasindex, relhasrules, relhasoids, "
4175                                                   "0 AS relfrozenxid, "
4176                                                   "0 AS toid, "
4177                                                   "0 AS tfrozenxid, "
4178                                                   "'p' AS relpersistence, "
4179                                                   "NULL AS reloftype, "
4180                                                   "d.refobjid AS owning_tab, "
4181                                                   "d.refobjsubid AS owning_col, "
4182                                                   "NULL AS reltablespace, "
4183                                                   "NULL AS reloptions, "
4184                                                   "NULL AS toast_reloptions "
4185                                                   "FROM pg_class c "
4186                                                   "LEFT JOIN pg_depend d ON "
4187                                                   "(c.relkind = '%c' AND "
4188                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4189                                                   "d.objsubid = 0 AND "
4190                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4191                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4192                                                   "ORDER BY c.oid",
4193                                                   username_subquery,
4194                                                   RELKIND_SEQUENCE,
4195                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4196                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4197         }
4198         else if (fout->remoteVersion >= 70200)
4199         {
4200                 appendPQExpBuffer(query,
4201                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4202                                                   "0::oid AS relnamespace, "
4203                                                   "(%s relowner) AS rolname, "
4204                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4205                                                   "relhasindex, relhasrules, relhasoids, "
4206                                                   "0 AS relfrozenxid, "
4207                                                   "0 AS toid, "
4208                                                   "0 AS tfrozenxid, "
4209                                                   "'p' AS relpersistence, "
4210                                                   "NULL AS reloftype, "
4211                                                   "NULL::oid AS owning_tab, "
4212                                                   "NULL::int4 AS owning_col, "
4213                                                   "NULL AS reltablespace, "
4214                                                   "NULL AS reloptions, "
4215                                                   "NULL AS toast_reloptions "
4216                                                   "FROM pg_class "
4217                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4218                                                   "ORDER BY oid",
4219                                                   username_subquery,
4220                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4221         }
4222         else if (fout->remoteVersion >= 70100)
4223         {
4224                 /* all tables have oids in 7.1 */
4225                 appendPQExpBuffer(query,
4226                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4227                                                   "0::oid AS relnamespace, "
4228                                                   "(%s relowner) AS rolname, "
4229                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4230                                                   "relhasindex, relhasrules, "
4231                                                   "'t'::bool AS relhasoids, "
4232                                                   "0 AS relfrozenxid, "
4233                                                   "0 AS toid, "
4234                                                   "0 AS tfrozenxid, "
4235                                                   "'p' AS relpersistence, "
4236                                                   "NULL AS reloftype, "
4237                                                   "NULL::oid AS owning_tab, "
4238                                                   "NULL::int4 AS owning_col, "
4239                                                   "NULL AS reltablespace, "
4240                                                   "NULL AS reloptions, "
4241                                                   "NULL AS toast_reloptions "
4242                                                   "FROM pg_class "
4243                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4244                                                   "ORDER BY oid",
4245                                                   username_subquery,
4246                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4247         }
4248         else
4249         {
4250                 /*
4251                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4252                  * have a view by looking for a rule in pg_rewrite.
4253                  */
4254                 appendPQExpBuffer(query,
4255                                                   "SELECT "
4256                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4257                                                   "oid, relname, relacl, "
4258                                                   "CASE WHEN relhasrules and relkind = 'r' "
4259                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4260                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4261                                                   "THEN '%c'::\"char\" "
4262                                                   "ELSE relkind END AS relkind,"
4263                                                   "0::oid AS relnamespace, "
4264                                                   "(%s relowner) AS rolname, "
4265                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4266                                                   "relhasindex, relhasrules, "
4267                                                   "'t'::bool AS relhasoids, "
4268                                                   "0 as relfrozenxid, "
4269                                                   "0 AS toid, "
4270                                                   "0 AS tfrozenxid, "
4271                                                   "'p' AS relpersistence, "
4272                                                   "NULL AS reloftype, "
4273                                                   "NULL::oid AS owning_tab, "
4274                                                   "NULL::int4 AS owning_col, "
4275                                                   "NULL AS reltablespace, "
4276                                                   "NULL AS reloptions, "
4277                                                   "NULL AS toast_reloptions "
4278                                                   "FROM pg_class c "
4279                                                   "WHERE relkind IN ('%c', '%c') "
4280                                                   "ORDER BY oid",
4281                                                   RELKIND_VIEW,
4282                                                   username_subquery,
4283                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4284         }
4285
4286         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4287
4288         ntups = PQntuples(res);
4289
4290         *numTables = ntups;
4291
4292         /*
4293          * Extract data from result and lock dumpable tables.  We do the locking
4294          * before anything else, to minimize the window wherein a table could
4295          * disappear under us.
4296          *
4297          * Note that we have to save info about all tables here, even when dumping
4298          * only one, because we don't yet know which tables might be inheritance
4299          * ancestors of the target table.
4300          */
4301         tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4302
4303         i_reltableoid = PQfnumber(res, "tableoid");
4304         i_reloid = PQfnumber(res, "oid");
4305         i_relname = PQfnumber(res, "relname");
4306         i_relnamespace = PQfnumber(res, "relnamespace");
4307         i_relacl = PQfnumber(res, "relacl");
4308         i_relkind = PQfnumber(res, "relkind");
4309         i_rolname = PQfnumber(res, "rolname");
4310         i_relchecks = PQfnumber(res, "relchecks");
4311         i_relhastriggers = PQfnumber(res, "relhastriggers");
4312         i_relhasindex = PQfnumber(res, "relhasindex");
4313         i_relhasrules = PQfnumber(res, "relhasrules");
4314         i_relhasoids = PQfnumber(res, "relhasoids");
4315         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4316         i_toastoid = PQfnumber(res, "toid");
4317         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4318         i_relpersistence = PQfnumber(res, "relpersistence");
4319         i_owning_tab = PQfnumber(res, "owning_tab");
4320         i_owning_col = PQfnumber(res, "owning_col");
4321         i_reltablespace = PQfnumber(res, "reltablespace");
4322         i_reloptions = PQfnumber(res, "reloptions");
4323         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4324         i_reloftype = PQfnumber(res, "reloftype");
4325
4326         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4327         {
4328                 /*
4329                  * Arrange to fail instead of waiting forever for a table lock.
4330                  *
4331                  * NB: this coding assumes that the only queries issued within the
4332                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4333                  * applied to other things too.
4334                  */
4335                 resetPQExpBuffer(query);
4336                 appendPQExpBuffer(query, "SET statement_timeout = ");
4337                 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
4338                 ExecuteSqlStatement(fout, query->data);
4339         }
4340
4341         for (i = 0; i < ntups; i++)
4342         {
4343                 tblinfo[i].dobj.objType = DO_TABLE;
4344                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4345                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4346                 AssignDumpId(&tblinfo[i].dobj);
4347                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4348                 tblinfo[i].dobj.namespace =
4349                         findNamespace(fout,
4350                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4351                                                   tblinfo[i].dobj.catId.oid);
4352                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4353                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4354                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4355                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4356                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4357                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4358                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4359                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4360                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4361                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4362                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4363                 if (PQgetisnull(res, i, i_reloftype))
4364                         tblinfo[i].reloftype = NULL;
4365                 else
4366                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4367                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4368                 if (PQgetisnull(res, i, i_owning_tab))
4369                 {
4370                         tblinfo[i].owning_tab = InvalidOid;
4371                         tblinfo[i].owning_col = 0;
4372                 }
4373                 else
4374                 {
4375                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4376                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4377                 }
4378                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4379                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4380                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4381
4382                 /* other fields were zeroed above */
4383
4384                 /*
4385                  * Decide whether we want to dump this table.
4386                  */
4387                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4388                         tblinfo[i].dobj.dump = false;
4389                 else
4390                         selectDumpableTable(&tblinfo[i]);
4391                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4392
4393                 /*
4394                  * Read-lock target tables to make sure they aren't DROPPED or altered
4395                  * in schema before we get around to dumping them.
4396                  *
4397                  * Note that we don't explicitly lock parents of the target tables; we
4398                  * assume our lock on the child is enough to prevent schema
4399                  * alterations to parent tables.
4400                  *
4401                  * NOTE: it'd be kinda nice to lock other relations too, not only
4402                  * plain tables, but the backend doesn't presently allow that.
4403                  */
4404                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4405                 {
4406                         resetPQExpBuffer(query);
4407                         appendPQExpBuffer(query,
4408                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4409                                                  fmtQualifiedId(fout,
4410                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4411                                                                                 tblinfo[i].dobj.name));
4412                         ExecuteSqlStatement(fout, query->data);
4413                 }
4414
4415                 /* Emit notice if join for owner failed */
4416                 if (strlen(tblinfo[i].rolname) == 0)
4417                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4418                                           tblinfo[i].dobj.name);
4419         }
4420
4421         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4422         {
4423                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4424         }
4425
4426         PQclear(res);
4427
4428         /*
4429          * Force sequences that are "owned" by table columns to be dumped whenever
4430          * their owning table is being dumped.
4431          */
4432         for (i = 0; i < ntups; i++)
4433         {
4434                 TableInfo  *seqinfo = &tblinfo[i];
4435                 int                     j;
4436
4437                 if (!OidIsValid(seqinfo->owning_tab))
4438                         continue;                       /* not an owned sequence */
4439                 if (seqinfo->dobj.dump)
4440                         continue;                       /* no need to search */
4441
4442                 /* can't use findTableByOid yet, unfortunately */
4443                 for (j = 0; j < ntups; j++)
4444                 {
4445                         if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4446                         {
4447                                 if (tblinfo[j].dobj.dump)
4448                                 {
4449                                         seqinfo->interesting = true;
4450                                         seqinfo->dobj.dump = true;
4451                                 }
4452                                 break;
4453                         }
4454                 }
4455         }
4456
4457         destroyPQExpBuffer(query);
4458
4459         return tblinfo;
4460 }
4461
4462 /*
4463  * getInherits
4464  *        read all the inheritance information
4465  * from the system catalogs return them in the InhInfo* structure
4466  *
4467  * numInherits is set to the number of pairs read in
4468  */
4469 InhInfo *
4470 getInherits(Archive *fout, int *numInherits)
4471 {
4472         PGresult   *res;
4473         int                     ntups;
4474         int                     i;
4475         PQExpBuffer query = createPQExpBuffer();
4476         InhInfo    *inhinfo;
4477
4478         int                     i_inhrelid;
4479         int                     i_inhparent;
4480
4481         /* Make sure we are in proper schema */
4482         selectSourceSchema(fout, "pg_catalog");
4483
4484         /* find all the inheritance information */
4485
4486         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4487
4488         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4489
4490         ntups = PQntuples(res);
4491
4492         *numInherits = ntups;
4493
4494         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4495
4496         i_inhrelid = PQfnumber(res, "inhrelid");
4497         i_inhparent = PQfnumber(res, "inhparent");
4498
4499         for (i = 0; i < ntups; i++)
4500         {
4501                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4502                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4503         }
4504
4505         PQclear(res);
4506
4507         destroyPQExpBuffer(query);
4508
4509         return inhinfo;
4510 }
4511
4512 /*
4513  * getIndexes
4514  *        get information about every index on a dumpable table
4515  *
4516  * Note: index data is not returned directly to the caller, but it
4517  * does get entered into the DumpableObject tables.
4518  */
4519 void
4520 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4521 {
4522         int                     i,
4523                                 j;
4524         PQExpBuffer query = createPQExpBuffer();
4525         PGresult   *res;
4526         IndxInfo   *indxinfo;
4527         ConstraintInfo *constrinfo;
4528         int                     i_tableoid,
4529                                 i_oid,
4530                                 i_indexname,
4531                                 i_indexdef,
4532                                 i_indnkeys,
4533                                 i_indkey,
4534                                 i_indisclustered,
4535                                 i_contype,
4536                                 i_conname,
4537                                 i_condeferrable,
4538                                 i_condeferred,
4539                                 i_contableoid,
4540                                 i_conoid,
4541                                 i_condef,
4542                                 i_tablespace,
4543                                 i_options;
4544         int                     ntups;
4545
4546         for (i = 0; i < numTables; i++)
4547         {
4548                 TableInfo  *tbinfo = &tblinfo[i];
4549
4550                 /* Only plain tables have indexes */
4551                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4552                         continue;
4553
4554                 /* Ignore indexes of tables not to be dumped */
4555                 if (!tbinfo->dobj.dump)
4556                         continue;
4557
4558                 if (g_verbose)
4559                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4560                                           tbinfo->dobj.name);
4561
4562                 /* Make sure we are in proper schema so indexdef is right */
4563                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4564
4565                 /*
4566                  * The point of the messy-looking outer join is to find a constraint
4567                  * that is related by an internal dependency link to the index. If we
4568                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4569                  * assume an index won't have more than one internal dependency.
4570                  *
4571                  * As of 9.0 we don't need to look at pg_depend but can check for a
4572                  * match to pg_constraint.conindid.  The check on conrelid is
4573                  * redundant but useful because that column is indexed while conindid
4574                  * is not.
4575                  */
4576                 resetPQExpBuffer(query);
4577                 if (fout->remoteVersion >= 90000)
4578                 {
4579                         appendPQExpBuffer(query,
4580                                                           "SELECT t.tableoid, t.oid, "
4581                                                           "t.relname AS indexname, "
4582                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4583                                                           "t.relnatts AS indnkeys, "
4584                                                           "i.indkey, i.indisclustered, "
4585                                                           "c.contype, c.conname, "
4586                                                           "c.condeferrable, c.condeferred, "
4587                                                           "c.tableoid AS contableoid, "
4588                                                           "c.oid AS conoid, "
4589                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4590                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4591                                                         "array_to_string(t.reloptions, ', ') AS options "
4592                                                           "FROM pg_catalog.pg_index i "
4593                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4594                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4595                                                           "ON (i.indrelid = c.conrelid AND "
4596                                                           "i.indexrelid = c.conindid AND "
4597                                                           "c.contype IN ('p','u','x')) "
4598                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4599                                                           "ORDER BY indexname",
4600                                                           tbinfo->dobj.catId.oid);
4601                 }
4602                 else if (fout->remoteVersion >= 80200)
4603                 {
4604                         appendPQExpBuffer(query,
4605                                                           "SELECT t.tableoid, t.oid, "
4606                                                           "t.relname AS indexname, "
4607                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4608                                                           "t.relnatts AS indnkeys, "
4609                                                           "i.indkey, i.indisclustered, "
4610                                                           "c.contype, c.conname, "
4611                                                           "c.condeferrable, c.condeferred, "
4612                                                           "c.tableoid AS contableoid, "
4613                                                           "c.oid AS conoid, "
4614                                                           "null AS condef, "
4615                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4616                                                         "array_to_string(t.reloptions, ', ') AS options "
4617                                                           "FROM pg_catalog.pg_index i "
4618                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4619                                                           "LEFT JOIN pg_catalog.pg_depend d "
4620                                                           "ON (d.classid = t.tableoid "
4621                                                           "AND d.objid = t.oid "
4622                                                           "AND d.deptype = 'i') "
4623                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4624                                                           "ON (d.refclassid = c.tableoid "
4625                                                           "AND d.refobjid = c.oid) "
4626                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4627                                                           "ORDER BY indexname",
4628                                                           tbinfo->dobj.catId.oid);
4629                 }
4630                 else if (fout->remoteVersion >= 80000)
4631                 {
4632                         appendPQExpBuffer(query,
4633                                                           "SELECT t.tableoid, t.oid, "
4634                                                           "t.relname AS indexname, "
4635                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4636                                                           "t.relnatts AS indnkeys, "
4637                                                           "i.indkey, i.indisclustered, "
4638                                                           "c.contype, c.conname, "
4639                                                           "c.condeferrable, c.condeferred, "
4640                                                           "c.tableoid AS contableoid, "
4641                                                           "c.oid AS conoid, "
4642                                                           "null AS condef, "
4643                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4644                                                           "null AS options "
4645                                                           "FROM pg_catalog.pg_index i "
4646                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4647                                                           "LEFT JOIN pg_catalog.pg_depend d "
4648                                                           "ON (d.classid = t.tableoid "
4649                                                           "AND d.objid = t.oid "
4650                                                           "AND d.deptype = 'i') "
4651                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4652                                                           "ON (d.refclassid = c.tableoid "
4653                                                           "AND d.refobjid = c.oid) "
4654                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4655                                                           "ORDER BY indexname",
4656                                                           tbinfo->dobj.catId.oid);
4657                 }
4658                 else if (fout->remoteVersion >= 70300)
4659                 {
4660                         appendPQExpBuffer(query,
4661                                                           "SELECT t.tableoid, t.oid, "
4662                                                           "t.relname AS indexname, "
4663                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4664                                                           "t.relnatts AS indnkeys, "
4665                                                           "i.indkey, i.indisclustered, "
4666                                                           "c.contype, c.conname, "
4667                                                           "c.condeferrable, c.condeferred, "
4668                                                           "c.tableoid AS contableoid, "
4669                                                           "c.oid AS conoid, "
4670                                                           "null AS condef, "
4671                                                           "NULL AS tablespace, "
4672                                                           "null AS options "
4673                                                           "FROM pg_catalog.pg_index i "
4674                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4675                                                           "LEFT JOIN pg_catalog.pg_depend d "
4676                                                           "ON (d.classid = t.tableoid "
4677                                                           "AND d.objid = t.oid "
4678                                                           "AND d.deptype = 'i') "
4679                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4680                                                           "ON (d.refclassid = c.tableoid "
4681                                                           "AND d.refobjid = c.oid) "
4682                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4683                                                           "ORDER BY indexname",
4684                                                           tbinfo->dobj.catId.oid);
4685                 }
4686                 else if (fout->remoteVersion >= 70100)
4687                 {
4688                         appendPQExpBuffer(query,
4689                                                           "SELECT t.tableoid, t.oid, "
4690                                                           "t.relname AS indexname, "
4691                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4692                                                           "t.relnatts AS indnkeys, "
4693                                                           "i.indkey, false AS indisclustered, "
4694                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4695                                                           "ELSE '0'::char END AS contype, "
4696                                                           "t.relname AS conname, "
4697                                                           "false AS condeferrable, "
4698                                                           "false AS condeferred, "
4699                                                           "0::oid AS contableoid, "
4700                                                           "t.oid AS conoid, "
4701                                                           "null AS condef, "
4702                                                           "NULL AS tablespace, "
4703                                                           "null AS options "
4704                                                           "FROM pg_index i, pg_class t "
4705                                                           "WHERE t.oid = i.indexrelid "
4706                                                           "AND i.indrelid = '%u'::oid "
4707                                                           "ORDER BY indexname",
4708                                                           tbinfo->dobj.catId.oid);
4709                 }
4710                 else
4711                 {
4712                         appendPQExpBuffer(query,
4713                                                           "SELECT "
4714                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4715                                                           "t.oid, "
4716                                                           "t.relname AS indexname, "
4717                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4718                                                           "t.relnatts AS indnkeys, "
4719                                                           "i.indkey, false AS indisclustered, "
4720                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4721                                                           "ELSE '0'::char END AS contype, "
4722                                                           "t.relname AS conname, "
4723                                                           "false AS condeferrable, "
4724                                                           "false AS condeferred, "
4725                                                           "0::oid AS contableoid, "
4726                                                           "t.oid AS conoid, "
4727                                                           "null AS condef, "
4728                                                           "NULL AS tablespace, "
4729                                                           "null AS options "
4730                                                           "FROM pg_index i, pg_class t "
4731                                                           "WHERE t.oid = i.indexrelid "
4732                                                           "AND i.indrelid = '%u'::oid "
4733                                                           "ORDER BY indexname",
4734                                                           tbinfo->dobj.catId.oid);
4735                 }
4736
4737                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4738
4739                 ntups = PQntuples(res);
4740
4741                 i_tableoid = PQfnumber(res, "tableoid");
4742                 i_oid = PQfnumber(res, "oid");
4743                 i_indexname = PQfnumber(res, "indexname");
4744                 i_indexdef = PQfnumber(res, "indexdef");
4745                 i_indnkeys = PQfnumber(res, "indnkeys");
4746                 i_indkey = PQfnumber(res, "indkey");
4747                 i_indisclustered = PQfnumber(res, "indisclustered");
4748                 i_contype = PQfnumber(res, "contype");
4749                 i_conname = PQfnumber(res, "conname");
4750                 i_condeferrable = PQfnumber(res, "condeferrable");
4751                 i_condeferred = PQfnumber(res, "condeferred");
4752                 i_contableoid = PQfnumber(res, "contableoid");
4753                 i_conoid = PQfnumber(res, "conoid");
4754                 i_condef = PQfnumber(res, "condef");
4755                 i_tablespace = PQfnumber(res, "tablespace");
4756                 i_options = PQfnumber(res, "options");
4757
4758                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4759                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4760
4761                 for (j = 0; j < ntups; j++)
4762                 {
4763                         char            contype;
4764
4765                         indxinfo[j].dobj.objType = DO_INDEX;
4766                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4767                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4768                         AssignDumpId(&indxinfo[j].dobj);
4769                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4770                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4771                         indxinfo[j].indextable = tbinfo;
4772                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4773                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4774                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4775                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4776
4777                         /*
4778                          * In pre-7.4 releases, indkeys may contain more entries than
4779                          * indnkeys says (since indnkeys will be 1 for a functional
4780                          * index).      We don't actually care about this case since we don't
4781                          * examine indkeys except for indexes associated with PRIMARY and
4782                          * UNIQUE constraints, which are never functional indexes. But we
4783                          * have to allocate enough space to keep parseOidArray from
4784                          * complaining.
4785                          */
4786                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4787                         parseOidArray(PQgetvalue(res, j, i_indkey),
4788                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4789                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4790                         contype = *(PQgetvalue(res, j, i_contype));
4791
4792                         if (contype == 'p' || contype == 'u' || contype == 'x')
4793                         {
4794                                 /*
4795                                  * If we found a constraint matching the index, create an
4796                                  * entry for it.
4797                                  *
4798                                  * In a pre-7.3 database, we take this path iff the index was
4799                                  * marked indisprimary.
4800                                  */
4801                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4802                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4803                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4804                                 AssignDumpId(&constrinfo[j].dobj);
4805                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4806                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4807                                 constrinfo[j].contable = tbinfo;
4808                                 constrinfo[j].condomain = NULL;
4809                                 constrinfo[j].contype = contype;
4810                                 if (contype == 'x')
4811                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4812                                 else
4813                                         constrinfo[j].condef = NULL;
4814                                 constrinfo[j].confrelid = InvalidOid;
4815                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4816                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4817                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4818                                 constrinfo[j].conislocal = true;
4819                                 constrinfo[j].separate = true;
4820
4821                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4822
4823                                 /* If pre-7.3 DB, better make sure table comes first */
4824                                 addObjectDependency(&constrinfo[j].dobj,
4825                                                                         tbinfo->dobj.dumpId);
4826                         }
4827                         else
4828                         {
4829                                 /* Plain secondary index */
4830                                 indxinfo[j].indexconstraint = 0;
4831                         }
4832                 }
4833
4834                 PQclear(res);
4835         }
4836
4837         destroyPQExpBuffer(query);
4838 }
4839
4840 /*
4841  * getConstraints
4842  *
4843  * Get info about constraints on dumpable tables.
4844  *
4845  * Currently handles foreign keys only.
4846  * Unique and primary key constraints are handled with indexes,
4847  * while check constraints are processed in getTableAttrs().
4848  */
4849 void
4850 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4851 {
4852         int                     i,
4853                                 j;
4854         ConstraintInfo *constrinfo;
4855         PQExpBuffer query;
4856         PGresult   *res;
4857         int                     i_contableoid,
4858                                 i_conoid,
4859                                 i_conname,
4860                                 i_confrelid,
4861                                 i_condef;
4862         int                     ntups;
4863
4864         /* pg_constraint was created in 7.3, so nothing to do if older */
4865         if (fout->remoteVersion < 70300)
4866                 return;
4867
4868         query = createPQExpBuffer();
4869
4870         for (i = 0; i < numTables; i++)
4871         {
4872                 TableInfo  *tbinfo = &tblinfo[i];
4873
4874                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4875                         continue;
4876
4877                 if (g_verbose)
4878                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4879                                           tbinfo->dobj.name);
4880
4881                 /*
4882                  * select table schema to ensure constraint expr is qualified if
4883                  * needed
4884                  */
4885                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4886
4887                 resetPQExpBuffer(query);
4888                 appendPQExpBuffer(query,
4889                                                   "SELECT tableoid, oid, conname, confrelid, "
4890                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4891                                                   "FROM pg_catalog.pg_constraint "
4892                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4893                                                   "AND contype = 'f'",
4894                                                   tbinfo->dobj.catId.oid);
4895                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4896
4897                 ntups = PQntuples(res);
4898
4899                 i_contableoid = PQfnumber(res, "tableoid");
4900                 i_conoid = PQfnumber(res, "oid");
4901                 i_conname = PQfnumber(res, "conname");
4902                 i_confrelid = PQfnumber(res, "confrelid");
4903                 i_condef = PQfnumber(res, "condef");
4904
4905                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4906
4907                 for (j = 0; j < ntups; j++)
4908                 {
4909                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4910                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4911                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4912                         AssignDumpId(&constrinfo[j].dobj);
4913                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4914                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4915                         constrinfo[j].contable = tbinfo;
4916                         constrinfo[j].condomain = NULL;
4917                         constrinfo[j].contype = 'f';
4918                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4919                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4920                         constrinfo[j].conindex = 0;
4921                         constrinfo[j].condeferrable = false;
4922                         constrinfo[j].condeferred = false;
4923                         constrinfo[j].conislocal = true;
4924                         constrinfo[j].separate = true;
4925                 }
4926
4927                 PQclear(res);
4928         }
4929
4930         destroyPQExpBuffer(query);
4931 }
4932
4933 /*
4934  * getDomainConstraints
4935  *
4936  * Get info about constraints on a domain.
4937  */
4938 static void
4939 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4940 {
4941         int                     i;
4942         ConstraintInfo *constrinfo;
4943         PQExpBuffer query;
4944         PGresult   *res;
4945         int                     i_tableoid,
4946                                 i_oid,
4947                                 i_conname,
4948                                 i_consrc;
4949         int                     ntups;
4950
4951         /* pg_constraint was created in 7.3, so nothing to do if older */
4952         if (fout->remoteVersion < 70300)
4953                 return;
4954
4955         /*
4956          * select appropriate schema to ensure names in constraint are properly
4957          * qualified
4958          */
4959         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4960
4961         query = createPQExpBuffer();
4962
4963         if (fout->remoteVersion >= 90100)
4964                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4965                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4966                                                   "convalidated "
4967                                                   "FROM pg_catalog.pg_constraint "
4968                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4969                                                   "ORDER BY conname",
4970                                                   tyinfo->dobj.catId.oid);
4971
4972         else if (fout->remoteVersion >= 70400)
4973                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4974                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4975                                                   "true as convalidated "
4976                                                   "FROM pg_catalog.pg_constraint "
4977                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4978                                                   "ORDER BY conname",
4979                                                   tyinfo->dobj.catId.oid);
4980         else
4981                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4982                                                   "'CHECK (' || consrc || ')' AS consrc, "
4983                                                   "true as convalidated "
4984                                                   "FROM pg_catalog.pg_constraint "
4985                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4986                                                   "ORDER BY conname",
4987                                                   tyinfo->dobj.catId.oid);
4988
4989         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4990
4991         ntups = PQntuples(res);
4992
4993         i_tableoid = PQfnumber(res, "tableoid");
4994         i_oid = PQfnumber(res, "oid");
4995         i_conname = PQfnumber(res, "conname");
4996         i_consrc = PQfnumber(res, "consrc");
4997
4998         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4999
5000         tyinfo->nDomChecks = ntups;
5001         tyinfo->domChecks = constrinfo;
5002
5003         for (i = 0; i < ntups; i++)
5004         {
5005                 bool    validated = PQgetvalue(res, i, 4)[0] == 't';
5006
5007                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5008                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5009                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5010                 AssignDumpId(&constrinfo[i].dobj);
5011                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5012                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5013                 constrinfo[i].contable = NULL;
5014                 constrinfo[i].condomain = tyinfo;
5015                 constrinfo[i].contype = 'c';
5016                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5017                 constrinfo[i].confrelid = InvalidOid;
5018                 constrinfo[i].conindex = 0;
5019                 constrinfo[i].condeferrable = false;
5020                 constrinfo[i].condeferred = false;
5021                 constrinfo[i].conislocal = true;
5022
5023                 constrinfo[i].separate = !validated;
5024
5025                 /*
5026                  * Make the domain depend on the constraint, ensuring it won't be
5027                  * output till any constraint dependencies are OK.  If the constraint
5028                  * has not been validated, it's going to be dumped after the domain
5029                  * anyway, so this doesn't matter.
5030                  */
5031                 if (validated)
5032                         addObjectDependency(&tyinfo->dobj,
5033                                                                 constrinfo[i].dobj.dumpId);
5034         }
5035
5036         PQclear(res);
5037
5038         destroyPQExpBuffer(query);
5039 }
5040
5041 /*
5042  * getRules
5043  *        get basic information about every rule in the system
5044  *
5045  * numRules is set to the number of rules read in
5046  */
5047 RuleInfo *
5048 getRules(Archive *fout, int *numRules)
5049 {
5050         PGresult   *res;
5051         int                     ntups;
5052         int                     i;
5053         PQExpBuffer query = createPQExpBuffer();
5054         RuleInfo   *ruleinfo;
5055         int                     i_tableoid;
5056         int                     i_oid;
5057         int                     i_rulename;
5058         int                     i_ruletable;
5059         int                     i_ev_type;
5060         int                     i_is_instead;
5061         int                     i_ev_enabled;
5062
5063         /* Make sure we are in proper schema */
5064         selectSourceSchema(fout, "pg_catalog");
5065
5066         if (fout->remoteVersion >= 80300)
5067         {
5068                 appendPQExpBuffer(query, "SELECT "
5069                                                   "tableoid, oid, rulename, "
5070                                                   "ev_class AS ruletable, ev_type, is_instead, "
5071                                                   "ev_enabled "
5072                                                   "FROM pg_rewrite "
5073                                                   "ORDER BY oid");
5074         }
5075         else if (fout->remoteVersion >= 70100)
5076         {
5077                 appendPQExpBuffer(query, "SELECT "
5078                                                   "tableoid, oid, rulename, "
5079                                                   "ev_class AS ruletable, ev_type, is_instead, "
5080                                                   "'O'::char AS ev_enabled "
5081                                                   "FROM pg_rewrite "
5082                                                   "ORDER BY oid");
5083         }
5084         else
5085         {
5086                 appendPQExpBuffer(query, "SELECT "
5087                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5088                                                   "oid, rulename, "
5089                                                   "ev_class AS ruletable, ev_type, is_instead, "
5090                                                   "'O'::char AS ev_enabled "
5091                                                   "FROM pg_rewrite "
5092                                                   "ORDER BY oid");
5093         }
5094
5095         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5096
5097         ntups = PQntuples(res);
5098
5099         *numRules = ntups;
5100
5101         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5102
5103         i_tableoid = PQfnumber(res, "tableoid");
5104         i_oid = PQfnumber(res, "oid");
5105         i_rulename = PQfnumber(res, "rulename");
5106         i_ruletable = PQfnumber(res, "ruletable");
5107         i_ev_type = PQfnumber(res, "ev_type");
5108         i_is_instead = PQfnumber(res, "is_instead");
5109         i_ev_enabled = PQfnumber(res, "ev_enabled");
5110
5111         for (i = 0; i < ntups; i++)
5112         {
5113                 Oid                     ruletableoid;
5114
5115                 ruleinfo[i].dobj.objType = DO_RULE;
5116                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5117                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5118                 AssignDumpId(&ruleinfo[i].dobj);
5119                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5120                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5121                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5122                 if (ruleinfo[i].ruletable == NULL)
5123                 {
5124                         write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5125                                           ruletableoid,
5126                                           ruleinfo[i].dobj.catId.oid);
5127                         exit_nicely();
5128                 }
5129                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5130                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5131                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5132                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5133                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5134                 if (ruleinfo[i].ruletable)
5135                 {
5136                         /*
5137                          * If the table is a view, force its ON SELECT rule to be sorted
5138                          * before the view itself --- this ensures that any dependencies
5139                          * for the rule affect the table's positioning. Other rules are
5140                          * forced to appear after their table.
5141                          */
5142                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5143                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5144                         {
5145                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5146                                                                         ruleinfo[i].dobj.dumpId);
5147                                 /* We'll merge the rule into CREATE VIEW, if possible */
5148                                 ruleinfo[i].separate = false;
5149                         }
5150                         else
5151                         {
5152                                 addObjectDependency(&ruleinfo[i].dobj,
5153                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5154                                 ruleinfo[i].separate = true;
5155                         }
5156                 }
5157                 else
5158                         ruleinfo[i].separate = true;
5159         }
5160
5161         PQclear(res);
5162
5163         destroyPQExpBuffer(query);
5164
5165         return ruleinfo;
5166 }
5167
5168 /*
5169  * getTriggers
5170  *        get information about every trigger on a dumpable table
5171  *
5172  * Note: trigger data is not returned directly to the caller, but it
5173  * does get entered into the DumpableObject tables.
5174  */
5175 void
5176 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5177 {
5178         int                     i,
5179                                 j;
5180         PQExpBuffer query = createPQExpBuffer();
5181         PGresult   *res;
5182         TriggerInfo *tginfo;
5183         int                     i_tableoid,
5184                                 i_oid,
5185                                 i_tgname,
5186                                 i_tgfname,
5187                                 i_tgtype,
5188                                 i_tgnargs,
5189                                 i_tgargs,
5190                                 i_tgisconstraint,
5191                                 i_tgconstrname,
5192                                 i_tgconstrrelid,
5193                                 i_tgconstrrelname,
5194                                 i_tgenabled,
5195                                 i_tgdeferrable,
5196                                 i_tginitdeferred,
5197                                 i_tgdef;
5198         int                     ntups;
5199
5200         for (i = 0; i < numTables; i++)
5201         {
5202                 TableInfo  *tbinfo = &tblinfo[i];
5203
5204                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5205                         continue;
5206
5207                 if (g_verbose)
5208                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5209                                           tbinfo->dobj.name);
5210
5211                 /*
5212                  * select table schema to ensure regproc name is qualified if needed
5213                  */
5214                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5215
5216                 resetPQExpBuffer(query);
5217                 if (fout->remoteVersion >= 90000)
5218                 {
5219                         /*
5220                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5221                          * could result in non-forward-compatible dumps of WHEN clauses
5222                          * due to under-parenthesization.
5223                          */
5224                         appendPQExpBuffer(query,
5225                                                           "SELECT tgname, "
5226                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5227                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5228                                                           "tgenabled, tableoid, oid "
5229                                                           "FROM pg_catalog.pg_trigger t "
5230                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5231                                                           "AND NOT tgisinternal",
5232                                                           tbinfo->dobj.catId.oid);
5233                 }
5234                 else if (fout->remoteVersion >= 80300)
5235                 {
5236                         /*
5237                          * We ignore triggers that are tied to a foreign-key constraint
5238                          */
5239                         appendPQExpBuffer(query,
5240                                                           "SELECT tgname, "
5241                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5242                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5243                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5244                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5245                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5246                                                           "FROM pg_catalog.pg_trigger t "
5247                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5248                                                           "AND tgconstraint = 0",
5249                                                           tbinfo->dobj.catId.oid);
5250                 }
5251                 else if (fout->remoteVersion >= 70300)
5252                 {
5253                         /*
5254                          * We ignore triggers that are tied to a foreign-key constraint,
5255                          * but in these versions we have to grovel through pg_constraint
5256                          * to find out
5257                          */
5258                         appendPQExpBuffer(query,
5259                                                           "SELECT tgname, "
5260                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5261                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5262                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5263                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5264                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5265                                                           "FROM pg_catalog.pg_trigger t "
5266                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5267                                                           "AND (NOT tgisconstraint "
5268                                                           " OR NOT EXISTS"
5269                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5270                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5271                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5272                                                           tbinfo->dobj.catId.oid);
5273                 }
5274                 else if (fout->remoteVersion >= 70100)
5275                 {
5276                         appendPQExpBuffer(query,
5277                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5278                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5279                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5280                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5281                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5282                                                           "             AS tgconstrrelname "
5283                                                           "FROM pg_trigger "
5284                                                           "WHERE tgrelid = '%u'::oid",
5285                                                           tbinfo->dobj.catId.oid);
5286                 }
5287                 else
5288                 {
5289                         appendPQExpBuffer(query,
5290                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5291                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5292                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5293                                                           "tgconstrrelid, tginitdeferred, "
5294                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5295                                                           "oid, "
5296                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5297                                                           "             AS tgconstrrelname "
5298                                                           "FROM pg_trigger "
5299                                                           "WHERE tgrelid = '%u'::oid",
5300                                                           tbinfo->dobj.catId.oid);
5301                 }
5302                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5303
5304                 ntups = PQntuples(res);
5305
5306                 i_tableoid = PQfnumber(res, "tableoid");
5307                 i_oid = PQfnumber(res, "oid");
5308                 i_tgname = PQfnumber(res, "tgname");
5309                 i_tgfname = PQfnumber(res, "tgfname");
5310                 i_tgtype = PQfnumber(res, "tgtype");
5311                 i_tgnargs = PQfnumber(res, "tgnargs");
5312                 i_tgargs = PQfnumber(res, "tgargs");
5313                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5314                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5315                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5316                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5317                 i_tgenabled = PQfnumber(res, "tgenabled");
5318                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5319                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5320                 i_tgdef = PQfnumber(res, "tgdef");
5321
5322                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5323
5324                 for (j = 0; j < ntups; j++)
5325                 {
5326                         tginfo[j].dobj.objType = DO_TRIGGER;
5327                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5328                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5329                         AssignDumpId(&tginfo[j].dobj);
5330                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5331                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5332                         tginfo[j].tgtable = tbinfo;
5333                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5334                         if (i_tgdef >= 0)
5335                         {
5336                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5337
5338                                 /* remaining fields are not valid if we have tgdef */
5339                                 tginfo[j].tgfname = NULL;
5340                                 tginfo[j].tgtype = 0;
5341                                 tginfo[j].tgnargs = 0;
5342                                 tginfo[j].tgargs = NULL;
5343                                 tginfo[j].tgisconstraint = false;
5344                                 tginfo[j].tgdeferrable = false;
5345                                 tginfo[j].tginitdeferred = false;
5346                                 tginfo[j].tgconstrname = NULL;
5347                                 tginfo[j].tgconstrrelid = InvalidOid;
5348                                 tginfo[j].tgconstrrelname = NULL;
5349                         }
5350                         else
5351                         {
5352                                 tginfo[j].tgdef = NULL;
5353
5354                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5355                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5356                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5357                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5358                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5359                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5360                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5361
5362                                 if (tginfo[j].tgisconstraint)
5363                                 {
5364                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5365                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5366                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5367                                         {
5368                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5369                                                 {
5370                                                         write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5371                                                                           tginfo[j].dobj.name, tbinfo->dobj.name,
5372                                                                           tginfo[j].tgconstrrelid);
5373                                                         exit_nicely();
5374                                                 }
5375                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5376                                         }
5377                                         else
5378                                                 tginfo[j].tgconstrrelname = NULL;
5379                                 }
5380                                 else
5381                                 {
5382                                         tginfo[j].tgconstrname = NULL;
5383                                         tginfo[j].tgconstrrelid = InvalidOid;
5384                                         tginfo[j].tgconstrrelname = NULL;
5385                                 }
5386                         }
5387                 }
5388
5389                 PQclear(res);
5390         }
5391
5392         destroyPQExpBuffer(query);
5393 }
5394
5395 /*
5396  * getProcLangs
5397  *        get basic information about every procedural language in the system
5398  *
5399  * numProcLangs is set to the number of langs read in
5400  *
5401  * NB: this must run after getFuncs() because we assume we can do
5402  * findFuncByOid().
5403  */
5404 ProcLangInfo *
5405 getProcLangs(Archive *fout, int *numProcLangs)
5406 {
5407         PGresult   *res;
5408         int                     ntups;
5409         int                     i;
5410         PQExpBuffer query = createPQExpBuffer();
5411         ProcLangInfo *planginfo;
5412         int                     i_tableoid;
5413         int                     i_oid;
5414         int                     i_lanname;
5415         int                     i_lanpltrusted;
5416         int                     i_lanplcallfoid;
5417         int                     i_laninline;
5418         int                     i_lanvalidator;
5419         int                     i_lanacl;
5420         int                     i_lanowner;
5421
5422         /* Make sure we are in proper schema */
5423         selectSourceSchema(fout, "pg_catalog");
5424
5425         if (fout->remoteVersion >= 90000)
5426         {
5427                 /* pg_language has a laninline column */
5428                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5429                                                   "lanname, lanpltrusted, lanplcallfoid, "
5430                                                   "laninline, lanvalidator,  lanacl, "
5431                                                   "(%s lanowner) AS lanowner "
5432                                                   "FROM pg_language "
5433                                                   "WHERE lanispl "
5434                                                   "ORDER BY oid",
5435                                                   username_subquery);
5436         }
5437         else if (fout->remoteVersion >= 80300)
5438         {
5439                 /* pg_language has a lanowner column */
5440                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5441                                                   "lanname, lanpltrusted, lanplcallfoid, "
5442                                                   "lanvalidator,  lanacl, "
5443                                                   "(%s lanowner) AS lanowner "
5444                                                   "FROM pg_language "
5445                                                   "WHERE lanispl "
5446                                                   "ORDER BY oid",
5447                                                   username_subquery);
5448         }
5449         else if (fout->remoteVersion >= 80100)
5450         {
5451                 /* Languages are owned by the bootstrap superuser, OID 10 */
5452                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5453                                                   "(%s '10') AS lanowner "
5454                                                   "FROM pg_language "
5455                                                   "WHERE lanispl "
5456                                                   "ORDER BY oid",
5457                                                   username_subquery);
5458         }
5459         else if (fout->remoteVersion >= 70400)
5460         {
5461                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5462                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5463                                                   "(%s '1') AS lanowner "
5464                                                   "FROM pg_language "
5465                                                   "WHERE lanispl "
5466                                                   "ORDER BY oid",
5467                                                   username_subquery);
5468         }
5469         else if (fout->remoteVersion >= 70100)
5470         {
5471                 /* No clear notion of an owner at all before 7.4 ... */
5472                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5473                                                   "WHERE lanispl "
5474                                                   "ORDER BY oid");
5475         }
5476         else
5477         {
5478                 appendPQExpBuffer(query, "SELECT "
5479                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5480                                                   "oid, * FROM pg_language "
5481                                                   "WHERE lanispl "
5482                                                   "ORDER BY oid");
5483         }
5484
5485         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5486
5487         ntups = PQntuples(res);
5488
5489         *numProcLangs = ntups;
5490
5491         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5492
5493         i_tableoid = PQfnumber(res, "tableoid");
5494         i_oid = PQfnumber(res, "oid");
5495         i_lanname = PQfnumber(res, "lanname");
5496         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5497         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5498         /* these may fail and return -1: */
5499         i_laninline = PQfnumber(res, "laninline");
5500         i_lanvalidator = PQfnumber(res, "lanvalidator");
5501         i_lanacl = PQfnumber(res, "lanacl");
5502         i_lanowner = PQfnumber(res, "lanowner");
5503
5504         for (i = 0; i < ntups; i++)
5505         {
5506                 planginfo[i].dobj.objType = DO_PROCLANG;
5507                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5508                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5509                 AssignDumpId(&planginfo[i].dobj);
5510
5511                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5512                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5513                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5514                 if (i_laninline >= 0)
5515                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5516                 else
5517                         planginfo[i].laninline = InvalidOid;
5518                 if (i_lanvalidator >= 0)
5519                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5520                 else
5521                         planginfo[i].lanvalidator = InvalidOid;
5522                 if (i_lanacl >= 0)
5523                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5524                 else
5525                         planginfo[i].lanacl = pg_strdup("{=U}");
5526                 if (i_lanowner >= 0)
5527                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5528                 else
5529                         planginfo[i].lanowner = pg_strdup("");
5530
5531                 if (fout->remoteVersion < 70300)
5532                 {
5533                         /*
5534                          * We need to make a dependency to ensure the function will be
5535                          * dumped first.  (In 7.3 and later the regular dependency
5536                          * mechanism will handle this for us.)
5537                          */
5538                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5539
5540                         if (funcInfo)
5541                                 addObjectDependency(&planginfo[i].dobj,
5542                                                                         funcInfo->dobj.dumpId);
5543                 }
5544         }
5545
5546         PQclear(res);
5547
5548         destroyPQExpBuffer(query);
5549
5550         return planginfo;
5551 }
5552
5553 /*
5554  * getCasts
5555  *        get basic information about every cast in the system
5556  *
5557  * numCasts is set to the number of casts read in
5558  */
5559 CastInfo *
5560 getCasts(Archive *fout, int *numCasts)
5561 {
5562         PGresult   *res;
5563         int                     ntups;
5564         int                     i;
5565         PQExpBuffer query = createPQExpBuffer();
5566         CastInfo   *castinfo;
5567         int                     i_tableoid;
5568         int                     i_oid;
5569         int                     i_castsource;
5570         int                     i_casttarget;
5571         int                     i_castfunc;
5572         int                     i_castcontext;
5573         int                     i_castmethod;
5574
5575         /* Make sure we are in proper schema */
5576         selectSourceSchema(fout, "pg_catalog");
5577
5578         if (fout->remoteVersion >= 80400)
5579         {
5580                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5581                                                   "castsource, casttarget, castfunc, castcontext, "
5582                                                   "castmethod "
5583                                                   "FROM pg_cast ORDER BY 3,4");
5584         }
5585         else if (fout->remoteVersion >= 70300)
5586         {
5587                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5588                                                   "castsource, casttarget, castfunc, castcontext, "
5589                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5590                                                   "FROM pg_cast ORDER BY 3,4");
5591         }
5592         else
5593         {
5594                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5595                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5596                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5597                                                   "'f' AS castmethod "
5598                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5599                                                   "WHERE p.pronargs = 1 AND "
5600                                                   "p.proargtypes[0] = t1.oid AND "
5601                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5602                                                   "ORDER BY 3,4");
5603         }
5604
5605         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5606
5607         ntups = PQntuples(res);
5608
5609         *numCasts = ntups;
5610
5611         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5612
5613         i_tableoid = PQfnumber(res, "tableoid");
5614         i_oid = PQfnumber(res, "oid");
5615         i_castsource = PQfnumber(res, "castsource");
5616         i_casttarget = PQfnumber(res, "casttarget");
5617         i_castfunc = PQfnumber(res, "castfunc");
5618         i_castcontext = PQfnumber(res, "castcontext");
5619         i_castmethod = PQfnumber(res, "castmethod");
5620
5621         for (i = 0; i < ntups; i++)
5622         {
5623                 PQExpBufferData namebuf;
5624                 TypeInfo   *sTypeInfo;
5625                 TypeInfo   *tTypeInfo;
5626
5627                 castinfo[i].dobj.objType = DO_CAST;
5628                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5629                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5630                 AssignDumpId(&castinfo[i].dobj);
5631                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5632                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5633                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5634                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5635                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5636
5637                 /*
5638                  * Try to name cast as concatenation of typnames.  This is only used
5639                  * for purposes of sorting.  If we fail to find either type, the name
5640                  * will be an empty string.
5641                  */
5642                 initPQExpBuffer(&namebuf);
5643                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5644                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5645                 if (sTypeInfo && tTypeInfo)
5646                         appendPQExpBuffer(&namebuf, "%s %s",
5647                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5648                 castinfo[i].dobj.name = namebuf.data;
5649
5650                 if (OidIsValid(castinfo[i].castfunc))
5651                 {
5652                         /*
5653                          * We need to make a dependency to ensure the function will be
5654                          * dumped first.  (In 7.3 and later the regular dependency
5655                          * mechanism will handle this for us.)
5656                          */
5657                         FuncInfo   *funcInfo;
5658
5659                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5660                         if (funcInfo)
5661                                 addObjectDependency(&castinfo[i].dobj,
5662                                                                         funcInfo->dobj.dumpId);
5663                 }
5664         }
5665
5666         PQclear(res);
5667
5668         destroyPQExpBuffer(query);
5669
5670         return castinfo;
5671 }
5672
5673 /*
5674  * getTableAttrs -
5675  *        for each interesting table, read info about its attributes
5676  *        (names, types, default values, CHECK constraints, etc)
5677  *
5678  * This is implemented in a very inefficient way right now, looping
5679  * through the tblinfo and doing a join per table to find the attrs and their
5680  * types.  However, because we want type names and so forth to be named
5681  * relative to the schema of each table, we couldn't do it in just one
5682  * query.  (Maybe one query per schema?)
5683  *
5684  *      modifies tblinfo
5685  */
5686 void
5687 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5688 {
5689         int                     i,
5690                                 j;
5691         PQExpBuffer q = createPQExpBuffer();
5692         int                     i_attnum;
5693         int                     i_attname;
5694         int                     i_atttypname;
5695         int                     i_atttypmod;
5696         int                     i_attstattarget;
5697         int                     i_attstorage;
5698         int                     i_typstorage;
5699         int                     i_attnotnull;
5700         int                     i_atthasdef;
5701         int                     i_attisdropped;
5702         int                     i_attlen;
5703         int                     i_attalign;
5704         int                     i_attislocal;
5705         int                     i_attoptions;
5706         int                     i_attcollation;
5707         int                     i_attfdwoptions;
5708         PGresult   *res;
5709         int                     ntups;
5710         bool            hasdefaults;
5711
5712         for (i = 0; i < numTables; i++)
5713         {
5714                 TableInfo  *tbinfo = &tblinfo[i];
5715
5716                 /* Don't bother to collect info for sequences */
5717                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5718                         continue;
5719
5720                 /* Don't bother with uninteresting tables, either */
5721                 if (!tbinfo->interesting)
5722                         continue;
5723
5724                 /*
5725                  * Make sure we are in proper schema for this table; this allows
5726                  * correct retrieval of formatted type names and default exprs
5727                  */
5728                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5729
5730                 /* find all the user attributes and their types */
5731
5732                 /*
5733                  * we must read the attribute names in attribute number order! because
5734                  * we will use the attnum to index into the attnames array later.  We
5735                  * actually ask to order by "attrelid, attnum" because (at least up to
5736                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5737                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5738                  */
5739                 if (g_verbose)
5740                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5741                                           tbinfo->dobj.name);
5742
5743                 resetPQExpBuffer(q);
5744
5745                 if (fout->remoteVersion >= 90200)
5746                 {
5747                         /*
5748                          * attfdwoptions is new in 9.2.
5749                          */
5750                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5751                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5752                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5753                                                           "a.attlen, a.attalign, a.attislocal, "
5754                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5755                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5756                                                           "CASE WHEN a.attcollation <> t.typcollation "
5757                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5758                                                           "pg_catalog.array_to_string(ARRAY("
5759                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5760                                                           "' ' || pg_catalog.quote_literal(option_value) "
5761                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5762                                                           "ORDER BY option_name"
5763                                                           "), E',\n    ') AS attfdwoptions "
5764                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5765                                                           "ON a.atttypid = t.oid "
5766                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5767                                                           "AND a.attnum > 0::pg_catalog.int2 "
5768                                                           "ORDER BY a.attrelid, a.attnum",
5769                                                           tbinfo->dobj.catId.oid);
5770                 }
5771                 else if (fout->remoteVersion >= 90100)
5772                 {
5773                         /*
5774                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5775                          * clauses for attributes whose collation is different from their
5776                          * type's default, we use a CASE here to suppress uninteresting
5777                          * attcollations cheaply.
5778                          */
5779                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5780                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5781                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5782                                                           "a.attlen, a.attalign, a.attislocal, "
5783                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5784                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5785                                                           "CASE WHEN a.attcollation <> t.typcollation "
5786                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5787                                                           "NULL AS attfdwoptions "
5788                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5789                                                           "ON a.atttypid = t.oid "
5790                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5791                                                           "AND a.attnum > 0::pg_catalog.int2 "
5792                                                           "ORDER BY a.attrelid, a.attnum",
5793                                                           tbinfo->dobj.catId.oid);
5794                 }
5795                 else if (fout->remoteVersion >= 90000)
5796                 {
5797                         /* attoptions is new in 9.0 */
5798                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5799                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5800                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5801                                                           "a.attlen, a.attalign, a.attislocal, "
5802                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5803                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5804                                                           "0 AS attcollation, "
5805                                                           "NULL AS attfdwoptions "
5806                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5807                                                           "ON a.atttypid = t.oid "
5808                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5809                                                           "AND a.attnum > 0::pg_catalog.int2 "
5810                                                           "ORDER BY a.attrelid, a.attnum",
5811                                                           tbinfo->dobj.catId.oid);
5812                 }
5813                 else if (fout->remoteVersion >= 70300)
5814                 {
5815                         /* need left join here to not fail on dropped columns ... */
5816                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5817                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5818                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5819                                                           "a.attlen, a.attalign, a.attislocal, "
5820                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5821                                                           "'' AS attoptions, 0 AS attcollation, "
5822                                                           "NULL AS attfdwoptions "
5823                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5824                                                           "ON a.atttypid = t.oid "
5825                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5826                                                           "AND a.attnum > 0::pg_catalog.int2 "
5827                                                           "ORDER BY a.attrelid, a.attnum",
5828                                                           tbinfo->dobj.catId.oid);
5829                 }
5830                 else if (fout->remoteVersion >= 70100)
5831                 {
5832                         /*
5833                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5834                          * we don't dump it because we can't tell whether it's been
5835                          * explicitly set or was just a default.
5836                          *
5837                          * attislocal doesn't exist before 7.3, either; in older databases
5838                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5839                          */
5840                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5841                                                           "-1 AS attstattarget, a.attstorage, "
5842                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5843                                                           "false AS attisdropped, a.attlen, "
5844                                                           "a.attalign, true AS attislocal, "
5845                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5846                                                           "'' AS attoptions, 0 AS attcollation, "
5847                                                           "NULL AS attfdwoptions "
5848                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5849                                                           "ON a.atttypid = t.oid "
5850                                                           "WHERE a.attrelid = '%u'::oid "
5851                                                           "AND a.attnum > 0::int2 "
5852                                                           "ORDER BY a.attrelid, a.attnum",
5853                                                           tbinfo->dobj.catId.oid);
5854                 }
5855                 else
5856                 {
5857                         /* format_type not available before 7.1 */
5858                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5859                                                           "-1 AS attstattarget, "
5860                                                           "attstorage, attstorage AS typstorage, "
5861                                                           "attnotnull, atthasdef, false AS attisdropped, "
5862                                                           "attlen, attalign, "
5863                                                           "true AS attislocal, "
5864                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5865                                                           "'' AS attoptions, 0 AS attcollation, "
5866                                                           "NULL AS attfdwoptions "
5867                                                           "FROM pg_attribute a "
5868                                                           "WHERE attrelid = '%u'::oid "
5869                                                           "AND attnum > 0::int2 "
5870                                                           "ORDER BY attrelid, attnum",
5871                                                           tbinfo->dobj.catId.oid);
5872                 }
5873
5874                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5875
5876                 ntups = PQntuples(res);
5877
5878                 i_attnum = PQfnumber(res, "attnum");
5879                 i_attname = PQfnumber(res, "attname");
5880                 i_atttypname = PQfnumber(res, "atttypname");
5881                 i_atttypmod = PQfnumber(res, "atttypmod");
5882                 i_attstattarget = PQfnumber(res, "attstattarget");
5883                 i_attstorage = PQfnumber(res, "attstorage");
5884                 i_typstorage = PQfnumber(res, "typstorage");
5885                 i_attnotnull = PQfnumber(res, "attnotnull");
5886                 i_atthasdef = PQfnumber(res, "atthasdef");
5887                 i_attisdropped = PQfnumber(res, "attisdropped");
5888                 i_attlen = PQfnumber(res, "attlen");
5889                 i_attalign = PQfnumber(res, "attalign");
5890                 i_attislocal = PQfnumber(res, "attislocal");
5891                 i_attoptions = PQfnumber(res, "attoptions");
5892                 i_attcollation = PQfnumber(res, "attcollation");
5893                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5894
5895                 tbinfo->numatts = ntups;
5896                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5897                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5898                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5899                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5900                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5901                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5902                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5903                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5904                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5905                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5906                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5907                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5908                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5909                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5910                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5911                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5912                 hasdefaults = false;
5913
5914                 for (j = 0; j < ntups; j++)
5915                 {
5916                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5917                         {
5918                                 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5919                                                   tbinfo->dobj.name);
5920                                 exit_nicely();
5921                         }
5922                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5923                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5924                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5925                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5926                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5927                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5928                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5929                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5930                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5931                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5932                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5933                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5934                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5935                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5936                         tbinfo->attrdefs[j] = NULL; /* fix below */
5937                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5938                                 hasdefaults = true;
5939                         /* these flags will be set in flagInhAttrs() */
5940                         tbinfo->inhNotNull[j] = false;
5941                 }
5942
5943                 PQclear(res);
5944
5945                 /*
5946                  * Get info about column defaults
5947                  */
5948                 if (hasdefaults)
5949                 {
5950                         AttrDefInfo *attrdefs;
5951                         int                     numDefaults;
5952
5953                         if (g_verbose)
5954                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5955                                                   tbinfo->dobj.name);
5956
5957                         resetPQExpBuffer(q);
5958                         if (fout->remoteVersion >= 70300)
5959                         {
5960                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5961                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5962                                                                   "FROM pg_catalog.pg_attrdef "
5963                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5964                                                                   tbinfo->dobj.catId.oid);
5965                         }
5966                         else if (fout->remoteVersion >= 70200)
5967                         {
5968                                 /* 7.2 did not have OIDs in pg_attrdef */
5969                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5970                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5971                                                                   "FROM pg_attrdef "
5972                                                                   "WHERE adrelid = '%u'::oid",
5973                                                                   tbinfo->dobj.catId.oid);
5974                         }
5975                         else if (fout->remoteVersion >= 70100)
5976                         {
5977                                 /* no pg_get_expr, so must rely on adsrc */
5978                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5979                                                                   "FROM pg_attrdef "
5980                                                                   "WHERE adrelid = '%u'::oid",
5981                                                                   tbinfo->dobj.catId.oid);
5982                         }
5983                         else
5984                         {
5985                                 /* no pg_get_expr, no tableoid either */
5986                                 appendPQExpBuffer(q, "SELECT "
5987                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5988                                                                   "oid, adnum, adsrc "
5989                                                                   "FROM pg_attrdef "
5990                                                                   "WHERE adrelid = '%u'::oid",
5991                                                                   tbinfo->dobj.catId.oid);
5992                         }
5993                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5994
5995                         numDefaults = PQntuples(res);
5996                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5997
5998                         for (j = 0; j < numDefaults; j++)
5999                         {
6000                                 int                     adnum;
6001
6002                                 adnum = atoi(PQgetvalue(res, j, 2));
6003
6004                                 if (adnum <= 0 || adnum > ntups)
6005                                 {
6006                                         write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
6007                                                           adnum, tbinfo->dobj.name);
6008                                         exit_nicely();
6009                                 }
6010
6011                                 /*
6012                                  * dropped columns shouldn't have defaults, but just in case,
6013                                  * ignore 'em
6014                                  */
6015                                 if (tbinfo->attisdropped[adnum - 1])
6016                                         continue;
6017
6018                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
6019                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6020                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6021                                 AssignDumpId(&attrdefs[j].dobj);
6022                                 attrdefs[j].adtable = tbinfo;
6023                                 attrdefs[j].adnum = adnum;
6024                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6025
6026                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6027                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6028
6029                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6030
6031                                 /*
6032                                  * Defaults on a VIEW must always be dumped as separate ALTER
6033                                  * TABLE commands.      Defaults on regular tables are dumped as
6034                                  * part of the CREATE TABLE if possible, which it won't be
6035                                  * if the column is not going to be emitted explicitly.
6036                                  */
6037                                 if (tbinfo->relkind == RELKIND_VIEW)
6038                                 {
6039                                         attrdefs[j].separate = true;
6040                                         /* needed in case pre-7.3 DB: */
6041                                         addObjectDependency(&attrdefs[j].dobj,
6042                                                                                 tbinfo->dobj.dumpId);
6043                                 }
6044                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6045                                 {
6046                                         /* column will be suppressed, print default separately */
6047                                         attrdefs[j].separate = true;
6048                                         /* needed in case pre-7.3 DB: */
6049                                         addObjectDependency(&attrdefs[j].dobj,
6050                                                                                 tbinfo->dobj.dumpId);
6051                                 }
6052                                 else
6053                                 {
6054                                         attrdefs[j].separate = false;
6055                                         /*
6056                                          * Mark the default as needing to appear before the table,
6057                                          * so that any dependencies it has must be emitted before
6058                                          * the CREATE TABLE.  If this is not possible, we'll
6059                                          * change to "separate" mode while sorting dependencies.
6060                                          */
6061                                         addObjectDependency(&tbinfo->dobj,
6062                                                                                 attrdefs[j].dobj.dumpId);
6063                                 }
6064
6065                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6066                         }
6067                         PQclear(res);
6068                 }
6069
6070                 /*
6071                  * Get info about table CHECK constraints
6072                  */
6073                 if (tbinfo->ncheck > 0)
6074                 {
6075                         ConstraintInfo *constrs;
6076                         int                     numConstrs;
6077
6078                         if (g_verbose)
6079                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6080                                                   tbinfo->dobj.name);
6081
6082                         resetPQExpBuffer(q);
6083                         if (fout->remoteVersion >= 90200)
6084                         {
6085                                 /*
6086                                  * conisonly and convalidated are new in 9.2 (actually, the latter
6087                                  * is there in 9.1, but it wasn't ever false for check constraints
6088                                  * until 9.2).
6089                                  */
6090                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6091                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6092                                                                   "conislocal, convalidated, conisonly "
6093                                                                   "FROM pg_catalog.pg_constraint "
6094                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6095                                                                   "   AND contype = 'c' "
6096                                                                   "ORDER BY conname",
6097                                                                   tbinfo->dobj.catId.oid);
6098                         }
6099                         else if (fout->remoteVersion >= 80400)
6100                         {
6101                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6102                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6103                                                                   "conislocal, true AS convalidated, "
6104                                                                   "false as conisonly "
6105                                                                   "FROM pg_catalog.pg_constraint "
6106                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6107                                                                   "   AND contype = 'c' "
6108                                                                   "ORDER BY conname",
6109                                                                   tbinfo->dobj.catId.oid);
6110                         }
6111                         else if (fout->remoteVersion >= 70400)
6112                         {
6113                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6114                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6115                                                                   "true AS conislocal, true AS convalidated, "
6116                                                                   "false as conisonly "
6117                                                                   "FROM pg_catalog.pg_constraint "
6118                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6119                                                                   "   AND contype = 'c' "
6120                                                                   "ORDER BY conname",
6121                                                                   tbinfo->dobj.catId.oid);
6122                         }
6123                         else if (fout->remoteVersion >= 70300)
6124                         {
6125                                 /* no pg_get_constraintdef, must use consrc */
6126                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6127                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6128                                                                   "true AS conislocal, true AS convalidated, "
6129                                                                   "false as conisonly "
6130                                                                   "FROM pg_catalog.pg_constraint "
6131                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6132                                                                   "   AND contype = 'c' "
6133                                                                   "ORDER BY conname",
6134                                                                   tbinfo->dobj.catId.oid);
6135                         }
6136                         else if (fout->remoteVersion >= 70200)
6137                         {
6138                                 /* 7.2 did not have OIDs in pg_relcheck */
6139                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6140                                                                   "rcname AS conname, "
6141                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6142                                                                   "true AS conislocal, true AS convalidated, "
6143                                                                   "false as conisonly "
6144                                                                   "FROM pg_relcheck "
6145                                                                   "WHERE rcrelid = '%u'::oid "
6146                                                                   "ORDER BY rcname",
6147                                                                   tbinfo->dobj.catId.oid);
6148                         }
6149                         else if (fout->remoteVersion >= 70100)
6150                         {
6151                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6152                                                                   "rcname AS conname, "
6153                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6154                                                                   "true AS conislocal, true AS convalidated, "
6155                                                                   "false as conisonly "
6156                                                                   "FROM pg_relcheck "
6157                                                                   "WHERE rcrelid = '%u'::oid "
6158                                                                   "ORDER BY rcname",
6159                                                                   tbinfo->dobj.catId.oid);
6160                         }
6161                         else
6162                         {
6163                                 /* no tableoid in 7.0 */
6164                                 appendPQExpBuffer(q, "SELECT "
6165                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6166                                                                   "oid, rcname AS conname, "
6167                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6168                                                                   "true AS conislocal, true AS convalidated, "
6169                                                                   "false as conisonly "
6170                                                                   "FROM pg_relcheck "
6171                                                                   "WHERE rcrelid = '%u'::oid "
6172                                                                   "ORDER BY rcname",
6173                                                                   tbinfo->dobj.catId.oid);
6174                         }
6175                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6176
6177                         numConstrs = PQntuples(res);
6178                         if (numConstrs != tbinfo->ncheck)
6179                         {
6180                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6181                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6182                                                                                  tbinfo->ncheck),
6183                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6184                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6185                                 exit_nicely();
6186                         }
6187
6188                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6189                         tbinfo->checkexprs = constrs;
6190
6191                         for (j = 0; j < numConstrs; j++)
6192                         {
6193                                 bool    validated = PQgetvalue(res, j, 5)[0] == 't';
6194                                 bool    isonly = PQgetvalue(res, j, 6)[0] == 't';
6195
6196                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6197                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6198                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6199                                 AssignDumpId(&constrs[j].dobj);
6200                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6201                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6202                                 constrs[j].contable = tbinfo;
6203                                 constrs[j].condomain = NULL;
6204                                 constrs[j].contype = 'c';
6205                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6206                                 constrs[j].confrelid = InvalidOid;
6207                                 constrs[j].conindex = 0;
6208                                 constrs[j].condeferrable = false;
6209                                 constrs[j].condeferred = false;
6210                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6211                                 constrs[j].conisonly = isonly;
6212                                 /*
6213                                  * An unvalidated constraint needs to be dumped separately, so
6214                                  * that potentially-violating existing data is loaded before
6215                                  * the constraint.  An ONLY constraint needs to be dumped
6216                                  * separately too.
6217                                  */
6218                                 constrs[j].separate = !validated || isonly;
6219
6220                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6221
6222                                 /*
6223                                  * Mark the constraint as needing to appear before the table
6224                                  * --- this is so that any other dependencies of the
6225                                  * constraint will be emitted before we try to create the
6226                                  * table.  If the constraint is to be dumped separately, it will be
6227                                  * dumped after data is loaded anyway, so don't do it.  (There's
6228                                  * an automatic dependency in the opposite direction anyway, so
6229                                  * don't need to add one manually here.)
6230                                  */
6231                                 if (!constrs[j].separate)
6232                                         addObjectDependency(&tbinfo->dobj,
6233                                                                                 constrs[j].dobj.dumpId);
6234
6235                                 /*
6236                                  * If the constraint is inherited, this will be detected later
6237                                  * (in pre-8.4 databases).      We also detect later if the
6238                                  * constraint must be split out from the table definition.
6239                                  */
6240                         }
6241                         PQclear(res);
6242                 }
6243         }
6244
6245         destroyPQExpBuffer(q);
6246 }
6247
6248 /*
6249  * Test whether a column should be printed as part of table's CREATE TABLE.
6250  * Column number is zero-based.
6251  *
6252  * Normally this is always true, but it's false for dropped columns, as well
6253  * as those that were inherited without any local definition.  (If we print
6254  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6255  * However, in binary_upgrade mode, we must print all such columns anyway and
6256  * fix the attislocal/attisdropped state later, so as to keep control of the
6257  * physical column order.
6258  *
6259  * This function exists because there are scattered nonobvious places that
6260  * must be kept in sync with this decision.
6261  */
6262 bool
6263 shouldPrintColumn(TableInfo *tbinfo, int colno)
6264 {
6265         if (binary_upgrade)
6266                 return true;
6267         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6268 }
6269
6270
6271 /*
6272  * getTSParsers:
6273  *        read all text search parsers in the system catalogs and return them
6274  *        in the TSParserInfo* structure
6275  *
6276  *      numTSParsers is set to the number of parsers read in
6277  */
6278 TSParserInfo *
6279 getTSParsers(Archive *fout, int *numTSParsers)
6280 {
6281         PGresult   *res;
6282         int                     ntups;
6283         int                     i;
6284         PQExpBuffer query = createPQExpBuffer();
6285         TSParserInfo *prsinfo;
6286         int                     i_tableoid;
6287         int                     i_oid;
6288         int                     i_prsname;
6289         int                     i_prsnamespace;
6290         int                     i_prsstart;
6291         int                     i_prstoken;
6292         int                     i_prsend;
6293         int                     i_prsheadline;
6294         int                     i_prslextype;
6295
6296         /* Before 8.3, there is no built-in text search support */
6297         if (fout->remoteVersion < 80300)
6298         {
6299                 *numTSParsers = 0;
6300                 return NULL;
6301         }
6302
6303         /*
6304          * find all text search objects, including builtin ones; we filter out
6305          * system-defined objects at dump-out time.
6306          */
6307
6308         /* Make sure we are in proper schema */
6309         selectSourceSchema(fout, "pg_catalog");
6310
6311         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6312                                           "prsstart::oid, prstoken::oid, "
6313                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6314                                           "FROM pg_ts_parser");
6315
6316         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6317
6318         ntups = PQntuples(res);
6319         *numTSParsers = ntups;
6320
6321         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6322
6323         i_tableoid = PQfnumber(res, "tableoid");
6324         i_oid = PQfnumber(res, "oid");
6325         i_prsname = PQfnumber(res, "prsname");
6326         i_prsnamespace = PQfnumber(res, "prsnamespace");
6327         i_prsstart = PQfnumber(res, "prsstart");
6328         i_prstoken = PQfnumber(res, "prstoken");
6329         i_prsend = PQfnumber(res, "prsend");
6330         i_prsheadline = PQfnumber(res, "prsheadline");
6331         i_prslextype = PQfnumber(res, "prslextype");
6332
6333         for (i = 0; i < ntups; i++)
6334         {
6335                 prsinfo[i].dobj.objType = DO_TSPARSER;
6336                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6337                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6338                 AssignDumpId(&prsinfo[i].dobj);
6339                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6340                 prsinfo[i].dobj.namespace =
6341                         findNamespace(fout,
6342                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6343                                                   prsinfo[i].dobj.catId.oid);
6344                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6345                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6346                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6347                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6348                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6349
6350                 /* Decide whether we want to dump it */
6351                 selectDumpableObject(&(prsinfo[i].dobj));
6352         }
6353
6354         PQclear(res);
6355
6356         destroyPQExpBuffer(query);
6357
6358         return prsinfo;
6359 }
6360
6361 /*
6362  * getTSDictionaries:
6363  *        read all text search dictionaries in the system catalogs and return them
6364  *        in the TSDictInfo* structure
6365  *
6366  *      numTSDicts is set to the number of dictionaries read in
6367  */
6368 TSDictInfo *
6369 getTSDictionaries(Archive *fout, int *numTSDicts)
6370 {
6371         PGresult   *res;
6372         int                     ntups;
6373         int                     i;
6374         PQExpBuffer query = createPQExpBuffer();
6375         TSDictInfo *dictinfo;
6376         int                     i_tableoid;
6377         int                     i_oid;
6378         int                     i_dictname;
6379         int                     i_dictnamespace;
6380         int                     i_rolname;
6381         int                     i_dicttemplate;
6382         int                     i_dictinitoption;
6383
6384         /* Before 8.3, there is no built-in text search support */
6385         if (fout->remoteVersion < 80300)
6386         {
6387                 *numTSDicts = 0;
6388                 return NULL;
6389         }
6390
6391         /* Make sure we are in proper schema */
6392         selectSourceSchema(fout, "pg_catalog");
6393
6394         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6395                                           "dictnamespace, (%s dictowner) AS rolname, "
6396                                           "dicttemplate, dictinitoption "
6397                                           "FROM pg_ts_dict",
6398                                           username_subquery);
6399
6400         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6401
6402         ntups = PQntuples(res);
6403         *numTSDicts = ntups;
6404
6405         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6406
6407         i_tableoid = PQfnumber(res, "tableoid");
6408         i_oid = PQfnumber(res, "oid");
6409         i_dictname = PQfnumber(res, "dictname");
6410         i_dictnamespace = PQfnumber(res, "dictnamespace");
6411         i_rolname = PQfnumber(res, "rolname");
6412         i_dictinitoption = PQfnumber(res, "dictinitoption");
6413         i_dicttemplate = PQfnumber(res, "dicttemplate");
6414
6415         for (i = 0; i < ntups; i++)
6416         {
6417                 dictinfo[i].dobj.objType = DO_TSDICT;
6418                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6419                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6420                 AssignDumpId(&dictinfo[i].dobj);
6421                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6422                 dictinfo[i].dobj.namespace =
6423                         findNamespace(fout,
6424                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6425                                                   dictinfo[i].dobj.catId.oid);
6426                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6427                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6428                 if (PQgetisnull(res, i, i_dictinitoption))
6429                         dictinfo[i].dictinitoption = NULL;
6430                 else
6431                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6432
6433                 /* Decide whether we want to dump it */
6434                 selectDumpableObject(&(dictinfo[i].dobj));
6435         }
6436
6437         PQclear(res);
6438
6439         destroyPQExpBuffer(query);
6440
6441         return dictinfo;
6442 }
6443
6444 /*
6445  * getTSTemplates:
6446  *        read all text search templates in the system catalogs and return them
6447  *        in the TSTemplateInfo* structure
6448  *
6449  *      numTSTemplates is set to the number of templates read in
6450  */
6451 TSTemplateInfo *
6452 getTSTemplates(Archive *fout, int *numTSTemplates)
6453 {
6454         PGresult   *res;
6455         int                     ntups;
6456         int                     i;
6457         PQExpBuffer query = createPQExpBuffer();
6458         TSTemplateInfo *tmplinfo;
6459         int                     i_tableoid;
6460         int                     i_oid;
6461         int                     i_tmplname;
6462         int                     i_tmplnamespace;
6463         int                     i_tmplinit;
6464         int                     i_tmpllexize;
6465
6466         /* Before 8.3, there is no built-in text search support */
6467         if (fout->remoteVersion < 80300)
6468         {
6469                 *numTSTemplates = 0;
6470                 return NULL;
6471         }
6472
6473         /* Make sure we are in proper schema */
6474         selectSourceSchema(fout, "pg_catalog");
6475
6476         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6477                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6478                                           "FROM pg_ts_template");
6479
6480         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6481
6482         ntups = PQntuples(res);
6483         *numTSTemplates = ntups;
6484
6485         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6486
6487         i_tableoid = PQfnumber(res, "tableoid");
6488         i_oid = PQfnumber(res, "oid");
6489         i_tmplname = PQfnumber(res, "tmplname");
6490         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6491         i_tmplinit = PQfnumber(res, "tmplinit");
6492         i_tmpllexize = PQfnumber(res, "tmpllexize");
6493
6494         for (i = 0; i < ntups; i++)
6495         {
6496                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6497                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6498                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6499                 AssignDumpId(&tmplinfo[i].dobj);
6500                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6501                 tmplinfo[i].dobj.namespace =
6502                         findNamespace(fout,
6503                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6504                                                   tmplinfo[i].dobj.catId.oid);
6505                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6506                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6507
6508                 /* Decide whether we want to dump it */
6509                 selectDumpableObject(&(tmplinfo[i].dobj));
6510         }
6511
6512         PQclear(res);
6513
6514         destroyPQExpBuffer(query);
6515
6516         return tmplinfo;
6517 }
6518
6519 /*
6520  * getTSConfigurations:
6521  *        read all text search configurations in the system catalogs and return
6522  *        them in the TSConfigInfo* structure
6523  *
6524  *      numTSConfigs is set to the number of configurations read in
6525  */
6526 TSConfigInfo *
6527 getTSConfigurations(Archive *fout, int *numTSConfigs)
6528 {
6529         PGresult   *res;
6530         int                     ntups;
6531         int                     i;
6532         PQExpBuffer query = createPQExpBuffer();
6533         TSConfigInfo *cfginfo;
6534         int                     i_tableoid;
6535         int                     i_oid;
6536         int                     i_cfgname;
6537         int                     i_cfgnamespace;
6538         int                     i_rolname;
6539         int                     i_cfgparser;
6540
6541         /* Before 8.3, there is no built-in text search support */
6542         if (fout->remoteVersion < 80300)
6543         {
6544                 *numTSConfigs = 0;
6545                 return NULL;
6546         }
6547
6548         /* Make sure we are in proper schema */
6549         selectSourceSchema(fout, "pg_catalog");
6550
6551         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6552                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6553                                           "FROM pg_ts_config",
6554                                           username_subquery);
6555
6556         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6557
6558         ntups = PQntuples(res);
6559         *numTSConfigs = ntups;
6560
6561         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6562
6563         i_tableoid = PQfnumber(res, "tableoid");
6564         i_oid = PQfnumber(res, "oid");
6565         i_cfgname = PQfnumber(res, "cfgname");
6566         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6567         i_rolname = PQfnumber(res, "rolname");
6568         i_cfgparser = PQfnumber(res, "cfgparser");
6569
6570         for (i = 0; i < ntups; i++)
6571         {
6572                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6573                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6574                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6575                 AssignDumpId(&cfginfo[i].dobj);
6576                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6577                 cfginfo[i].dobj.namespace =
6578                         findNamespace(fout,
6579                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6580                                                   cfginfo[i].dobj.catId.oid);
6581                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6582                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6583
6584                 /* Decide whether we want to dump it */
6585                 selectDumpableObject(&(cfginfo[i].dobj));
6586         }
6587
6588         PQclear(res);
6589
6590         destroyPQExpBuffer(query);
6591
6592         return cfginfo;
6593 }
6594
6595 /*
6596  * getForeignDataWrappers:
6597  *        read all foreign-data wrappers in the system catalogs and return
6598  *        them in the FdwInfo* structure
6599  *
6600  *      numForeignDataWrappers is set to the number of fdws read in
6601  */
6602 FdwInfo *
6603 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6604 {
6605         PGresult   *res;
6606         int                     ntups;
6607         int                     i;
6608         PQExpBuffer query = createPQExpBuffer();
6609         FdwInfo    *fdwinfo;
6610         int                     i_tableoid;
6611         int                     i_oid;
6612         int                     i_fdwname;
6613         int                     i_rolname;
6614         int                     i_fdwhandler;
6615         int                     i_fdwvalidator;
6616         int                     i_fdwacl;
6617         int                     i_fdwoptions;
6618
6619         /* Before 8.4, there are no foreign-data wrappers */
6620         if (fout->remoteVersion < 80400)
6621         {
6622                 *numForeignDataWrappers = 0;
6623                 return NULL;
6624         }
6625
6626         /* Make sure we are in proper schema */
6627         selectSourceSchema(fout, "pg_catalog");
6628
6629         if (fout->remoteVersion >= 90100)
6630         {
6631                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6632                                                   "(%s fdwowner) AS rolname, "
6633                                                   "fdwhandler::pg_catalog.regproc, "
6634                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6635                                                   "array_to_string(ARRAY("
6636                                                   "SELECT quote_ident(option_name) || ' ' || "
6637                                                   "quote_literal(option_value) "
6638                                                   "FROM pg_options_to_table(fdwoptions) "
6639                                                   "ORDER BY option_name"
6640                                                   "), E',\n    ') AS fdwoptions "
6641                                                   "FROM pg_foreign_data_wrapper",
6642                                                   username_subquery);
6643         }
6644         else
6645         {
6646                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6647                                                   "(%s fdwowner) AS rolname, "
6648                                                   "'-' AS fdwhandler, "
6649                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6650                                                   "array_to_string(ARRAY("
6651                                                   "SELECT quote_ident(option_name) || ' ' || "
6652                                                   "quote_literal(option_value) "
6653                                                   "FROM pg_options_to_table(fdwoptions) "
6654                                                   "ORDER BY option_name"
6655                                                   "), E',\n    ') AS fdwoptions "
6656                                                   "FROM pg_foreign_data_wrapper",
6657                                                   username_subquery);
6658         }
6659
6660         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6661
6662         ntups = PQntuples(res);
6663         *numForeignDataWrappers = ntups;
6664
6665         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6666
6667         i_tableoid = PQfnumber(res, "tableoid");
6668         i_oid = PQfnumber(res, "oid");
6669         i_fdwname = PQfnumber(res, "fdwname");
6670         i_rolname = PQfnumber(res, "rolname");
6671         i_fdwhandler = PQfnumber(res, "fdwhandler");
6672         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6673         i_fdwacl = PQfnumber(res, "fdwacl");
6674         i_fdwoptions = PQfnumber(res, "fdwoptions");
6675
6676         for (i = 0; i < ntups; i++)
6677         {
6678                 fdwinfo[i].dobj.objType = DO_FDW;
6679                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6680                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6681                 AssignDumpId(&fdwinfo[i].dobj);
6682                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6683                 fdwinfo[i].dobj.namespace = NULL;
6684                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6685                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6686                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6687                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6688                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6689
6690                 /* Decide whether we want to dump it */
6691                 selectDumpableObject(&(fdwinfo[i].dobj));
6692         }
6693
6694         PQclear(res);
6695
6696         destroyPQExpBuffer(query);
6697
6698         return fdwinfo;
6699 }
6700
6701 /*
6702  * getForeignServers:
6703  *        read all foreign servers in the system catalogs and return
6704  *        them in the ForeignServerInfo * structure
6705  *
6706  *      numForeignServers is set to the number of servers read in
6707  */
6708 ForeignServerInfo *
6709 getForeignServers(Archive *fout, int *numForeignServers)
6710 {
6711         PGresult   *res;
6712         int                     ntups;
6713         int                     i;
6714         PQExpBuffer query = createPQExpBuffer();
6715         ForeignServerInfo *srvinfo;
6716         int                     i_tableoid;
6717         int                     i_oid;
6718         int                     i_srvname;
6719         int                     i_rolname;
6720         int                     i_srvfdw;
6721         int                     i_srvtype;
6722         int                     i_srvversion;
6723         int                     i_srvacl;
6724         int                     i_srvoptions;
6725
6726         /* Before 8.4, there are no foreign servers */
6727         if (fout->remoteVersion < 80400)
6728         {
6729                 *numForeignServers = 0;
6730                 return NULL;
6731         }
6732
6733         /* Make sure we are in proper schema */
6734         selectSourceSchema(fout,"pg_catalog");
6735
6736         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6737                                           "(%s srvowner) AS rolname, "
6738                                           "srvfdw, srvtype, srvversion, srvacl,"
6739                                           "array_to_string(ARRAY("
6740                                           "SELECT quote_ident(option_name) || ' ' || "
6741                                           "quote_literal(option_value) "
6742                                           "FROM pg_options_to_table(srvoptions) "
6743                                           "ORDER BY option_name"
6744                                           "), E',\n    ') AS srvoptions "
6745                                           "FROM pg_foreign_server",
6746                                           username_subquery);
6747
6748         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6749
6750         ntups = PQntuples(res);
6751         *numForeignServers = ntups;
6752
6753         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6754
6755         i_tableoid = PQfnumber(res, "tableoid");
6756         i_oid = PQfnumber(res, "oid");
6757         i_srvname = PQfnumber(res, "srvname");
6758         i_rolname = PQfnumber(res, "rolname");
6759         i_srvfdw = PQfnumber(res, "srvfdw");
6760         i_srvtype = PQfnumber(res, "srvtype");
6761         i_srvversion = PQfnumber(res, "srvversion");
6762         i_srvacl = PQfnumber(res, "srvacl");
6763         i_srvoptions = PQfnumber(res, "srvoptions");
6764
6765         for (i = 0; i < ntups; i++)
6766         {
6767                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6768                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6769                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6770                 AssignDumpId(&srvinfo[i].dobj);
6771                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6772                 srvinfo[i].dobj.namespace = NULL;
6773                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6774                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6775                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6776                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6777                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6778                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6779
6780                 /* Decide whether we want to dump it */
6781                 selectDumpableObject(&(srvinfo[i].dobj));
6782         }
6783
6784         PQclear(res);
6785
6786         destroyPQExpBuffer(query);
6787
6788         return srvinfo;
6789 }
6790
6791 /*
6792  * getDefaultACLs:
6793  *        read all default ACL information in the system catalogs and return
6794  *        them in the DefaultACLInfo structure
6795  *
6796  *      numDefaultACLs is set to the number of ACLs read in
6797  */
6798 DefaultACLInfo *
6799 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6800 {
6801         DefaultACLInfo *daclinfo;
6802         PQExpBuffer query;
6803         PGresult   *res;
6804         int                     i_oid;
6805         int                     i_tableoid;
6806         int                     i_defaclrole;
6807         int                     i_defaclnamespace;
6808         int                     i_defaclobjtype;
6809         int                     i_defaclacl;
6810         int                     i,
6811                                 ntups;
6812
6813         if (fout->remoteVersion < 90000)
6814         {
6815                 *numDefaultACLs = 0;
6816                 return NULL;
6817         }
6818
6819         query = createPQExpBuffer();
6820
6821         /* Make sure we are in proper schema */
6822         selectSourceSchema(fout, "pg_catalog");
6823
6824         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6825                                           "(%s defaclrole) AS defaclrole, "
6826                                           "defaclnamespace, "
6827                                           "defaclobjtype, "
6828                                           "defaclacl "
6829                                           "FROM pg_default_acl",
6830                                           username_subquery);
6831
6832         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6833
6834         ntups = PQntuples(res);
6835         *numDefaultACLs = ntups;
6836
6837         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6838
6839         i_oid = PQfnumber(res, "oid");
6840         i_tableoid = PQfnumber(res, "tableoid");
6841         i_defaclrole = PQfnumber(res, "defaclrole");
6842         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6843         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6844         i_defaclacl = PQfnumber(res, "defaclacl");
6845
6846         for (i = 0; i < ntups; i++)
6847         {
6848                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6849
6850                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6851                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6852                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6853                 AssignDumpId(&daclinfo[i].dobj);
6854                 /* cheesy ... is it worth coming up with a better object name? */
6855                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6856
6857                 if (nspid != InvalidOid)
6858                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6859                                                                                                  daclinfo[i].dobj.catId.oid);
6860                 else
6861                         daclinfo[i].dobj.namespace = NULL;
6862
6863                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6864                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6865                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6866
6867                 /* Decide whether we want to dump it */
6868                 selectDumpableDefaultACL(&(daclinfo[i]));
6869         }
6870
6871         PQclear(res);
6872
6873         destroyPQExpBuffer(query);
6874
6875         return daclinfo;
6876 }
6877
6878 /*
6879  * dumpComment --
6880  *
6881  * This routine is used to dump any comments associated with the
6882  * object handed to this routine. The routine takes a constant character
6883  * string for the target part of the comment-creation command, plus
6884  * the namespace and owner of the object (for labeling the ArchiveEntry),
6885  * plus catalog ID and subid which are the lookup key for pg_description,
6886  * plus the dump ID for the object (for setting a dependency).
6887  * If a matching pg_description entry is found, it is dumped.
6888  *
6889  * Note: although this routine takes a dumpId for dependency purposes,
6890  * that purpose is just to mark the dependency in the emitted dump file
6891  * for possible future use by pg_restore.  We do NOT use it for determining
6892  * ordering of the comment in the dump file, because this routine is called
6893  * after dependency sorting occurs.  This routine should be called just after
6894  * calling ArchiveEntry() for the specified object.
6895  */
6896 static void
6897 dumpComment(Archive *fout, const char *target,
6898                         const char *namespace, const char *owner,
6899                         CatalogId catalogId, int subid, DumpId dumpId)
6900 {
6901         CommentItem *comments;
6902         int                     ncomments;
6903
6904         /* Comments are schema not data ... except blob comments are data */
6905         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6906         {
6907                 if (dataOnly)
6908                         return;
6909         }
6910         else
6911         {
6912                 if (schemaOnly)
6913                         return;
6914         }
6915
6916         /* Search for comments associated with catalogId, using table */
6917         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6918                                                          &comments);
6919
6920         /* Is there one matching the subid? */
6921         while (ncomments > 0)
6922         {
6923                 if (comments->objsubid == subid)
6924                         break;
6925                 comments++;
6926                 ncomments--;
6927         }
6928
6929         /* If a comment exists, build COMMENT ON statement */
6930         if (ncomments > 0)
6931         {
6932                 PQExpBuffer query = createPQExpBuffer();
6933
6934                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6935                 appendStringLiteralAH(query, comments->descr, fout);
6936                 appendPQExpBuffer(query, ";\n");
6937
6938                 /*
6939                  * We mark comments as SECTION_NONE because they really belong in the
6940                  * same section as their parent, whether that is pre-data or
6941                  * post-data.
6942                  */
6943                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6944                                          target, namespace, NULL, owner,
6945                                          false, "COMMENT", SECTION_NONE,
6946                                          query->data, "", NULL,
6947                                          &(dumpId), 1,
6948                                          NULL, NULL);
6949
6950                 destroyPQExpBuffer(query);
6951         }
6952 }
6953
6954 /*
6955  * dumpTableComment --
6956  *
6957  * As above, but dump comments for both the specified table (or view)
6958  * and its columns.
6959  */
6960 static void
6961 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6962                                  const char *reltypename)
6963 {
6964         CommentItem *comments;
6965         int                     ncomments;
6966         PQExpBuffer query;
6967         PQExpBuffer target;
6968
6969         /* Comments are SCHEMA not data */
6970         if (dataOnly)
6971                 return;
6972
6973         /* Search for comments associated with relation, using table */
6974         ncomments = findComments(fout,
6975                                                          tbinfo->dobj.catId.tableoid,
6976                                                          tbinfo->dobj.catId.oid,
6977                                                          &comments);
6978
6979         /* If comments exist, build COMMENT ON statements */
6980         if (ncomments <= 0)
6981                 return;
6982
6983         query = createPQExpBuffer();
6984         target = createPQExpBuffer();
6985
6986         while (ncomments > 0)
6987         {
6988                 const char *descr = comments->descr;
6989                 int                     objsubid = comments->objsubid;
6990
6991                 if (objsubid == 0)
6992                 {
6993                         resetPQExpBuffer(target);
6994                         appendPQExpBuffer(target, "%s %s", reltypename,
6995                                                           fmtId(tbinfo->dobj.name));
6996
6997                         resetPQExpBuffer(query);
6998                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6999                         appendStringLiteralAH(query, descr, fout);
7000                         appendPQExpBuffer(query, ";\n");
7001
7002                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7003                                                  target->data,
7004                                                  tbinfo->dobj.namespace->dobj.name,
7005                                                  NULL, tbinfo->rolname,
7006                                                  false, "COMMENT", SECTION_NONE,
7007                                                  query->data, "", NULL,
7008                                                  &(tbinfo->dobj.dumpId), 1,
7009                                                  NULL, NULL);
7010                 }
7011                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7012                 {
7013                         resetPQExpBuffer(target);
7014                         appendPQExpBuffer(target, "COLUMN %s.",
7015                                                           fmtId(tbinfo->dobj.name));
7016                         appendPQExpBuffer(target, "%s",
7017                                                           fmtId(tbinfo->attnames[objsubid - 1]));
7018
7019                         resetPQExpBuffer(query);
7020                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7021                         appendStringLiteralAH(query, descr, fout);
7022                         appendPQExpBuffer(query, ";\n");
7023
7024                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7025                                                  target->data,
7026                                                  tbinfo->dobj.namespace->dobj.name,
7027                                                  NULL, tbinfo->rolname,
7028                                                  false, "COMMENT", SECTION_NONE,
7029                                                  query->data, "", NULL,
7030                                                  &(tbinfo->dobj.dumpId), 1,
7031                                                  NULL, NULL);
7032                 }
7033
7034                 comments++;
7035                 ncomments--;
7036         }
7037
7038         destroyPQExpBuffer(query);
7039         destroyPQExpBuffer(target);
7040 }
7041
7042 /*
7043  * findComments --
7044  *
7045  * Find the comment(s), if any, associated with the given object.  All the
7046  * objsubid values associated with the given classoid/objoid are found with
7047  * one search.
7048  */
7049 static int
7050 findComments(Archive *fout, Oid classoid, Oid objoid,
7051                          CommentItem **items)
7052 {
7053         /* static storage for table of comments */
7054         static CommentItem *comments = NULL;
7055         static int      ncomments = -1;
7056
7057         CommentItem *middle = NULL;
7058         CommentItem *low;
7059         CommentItem *high;
7060         int                     nmatch;
7061
7062         /* Get comments if we didn't already */
7063         if (ncomments < 0)
7064                 ncomments = collectComments(fout, &comments);
7065
7066         /*
7067          * Pre-7.2, pg_description does not contain classoid, so collectComments
7068          * just stores a zero.  If there's a collision on object OID, well, you
7069          * get duplicate comments.
7070          */
7071         if (fout->remoteVersion < 70200)
7072                 classoid = 0;
7073
7074         /*
7075          * Do binary search to find some item matching the object.
7076          */
7077         low = &comments[0];
7078         high = &comments[ncomments - 1];
7079         while (low <= high)
7080         {
7081                 middle = low + (high - low) / 2;
7082
7083                 if (classoid < middle->classoid)
7084                         high = middle - 1;
7085                 else if (classoid > middle->classoid)
7086                         low = middle + 1;
7087                 else if (objoid < middle->objoid)
7088                         high = middle - 1;
7089                 else if (objoid > middle->objoid)
7090                         low = middle + 1;
7091                 else
7092                         break;                          /* found a match */
7093         }
7094
7095         if (low > high)                         /* no matches */
7096         {
7097                 *items = NULL;
7098                 return 0;
7099         }
7100
7101         /*
7102          * Now determine how many items match the object.  The search loop
7103          * invariant still holds: only items between low and high inclusive could
7104          * match.
7105          */
7106         nmatch = 1;
7107         while (middle > low)
7108         {
7109                 if (classoid != middle[-1].classoid ||
7110                         objoid != middle[-1].objoid)
7111                         break;
7112                 middle--;
7113                 nmatch++;
7114         }
7115
7116         *items = middle;
7117
7118         middle += nmatch;
7119         while (middle <= high)
7120         {
7121                 if (classoid != middle->classoid ||
7122                         objoid != middle->objoid)
7123                         break;
7124                 middle++;
7125                 nmatch++;
7126         }
7127
7128         return nmatch;
7129 }
7130
7131 /*
7132  * collectComments --
7133  *
7134  * Construct a table of all comments available for database objects.
7135  * We used to do per-object queries for the comments, but it's much faster
7136  * to pull them all over at once, and on most databases the memory cost
7137  * isn't high.
7138  *
7139  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7140  */
7141 static int
7142 collectComments(Archive *fout, CommentItem **items)
7143 {
7144         PGresult   *res;
7145         PQExpBuffer query;
7146         int                     i_description;
7147         int                     i_classoid;
7148         int                     i_objoid;
7149         int                     i_objsubid;
7150         int                     ntups;
7151         int                     i;
7152         CommentItem *comments;
7153
7154         /*
7155          * Note we do NOT change source schema here; preserve the caller's
7156          * setting, instead.
7157          */
7158
7159         query = createPQExpBuffer();
7160
7161         if (fout->remoteVersion >= 70300)
7162         {
7163                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7164                                                   "FROM pg_catalog.pg_description "
7165                                                   "ORDER BY classoid, objoid, objsubid");
7166         }
7167         else if (fout->remoteVersion >= 70200)
7168         {
7169                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7170                                                   "FROM pg_description "
7171                                                   "ORDER BY classoid, objoid, objsubid");
7172         }
7173         else
7174         {
7175                 /* Note: this will fail to find attribute comments in pre-7.2... */
7176                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7177                                                   "FROM pg_description "
7178                                                   "ORDER BY objoid");
7179         }
7180
7181         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7182
7183         /* Construct lookup table containing OIDs in numeric form */
7184
7185         i_description = PQfnumber(res, "description");
7186         i_classoid = PQfnumber(res, "classoid");
7187         i_objoid = PQfnumber(res, "objoid");
7188         i_objsubid = PQfnumber(res, "objsubid");
7189
7190         ntups = PQntuples(res);
7191
7192         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7193
7194         for (i = 0; i < ntups; i++)
7195         {
7196                 comments[i].descr = PQgetvalue(res, i, i_description);
7197                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7198                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7199                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7200         }
7201
7202         /* Do NOT free the PGresult since we are keeping pointers into it */
7203         destroyPQExpBuffer(query);
7204
7205         *items = comments;
7206         return ntups;
7207 }
7208
7209 /*
7210  * dumpDumpableObject
7211  *
7212  * This routine and its subsidiaries are responsible for creating
7213  * ArchiveEntries (TOC objects) for each object to be dumped.
7214  */
7215 static void
7216 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7217 {
7218
7219         bool skip = false;
7220
7221         switch (dobj->objType)
7222         {
7223                 case DO_INDEX:
7224                 case DO_TRIGGER:
7225                 case DO_CONSTRAINT:
7226                 case DO_FK_CONSTRAINT:
7227                 case DO_RULE:
7228                         skip = !(dumpSections & DUMP_POST_DATA);
7229                         break;
7230                 case DO_TABLE_DATA:
7231                         skip = !(dumpSections & DUMP_DATA);
7232                         break;
7233                 default:
7234                         skip = !(dumpSections & DUMP_PRE_DATA);
7235         }
7236
7237         if (skip)
7238                 return;
7239
7240         switch (dobj->objType)
7241         {
7242                 case DO_NAMESPACE:
7243                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7244                         break;
7245                 case DO_EXTENSION:
7246                         dumpExtension(fout, (ExtensionInfo *) dobj);
7247                         break;
7248                 case DO_TYPE:
7249                         dumpType(fout, (TypeInfo *) dobj);
7250                         break;
7251                 case DO_SHELL_TYPE:
7252                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7253                         break;
7254                 case DO_FUNC:
7255                         dumpFunc(fout, (FuncInfo *) dobj);
7256                         break;
7257                 case DO_AGG:
7258                         dumpAgg(fout, (AggInfo *) dobj);
7259                         break;
7260                 case DO_OPERATOR:
7261                         dumpOpr(fout, (OprInfo *) dobj);
7262                         break;
7263                 case DO_OPCLASS:
7264                         dumpOpclass(fout, (OpclassInfo *) dobj);
7265                         break;
7266                 case DO_OPFAMILY:
7267                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7268                         break;
7269                 case DO_COLLATION:
7270                         dumpCollation(fout, (CollInfo *) dobj);
7271                         break;
7272                 case DO_CONVERSION:
7273                         dumpConversion(fout, (ConvInfo *) dobj);
7274                         break;
7275                 case DO_TABLE:
7276                         dumpTable(fout, (TableInfo *) dobj);
7277                         break;
7278                 case DO_ATTRDEF:
7279                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7280                         break;
7281                 case DO_INDEX:
7282                         dumpIndex(fout, (IndxInfo *) dobj);
7283                         break;
7284                 case DO_RULE:
7285                         dumpRule(fout, (RuleInfo *) dobj);
7286                         break;
7287                 case DO_TRIGGER:
7288                         dumpTrigger(fout, (TriggerInfo *) dobj);
7289                         break;
7290                 case DO_CONSTRAINT:
7291                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7292                         break;
7293                 case DO_FK_CONSTRAINT:
7294                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7295                         break;
7296                 case DO_PROCLANG:
7297                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7298                         break;
7299                 case DO_CAST:
7300                         dumpCast(fout, (CastInfo *) dobj);
7301                         break;
7302                 case DO_TABLE_DATA:
7303                         dumpTableData(fout, (TableDataInfo *) dobj);
7304                         break;
7305                 case DO_DUMMY_TYPE:
7306                         /* table rowtypes and array types are never dumped separately */
7307                         break;
7308                 case DO_TSPARSER:
7309                         dumpTSParser(fout, (TSParserInfo *) dobj);
7310                         break;
7311                 case DO_TSDICT:
7312                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7313                         break;
7314                 case DO_TSTEMPLATE:
7315                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7316                         break;
7317                 case DO_TSCONFIG:
7318                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7319                         break;
7320                 case DO_FDW:
7321                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7322                         break;
7323                 case DO_FOREIGN_SERVER:
7324                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7325                         break;
7326                 case DO_DEFAULT_ACL:
7327                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7328                         break;
7329                 case DO_BLOB:
7330                         dumpBlob(fout, (BlobInfo *) dobj);
7331                         break;
7332                 case DO_BLOB_DATA:
7333                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7334                                                  dobj->name, NULL, NULL, "",
7335                                                  false, "BLOBS", SECTION_DATA,
7336                                                  "", "", NULL,
7337                                                  dobj->dependencies, dobj->nDeps,
7338                                                  dumpBlobs, NULL);
7339                         break;
7340         }
7341 }
7342
7343 /*
7344  * dumpNamespace
7345  *        writes out to fout the queries to recreate a user-defined namespace
7346  */
7347 static void
7348 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7349 {
7350         PQExpBuffer q;
7351         PQExpBuffer delq;
7352         PQExpBuffer labelq;
7353         char       *qnspname;
7354
7355         /* Skip if not to be dumped */
7356         if (!nspinfo->dobj.dump || dataOnly)
7357                 return;
7358
7359         /* don't dump dummy namespace from pre-7.3 source */
7360         if (strlen(nspinfo->dobj.name) == 0)
7361                 return;
7362
7363         q = createPQExpBuffer();
7364         delq = createPQExpBuffer();
7365         labelq = createPQExpBuffer();
7366
7367         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7368
7369         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7370
7371         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7372
7373         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7374
7375         if (binary_upgrade)
7376                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7377
7378         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7379                                  nspinfo->dobj.name,
7380                                  NULL, NULL,
7381                                  nspinfo->rolname,
7382                                  false, "SCHEMA", SECTION_PRE_DATA,
7383                                  q->data, delq->data, NULL,
7384                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7385                                  NULL, NULL);
7386
7387         /* Dump Schema Comments and Security Labels */
7388         dumpComment(fout, labelq->data,
7389                                 NULL, nspinfo->rolname,
7390                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7391         dumpSecLabel(fout, labelq->data,
7392                                  NULL, nspinfo->rolname,
7393                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7394
7395         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7396                         qnspname, NULL, nspinfo->dobj.name, NULL,
7397                         nspinfo->rolname, nspinfo->nspacl);
7398
7399         free(qnspname);
7400
7401         destroyPQExpBuffer(q);
7402         destroyPQExpBuffer(delq);
7403         destroyPQExpBuffer(labelq);
7404 }
7405
7406 /*
7407  * dumpExtension
7408  *        writes out to fout the queries to recreate an extension
7409  */
7410 static void
7411 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7412 {
7413         PQExpBuffer q;
7414         PQExpBuffer delq;
7415         PQExpBuffer labelq;
7416         char       *qextname;
7417
7418         /* Skip if not to be dumped */
7419         if (!extinfo->dobj.dump || dataOnly)
7420                 return;
7421
7422         q = createPQExpBuffer();
7423         delq = createPQExpBuffer();
7424         labelq = createPQExpBuffer();
7425
7426         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7427
7428         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7429
7430         if (!binary_upgrade)
7431         {
7432                 /*
7433                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7434                  * problem if the extension already exists in the target database;
7435                  * this is essential for installed-by-default extensions such as
7436                  * plpgsql.
7437                  *
7438                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7439                  * built-in extensions based on their OIDs; see
7440                  * selectDumpableExtension.
7441                  */
7442                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7443                                                   qextname, fmtId(extinfo->namespace));
7444         }
7445         else
7446         {
7447                 int                     i;
7448                 int                     n;
7449
7450                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7451                 appendPQExpBuffer(q,
7452                                                   "SELECT binary_upgrade.create_empty_extension(");
7453                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7454                 appendPQExpBuffer(q, ", ");
7455                 appendStringLiteralAH(q, extinfo->namespace, fout);
7456                 appendPQExpBuffer(q, ", ");
7457                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7458                 appendStringLiteralAH(q, extinfo->extversion, fout);
7459                 appendPQExpBuffer(q, ", ");
7460
7461                 /*
7462                  * Note that we're pushing extconfig (an OID array) back into
7463                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7464                  * preserved in binary upgrade.
7465                  */
7466                 if (strlen(extinfo->extconfig) > 2)
7467                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7468                 else
7469                         appendPQExpBuffer(q, "NULL");
7470                 appendPQExpBuffer(q, ", ");
7471                 if (strlen(extinfo->extcondition) > 2)
7472                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7473                 else
7474                         appendPQExpBuffer(q, "NULL");
7475                 appendPQExpBuffer(q, ", ");
7476                 appendPQExpBuffer(q, "ARRAY[");
7477                 n = 0;
7478                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7479                 {
7480                         DumpableObject *extobj;
7481
7482                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7483                         if (extobj && extobj->objType == DO_EXTENSION)
7484                         {
7485                                 if (n++ > 0)
7486                                         appendPQExpBuffer(q, ",");
7487                                 appendStringLiteralAH(q, extobj->name, fout);
7488                         }
7489                 }
7490                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7491                 appendPQExpBuffer(q, ");\n");
7492         }
7493
7494         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7495
7496         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7497                                  extinfo->dobj.name,
7498                                  NULL, NULL,
7499                                  "",
7500                                  false, "EXTENSION", SECTION_PRE_DATA,
7501                                  q->data, delq->data, NULL,
7502                                  extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7503                                  NULL, NULL);
7504
7505         /* Dump Extension Comments and Security Labels */
7506         dumpComment(fout, labelq->data,
7507                                 NULL, "",
7508                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7509         dumpSecLabel(fout, labelq->data,
7510                                  NULL, "",
7511                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7512
7513         free(qextname);
7514
7515         destroyPQExpBuffer(q);
7516         destroyPQExpBuffer(delq);
7517         destroyPQExpBuffer(labelq);
7518 }
7519
7520 /*
7521  * dumpType
7522  *        writes out to fout the queries to recreate a user-defined type
7523  */
7524 static void
7525 dumpType(Archive *fout, TypeInfo *tyinfo)
7526 {
7527         /* Skip if not to be dumped */
7528         if (!tyinfo->dobj.dump || dataOnly)
7529                 return;
7530
7531         /* Dump out in proper style */
7532         if (tyinfo->typtype == TYPTYPE_BASE)
7533                 dumpBaseType(fout, tyinfo);
7534         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7535                 dumpDomain(fout, tyinfo);
7536         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7537                 dumpCompositeType(fout, tyinfo);
7538         else if (tyinfo->typtype == TYPTYPE_ENUM)
7539                 dumpEnumType(fout, tyinfo);
7540         else if (tyinfo->typtype == TYPTYPE_RANGE)
7541                 dumpRangeType(fout, tyinfo);
7542         else
7543                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7544                                   tyinfo->dobj.name);
7545 }
7546
7547 /*
7548  * dumpEnumType
7549  *        writes out to fout the queries to recreate a user-defined enum type
7550  */
7551 static void
7552 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7553 {
7554         PQExpBuffer q = createPQExpBuffer();
7555         PQExpBuffer delq = createPQExpBuffer();
7556         PQExpBuffer labelq = createPQExpBuffer();
7557         PQExpBuffer query = createPQExpBuffer();
7558         PGresult   *res;
7559         int                     num,
7560                                 i;
7561         Oid                     enum_oid;
7562         char       *label;
7563
7564         /* Set proper schema search path */
7565         selectSourceSchema(fout, "pg_catalog");
7566
7567         if (fout->remoteVersion >= 90100)
7568                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7569                                                   "FROM pg_catalog.pg_enum "
7570                                                   "WHERE enumtypid = '%u'"
7571                                                   "ORDER BY enumsortorder",
7572                                                   tyinfo->dobj.catId.oid);
7573         else
7574                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7575                                                   "FROM pg_catalog.pg_enum "
7576                                                   "WHERE enumtypid = '%u'"
7577                                                   "ORDER BY oid",
7578                                                   tyinfo->dobj.catId.oid);
7579
7580         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7581
7582         num = PQntuples(res);
7583
7584         /*
7585          * DROP must be fully qualified in case same name appears in pg_catalog.
7586          * CASCADE shouldn't be required here as for normal types since the I/O
7587          * functions are generic and do not get dropped.
7588          */
7589         appendPQExpBuffer(delq, "DROP TYPE %s.",
7590                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7591         appendPQExpBuffer(delq, "%s;\n",
7592                                           fmtId(tyinfo->dobj.name));
7593
7594         if (binary_upgrade)
7595                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7596                                                                                                  tyinfo->dobj.catId.oid);
7597
7598         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7599                                           fmtId(tyinfo->dobj.name));
7600
7601         if (!binary_upgrade)
7602         {
7603                 /* Labels with server-assigned oids */
7604                 for (i = 0; i < num; i++)
7605                 {
7606                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7607                         if (i > 0)
7608                                 appendPQExpBuffer(q, ",");
7609                         appendPQExpBuffer(q, "\n    ");
7610                         appendStringLiteralAH(q, label, fout);
7611                 }
7612         }
7613
7614         appendPQExpBuffer(q, "\n);\n");
7615
7616         if (binary_upgrade)
7617         {
7618                 /* Labels with dump-assigned (preserved) oids */
7619                 for (i = 0; i < num; i++)
7620                 {
7621                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7622                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7623
7624                         if (i == 0)
7625                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7626                         appendPQExpBuffer(q,
7627                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7628                                                           enum_oid);
7629                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7630                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7631                         appendPQExpBuffer(q, "%s ADD VALUE ",
7632                                                           fmtId(tyinfo->dobj.name));
7633                         appendStringLiteralAH(q, label, fout);
7634                         appendPQExpBuffer(q, ";\n\n");
7635                 }
7636         }
7637
7638         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7639
7640         if (binary_upgrade)
7641                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7642
7643         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7644                                  tyinfo->dobj.name,
7645                                  tyinfo->dobj.namespace->dobj.name,
7646                                  NULL,
7647                                  tyinfo->rolname, false,
7648                                  "TYPE", SECTION_PRE_DATA,
7649                                  q->data, delq->data, NULL,
7650                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7651                                  NULL, NULL);
7652
7653         /* Dump Type Comments and Security Labels */
7654         dumpComment(fout, labelq->data,
7655                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7656                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7657         dumpSecLabel(fout, labelq->data,
7658                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7659                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7660
7661         PQclear(res);
7662         destroyPQExpBuffer(q);
7663         destroyPQExpBuffer(delq);
7664         destroyPQExpBuffer(labelq);
7665         destroyPQExpBuffer(query);
7666 }
7667
7668 /*
7669  * dumpRangeType
7670  *        writes out to fout the queries to recreate a user-defined range type
7671  */
7672 static void
7673 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7674 {
7675         PQExpBuffer q = createPQExpBuffer();
7676         PQExpBuffer delq = createPQExpBuffer();
7677         PQExpBuffer labelq = createPQExpBuffer();
7678         PQExpBuffer query = createPQExpBuffer();
7679         PGresult   *res;
7680         Oid                     collationOid;
7681         char       *procname;
7682
7683         /*
7684          * select appropriate schema to ensure names in CREATE are properly
7685          * qualified
7686          */
7687         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7688
7689         appendPQExpBuffer(query,
7690                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7691                                           "opc.opcname AS opcname, "
7692                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7693                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7694                                           "opc.opcdefault, "
7695                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7696                                           "     ELSE rngcollation END AS collation, "
7697                                           "rngcanonical, rngsubdiff "
7698                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7699                                           "     pg_catalog.pg_opclass opc "
7700                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7701                                           "rngtypid = '%u'",
7702                                           tyinfo->dobj.catId.oid);
7703
7704         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7705         if (PQntuples(res) != 1)
7706         {
7707                 write_msg(NULL, "query returned %d pg_range entries for range type \"%s\"\n",
7708                                   PQntuples(res), tyinfo->dobj.name);
7709                 exit_nicely();
7710         }
7711
7712         /*
7713          * DROP must be fully qualified in case same name appears in pg_catalog.
7714          * CASCADE shouldn't be required here as for normal types since the I/O
7715          * functions are generic and do not get dropped.
7716          */
7717         appendPQExpBuffer(delq, "DROP TYPE %s.",
7718                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7719         appendPQExpBuffer(delq, "%s;\n",
7720                                           fmtId(tyinfo->dobj.name));
7721
7722         if (binary_upgrade)
7723                 binary_upgrade_set_type_oids_by_type_oid(fout,
7724                                                                                                  q, tyinfo->dobj.catId.oid);
7725
7726         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7727                                           fmtId(tyinfo->dobj.name));
7728
7729         appendPQExpBuffer(q, "\n    subtype = %s",
7730                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7731
7732         /* print subtype_opclass only if not default for subtype */
7733         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7734         {
7735                 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7736                 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7737
7738                 /* always schema-qualify, don't try to be smart */
7739                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7740                                                   fmtId(nspname));
7741                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7742         }
7743
7744         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7745         if (OidIsValid(collationOid))
7746         {
7747                 CollInfo   *coll = findCollationByOid(collationOid);
7748
7749                 if (coll)
7750                 {
7751                         /* always schema-qualify, don't try to be smart */
7752                         appendPQExpBuffer(q, ",\n    collation = %s.",
7753                                                           fmtId(coll->dobj.namespace->dobj.name));
7754                         appendPQExpBuffer(q, "%s",
7755                                                           fmtId(coll->dobj.name));
7756                 }
7757         }
7758
7759         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7760         if (strcmp(procname, "-") != 0)
7761                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7762
7763         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7764         if (strcmp(procname, "-") != 0)
7765                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7766
7767         appendPQExpBuffer(q, "\n);\n");
7768
7769         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7770
7771         if (binary_upgrade)
7772                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7773
7774         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7775                                  tyinfo->dobj.name,
7776                                  tyinfo->dobj.namespace->dobj.name,
7777                                  NULL,
7778                                  tyinfo->rolname, false,
7779                                  "TYPE", SECTION_PRE_DATA,
7780                                  q->data, delq->data, NULL,
7781                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7782                                  NULL, NULL);
7783
7784         /* Dump Type Comments and Security Labels */
7785         dumpComment(fout, labelq->data,
7786                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7787                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7788         dumpSecLabel(fout, labelq->data,
7789                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7790                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7791
7792         PQclear(res);
7793         destroyPQExpBuffer(q);
7794         destroyPQExpBuffer(delq);
7795         destroyPQExpBuffer(labelq);
7796         destroyPQExpBuffer(query);
7797 }
7798
7799 /*
7800  * dumpBaseType
7801  *        writes out to fout the queries to recreate a user-defined base type
7802  */
7803 static void
7804 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7805 {
7806         PQExpBuffer q = createPQExpBuffer();
7807         PQExpBuffer delq = createPQExpBuffer();
7808         PQExpBuffer labelq = createPQExpBuffer();
7809         PQExpBuffer query = createPQExpBuffer();
7810         PGresult   *res;
7811         int                     ntups;
7812         char       *typlen;
7813         char       *typinput;
7814         char       *typoutput;
7815         char       *typreceive;
7816         char       *typsend;
7817         char       *typmodin;
7818         char       *typmodout;
7819         char       *typanalyze;
7820         Oid                     typreceiveoid;
7821         Oid                     typsendoid;
7822         Oid                     typmodinoid;
7823         Oid                     typmodoutoid;
7824         Oid                     typanalyzeoid;
7825         char       *typcategory;
7826         char       *typispreferred;
7827         char       *typdelim;
7828         char       *typbyval;
7829         char       *typalign;
7830         char       *typstorage;
7831         char       *typcollatable;
7832         char       *typdefault;
7833         bool            typdefault_is_literal = false;
7834
7835         /* Set proper schema search path so regproc references list correctly */
7836         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7837
7838         /* Fetch type-specific details */
7839         if (fout->remoteVersion >= 90100)
7840         {
7841                 appendPQExpBuffer(query, "SELECT typlen, "
7842                                                   "typinput, typoutput, typreceive, typsend, "
7843                                                   "typmodin, typmodout, typanalyze, "
7844                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7845                                                   "typsend::pg_catalog.oid AS typsendoid, "
7846                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7847                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7848                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7849                                                   "typcategory, typispreferred, "
7850                                                   "typdelim, typbyval, typalign, typstorage, "
7851                                                   "(typcollation <> 0) AS typcollatable, "
7852                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7853                                                   "FROM pg_catalog.pg_type "
7854                                                   "WHERE oid = '%u'::pg_catalog.oid",
7855                                                   tyinfo->dobj.catId.oid);
7856         }
7857         else if (fout->remoteVersion >= 80400)
7858         {
7859                 appendPQExpBuffer(query, "SELECT typlen, "
7860                                                   "typinput, typoutput, typreceive, typsend, "
7861                                                   "typmodin, typmodout, typanalyze, "
7862                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7863                                                   "typsend::pg_catalog.oid AS typsendoid, "
7864                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7865                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7866                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7867                                                   "typcategory, typispreferred, "
7868                                                   "typdelim, typbyval, typalign, typstorage, "
7869                                                   "false AS typcollatable, "
7870                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7871                                                   "FROM pg_catalog.pg_type "
7872                                                   "WHERE oid = '%u'::pg_catalog.oid",
7873                                                   tyinfo->dobj.catId.oid);
7874         }
7875         else if (fout->remoteVersion >= 80300)
7876         {
7877                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7878                 appendPQExpBuffer(query, "SELECT typlen, "
7879                                                   "typinput, typoutput, typreceive, typsend, "
7880                                                   "typmodin, typmodout, typanalyze, "
7881                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7882                                                   "typsend::pg_catalog.oid AS typsendoid, "
7883                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7884                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7885                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7886                                                   "'U' AS typcategory, false AS typispreferred, "
7887                                                   "typdelim, typbyval, typalign, typstorage, "
7888                                                   "false AS typcollatable, "
7889                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7890                                                   "FROM pg_catalog.pg_type "
7891                                                   "WHERE oid = '%u'::pg_catalog.oid",
7892                                                   tyinfo->dobj.catId.oid);
7893         }
7894         else if (fout->remoteVersion >= 80000)
7895         {
7896                 appendPQExpBuffer(query, "SELECT typlen, "
7897                                                   "typinput, typoutput, typreceive, typsend, "
7898                                                   "'-' AS typmodin, '-' AS typmodout, "
7899                                                   "typanalyze, "
7900                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7901                                                   "typsend::pg_catalog.oid AS typsendoid, "
7902                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7903                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7904                                                   "'U' AS typcategory, false AS typispreferred, "
7905                                                   "typdelim, typbyval, typalign, typstorage, "
7906                                                   "false AS typcollatable, "
7907                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7908                                                   "FROM pg_catalog.pg_type "
7909                                                   "WHERE oid = '%u'::pg_catalog.oid",
7910                                                   tyinfo->dobj.catId.oid);
7911         }
7912         else if (fout->remoteVersion >= 70400)
7913         {
7914                 appendPQExpBuffer(query, "SELECT typlen, "
7915                                                   "typinput, typoutput, typreceive, typsend, "
7916                                                   "'-' AS typmodin, '-' AS typmodout, "
7917                                                   "'-' AS typanalyze, "
7918                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7919                                                   "typsend::pg_catalog.oid AS typsendoid, "
7920                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7921                                                   "0 AS typanalyzeoid, "
7922                                                   "'U' AS typcategory, false AS typispreferred, "
7923                                                   "typdelim, typbyval, typalign, typstorage, "
7924                                                   "false AS typcollatable, "
7925                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7926                                                   "FROM pg_catalog.pg_type "
7927                                                   "WHERE oid = '%u'::pg_catalog.oid",
7928                                                   tyinfo->dobj.catId.oid);
7929         }
7930         else if (fout->remoteVersion >= 70300)
7931         {
7932                 appendPQExpBuffer(query, "SELECT typlen, "
7933                                                   "typinput, typoutput, "
7934                                                   "'-' AS typreceive, '-' AS typsend, "
7935                                                   "'-' AS typmodin, '-' AS typmodout, "
7936                                                   "'-' AS typanalyze, "
7937                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7938                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7939                                                   "0 AS typanalyzeoid, "
7940                                                   "'U' AS typcategory, false AS typispreferred, "
7941                                                   "typdelim, typbyval, typalign, typstorage, "
7942                                                   "false AS typcollatable, "
7943                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7944                                                   "FROM pg_catalog.pg_type "
7945                                                   "WHERE oid = '%u'::pg_catalog.oid",
7946                                                   tyinfo->dobj.catId.oid);
7947         }
7948         else if (fout->remoteVersion >= 70200)
7949         {
7950                 /*
7951                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7952                  * ignore them because they are not right.
7953                  */
7954                 appendPQExpBuffer(query, "SELECT typlen, "
7955                                                   "typinput, typoutput, "
7956                                                   "'-' AS typreceive, '-' AS typsend, "
7957                                                   "'-' AS typmodin, '-' AS typmodout, "
7958                                                   "'-' AS typanalyze, "
7959                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7960                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7961                                                   "0 AS typanalyzeoid, "
7962                                                   "'U' AS typcategory, false AS typispreferred, "
7963                                                   "typdelim, typbyval, typalign, typstorage, "
7964                                                   "false AS typcollatable, "
7965                                                   "NULL AS typdefaultbin, typdefault "
7966                                                   "FROM pg_type "
7967                                                   "WHERE oid = '%u'::oid",
7968                                                   tyinfo->dobj.catId.oid);
7969         }
7970         else if (fout->remoteVersion >= 70100)
7971         {
7972                 /*
7973                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7974                  * representation.
7975                  */
7976                 appendPQExpBuffer(query, "SELECT typlen, "
7977                                                   "typinput, typoutput, "
7978                                                   "'-' AS typreceive, '-' AS typsend, "
7979                                                   "'-' AS typmodin, '-' AS typmodout, "
7980                                                   "'-' AS typanalyze, "
7981                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7982                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7983                                                   "0 AS typanalyzeoid, "
7984                                                   "'U' AS typcategory, false AS typispreferred, "
7985                                                   "typdelim, typbyval, typalign, typstorage, "
7986                                                   "false AS typcollatable, "
7987                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7988                                                   "FROM pg_type "
7989                                                   "WHERE oid = '%u'::oid",
7990                                                   tyinfo->dobj.catId.oid);
7991         }
7992         else
7993         {
7994                 appendPQExpBuffer(query, "SELECT typlen, "
7995                                                   "typinput, typoutput, "
7996                                                   "'-' AS typreceive, '-' AS typsend, "
7997                                                   "'-' AS typmodin, '-' AS typmodout, "
7998                                                   "'-' AS typanalyze, "
7999                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8000                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8001                                                   "0 AS typanalyzeoid, "
8002                                                   "'U' AS typcategory, false AS typispreferred, "
8003                                                   "typdelim, typbyval, typalign, "
8004                                                   "'p'::char AS typstorage, "
8005                                                   "false AS typcollatable, "
8006                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8007                                                   "FROM pg_type "
8008                                                   "WHERE oid = '%u'::oid",
8009                                                   tyinfo->dobj.catId.oid);
8010         }
8011
8012         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8013
8014         /* Expecting a single result only */
8015         ntups = PQntuples(res);
8016         if (ntups != 1)
8017         {
8018                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8019                                                            "query returned %d rows instead of one: %s\n",
8020                                                                  ntups),
8021                                   ntups, query->data);
8022                 exit_nicely();
8023         }
8024
8025         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8026         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8027         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8028         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8029         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8030         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8031         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8032         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8033         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8034         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8035         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8036         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8037         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8038         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8039         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8040         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8041         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8042         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8043         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8044         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8045         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8046                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8047         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8048         {
8049                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8050                 typdefault_is_literal = true;   /* it needs quotes */
8051         }
8052         else
8053                 typdefault = NULL;
8054
8055         /*
8056          * DROP must be fully qualified in case same name appears in pg_catalog.
8057          * The reason we include CASCADE is that the circular dependency between
8058          * the type and its I/O functions makes it impossible to drop the type any
8059          * other way.
8060          */
8061         appendPQExpBuffer(delq, "DROP TYPE %s.",
8062                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8063         appendPQExpBuffer(delq, "%s CASCADE;\n",
8064                                           fmtId(tyinfo->dobj.name));
8065
8066         /* We might already have a shell type, but setting pg_type_oid is harmless */
8067         if (binary_upgrade)
8068                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8069                                                                                                  tyinfo->dobj.catId.oid);
8070
8071         appendPQExpBuffer(q,
8072                                           "CREATE TYPE %s (\n"
8073                                           "    INTERNALLENGTH = %s",
8074                                           fmtId(tyinfo->dobj.name),
8075                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8076
8077         if (fout->remoteVersion >= 70300)
8078         {
8079                 /* regproc result is correctly quoted as of 7.3 */
8080                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
8081                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
8082                 if (OidIsValid(typreceiveoid))
8083                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
8084                 if (OidIsValid(typsendoid))
8085                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
8086                 if (OidIsValid(typmodinoid))
8087                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
8088                 if (OidIsValid(typmodoutoid))
8089                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
8090                 if (OidIsValid(typanalyzeoid))
8091                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
8092         }
8093         else
8094         {
8095                 /* regproc delivers an unquoted name before 7.3 */
8096                 /* cannot combine these because fmtId uses static result area */
8097                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
8098                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
8099                 /* receive/send/typmodin/typmodout/analyze need not be printed */
8100         }
8101
8102         if (strcmp(typcollatable, "t") == 0)
8103                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
8104
8105         if (typdefault != NULL)
8106         {
8107                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
8108                 if (typdefault_is_literal)
8109                         appendStringLiteralAH(q, typdefault, fout);
8110                 else
8111                         appendPQExpBufferStr(q, typdefault);
8112         }
8113
8114         if (OidIsValid(tyinfo->typelem))
8115         {
8116                 char       *elemType;
8117
8118                 /* reselect schema in case changed by function dump */
8119                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8120                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8121                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8122                 free(elemType);
8123         }
8124
8125         if (strcmp(typcategory, "U") != 0)
8126         {
8127                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8128                 appendStringLiteralAH(q, typcategory, fout);
8129         }
8130
8131         if (strcmp(typispreferred, "t") == 0)
8132                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8133
8134         if (typdelim && strcmp(typdelim, ",") != 0)
8135         {
8136                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8137                 appendStringLiteralAH(q, typdelim, fout);
8138         }
8139
8140         if (strcmp(typalign, "c") == 0)
8141                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8142         else if (strcmp(typalign, "s") == 0)
8143                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8144         else if (strcmp(typalign, "i") == 0)
8145                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8146         else if (strcmp(typalign, "d") == 0)
8147                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8148
8149         if (strcmp(typstorage, "p") == 0)
8150                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8151         else if (strcmp(typstorage, "e") == 0)
8152                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8153         else if (strcmp(typstorage, "x") == 0)
8154                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8155         else if (strcmp(typstorage, "m") == 0)
8156                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8157
8158         if (strcmp(typbyval, "t") == 0)
8159                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8160
8161         appendPQExpBuffer(q, "\n);\n");
8162
8163         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8164
8165         if (binary_upgrade)
8166                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8167
8168         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8169                                  tyinfo->dobj.name,
8170                                  tyinfo->dobj.namespace->dobj.name,
8171                                  NULL,
8172                                  tyinfo->rolname, false,
8173                                  "TYPE", SECTION_PRE_DATA,
8174                                  q->data, delq->data, NULL,
8175                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8176                                  NULL, NULL);
8177
8178         /* Dump Type Comments and Security Labels */
8179         dumpComment(fout, labelq->data,
8180                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8181                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8182         dumpSecLabel(fout, labelq->data,
8183                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8184                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8185
8186         PQclear(res);
8187         destroyPQExpBuffer(q);
8188         destroyPQExpBuffer(delq);
8189         destroyPQExpBuffer(labelq);
8190         destroyPQExpBuffer(query);
8191 }
8192
8193 /*
8194  * dumpDomain
8195  *        writes out to fout the queries to recreate a user-defined domain
8196  */
8197 static void
8198 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8199 {
8200         PQExpBuffer q = createPQExpBuffer();
8201         PQExpBuffer delq = createPQExpBuffer();
8202         PQExpBuffer labelq = createPQExpBuffer();
8203         PQExpBuffer query = createPQExpBuffer();
8204         PGresult   *res;
8205         int                     ntups;
8206         int                     i;
8207         char       *typnotnull;
8208         char       *typdefn;
8209         char       *typdefault;
8210         Oid                     typcollation;
8211         bool            typdefault_is_literal = false;
8212
8213         /* Set proper schema search path so type references list correctly */
8214         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8215
8216         /* Fetch domain specific details */
8217         if (fout->remoteVersion >= 90100)
8218         {
8219                 /* typcollation is new in 9.1 */
8220                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8221                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8222                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8223                                                   "t.typdefault, "
8224                                                   "CASE WHEN t.typcollation <> u.typcollation "
8225                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8226                                                   "FROM pg_catalog.pg_type t "
8227                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8228                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8229                                                   tyinfo->dobj.catId.oid);
8230         }
8231         else
8232         {
8233                 /* We assume here that remoteVersion must be at least 70300 */
8234                 appendPQExpBuffer(query, "SELECT typnotnull, "
8235                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8236                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8237                                                   "typdefault, 0 AS typcollation "
8238                                                   "FROM pg_catalog.pg_type "
8239                                                   "WHERE oid = '%u'::pg_catalog.oid",
8240                                                   tyinfo->dobj.catId.oid);
8241         }
8242
8243         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8244
8245         /* Expecting a single result only */
8246         ntups = PQntuples(res);
8247         if (ntups != 1)
8248         {
8249                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8250                                                            "query returned %d rows instead of one: %s\n",
8251                                                                  ntups),
8252                                   ntups, query->data);
8253                 exit_nicely();
8254         }
8255
8256         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8257         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8258         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8259                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8260         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8261         {
8262                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8263                 typdefault_is_literal = true;   /* it needs quotes */
8264         }
8265         else
8266                 typdefault = NULL;
8267         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8268
8269         if (binary_upgrade)
8270                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8271                                                                                                  tyinfo->dobj.catId.oid);
8272
8273         appendPQExpBuffer(q,
8274                                           "CREATE DOMAIN %s AS %s",
8275                                           fmtId(tyinfo->dobj.name),
8276                                           typdefn);
8277
8278         /* Print collation only if different from base type's collation */
8279         if (OidIsValid(typcollation))
8280         {
8281                 CollInfo   *coll;
8282
8283                 coll = findCollationByOid(typcollation);
8284                 if (coll)
8285                 {
8286                         /* always schema-qualify, don't try to be smart */
8287                         appendPQExpBuffer(q, " COLLATE %s.",
8288                                                           fmtId(coll->dobj.namespace->dobj.name));
8289                         appendPQExpBuffer(q, "%s",
8290                                                           fmtId(coll->dobj.name));
8291                 }
8292         }
8293
8294         if (typnotnull[0] == 't')
8295                 appendPQExpBuffer(q, " NOT NULL");
8296
8297         if (typdefault != NULL)
8298         {
8299                 appendPQExpBuffer(q, " DEFAULT ");
8300                 if (typdefault_is_literal)
8301                         appendStringLiteralAH(q, typdefault, fout);
8302                 else
8303                         appendPQExpBufferStr(q, typdefault);
8304         }
8305
8306         PQclear(res);
8307
8308         /*
8309          * Add any CHECK constraints for the domain
8310          */
8311         for (i = 0; i < tyinfo->nDomChecks; i++)
8312         {
8313                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8314
8315                 if (!domcheck->separate)
8316                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8317                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8318         }
8319
8320         appendPQExpBuffer(q, ";\n");
8321
8322         /*
8323          * DROP must be fully qualified in case same name appears in pg_catalog
8324          */
8325         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8326                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8327         appendPQExpBuffer(delq, "%s;\n",
8328                                           fmtId(tyinfo->dobj.name));
8329
8330         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8331
8332         if (binary_upgrade)
8333                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8334
8335         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8336                                  tyinfo->dobj.name,
8337                                  tyinfo->dobj.namespace->dobj.name,
8338                                  NULL,
8339                                  tyinfo->rolname, false,
8340                                  "DOMAIN", SECTION_PRE_DATA,
8341                                  q->data, delq->data, NULL,
8342                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8343                                  NULL, NULL);
8344
8345         /* Dump Domain Comments and Security Labels */
8346         dumpComment(fout, labelq->data,
8347                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8348                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8349         dumpSecLabel(fout, labelq->data,
8350                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8351                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8352
8353         destroyPQExpBuffer(q);
8354         destroyPQExpBuffer(delq);
8355         destroyPQExpBuffer(labelq);
8356         destroyPQExpBuffer(query);
8357 }
8358
8359 /*
8360  * dumpCompositeType
8361  *        writes out to fout the queries to recreate a user-defined stand-alone
8362  *        composite type
8363  */
8364 static void
8365 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8366 {
8367         PQExpBuffer q = createPQExpBuffer();
8368         PQExpBuffer dropped = createPQExpBuffer();
8369         PQExpBuffer delq = createPQExpBuffer();
8370         PQExpBuffer labelq = createPQExpBuffer();
8371         PQExpBuffer query = createPQExpBuffer();
8372         PGresult   *res;
8373         int                     ntups;
8374         int                     i_attname;
8375         int                     i_atttypdefn;
8376         int                     i_attlen;
8377         int                     i_attalign;
8378         int                     i_attisdropped;
8379         int                     i_attcollation;
8380         int                     i_typrelid;
8381         int                     i;
8382         int                     actual_atts;
8383
8384         /* Set proper schema search path so type references list correctly */
8385         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8386
8387         /* Fetch type specific details */
8388         if (fout->remoteVersion >= 90100)
8389         {
8390                 /*
8391                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8392                  * clauses for attributes whose collation is different from their
8393                  * type's default, we use a CASE here to suppress uninteresting
8394                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8395                  * collation does not matter for those.
8396                  */
8397                 appendPQExpBuffer(query, "SELECT a.attname, "
8398                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8399                                                   "a.attlen, a.attalign, a.attisdropped, "
8400                                                   "CASE WHEN a.attcollation <> at.typcollation "
8401                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8402                                                   "ct.typrelid "
8403                                                   "FROM pg_catalog.pg_type ct "
8404                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8405                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8406                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8407                                                   "ORDER BY a.attnum ",
8408                                                   tyinfo->dobj.catId.oid);
8409         }
8410         else
8411         {
8412                 /*
8413                  * We assume here that remoteVersion must be at least 70300.  Since
8414                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8415                  * always be false.
8416                  */
8417                 appendPQExpBuffer(query, "SELECT a.attname, "
8418                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8419                                                   "a.attlen, a.attalign, a.attisdropped, "
8420                                                   "0 AS attcollation, "
8421                                                   "ct.typrelid "
8422                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8423                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8424                                                   "AND a.attrelid = ct.typrelid "
8425                                                   "ORDER BY a.attnum ",
8426                                                   tyinfo->dobj.catId.oid);
8427         }
8428
8429         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8430
8431         ntups = PQntuples(res);
8432
8433         i_attname = PQfnumber(res, "attname");
8434         i_atttypdefn = PQfnumber(res, "atttypdefn");
8435         i_attlen = PQfnumber(res, "attlen");
8436         i_attalign = PQfnumber(res, "attalign");
8437         i_attisdropped = PQfnumber(res, "attisdropped");
8438         i_attcollation = PQfnumber(res, "attcollation");
8439         i_typrelid = PQfnumber(res, "typrelid");
8440
8441         if (binary_upgrade)
8442         {
8443                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8444
8445                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8446                                                                                                  tyinfo->dobj.catId.oid);
8447                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8448         }
8449
8450         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8451                                           fmtId(tyinfo->dobj.name));
8452
8453         actual_atts = 0;
8454         for (i = 0; i < ntups; i++)
8455         {
8456                 char       *attname;
8457                 char       *atttypdefn;
8458                 char       *attlen;
8459                 char       *attalign;
8460                 bool            attisdropped;
8461                 Oid                     attcollation;
8462
8463                 attname = PQgetvalue(res, i, i_attname);
8464                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8465                 attlen = PQgetvalue(res, i, i_attlen);
8466                 attalign = PQgetvalue(res, i, i_attalign);
8467                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8468                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8469
8470                 if (attisdropped && !binary_upgrade)
8471                         continue;
8472
8473                 /* Format properly if not first attr */
8474                 if (actual_atts++ > 0)
8475                         appendPQExpBuffer(q, ",");
8476                 appendPQExpBuffer(q, "\n\t");
8477
8478                 if (!attisdropped)
8479                 {
8480                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8481
8482                         /* Add collation if not default for the column type */
8483                         if (OidIsValid(attcollation))
8484                         {
8485                                 CollInfo   *coll;
8486
8487                                 coll = findCollationByOid(attcollation);
8488                                 if (coll)
8489                                 {
8490                                         /* always schema-qualify, don't try to be smart */
8491                                         appendPQExpBuffer(q, " COLLATE %s.",
8492                                                                           fmtId(coll->dobj.namespace->dobj.name));
8493                                         appendPQExpBuffer(q, "%s",
8494                                                                           fmtId(coll->dobj.name));
8495                                 }
8496                         }
8497                 }
8498                 else
8499                 {
8500                         /*
8501                          * This is a dropped attribute and we're in binary_upgrade mode.
8502                          * Insert a placeholder for it in the CREATE TYPE command, and set
8503                          * length and alignment with direct UPDATE to the catalogs
8504                          * afterwards. See similar code in dumpTableSchema().
8505                          */
8506                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8507
8508                         /* stash separately for insertion after the CREATE TYPE */
8509                         appendPQExpBuffer(dropped,
8510                                           "\n-- For binary upgrade, recreate dropped column.\n");
8511                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8512                                                           "SET attlen = %s, "
8513                                                           "attalign = '%s', attbyval = false\n"
8514                                                           "WHERE attname = ", attlen, attalign);
8515                         appendStringLiteralAH(dropped, attname, fout);
8516                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8517                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8518                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8519
8520                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8521                                                           fmtId(tyinfo->dobj.name));
8522                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8523                                                           fmtId(attname));
8524                 }
8525         }
8526         appendPQExpBuffer(q, "\n);\n");
8527         appendPQExpBufferStr(q, dropped->data);
8528
8529         /*
8530          * DROP must be fully qualified in case same name appears in pg_catalog
8531          */
8532         appendPQExpBuffer(delq, "DROP TYPE %s.",
8533                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8534         appendPQExpBuffer(delq, "%s;\n",
8535                                           fmtId(tyinfo->dobj.name));
8536
8537         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8538
8539         if (binary_upgrade)
8540                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8541
8542         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8543                                  tyinfo->dobj.name,
8544                                  tyinfo->dobj.namespace->dobj.name,
8545                                  NULL,
8546                                  tyinfo->rolname, false,
8547                                  "TYPE", SECTION_PRE_DATA,
8548                                  q->data, delq->data, NULL,
8549                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8550                                  NULL, NULL);
8551
8552
8553         /* Dump Type Comments and Security Labels */
8554         dumpComment(fout, labelq->data,
8555                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8556                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8557         dumpSecLabel(fout, labelq->data,
8558                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8559                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8560
8561         PQclear(res);
8562         destroyPQExpBuffer(q);
8563         destroyPQExpBuffer(dropped);
8564         destroyPQExpBuffer(delq);
8565         destroyPQExpBuffer(labelq);
8566         destroyPQExpBuffer(query);
8567
8568         /* Dump any per-column comments */
8569         dumpCompositeTypeColComments(fout, tyinfo);
8570 }
8571
8572 /*
8573  * dumpCompositeTypeColComments
8574  *        writes out to fout the queries to recreate comments on the columns of
8575  *        a user-defined stand-alone composite type
8576  */
8577 static void
8578 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8579 {
8580         CommentItem *comments;
8581         int                     ncomments;
8582         PGresult   *res;
8583         PQExpBuffer query;
8584         PQExpBuffer target;
8585         Oid                     pgClassOid;
8586         int                     i;
8587         int                     ntups;
8588         int                     i_attname;
8589         int                     i_attnum;
8590
8591         query = createPQExpBuffer();
8592
8593         /* We assume here that remoteVersion must be at least 70300 */
8594         appendPQExpBuffer(query,
8595                                           "SELECT c.tableoid, a.attname, a.attnum "
8596                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8597                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8598                                           "  AND NOT a.attisdropped "
8599                                           "ORDER BY a.attnum ",
8600                                           tyinfo->typrelid);
8601
8602         /* Fetch column attnames */
8603         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8604
8605         ntups = PQntuples(res);
8606         if (ntups < 1)
8607         {
8608                 PQclear(res);
8609                 destroyPQExpBuffer(query);
8610                 return;
8611         }
8612
8613         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8614
8615         /* Search for comments associated with type's pg_class OID */
8616         ncomments = findComments(fout,
8617                                                          pgClassOid,
8618                                                          tyinfo->typrelid,
8619                                                          &comments);
8620
8621         /* If no comments exist, we're done */
8622         if (ncomments <= 0)
8623         {
8624                 PQclear(res);
8625                 destroyPQExpBuffer(query);
8626                 return;
8627         }
8628
8629         /* Build COMMENT ON statements */
8630         target = createPQExpBuffer();
8631
8632         i_attnum = PQfnumber(res, "attnum");
8633         i_attname = PQfnumber(res, "attname");
8634         while (ncomments > 0)
8635         {
8636                 const char *attname;
8637
8638                 attname = NULL;
8639                 for (i = 0; i < ntups; i++)
8640                 {
8641                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8642                         {
8643                                 attname = PQgetvalue(res, i, i_attname);
8644                                 break;
8645                         }
8646                 }
8647                 if (attname)                    /* just in case we don't find it */
8648                 {
8649                         const char *descr = comments->descr;
8650
8651                         resetPQExpBuffer(target);
8652                         appendPQExpBuffer(target, "COLUMN %s.",
8653                                                           fmtId(tyinfo->dobj.name));
8654                         appendPQExpBuffer(target, "%s",
8655                                                           fmtId(attname));
8656
8657                         resetPQExpBuffer(query);
8658                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8659                         appendStringLiteralAH(query, descr, fout);
8660                         appendPQExpBuffer(query, ";\n");
8661
8662                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8663                                                  target->data,
8664                                                  tyinfo->dobj.namespace->dobj.name,
8665                                                  NULL, tyinfo->rolname,
8666                                                  false, "COMMENT", SECTION_NONE,
8667                                                  query->data, "", NULL,
8668                                                  &(tyinfo->dobj.dumpId), 1,
8669                                                  NULL, NULL);
8670                 }
8671
8672                 comments++;
8673                 ncomments--;
8674         }
8675
8676         PQclear(res);
8677         destroyPQExpBuffer(query);
8678         destroyPQExpBuffer(target);
8679 }
8680
8681 /*
8682  * dumpShellType
8683  *        writes out to fout the queries to create a shell type
8684  *
8685  * We dump a shell definition in advance of the I/O functions for the type.
8686  */
8687 static void
8688 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8689 {
8690         PQExpBuffer q;
8691
8692         /* Skip if not to be dumped */
8693         if (!stinfo->dobj.dump || dataOnly)
8694                 return;
8695
8696         q = createPQExpBuffer();
8697
8698         /*
8699          * Note the lack of a DROP command for the shell type; any required DROP
8700          * is driven off the base type entry, instead.  This interacts with
8701          * _printTocEntry()'s use of the presence of a DROP command to decide
8702          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8703          * the shell type's owner immediately on creation; that should happen only
8704          * after it's filled in, otherwise the backend complains.
8705          */
8706
8707         if (binary_upgrade)
8708                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8709                                                                                    stinfo->baseType->dobj.catId.oid);
8710
8711         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8712                                           fmtId(stinfo->dobj.name));
8713
8714         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8715                                  stinfo->dobj.name,
8716                                  stinfo->dobj.namespace->dobj.name,
8717                                  NULL,
8718                                  stinfo->baseType->rolname, false,
8719                                  "SHELL TYPE", SECTION_PRE_DATA,
8720                                  q->data, "", NULL,
8721                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8722                                  NULL, NULL);
8723
8724         destroyPQExpBuffer(q);
8725 }
8726
8727 /*
8728  * Determine whether we want to dump definitions for procedural languages.
8729  * Since the languages themselves don't have schemas, we can't rely on
8730  * the normal schema-based selection mechanism.  We choose to dump them
8731  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8732  * the dump flag of the PL's call handler function, but in 8.1 this will
8733  * probably always be false since call handlers are created in pg_catalog.)
8734  *
8735  * For some backwards compatibility with the older behavior, we forcibly
8736  * dump a PL if its handler function (and validator if any) are in a
8737  * dumpable namespace.  That case is not checked here.
8738  *
8739  * Also, if the PL belongs to an extension, we do not use this heuristic.
8740  * That case isn't checked here either.
8741  */
8742 static bool
8743 shouldDumpProcLangs(void)
8744 {
8745         if (!include_everything)
8746                 return false;
8747         /* And they're schema not data */
8748         if (dataOnly)
8749                 return false;
8750         return true;
8751 }
8752
8753 /*
8754  * dumpProcLang
8755  *                writes out to fout the queries to recreate a user-defined
8756  *                procedural language
8757  */
8758 static void
8759 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8760 {
8761         PQExpBuffer defqry;
8762         PQExpBuffer delqry;
8763         PQExpBuffer labelq;
8764         bool            useParams;
8765         char       *qlanname;
8766         char       *lanschema;
8767         FuncInfo   *funcInfo;
8768         FuncInfo   *inlineInfo = NULL;
8769         FuncInfo   *validatorInfo = NULL;
8770
8771         /* Skip if not to be dumped */
8772         if (!plang->dobj.dump || dataOnly)
8773                 return;
8774
8775         /*
8776          * Try to find the support function(s).  It is not an error if we don't
8777          * find them --- if the functions are in the pg_catalog schema, as is
8778          * standard in 8.1 and up, then we won't have loaded them. (In this case
8779          * we will emit a parameterless CREATE LANGUAGE command, which will
8780          * require PL template knowledge in the backend to reload.)
8781          */
8782
8783         funcInfo = findFuncByOid(plang->lanplcallfoid);
8784         if (funcInfo != NULL && !funcInfo->dobj.dump)
8785                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8786
8787         if (OidIsValid(plang->laninline))
8788         {
8789                 inlineInfo = findFuncByOid(plang->laninline);
8790                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8791                         inlineInfo = NULL;
8792         }
8793
8794         if (OidIsValid(plang->lanvalidator))
8795         {
8796                 validatorInfo = findFuncByOid(plang->lanvalidator);
8797                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8798                         validatorInfo = NULL;
8799         }
8800
8801         /*
8802          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8803          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8804          * dump it.
8805          *
8806          * However, for a language that belongs to an extension, we must not use
8807          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8808          * told to (via dobj.dump).  Generally the support functions will belong
8809          * to the same extension and so have the same dump flags ... if they
8810          * don't, this might not work terribly nicely.
8811          */
8812         useParams = (funcInfo != NULL &&
8813                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8814                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8815
8816         if (!plang->dobj.ext_member)
8817         {
8818                 if (!useParams && !shouldDumpProcLangs())
8819                         return;
8820         }
8821
8822         defqry = createPQExpBuffer();
8823         delqry = createPQExpBuffer();
8824         labelq = createPQExpBuffer();
8825
8826         qlanname = pg_strdup(fmtId(plang->dobj.name));
8827
8828         /*
8829          * If dumping a HANDLER clause, treat the language as being in the handler
8830          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8831          * it doesn't really have a schema.
8832          */
8833         if (useParams)
8834                 lanschema = funcInfo->dobj.namespace->dobj.name;
8835         else
8836                 lanschema = NULL;
8837
8838         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8839                                           qlanname);
8840
8841         if (useParams)
8842         {
8843                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8844                                                   plang->lanpltrusted ? "TRUSTED " : "",
8845                                                   qlanname);
8846                 appendPQExpBuffer(defqry, " HANDLER %s",
8847                                                   fmtId(funcInfo->dobj.name));
8848                 if (OidIsValid(plang->laninline))
8849                 {
8850                         appendPQExpBuffer(defqry, " INLINE ");
8851                         /* Cope with possibility that inline is in different schema */
8852                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8853                                 appendPQExpBuffer(defqry, "%s.",
8854                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8855                         appendPQExpBuffer(defqry, "%s",
8856                                                           fmtId(inlineInfo->dobj.name));
8857                 }
8858                 if (OidIsValid(plang->lanvalidator))
8859                 {
8860                         appendPQExpBuffer(defqry, " VALIDATOR ");
8861                         /* Cope with possibility that validator is in different schema */
8862                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8863                                 appendPQExpBuffer(defqry, "%s.",
8864                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8865                         appendPQExpBuffer(defqry, "%s",
8866                                                           fmtId(validatorInfo->dobj.name));
8867                 }
8868         }
8869         else
8870         {
8871                 /*
8872                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8873                  * command will not fail if the language is preinstalled in the target
8874                  * database.  We restrict the use of REPLACE to this case so as to
8875                  * eliminate the risk of replacing a language with incompatible
8876                  * parameter settings: this command will only succeed at all if there
8877                  * is a pg_pltemplate entry, and if there is one, the existing entry
8878                  * must match it too.
8879                  */
8880                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8881                                                   qlanname);
8882         }
8883         appendPQExpBuffer(defqry, ";\n");
8884
8885         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8886
8887         if (binary_upgrade)
8888                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8889
8890         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8891                                  plang->dobj.name,
8892                                  lanschema, NULL, plang->lanowner,
8893                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8894                                  defqry->data, delqry->data, NULL,
8895                                  plang->dobj.dependencies, plang->dobj.nDeps,
8896                                  NULL, NULL);
8897
8898         /* Dump Proc Lang Comments and Security Labels */
8899         dumpComment(fout, labelq->data,
8900                                 NULL, "",
8901                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8902         dumpSecLabel(fout, labelq->data,
8903                                  NULL, "",
8904                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8905
8906         if (plang->lanpltrusted)
8907                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8908                                 qlanname, NULL, plang->dobj.name,
8909                                 lanschema,
8910                                 plang->lanowner, plang->lanacl);
8911
8912         free(qlanname);
8913
8914         destroyPQExpBuffer(defqry);
8915         destroyPQExpBuffer(delqry);
8916         destroyPQExpBuffer(labelq);
8917 }
8918
8919 /*
8920  * format_function_arguments: generate function name and argument list
8921  *
8922  * This is used when we can rely on pg_get_function_arguments to format
8923  * the argument list.
8924  */
8925 static char *
8926 format_function_arguments(FuncInfo *finfo, char *funcargs)
8927 {
8928         PQExpBufferData fn;
8929
8930         initPQExpBuffer(&fn);
8931         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8932         return fn.data;
8933 }
8934
8935 /*
8936  * format_function_arguments_old: generate function name and argument list
8937  *
8938  * The argument type names are qualified if needed.  The function name
8939  * is never qualified.
8940  *
8941  * This is used only with pre-8.4 servers, so we aren't expecting to see
8942  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8943  *
8944  * Any or all of allargtypes, argmodes, argnames may be NULL.
8945  */
8946 static char *
8947 format_function_arguments_old(Archive *fout,
8948                                                           FuncInfo *finfo, int nallargs,
8949                                                           char **allargtypes,
8950                                                           char **argmodes,
8951                                                           char **argnames)
8952 {
8953         PQExpBufferData fn;
8954         int                     j;
8955
8956         initPQExpBuffer(&fn);
8957         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8958         for (j = 0; j < nallargs; j++)
8959         {
8960                 Oid                     typid;
8961                 char       *typname;
8962                 const char *argmode;
8963                 const char *argname;
8964
8965                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8966                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8967
8968                 if (argmodes)
8969                 {
8970                         switch (argmodes[j][0])
8971                         {
8972                                 case PROARGMODE_IN:
8973                                         argmode = "";
8974                                         break;
8975                                 case PROARGMODE_OUT:
8976                                         argmode = "OUT ";
8977                                         break;
8978                                 case PROARGMODE_INOUT:
8979                                         argmode = "INOUT ";
8980                                         break;
8981                                 default:
8982                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8983                                         argmode = "";
8984                                         break;
8985                         }
8986                 }
8987                 else
8988                         argmode = "";
8989
8990                 argname = argnames ? argnames[j] : (char *) NULL;
8991                 if (argname && argname[0] == '\0')
8992                         argname = NULL;
8993
8994                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8995                                                   (j > 0) ? ", " : "",
8996                                                   argmode,
8997                                                   argname ? fmtId(argname) : "",
8998                                                   argname ? " " : "",
8999                                                   typname);
9000                 free(typname);
9001         }
9002         appendPQExpBuffer(&fn, ")");
9003         return fn.data;
9004 }
9005
9006 /*
9007  * format_function_signature: generate function name and argument list
9008  *
9009  * This is like format_function_arguments_old except that only a minimal
9010  * list of input argument types is generated; this is sufficient to
9011  * reference the function, but not to define it.
9012  *
9013  * If honor_quotes is false then the function name is never quoted.
9014  * This is appropriate for use in TOC tags, but not in SQL commands.
9015  */
9016 static char *
9017 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9018 {
9019         PQExpBufferData fn;
9020         int                     j;
9021
9022         initPQExpBuffer(&fn);
9023         if (honor_quotes)
9024                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9025         else
9026                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9027         for (j = 0; j < finfo->nargs; j++)
9028         {
9029                 char       *typname;
9030
9031                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9032                                                                            zeroAsOpaque);
9033
9034                 appendPQExpBuffer(&fn, "%s%s",
9035                                                   (j > 0) ? ", " : "",
9036                                                   typname);
9037                 free(typname);
9038         }
9039         appendPQExpBuffer(&fn, ")");
9040         return fn.data;
9041 }
9042
9043
9044 /*
9045  * dumpFunc:
9046  *        dump out one function
9047  */
9048 static void
9049 dumpFunc(Archive *fout, FuncInfo *finfo)
9050 {
9051         PQExpBuffer query;
9052         PQExpBuffer q;
9053         PQExpBuffer delqry;
9054         PQExpBuffer labelq;
9055         PQExpBuffer asPart;
9056         PGresult   *res;
9057         char       *funcsig;            /* identity signature */
9058         char       *funcfullsig;        /* full signature */
9059         char       *funcsig_tag;
9060         int                     ntups;
9061         char       *proretset;
9062         char       *prosrc;
9063         char       *probin;
9064         char       *funcargs;
9065         char       *funciargs;
9066         char       *funcresult;
9067         char       *proallargtypes;
9068         char       *proargmodes;
9069         char       *proargnames;
9070         char       *proiswindow;
9071         char       *provolatile;
9072         char       *proisstrict;
9073         char       *prosecdef;
9074         char       *proleakproof;
9075         char       *proconfig;
9076         char       *procost;
9077         char       *prorows;
9078         char       *lanname;
9079         char       *rettypename;
9080         int                     nallargs;
9081         char      **allargtypes = NULL;
9082         char      **argmodes = NULL;
9083         char      **argnames = NULL;
9084         char      **configitems = NULL;
9085         int                     nconfigitems = 0;
9086         int                     i;
9087
9088         /* Skip if not to be dumped */
9089         if (!finfo->dobj.dump || dataOnly)
9090                 return;
9091
9092         query = createPQExpBuffer();
9093         q = createPQExpBuffer();
9094         delqry = createPQExpBuffer();
9095         labelq = createPQExpBuffer();
9096         asPart = createPQExpBuffer();
9097
9098         /* Set proper schema search path so type references list correctly */
9099         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9100
9101         /* Fetch function-specific details */
9102         if (fout->remoteVersion >= 90200)
9103         {
9104                 /*
9105                  * proleakproof was added at v9.2
9106                  */
9107                 appendPQExpBuffer(query,
9108                                                   "SELECT proretset, prosrc, probin, "
9109                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9110                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9111                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9112                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9113                                                   "proleakproof, proconfig, procost, prorows, "
9114                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9115                                                   "FROM pg_catalog.pg_proc "
9116                                                   "WHERE oid = '%u'::pg_catalog.oid",
9117                                                   finfo->dobj.catId.oid);
9118         }
9119         else if (fout->remoteVersion >= 80400)
9120         {
9121                 /*
9122                  * In 8.4 and up we rely on pg_get_function_arguments and
9123                  * pg_get_function_result instead of examining proallargtypes etc.
9124                  */
9125                 appendPQExpBuffer(query,
9126                                                   "SELECT proretset, prosrc, probin, "
9127                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9128                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9129                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9130                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9131                                                   "false AS proleakproof, "
9132                                                   " proconfig, procost, prorows, "
9133                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9134                                                   "FROM pg_catalog.pg_proc "
9135                                                   "WHERE oid = '%u'::pg_catalog.oid",
9136                                                   finfo->dobj.catId.oid);
9137         }
9138         else if (fout->remoteVersion >= 80300)
9139         {
9140                 appendPQExpBuffer(query,
9141                                                   "SELECT proretset, prosrc, probin, "
9142                                                   "proallargtypes, proargmodes, proargnames, "
9143                                                   "false AS proiswindow, "
9144                                                   "provolatile, proisstrict, prosecdef, "
9145                                                   "false AS proleakproof, "
9146                                                   "proconfig, procost, prorows, "
9147                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9148                                                   "FROM pg_catalog.pg_proc "
9149                                                   "WHERE oid = '%u'::pg_catalog.oid",
9150                                                   finfo->dobj.catId.oid);
9151         }
9152         else if (fout->remoteVersion >= 80100)
9153         {
9154                 appendPQExpBuffer(query,
9155                                                   "SELECT proretset, prosrc, probin, "
9156                                                   "proallargtypes, proargmodes, proargnames, "
9157                                                   "false AS proiswindow, "
9158                                                   "provolatile, proisstrict, prosecdef, "
9159                                                   "false AS proleakproof, "
9160                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9161                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9162                                                   "FROM pg_catalog.pg_proc "
9163                                                   "WHERE oid = '%u'::pg_catalog.oid",
9164                                                   finfo->dobj.catId.oid);
9165         }
9166         else if (fout->remoteVersion >= 80000)
9167         {
9168                 appendPQExpBuffer(query,
9169                                                   "SELECT proretset, prosrc, probin, "
9170                                                   "null AS proallargtypes, "
9171                                                   "null AS proargmodes, "
9172                                                   "proargnames, "
9173                                                   "false AS proiswindow, "
9174                                                   "provolatile, proisstrict, prosecdef, "
9175                                                   "false AS proleakproof, "
9176                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9177                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9178                                                   "FROM pg_catalog.pg_proc "
9179                                                   "WHERE oid = '%u'::pg_catalog.oid",
9180                                                   finfo->dobj.catId.oid);
9181         }
9182         else if (fout->remoteVersion >= 70300)
9183         {
9184                 appendPQExpBuffer(query,
9185                                                   "SELECT proretset, prosrc, probin, "
9186                                                   "null AS proallargtypes, "
9187                                                   "null AS proargmodes, "
9188                                                   "null AS proargnames, "
9189                                                   "false AS proiswindow, "
9190                                                   "provolatile, proisstrict, prosecdef, "
9191                                                   "false AS proleakproof, "
9192                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9193                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9194                                                   "FROM pg_catalog.pg_proc "
9195                                                   "WHERE oid = '%u'::pg_catalog.oid",
9196                                                   finfo->dobj.catId.oid);
9197         }
9198         else if (fout->remoteVersion >= 70100)
9199         {
9200                 appendPQExpBuffer(query,
9201                                                   "SELECT proretset, prosrc, probin, "
9202                                                   "null AS proallargtypes, "
9203                                                   "null AS proargmodes, "
9204                                                   "null AS proargnames, "
9205                                                   "false AS proiswindow, "
9206                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9207                                                   "proisstrict, "
9208                                                   "false AS prosecdef, "
9209                                                   "false AS proleakproof, "
9210                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9211                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9212                                                   "FROM pg_proc "
9213                                                   "WHERE oid = '%u'::oid",
9214                                                   finfo->dobj.catId.oid);
9215         }
9216         else
9217         {
9218                 appendPQExpBuffer(query,
9219                                                   "SELECT proretset, prosrc, probin, "
9220                                                   "null AS proallargtypes, "
9221                                                   "null AS proargmodes, "
9222                                                   "null AS proargnames, "
9223                                                   "false AS proiswindow, "
9224                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9225                                                   "false AS proisstrict, "
9226                                                   "false AS prosecdef, "
9227                                                   "false AS proleakproof, "
9228                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9229                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9230                                                   "FROM pg_proc "
9231                                                   "WHERE oid = '%u'::oid",
9232                                                   finfo->dobj.catId.oid);
9233         }
9234
9235         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9236
9237         /* Expecting a single result only */
9238         ntups = PQntuples(res);
9239         if (ntups != 1)
9240         {
9241                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9242                                                            "query returned %d rows instead of one: %s\n",
9243                                                                  ntups),
9244                                   ntups, query->data);
9245                 exit_nicely();
9246         }
9247
9248         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9249         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9250         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9251         if (fout->remoteVersion >= 80400)
9252         {
9253                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9254                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9255                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9256                 proallargtypes = proargmodes = proargnames = NULL;
9257         }
9258         else
9259         {
9260                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9261                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9262                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9263                 funcargs = funciargs = funcresult = NULL;
9264         }
9265         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9266         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9267         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9268         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9269         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9270         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9271         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9272         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9273         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9274
9275         /*
9276          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9277          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9278          * versions would set it to "-".  There are no known cases in which prosrc
9279          * is unused, so the tests below for "-" are probably useless.
9280          */
9281         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9282         {
9283                 appendPQExpBuffer(asPart, "AS ");
9284                 appendStringLiteralAH(asPart, probin, fout);
9285                 if (strcmp(prosrc, "-") != 0)
9286                 {
9287                         appendPQExpBuffer(asPart, ", ");
9288
9289                         /*
9290                          * where we have bin, use dollar quoting if allowed and src
9291                          * contains quote or backslash; else use regular quoting.
9292                          */
9293                         if (disable_dollar_quoting ||
9294                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9295                                 appendStringLiteralAH(asPart, prosrc, fout);
9296                         else
9297                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9298                 }
9299         }
9300         else
9301         {
9302                 if (strcmp(prosrc, "-") != 0)
9303                 {
9304                         appendPQExpBuffer(asPart, "AS ");
9305                         /* with no bin, dollar quote src unconditionally if allowed */
9306                         if (disable_dollar_quoting)
9307                                 appendStringLiteralAH(asPart, prosrc, fout);
9308                         else
9309                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9310                 }
9311         }
9312
9313         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9314
9315         if (proallargtypes && *proallargtypes)
9316         {
9317                 int                     nitems = 0;
9318
9319                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9320                         nitems < finfo->nargs)
9321                 {
9322                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9323                         if (allargtypes)
9324                                 free(allargtypes);
9325                         allargtypes = NULL;
9326                 }
9327                 else
9328                         nallargs = nitems;
9329         }
9330
9331         if (proargmodes && *proargmodes)
9332         {
9333                 int                     nitems = 0;
9334
9335                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9336                         nitems != nallargs)
9337                 {
9338                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9339                         if (argmodes)
9340                                 free(argmodes);
9341                         argmodes = NULL;
9342                 }
9343         }
9344
9345         if (proargnames && *proargnames)
9346         {
9347                 int                     nitems = 0;
9348
9349                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9350                         nitems != nallargs)
9351                 {
9352                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9353                         if (argnames)
9354                                 free(argnames);
9355                         argnames = NULL;
9356                 }
9357         }
9358
9359         if (proconfig && *proconfig)
9360         {
9361                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9362                 {
9363                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9364                         if (configitems)
9365                                 free(configitems);
9366                         configitems = NULL;
9367                         nconfigitems = 0;
9368                 }
9369         }
9370
9371         if (funcargs)
9372         {
9373                 /* 8.4 or later; we rely on server-side code for most of the work */
9374                 funcfullsig = format_function_arguments(finfo, funcargs);
9375                 funcsig = format_function_arguments(finfo, funciargs);
9376         }
9377         else
9378         {
9379                 /* pre-8.4, do it ourselves */
9380                 funcsig = format_function_arguments_old(fout,
9381                                                                                                 finfo, nallargs, allargtypes,
9382                                                                                                 argmodes, argnames);
9383                 funcfullsig = funcsig;
9384         }
9385
9386         funcsig_tag = format_function_signature(fout, finfo, false);
9387
9388         /*
9389          * DROP must be fully qualified in case same name appears in pg_catalog
9390          */
9391         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9392                                           fmtId(finfo->dobj.namespace->dobj.name),
9393                                           funcsig);
9394
9395         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9396         if (funcresult)
9397                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9398         else
9399         {
9400                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9401                                                                                    zeroAsOpaque);
9402                 appendPQExpBuffer(q, "RETURNS %s%s",
9403                                                   (proretset[0] == 't') ? "SETOF " : "",
9404                                                   rettypename);
9405                 free(rettypename);
9406         }
9407
9408         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9409
9410         if (proiswindow[0] == 't')
9411                 appendPQExpBuffer(q, " WINDOW");
9412
9413         if (provolatile[0] != PROVOLATILE_VOLATILE)
9414         {
9415                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9416                         appendPQExpBuffer(q, " IMMUTABLE");
9417                 else if (provolatile[0] == PROVOLATILE_STABLE)
9418                         appendPQExpBuffer(q, " STABLE");
9419                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9420                 {
9421                         write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
9422                                           finfo->dobj.name);
9423                         exit_nicely();
9424                 }
9425         }
9426
9427         if (proisstrict[0] == 't')
9428                 appendPQExpBuffer(q, " STRICT");
9429
9430         if (prosecdef[0] == 't')
9431                 appendPQExpBuffer(q, " SECURITY DEFINER");
9432
9433         if (proleakproof[0] == 't')
9434                 appendPQExpBuffer(q, " LEAKPROOF");
9435
9436         /*
9437          * COST and ROWS are emitted only if present and not default, so as not to
9438          * break backwards-compatibility of the dump without need.      Keep this code
9439          * in sync with the defaults in functioncmds.c.
9440          */
9441         if (strcmp(procost, "0") != 0)
9442         {
9443                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9444                 {
9445                         /* default cost is 1 */
9446                         if (strcmp(procost, "1") != 0)
9447                                 appendPQExpBuffer(q, " COST %s", procost);
9448                 }
9449                 else
9450                 {
9451                         /* default cost is 100 */
9452                         if (strcmp(procost, "100") != 0)
9453                                 appendPQExpBuffer(q, " COST %s", procost);
9454                 }
9455         }
9456         if (proretset[0] == 't' &&
9457                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9458                 appendPQExpBuffer(q, " ROWS %s", prorows);
9459
9460         for (i = 0; i < nconfigitems; i++)
9461         {
9462                 /* we feel free to scribble on configitems[] here */
9463                 char       *configitem = configitems[i];
9464                 char       *pos;
9465
9466                 pos = strchr(configitem, '=');
9467                 if (pos == NULL)
9468                         continue;
9469                 *pos++ = '\0';
9470                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9471
9472                 /*
9473                  * Some GUC variable names are 'LIST' type and hence must not be
9474                  * quoted.
9475                  */
9476                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9477                         || pg_strcasecmp(configitem, "search_path") == 0)
9478                         appendPQExpBuffer(q, "%s", pos);
9479                 else
9480                         appendStringLiteralAH(q, pos, fout);
9481         }
9482
9483         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9484
9485         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9486
9487         if (binary_upgrade)
9488                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9489
9490         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9491                                  funcsig_tag,
9492                                  finfo->dobj.namespace->dobj.name,
9493                                  NULL,
9494                                  finfo->rolname, false,
9495                                  "FUNCTION", SECTION_PRE_DATA,
9496                                  q->data, delqry->data, NULL,
9497                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
9498                                  NULL, NULL);
9499
9500         /* Dump Function Comments and Security Labels */
9501         dumpComment(fout, labelq->data,
9502                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9503                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9504         dumpSecLabel(fout, labelq->data,
9505                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9506                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9507
9508         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9509                         funcsig, NULL, funcsig_tag,
9510                         finfo->dobj.namespace->dobj.name,
9511                         finfo->rolname, finfo->proacl);
9512
9513         PQclear(res);
9514
9515         destroyPQExpBuffer(query);
9516         destroyPQExpBuffer(q);
9517         destroyPQExpBuffer(delqry);
9518         destroyPQExpBuffer(labelq);
9519         destroyPQExpBuffer(asPart);
9520         free(funcsig);
9521         free(funcsig_tag);
9522         if (allargtypes)
9523                 free(allargtypes);
9524         if (argmodes)
9525                 free(argmodes);
9526         if (argnames)
9527                 free(argnames);
9528         if (configitems)
9529                 free(configitems);
9530 }
9531
9532
9533 /*
9534  * Dump a user-defined cast
9535  */
9536 static void
9537 dumpCast(Archive *fout, CastInfo *cast)
9538 {
9539         PQExpBuffer defqry;
9540         PQExpBuffer delqry;
9541         PQExpBuffer labelq;
9542         FuncInfo   *funcInfo = NULL;
9543
9544         /* Skip if not to be dumped */
9545         if (!cast->dobj.dump || dataOnly)
9546                 return;
9547
9548         /* Cannot dump if we don't have the cast function's info */
9549         if (OidIsValid(cast->castfunc))
9550         {
9551                 funcInfo = findFuncByOid(cast->castfunc);
9552                 if (funcInfo == NULL)
9553                         return;
9554         }
9555
9556         /*
9557          * As per discussion we dump casts if one or more of the underlying
9558          * objects (the conversion function and the two data types) are not
9559          * builtin AND if all of the non-builtin objects are included in the dump.
9560          * Builtin meaning, the namespace name does not start with "pg_".
9561          *
9562          * However, for a cast that belongs to an extension, we must not use this
9563          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9564          */
9565         if (!cast->dobj.ext_member)
9566         {
9567                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9568                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9569
9570                 if (sourceInfo == NULL || targetInfo == NULL)
9571                         return;
9572
9573                 /*
9574                  * Skip this cast if all objects are from pg_
9575                  */
9576                 if ((funcInfo == NULL ||
9577                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9578                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9579                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9580                         return;
9581
9582                 /*
9583                  * Skip cast if function isn't from pg_ and is not to be dumped.
9584                  */
9585                 if (funcInfo &&
9586                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9587                         !funcInfo->dobj.dump)
9588                         return;
9589
9590                 /*
9591                  * Same for the source type
9592                  */
9593                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9594                         !sourceInfo->dobj.dump)
9595                         return;
9596
9597                 /*
9598                  * and the target type.
9599                  */
9600                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9601                         !targetInfo->dobj.dump)
9602                         return;
9603         }
9604
9605         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9606         selectSourceSchema(fout, "pg_catalog");
9607
9608         defqry = createPQExpBuffer();
9609         delqry = createPQExpBuffer();
9610         labelq = createPQExpBuffer();
9611
9612         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9613                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9614                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9615
9616         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9617                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9618                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9619
9620         switch (cast->castmethod)
9621         {
9622                 case COERCION_METHOD_BINARY:
9623                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9624                         break;
9625                 case COERCION_METHOD_INOUT:
9626                         appendPQExpBuffer(defqry, "WITH INOUT");
9627                         break;
9628                 case COERCION_METHOD_FUNCTION:
9629
9630                         /*
9631                          * Always qualify the function name, in case it is not in
9632                          * pg_catalog schema (format_function_signature won't qualify it).
9633                          */
9634                         appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
9635                                                           fmtId(funcInfo->dobj.namespace->dobj.name));
9636                         appendPQExpBuffer(defqry, "%s",
9637                                                   format_function_signature(fout, funcInfo, true));
9638                         break;
9639                 default:
9640                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9641         }
9642
9643         if (cast->castcontext == 'a')
9644                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9645         else if (cast->castcontext == 'i')
9646                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9647         appendPQExpBuffer(defqry, ";\n");
9648
9649         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9650                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9651                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9652
9653         if (binary_upgrade)
9654                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9655
9656         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9657                                  labelq->data,
9658                                  "pg_catalog", NULL, "",
9659                                  false, "CAST", SECTION_PRE_DATA,
9660                                  defqry->data, delqry->data, NULL,
9661                                  cast->dobj.dependencies, cast->dobj.nDeps,
9662                                  NULL, NULL);
9663
9664         /* Dump Cast Comments */
9665         dumpComment(fout, labelq->data,
9666                                 NULL, "",
9667                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9668
9669         destroyPQExpBuffer(defqry);
9670         destroyPQExpBuffer(delqry);
9671         destroyPQExpBuffer(labelq);
9672 }
9673
9674 /*
9675  * dumpOpr
9676  *        write out a single operator definition
9677  */
9678 static void
9679 dumpOpr(Archive *fout, OprInfo *oprinfo)
9680 {
9681         PQExpBuffer query;
9682         PQExpBuffer q;
9683         PQExpBuffer delq;
9684         PQExpBuffer labelq;
9685         PQExpBuffer oprid;
9686         PQExpBuffer details;
9687         const char *name;
9688         PGresult   *res;
9689         int                     ntups;
9690         int                     i_oprkind;
9691         int                     i_oprcode;
9692         int                     i_oprleft;
9693         int                     i_oprright;
9694         int                     i_oprcom;
9695         int                     i_oprnegate;
9696         int                     i_oprrest;
9697         int                     i_oprjoin;
9698         int                     i_oprcanmerge;
9699         int                     i_oprcanhash;
9700         char       *oprkind;
9701         char       *oprcode;
9702         char       *oprleft;
9703         char       *oprright;
9704         char       *oprcom;
9705         char       *oprnegate;
9706         char       *oprrest;
9707         char       *oprjoin;
9708         char       *oprcanmerge;
9709         char       *oprcanhash;
9710
9711         /* Skip if not to be dumped */
9712         if (!oprinfo->dobj.dump || dataOnly)
9713                 return;
9714
9715         /*
9716          * some operators are invalid because they were the result of user
9717          * defining operators before commutators exist
9718          */
9719         if (!OidIsValid(oprinfo->oprcode))
9720                 return;
9721
9722         query = createPQExpBuffer();
9723         q = createPQExpBuffer();
9724         delq = createPQExpBuffer();
9725         labelq = createPQExpBuffer();
9726         oprid = createPQExpBuffer();
9727         details = createPQExpBuffer();
9728
9729         /* Make sure we are in proper schema so regoperator works correctly */
9730         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9731
9732         if (fout->remoteVersion >= 80300)
9733         {
9734                 appendPQExpBuffer(query, "SELECT oprkind, "
9735                                                   "oprcode::pg_catalog.regprocedure, "
9736                                                   "oprleft::pg_catalog.regtype, "
9737                                                   "oprright::pg_catalog.regtype, "
9738                                                   "oprcom::pg_catalog.regoperator, "
9739                                                   "oprnegate::pg_catalog.regoperator, "
9740                                                   "oprrest::pg_catalog.regprocedure, "
9741                                                   "oprjoin::pg_catalog.regprocedure, "
9742                                                   "oprcanmerge, oprcanhash "
9743                                                   "FROM pg_catalog.pg_operator "
9744                                                   "WHERE oid = '%u'::pg_catalog.oid",
9745                                                   oprinfo->dobj.catId.oid);
9746         }
9747         else if (fout->remoteVersion >= 70300)
9748         {
9749                 appendPQExpBuffer(query, "SELECT oprkind, "
9750                                                   "oprcode::pg_catalog.regprocedure, "
9751                                                   "oprleft::pg_catalog.regtype, "
9752                                                   "oprright::pg_catalog.regtype, "
9753                                                   "oprcom::pg_catalog.regoperator, "
9754                                                   "oprnegate::pg_catalog.regoperator, "
9755                                                   "oprrest::pg_catalog.regprocedure, "
9756                                                   "oprjoin::pg_catalog.regprocedure, "
9757                                                   "(oprlsortop != 0) AS oprcanmerge, "
9758                                                   "oprcanhash "
9759                                                   "FROM pg_catalog.pg_operator "
9760                                                   "WHERE oid = '%u'::pg_catalog.oid",
9761                                                   oprinfo->dobj.catId.oid);
9762         }
9763         else if (fout->remoteVersion >= 70100)
9764         {
9765                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9766                                                   "CASE WHEN oprleft = 0 THEN '-' "
9767                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9768                                                   "CASE WHEN oprright = 0 THEN '-' "
9769                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9770                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9771                                                   "(oprlsortop != 0) AS oprcanmerge, "
9772                                                   "oprcanhash "
9773                                                   "FROM pg_operator "
9774                                                   "WHERE oid = '%u'::oid",
9775                                                   oprinfo->dobj.catId.oid);
9776         }
9777         else
9778         {
9779                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9780                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9781                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9782                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9783                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9784                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9785                                                   "(oprlsortop != 0) AS oprcanmerge, "
9786                                                   "oprcanhash "
9787                                                   "FROM pg_operator "
9788                                                   "WHERE oid = '%u'::oid",
9789                                                   oprinfo->dobj.catId.oid);
9790         }
9791
9792         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9793
9794         /* Expecting a single result only */
9795         ntups = PQntuples(res);
9796         if (ntups != 1)
9797         {
9798                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9799                                                            "query returned %d rows instead of one: %s\n",
9800                                                                  ntups),
9801                                   ntups, query->data);
9802                 exit_nicely();
9803         }
9804
9805         i_oprkind = PQfnumber(res, "oprkind");
9806         i_oprcode = PQfnumber(res, "oprcode");
9807         i_oprleft = PQfnumber(res, "oprleft");
9808         i_oprright = PQfnumber(res, "oprright");
9809         i_oprcom = PQfnumber(res, "oprcom");
9810         i_oprnegate = PQfnumber(res, "oprnegate");
9811         i_oprrest = PQfnumber(res, "oprrest");
9812         i_oprjoin = PQfnumber(res, "oprjoin");
9813         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9814         i_oprcanhash = PQfnumber(res, "oprcanhash");
9815
9816         oprkind = PQgetvalue(res, 0, i_oprkind);
9817         oprcode = PQgetvalue(res, 0, i_oprcode);
9818         oprleft = PQgetvalue(res, 0, i_oprleft);
9819         oprright = PQgetvalue(res, 0, i_oprright);
9820         oprcom = PQgetvalue(res, 0, i_oprcom);
9821         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9822         oprrest = PQgetvalue(res, 0, i_oprrest);
9823         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9824         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9825         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9826
9827         appendPQExpBuffer(details, "    PROCEDURE = %s",
9828                                           convertRegProcReference(fout, oprcode));
9829
9830         appendPQExpBuffer(oprid, "%s (",
9831                                           oprinfo->dobj.name);
9832
9833         /*
9834          * right unary means there's a left arg and left unary means there's a
9835          * right arg
9836          */
9837         if (strcmp(oprkind, "r") == 0 ||
9838                 strcmp(oprkind, "b") == 0)
9839         {
9840                 if (fout->remoteVersion >= 70100)
9841                         name = oprleft;
9842                 else
9843                         name = fmtId(oprleft);
9844                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9845                 appendPQExpBuffer(oprid, "%s", name);
9846         }
9847         else
9848                 appendPQExpBuffer(oprid, "NONE");
9849
9850         if (strcmp(oprkind, "l") == 0 ||
9851                 strcmp(oprkind, "b") == 0)
9852         {
9853                 if (fout->remoteVersion >= 70100)
9854                         name = oprright;
9855                 else
9856                         name = fmtId(oprright);
9857                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9858                 appendPQExpBuffer(oprid, ", %s)", name);
9859         }
9860         else
9861                 appendPQExpBuffer(oprid, ", NONE)");
9862
9863         name = convertOperatorReference(fout, oprcom);
9864         if (name)
9865                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9866
9867         name = convertOperatorReference(fout, oprnegate);
9868         if (name)
9869                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9870
9871         if (strcmp(oprcanmerge, "t") == 0)
9872                 appendPQExpBuffer(details, ",\n    MERGES");
9873
9874         if (strcmp(oprcanhash, "t") == 0)
9875                 appendPQExpBuffer(details, ",\n    HASHES");
9876
9877         name = convertRegProcReference(fout, oprrest);
9878         if (name)
9879                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9880
9881         name = convertRegProcReference(fout, oprjoin);
9882         if (name)
9883                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9884
9885         /*
9886          * DROP must be fully qualified in case same name appears in pg_catalog
9887          */
9888         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9889                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9890                                           oprid->data);
9891
9892         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9893                                           oprinfo->dobj.name, details->data);
9894
9895         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9896
9897         if (binary_upgrade)
9898                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9899
9900         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9901                                  oprinfo->dobj.name,
9902                                  oprinfo->dobj.namespace->dobj.name,
9903                                  NULL,
9904                                  oprinfo->rolname,
9905                                  false, "OPERATOR", SECTION_PRE_DATA,
9906                                  q->data, delq->data, NULL,
9907                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9908                                  NULL, NULL);
9909
9910         /* Dump Operator Comments */
9911         dumpComment(fout, labelq->data,
9912                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9913                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9914
9915         PQclear(res);
9916
9917         destroyPQExpBuffer(query);
9918         destroyPQExpBuffer(q);
9919         destroyPQExpBuffer(delq);
9920         destroyPQExpBuffer(labelq);
9921         destroyPQExpBuffer(oprid);
9922         destroyPQExpBuffer(details);
9923 }
9924
9925 /*
9926  * Convert a function reference obtained from pg_operator
9927  *
9928  * Returns what to print, or NULL if function references is InvalidOid
9929  *
9930  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9931  * argument-types part.  In prior versions, the input is a REGPROC display.
9932  */
9933 static const char *
9934 convertRegProcReference(Archive *fout, const char *proc)
9935 {
9936         /* In all cases "-" means a null reference */
9937         if (strcmp(proc, "-") == 0)
9938                 return NULL;
9939
9940         if (fout->remoteVersion >= 70300)
9941         {
9942                 char       *name;
9943                 char       *paren;
9944                 bool            inquote;
9945
9946                 name = pg_strdup(proc);
9947                 /* find non-double-quoted left paren */
9948                 inquote = false;
9949                 for (paren = name; *paren; paren++)
9950                 {
9951                         if (*paren == '(' && !inquote)
9952                         {
9953                                 *paren = '\0';
9954                                 break;
9955                         }
9956                         if (*paren == '"')
9957                                 inquote = !inquote;
9958                 }
9959                 return name;
9960         }
9961
9962         /* REGPROC before 7.3 does not quote its result */
9963         return fmtId(proc);
9964 }
9965
9966 /*
9967  * Convert an operator cross-reference obtained from pg_operator
9968  *
9969  * Returns what to print, or NULL to print nothing
9970  *
9971  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9972  * argument-types part, and add OPERATOR() decoration if the name is
9973  * schema-qualified.  In older versions, the input is just a numeric OID,
9974  * which we search our operator list for.
9975  */
9976 static const char *
9977 convertOperatorReference(Archive *fout, const char *opr)
9978 {
9979         OprInfo    *oprInfo;
9980
9981         /* In all cases "0" means a null reference */
9982         if (strcmp(opr, "0") == 0)
9983                 return NULL;
9984
9985         if (fout->remoteVersion >= 70300)
9986         {
9987                 char       *name;
9988                 char       *oname;
9989                 char       *ptr;
9990                 bool            inquote;
9991                 bool            sawdot;
9992
9993                 name = pg_strdup(opr);
9994                 /* find non-double-quoted left paren, and check for non-quoted dot */
9995                 inquote = false;
9996                 sawdot = false;
9997                 for (ptr = name; *ptr; ptr++)
9998                 {
9999                         if (*ptr == '"')
10000                                 inquote = !inquote;
10001                         else if (*ptr == '.' && !inquote)
10002                                 sawdot = true;
10003                         else if (*ptr == '(' && !inquote)
10004                         {
10005                                 *ptr = '\0';
10006                                 break;
10007                         }
10008                 }
10009                 /* If not schema-qualified, don't need to add OPERATOR() */
10010                 if (!sawdot)
10011                         return name;
10012                 oname = pg_malloc(strlen(name) + 11);
10013                 sprintf(oname, "OPERATOR(%s)", name);
10014                 free(name);
10015                 return oname;
10016         }
10017
10018         oprInfo = findOprByOid(atooid(opr));
10019         if (oprInfo == NULL)
10020         {
10021                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10022                                   opr);
10023                 return NULL;
10024         }
10025         return oprInfo->dobj.name;
10026 }
10027
10028 /*
10029  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10030  *
10031  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10032  * argument lists of these functions are predetermined.  Note that the
10033  * caller should ensure we are in the proper schema, because the results
10034  * are search path dependent!
10035  */
10036 static const char *
10037 convertTSFunction(Archive *fout, Oid funcOid)
10038 {
10039         char       *result;
10040         char            query[128];
10041         PGresult   *res;
10042         int                     ntups;
10043
10044         snprintf(query, sizeof(query),
10045                          "SELECT '%u'::pg_catalog.regproc", funcOid);
10046         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
10047
10048         ntups = PQntuples(res);
10049         if (ntups != 1)
10050         {
10051                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10052                                                            "query returned %d rows instead of one: %s\n",
10053                                                                  ntups),
10054                                   ntups, query);
10055                 exit_nicely();
10056         }
10057
10058         result = pg_strdup(PQgetvalue(res, 0, 0));
10059
10060         PQclear(res);
10061
10062         return result;
10063 }
10064
10065
10066 /*
10067  * dumpOpclass
10068  *        write out a single operator class definition
10069  */
10070 static void
10071 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10072 {
10073         PQExpBuffer query;
10074         PQExpBuffer q;
10075         PQExpBuffer delq;
10076         PQExpBuffer labelq;
10077         PGresult   *res;
10078         int                     ntups;
10079         int                     i_opcintype;
10080         int                     i_opckeytype;
10081         int                     i_opcdefault;
10082         int                     i_opcfamily;
10083         int                     i_opcfamilyname;
10084         int                     i_opcfamilynsp;
10085         int                     i_amname;
10086         int                     i_amopstrategy;
10087         int                     i_amopreqcheck;
10088         int                     i_amopopr;
10089         int                     i_sortfamily;
10090         int                     i_sortfamilynsp;
10091         int                     i_amprocnum;
10092         int                     i_amproc;
10093         int                     i_amproclefttype;
10094         int                     i_amprocrighttype;
10095         char       *opcintype;
10096         char       *opckeytype;
10097         char       *opcdefault;
10098         char       *opcfamily;
10099         char       *opcfamilyname;
10100         char       *opcfamilynsp;
10101         char       *amname;
10102         char       *amopstrategy;
10103         char       *amopreqcheck;
10104         char       *amopopr;
10105         char       *sortfamily;
10106         char       *sortfamilynsp;
10107         char       *amprocnum;
10108         char       *amproc;
10109         char       *amproclefttype;
10110         char       *amprocrighttype;
10111         bool            needComma;
10112         int                     i;
10113
10114         /* Skip if not to be dumped */
10115         if (!opcinfo->dobj.dump || dataOnly)
10116                 return;
10117
10118         /*
10119          * XXX currently we do not implement dumping of operator classes from
10120          * pre-7.3 databases.  This could be done but it seems not worth the
10121          * trouble.
10122          */
10123         if (fout->remoteVersion < 70300)
10124                 return;
10125
10126         query = createPQExpBuffer();
10127         q = createPQExpBuffer();
10128         delq = createPQExpBuffer();
10129         labelq = createPQExpBuffer();
10130
10131         /* Make sure we are in proper schema so regoperator works correctly */
10132         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10133
10134         /* Get additional fields from the pg_opclass row */
10135         if (fout->remoteVersion >= 80300)
10136         {
10137                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10138                                                   "opckeytype::pg_catalog.regtype, "
10139                                                   "opcdefault, opcfamily, "
10140                                                   "opfname AS opcfamilyname, "
10141                                                   "nspname AS opcfamilynsp, "
10142                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10143                                                   "FROM pg_catalog.pg_opclass c "
10144                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10145                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10146                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
10147                                                   opcinfo->dobj.catId.oid);
10148         }
10149         else
10150         {
10151                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10152                                                   "opckeytype::pg_catalog.regtype, "
10153                                                   "opcdefault, NULL AS opcfamily, "
10154                                                   "NULL AS opcfamilyname, "
10155                                                   "NULL AS opcfamilynsp, "
10156                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10157                                                   "FROM pg_catalog.pg_opclass "
10158                                                   "WHERE oid = '%u'::pg_catalog.oid",
10159                                                   opcinfo->dobj.catId.oid);
10160         }
10161
10162         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10163
10164         /* Expecting a single result only */
10165         ntups = PQntuples(res);
10166         if (ntups != 1)
10167         {
10168                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10169                                                            "query returned %d rows instead of one: %s\n",
10170                                                                  ntups),
10171                                   ntups, query->data);
10172                 exit_nicely();
10173         }
10174
10175         i_opcintype = PQfnumber(res, "opcintype");
10176         i_opckeytype = PQfnumber(res, "opckeytype");
10177         i_opcdefault = PQfnumber(res, "opcdefault");
10178         i_opcfamily = PQfnumber(res, "opcfamily");
10179         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10180         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10181         i_amname = PQfnumber(res, "amname");
10182
10183         opcintype = PQgetvalue(res, 0, i_opcintype);
10184         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10185         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10186         /* opcfamily will still be needed after we PQclear res */
10187         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10188         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10189         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10190         /* amname will still be needed after we PQclear res */
10191         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10192
10193         /*
10194          * DROP must be fully qualified in case same name appears in pg_catalog
10195          */
10196         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10197                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10198         appendPQExpBuffer(delq, ".%s",
10199                                           fmtId(opcinfo->dobj.name));
10200         appendPQExpBuffer(delq, " USING %s;\n",
10201                                           fmtId(amname));
10202
10203         /* Build the fixed portion of the CREATE command */
10204         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10205                                           fmtId(opcinfo->dobj.name));
10206         if (strcmp(opcdefault, "t") == 0)
10207                 appendPQExpBuffer(q, "DEFAULT ");
10208         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10209                                           opcintype,
10210                                           fmtId(amname));
10211         if (strlen(opcfamilyname) > 0 &&
10212                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10213                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10214         {
10215                 appendPQExpBuffer(q, " FAMILY ");
10216                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10217                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10218                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10219         }
10220         appendPQExpBuffer(q, " AS\n    ");
10221
10222         needComma = false;
10223
10224         if (strcmp(opckeytype, "-") != 0)
10225         {
10226                 appendPQExpBuffer(q, "STORAGE %s",
10227                                                   opckeytype);
10228                 needComma = true;
10229         }
10230
10231         PQclear(res);
10232
10233         /*
10234          * Now fetch and print the OPERATOR entries (pg_amop rows).
10235          *
10236          * Print only those opfamily members that are tied to the opclass by
10237          * pg_depend entries.
10238          *
10239          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10240          * older server's opclass in which it is used.  This is to avoid
10241          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10242          * older server and then reload into that old version.  This can go away
10243          * once 8.3 is so old as to not be of interest to anyone.
10244          */
10245         resetPQExpBuffer(query);
10246
10247         if (fout->remoteVersion >= 90100)
10248         {
10249                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10250                                                   "amopopr::pg_catalog.regoperator, "
10251                                                   "opfname AS sortfamily, "
10252                                                   "nspname AS sortfamilynsp "
10253                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10254                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10255                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10256                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10257                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10258                                                   "AND refobjid = '%u'::pg_catalog.oid "
10259                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10260                                                   "ORDER BY amopstrategy",
10261                                                   opcinfo->dobj.catId.oid,
10262                                                   opcfamily);
10263         }
10264         else if (fout->remoteVersion >= 80400)
10265         {
10266                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10267                                                   "amopopr::pg_catalog.regoperator, "
10268                                                   "NULL AS sortfamily, "
10269                                                   "NULL AS sortfamilynsp "
10270                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10271                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10272                                                   "AND refobjid = '%u'::pg_catalog.oid "
10273                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10274                                                   "AND objid = ao.oid "
10275                                                   "ORDER BY amopstrategy",
10276                                                   opcinfo->dobj.catId.oid);
10277         }
10278         else if (fout->remoteVersion >= 80300)
10279         {
10280                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10281                                                   "amopopr::pg_catalog.regoperator, "
10282                                                   "NULL AS sortfamily, "
10283                                                   "NULL AS sortfamilynsp "
10284                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10285                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10286                                                   "AND refobjid = '%u'::pg_catalog.oid "
10287                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10288                                                   "AND objid = ao.oid "
10289                                                   "ORDER BY amopstrategy",
10290                                                   opcinfo->dobj.catId.oid);
10291         }
10292         else
10293         {
10294                 /*
10295                  * Here, we print all entries since there are no opfamilies and hence
10296                  * no loose operators to worry about.
10297                  */
10298                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10299                                                   "amopopr::pg_catalog.regoperator, "
10300                                                   "NULL AS sortfamily, "
10301                                                   "NULL AS sortfamilynsp "
10302                                                   "FROM pg_catalog.pg_amop "
10303                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10304                                                   "ORDER BY amopstrategy",
10305                                                   opcinfo->dobj.catId.oid);
10306         }
10307
10308         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10309
10310         ntups = PQntuples(res);
10311
10312         i_amopstrategy = PQfnumber(res, "amopstrategy");
10313         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10314         i_amopopr = PQfnumber(res, "amopopr");
10315         i_sortfamily = PQfnumber(res, "sortfamily");
10316         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10317
10318         for (i = 0; i < ntups; i++)
10319         {
10320                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10321                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10322                 amopopr = PQgetvalue(res, i, i_amopopr);
10323                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10324                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10325
10326                 if (needComma)
10327                         appendPQExpBuffer(q, " ,\n    ");
10328
10329                 appendPQExpBuffer(q, "OPERATOR %s %s",
10330                                                   amopstrategy, amopopr);
10331
10332                 if (strlen(sortfamily) > 0)
10333                 {
10334                         appendPQExpBuffer(q, " FOR ORDER BY ");
10335                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10336                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10337                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10338                 }
10339
10340                 if (strcmp(amopreqcheck, "t") == 0)
10341                         appendPQExpBuffer(q, " RECHECK");
10342
10343                 needComma = true;
10344         }
10345
10346         PQclear(res);
10347
10348         /*
10349          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10350          *
10351          * Print only those opfamily members that are tied to the opclass by
10352          * pg_depend entries.
10353          *
10354          * We print the amproclefttype/amprocrighttype even though in most cases
10355          * the backend could deduce the right values, because of the corner case
10356          * of a btree sort support function for a cross-type comparison.  That's
10357          * only allowed in 9.2 and later, but for simplicity print them in all
10358          * versions that have the columns.
10359          */
10360         resetPQExpBuffer(query);
10361
10362         if (fout->remoteVersion >= 80300)
10363         {
10364                 appendPQExpBuffer(query, "SELECT amprocnum, "
10365                                                   "amproc::pg_catalog.regprocedure, "
10366                                                   "amproclefttype::pg_catalog.regtype, "
10367                                                   "amprocrighttype::pg_catalog.regtype "
10368                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10369                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10370                                                   "AND refobjid = '%u'::pg_catalog.oid "
10371                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10372                                                   "AND objid = ap.oid "
10373                                                   "ORDER BY amprocnum",
10374                                                   opcinfo->dobj.catId.oid);
10375         }
10376         else
10377         {
10378                 appendPQExpBuffer(query, "SELECT amprocnum, "
10379                                                   "amproc::pg_catalog.regprocedure, "
10380                                                   "'' AS amproclefttype, "
10381                                                   "'' AS amprocrighttype "
10382                                                   "FROM pg_catalog.pg_amproc "
10383                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10384                                                   "ORDER BY amprocnum",
10385                                                   opcinfo->dobj.catId.oid);
10386         }
10387
10388         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10389
10390         ntups = PQntuples(res);
10391
10392         i_amprocnum = PQfnumber(res, "amprocnum");
10393         i_amproc = PQfnumber(res, "amproc");
10394         i_amproclefttype = PQfnumber(res, "amproclefttype");
10395         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10396
10397         for (i = 0; i < ntups; i++)
10398         {
10399                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10400                 amproc = PQgetvalue(res, i, i_amproc);
10401                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10402                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10403
10404                 if (needComma)
10405                         appendPQExpBuffer(q, " ,\n    ");
10406
10407                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10408
10409                 if (*amproclefttype && *amprocrighttype)
10410                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10411
10412                 appendPQExpBuffer(q, " %s", amproc);
10413
10414                 needComma = true;
10415         }
10416
10417         PQclear(res);
10418
10419         appendPQExpBuffer(q, ";\n");
10420
10421         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10422                                           fmtId(opcinfo->dobj.name));
10423         appendPQExpBuffer(labelq, " USING %s",
10424                                           fmtId(amname));
10425
10426         if (binary_upgrade)
10427                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10428
10429         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10430                                  opcinfo->dobj.name,
10431                                  opcinfo->dobj.namespace->dobj.name,
10432                                  NULL,
10433                                  opcinfo->rolname,
10434                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10435                                  q->data, delq->data, NULL,
10436                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10437                                  NULL, NULL);
10438
10439         /* Dump Operator Class Comments */
10440         dumpComment(fout, labelq->data,
10441                                 NULL, opcinfo->rolname,
10442                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10443
10444         free(amname);
10445         destroyPQExpBuffer(query);
10446         destroyPQExpBuffer(q);
10447         destroyPQExpBuffer(delq);
10448         destroyPQExpBuffer(labelq);
10449 }
10450
10451 /*
10452  * dumpOpfamily
10453  *        write out a single operator family definition
10454  *
10455  * Note: this also dumps any "loose" operator members that aren't bound to a
10456  * specific opclass within the opfamily.
10457  */
10458 static void
10459 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10460 {
10461         PQExpBuffer query;
10462         PQExpBuffer q;
10463         PQExpBuffer delq;
10464         PQExpBuffer labelq;
10465         PGresult   *res;
10466         PGresult   *res_ops;
10467         PGresult   *res_procs;
10468         int                     ntups;
10469         int                     i_amname;
10470         int                     i_amopstrategy;
10471         int                     i_amopreqcheck;
10472         int                     i_amopopr;
10473         int                     i_sortfamily;
10474         int                     i_sortfamilynsp;
10475         int                     i_amprocnum;
10476         int                     i_amproc;
10477         int                     i_amproclefttype;
10478         int                     i_amprocrighttype;
10479         char       *amname;
10480         char       *amopstrategy;
10481         char       *amopreqcheck;
10482         char       *amopopr;
10483         char       *sortfamily;
10484         char       *sortfamilynsp;
10485         char       *amprocnum;
10486         char       *amproc;
10487         char       *amproclefttype;
10488         char       *amprocrighttype;
10489         bool            needComma;
10490         int                     i;
10491
10492         /* Skip if not to be dumped */
10493         if (!opfinfo->dobj.dump || dataOnly)
10494                 return;
10495
10496         /*
10497          * We want to dump the opfamily only if (1) it contains "loose" operators
10498          * or functions, or (2) it contains an opclass with a different name or
10499          * owner.  Otherwise it's sufficient to let it be created during creation
10500          * of the contained opclass, and not dumping it improves portability of
10501          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10502          * that first.
10503          */
10504
10505         query = createPQExpBuffer();
10506         q = createPQExpBuffer();
10507         delq = createPQExpBuffer();
10508         labelq = createPQExpBuffer();
10509
10510         /* Make sure we are in proper schema so regoperator works correctly */
10511         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10512
10513         /*
10514          * Fetch only those opfamily members that are tied directly to the
10515          * opfamily by pg_depend entries.
10516          *
10517          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10518          * older server's opclass in which it is used.  This is to avoid
10519          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10520          * older server and then reload into that old version.  This can go away
10521          * once 8.3 is so old as to not be of interest to anyone.
10522          */
10523         if (fout->remoteVersion >= 90100)
10524         {
10525                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10526                                                   "amopopr::pg_catalog.regoperator, "
10527                                                   "opfname AS sortfamily, "
10528                                                   "nspname AS sortfamilynsp "
10529                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10530                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10531                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10532                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10533                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10534                                                   "AND refobjid = '%u'::pg_catalog.oid "
10535                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10536                                                   "ORDER BY amopstrategy",
10537                                                   opfinfo->dobj.catId.oid,
10538                                                   opfinfo->dobj.catId.oid);
10539         }
10540         else if (fout->remoteVersion >= 80400)
10541         {
10542                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10543                                                   "amopopr::pg_catalog.regoperator, "
10544                                                   "NULL AS sortfamily, "
10545                                                   "NULL AS sortfamilynsp "
10546                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10547                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10548                                                   "AND refobjid = '%u'::pg_catalog.oid "
10549                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10550                                                   "AND objid = ao.oid "
10551                                                   "ORDER BY amopstrategy",
10552                                                   opfinfo->dobj.catId.oid);
10553         }
10554         else
10555         {
10556                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10557                                                   "amopopr::pg_catalog.regoperator, "
10558                                                   "NULL AS sortfamily, "
10559                                                   "NULL AS sortfamilynsp "
10560                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10561                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10562                                                   "AND refobjid = '%u'::pg_catalog.oid "
10563                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10564                                                   "AND objid = ao.oid "
10565                                                   "ORDER BY amopstrategy",
10566                                                   opfinfo->dobj.catId.oid);
10567         }
10568
10569         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10570
10571         resetPQExpBuffer(query);
10572
10573         appendPQExpBuffer(query, "SELECT amprocnum, "
10574                                           "amproc::pg_catalog.regprocedure, "
10575                                           "amproclefttype::pg_catalog.regtype, "
10576                                           "amprocrighttype::pg_catalog.regtype "
10577                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10578                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10579                                           "AND refobjid = '%u'::pg_catalog.oid "
10580                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10581                                           "AND objid = ap.oid "
10582                                           "ORDER BY amprocnum",
10583                                           opfinfo->dobj.catId.oid);
10584
10585         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10586
10587         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10588         {
10589                 /* No loose members, so check contained opclasses */
10590                 resetPQExpBuffer(query);
10591
10592                 appendPQExpBuffer(query, "SELECT 1 "
10593                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10594                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10595                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10596                                                   "AND refobjid = f.oid "
10597                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10598                                                   "AND objid = c.oid "
10599                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10600                                                   "LIMIT 1",
10601                                                   opfinfo->dobj.catId.oid);
10602
10603                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10604
10605                 if (PQntuples(res) == 0)
10606                 {
10607                         /* no need to dump it, so bail out */
10608                         PQclear(res);
10609                         PQclear(res_ops);
10610                         PQclear(res_procs);
10611                         destroyPQExpBuffer(query);
10612                         destroyPQExpBuffer(q);
10613                         destroyPQExpBuffer(delq);
10614                         destroyPQExpBuffer(labelq);
10615                         return;
10616                 }
10617
10618                 PQclear(res);
10619         }
10620
10621         /* Get additional fields from the pg_opfamily row */
10622         resetPQExpBuffer(query);
10623
10624         appendPQExpBuffer(query, "SELECT "
10625          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10626                                           "FROM pg_catalog.pg_opfamily "
10627                                           "WHERE oid = '%u'::pg_catalog.oid",
10628                                           opfinfo->dobj.catId.oid);
10629
10630         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10631
10632         /* Expecting a single result only */
10633         ntups = PQntuples(res);
10634         if (ntups != 1)
10635         {
10636                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10637                                                            "query returned %d rows instead of one: %s\n",
10638                                                                  ntups),
10639                                   ntups, query->data);
10640                 exit_nicely();
10641         }
10642
10643         i_amname = PQfnumber(res, "amname");
10644
10645         /* amname will still be needed after we PQclear res */
10646         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10647
10648         /*
10649          * DROP must be fully qualified in case same name appears in pg_catalog
10650          */
10651         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10652                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10653         appendPQExpBuffer(delq, ".%s",
10654                                           fmtId(opfinfo->dobj.name));
10655         appendPQExpBuffer(delq, " USING %s;\n",
10656                                           fmtId(amname));
10657
10658         /* Build the fixed portion of the CREATE command */
10659         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10660                                           fmtId(opfinfo->dobj.name));
10661         appendPQExpBuffer(q, " USING %s;\n",
10662                                           fmtId(amname));
10663
10664         PQclear(res);
10665
10666         /* Do we need an ALTER to add loose members? */
10667         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10668         {
10669                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10670                                                   fmtId(opfinfo->dobj.name));
10671                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10672                                                   fmtId(amname));
10673
10674                 needComma = false;
10675
10676                 /*
10677                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10678                  */
10679                 ntups = PQntuples(res_ops);
10680
10681                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10682                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10683                 i_amopopr = PQfnumber(res_ops, "amopopr");
10684                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10685                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10686
10687                 for (i = 0; i < ntups; i++)
10688                 {
10689                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10690                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10691                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10692                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10693                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10694
10695                         if (needComma)
10696                                 appendPQExpBuffer(q, " ,\n    ");
10697
10698                         appendPQExpBuffer(q, "OPERATOR %s %s",
10699                                                           amopstrategy, amopopr);
10700
10701                         if (strlen(sortfamily) > 0)
10702                         {
10703                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10704                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10705                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10706                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10707                         }
10708
10709                         if (strcmp(amopreqcheck, "t") == 0)
10710                                 appendPQExpBuffer(q, " RECHECK");
10711
10712                         needComma = true;
10713                 }
10714
10715                 /*
10716                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10717                  */
10718                 ntups = PQntuples(res_procs);
10719
10720                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10721                 i_amproc = PQfnumber(res_procs, "amproc");
10722                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10723                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10724
10725                 for (i = 0; i < ntups; i++)
10726                 {
10727                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10728                         amproc = PQgetvalue(res_procs, i, i_amproc);
10729                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10730                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10731
10732                         if (needComma)
10733                                 appendPQExpBuffer(q, " ,\n    ");
10734
10735                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10736                                                           amprocnum, amproclefttype, amprocrighttype,
10737                                                           amproc);
10738
10739                         needComma = true;
10740                 }
10741
10742                 appendPQExpBuffer(q, ";\n");
10743         }
10744
10745         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10746                                           fmtId(opfinfo->dobj.name));
10747         appendPQExpBuffer(labelq, " USING %s",
10748                                           fmtId(amname));
10749
10750         if (binary_upgrade)
10751                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10752
10753         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10754                                  opfinfo->dobj.name,
10755                                  opfinfo->dobj.namespace->dobj.name,
10756                                  NULL,
10757                                  opfinfo->rolname,
10758                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10759                                  q->data, delq->data, NULL,
10760                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10761                                  NULL, NULL);
10762
10763         /* Dump Operator Family Comments */
10764         dumpComment(fout, labelq->data,
10765                                 NULL, opfinfo->rolname,
10766                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10767
10768         free(amname);
10769         PQclear(res_ops);
10770         PQclear(res_procs);
10771         destroyPQExpBuffer(query);
10772         destroyPQExpBuffer(q);
10773         destroyPQExpBuffer(delq);
10774         destroyPQExpBuffer(labelq);
10775 }
10776
10777 /*
10778  * dumpCollation
10779  *        write out a single collation definition
10780  */
10781 static void
10782 dumpCollation(Archive *fout, CollInfo *collinfo)
10783 {
10784         PQExpBuffer query;
10785         PQExpBuffer q;
10786         PQExpBuffer delq;
10787         PQExpBuffer labelq;
10788         PGresult   *res;
10789         int                     ntups;
10790         int                     i_collcollate;
10791         int                     i_collctype;
10792         const char *collcollate;
10793         const char *collctype;
10794
10795         /* Skip if not to be dumped */
10796         if (!collinfo->dobj.dump || dataOnly)
10797                 return;
10798
10799         query = createPQExpBuffer();
10800         q = createPQExpBuffer();
10801         delq = createPQExpBuffer();
10802         labelq = createPQExpBuffer();
10803
10804         /* Make sure we are in proper schema */
10805         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10806
10807         /* Get conversion-specific details */
10808         appendPQExpBuffer(query, "SELECT "
10809                                           "collcollate, "
10810                                           "collctype "
10811                                           "FROM pg_catalog.pg_collation c "
10812                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10813                                           collinfo->dobj.catId.oid);
10814
10815         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10816
10817         /* Expecting a single result only */
10818         ntups = PQntuples(res);
10819         if (ntups != 1)
10820         {
10821                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10822                                                            "query returned %d rows instead of one: %s\n",
10823                                                                  ntups),
10824                                   ntups, query->data);
10825                 exit_nicely();
10826         }
10827
10828         i_collcollate = PQfnumber(res, "collcollate");
10829         i_collctype = PQfnumber(res, "collctype");
10830
10831         collcollate = PQgetvalue(res, 0, i_collcollate);
10832         collctype = PQgetvalue(res, 0, i_collctype);
10833
10834         /*
10835          * DROP must be fully qualified in case same name appears in pg_catalog
10836          */
10837         appendPQExpBuffer(delq, "DROP COLLATION %s",
10838                                           fmtId(collinfo->dobj.namespace->dobj.name));
10839         appendPQExpBuffer(delq, ".%s;\n",
10840                                           fmtId(collinfo->dobj.name));
10841
10842         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10843                                           fmtId(collinfo->dobj.name));
10844         appendStringLiteralAH(q, collcollate, fout);
10845         appendPQExpBuffer(q, ", lc_ctype = ");
10846         appendStringLiteralAH(q, collctype, fout);
10847         appendPQExpBuffer(q, ");\n");
10848
10849         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10850
10851         if (binary_upgrade)
10852                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10853
10854         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10855                                  collinfo->dobj.name,
10856                                  collinfo->dobj.namespace->dobj.name,
10857                                  NULL,
10858                                  collinfo->rolname,
10859                                  false, "COLLATION", SECTION_PRE_DATA,
10860                                  q->data, delq->data, NULL,
10861                                  collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10862                                  NULL, NULL);
10863
10864         /* Dump Collation Comments */
10865         dumpComment(fout, labelq->data,
10866                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10867                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10868
10869         PQclear(res);
10870
10871         destroyPQExpBuffer(query);
10872         destroyPQExpBuffer(q);
10873         destroyPQExpBuffer(delq);
10874         destroyPQExpBuffer(labelq);
10875 }
10876
10877 /*
10878  * dumpConversion
10879  *        write out a single conversion definition
10880  */
10881 static void
10882 dumpConversion(Archive *fout, ConvInfo *convinfo)
10883 {
10884         PQExpBuffer query;
10885         PQExpBuffer q;
10886         PQExpBuffer delq;
10887         PQExpBuffer labelq;
10888         PGresult   *res;
10889         int                     ntups;
10890         int                     i_conforencoding;
10891         int                     i_contoencoding;
10892         int                     i_conproc;
10893         int                     i_condefault;
10894         const char *conforencoding;
10895         const char *contoencoding;
10896         const char *conproc;
10897         bool            condefault;
10898
10899         /* Skip if not to be dumped */
10900         if (!convinfo->dobj.dump || dataOnly)
10901                 return;
10902
10903         query = createPQExpBuffer();
10904         q = createPQExpBuffer();
10905         delq = createPQExpBuffer();
10906         labelq = createPQExpBuffer();
10907
10908         /* Make sure we are in proper schema */
10909         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10910
10911         /* Get conversion-specific details */
10912         appendPQExpBuffer(query, "SELECT "
10913                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10914                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10915                                           "conproc, condefault "
10916                                           "FROM pg_catalog.pg_conversion c "
10917                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10918                                           convinfo->dobj.catId.oid);
10919
10920         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10921
10922         /* Expecting a single result only */
10923         ntups = PQntuples(res);
10924         if (ntups != 1)
10925         {
10926                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10927                                                            "query returned %d rows instead of one: %s\n",
10928                                                                  ntups),
10929                                   ntups, query->data);
10930                 exit_nicely();
10931         }
10932
10933         i_conforencoding = PQfnumber(res, "conforencoding");
10934         i_contoencoding = PQfnumber(res, "contoencoding");
10935         i_conproc = PQfnumber(res, "conproc");
10936         i_condefault = PQfnumber(res, "condefault");
10937
10938         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10939         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10940         conproc = PQgetvalue(res, 0, i_conproc);
10941         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10942
10943         /*
10944          * DROP must be fully qualified in case same name appears in pg_catalog
10945          */
10946         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10947                                           fmtId(convinfo->dobj.namespace->dobj.name));
10948         appendPQExpBuffer(delq, ".%s;\n",
10949                                           fmtId(convinfo->dobj.name));
10950
10951         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10952                                           (condefault) ? "DEFAULT " : "",
10953                                           fmtId(convinfo->dobj.name));
10954         appendStringLiteralAH(q, conforencoding, fout);
10955         appendPQExpBuffer(q, " TO ");
10956         appendStringLiteralAH(q, contoencoding, fout);
10957         /* regproc is automatically quoted in 7.3 and above */
10958         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10959
10960         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10961
10962         if (binary_upgrade)
10963                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10964
10965         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10966                                  convinfo->dobj.name,
10967                                  convinfo->dobj.namespace->dobj.name,
10968                                  NULL,
10969                                  convinfo->rolname,
10970                                  false, "CONVERSION", SECTION_PRE_DATA,
10971                                  q->data, delq->data, NULL,
10972                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10973                                  NULL, NULL);
10974
10975         /* Dump Conversion Comments */
10976         dumpComment(fout, labelq->data,
10977                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10978                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10979
10980         PQclear(res);
10981
10982         destroyPQExpBuffer(query);
10983         destroyPQExpBuffer(q);
10984         destroyPQExpBuffer(delq);
10985         destroyPQExpBuffer(labelq);
10986 }
10987
10988 /*
10989  * format_aggregate_signature: generate aggregate name and argument list
10990  *
10991  * The argument type names are qualified if needed.  The aggregate name
10992  * is never qualified.
10993  */
10994 static char *
10995 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10996 {
10997         PQExpBufferData buf;
10998         int                     j;
10999
11000         initPQExpBuffer(&buf);
11001         if (honor_quotes)
11002                 appendPQExpBuffer(&buf, "%s",
11003                                                   fmtId(agginfo->aggfn.dobj.name));
11004         else
11005                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11006
11007         if (agginfo->aggfn.nargs == 0)
11008                 appendPQExpBuffer(&buf, "(*)");
11009         else
11010         {
11011                 appendPQExpBuffer(&buf, "(");
11012                 for (j = 0; j < agginfo->aggfn.nargs; j++)
11013                 {
11014                         char       *typname;
11015
11016                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11017                                                                                    zeroAsOpaque);
11018
11019                         appendPQExpBuffer(&buf, "%s%s",
11020                                                           (j > 0) ? ", " : "",
11021                                                           typname);
11022                         free(typname);
11023                 }
11024                 appendPQExpBuffer(&buf, ")");
11025         }
11026         return buf.data;
11027 }
11028
11029 /*
11030  * dumpAgg
11031  *        write out a single aggregate definition
11032  */
11033 static void
11034 dumpAgg(Archive *fout, AggInfo *agginfo)
11035 {
11036         PQExpBuffer query;
11037         PQExpBuffer q;
11038         PQExpBuffer delq;
11039         PQExpBuffer labelq;
11040         PQExpBuffer details;
11041         char       *aggsig;
11042         char       *aggsig_tag;
11043         PGresult   *res;
11044         int                     ntups;
11045         int                     i_aggtransfn;
11046         int                     i_aggfinalfn;
11047         int                     i_aggsortop;
11048         int                     i_aggtranstype;
11049         int                     i_agginitval;
11050         int                     i_convertok;
11051         const char *aggtransfn;
11052         const char *aggfinalfn;
11053         const char *aggsortop;
11054         const char *aggtranstype;
11055         const char *agginitval;
11056         bool            convertok;
11057
11058         /* Skip if not to be dumped */
11059         if (!agginfo->aggfn.dobj.dump || dataOnly)
11060                 return;
11061
11062         query = createPQExpBuffer();
11063         q = createPQExpBuffer();
11064         delq = createPQExpBuffer();
11065         labelq = createPQExpBuffer();
11066         details = createPQExpBuffer();
11067
11068         /* Make sure we are in proper schema */
11069         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11070
11071         /* Get aggregate-specific details */
11072         if (fout->remoteVersion >= 80100)
11073         {
11074                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11075                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11076                                                   "aggsortop::pg_catalog.regoperator, "
11077                                                   "agginitval, "
11078                                                   "'t'::boolean AS convertok "
11079                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11080                                                   "WHERE a.aggfnoid = p.oid "
11081                                                   "AND p.oid = '%u'::pg_catalog.oid",
11082                                                   agginfo->aggfn.dobj.catId.oid);
11083         }
11084         else if (fout->remoteVersion >= 70300)
11085         {
11086                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11087                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11088                                                   "0 AS aggsortop, "
11089                                                   "agginitval, "
11090                                                   "'t'::boolean AS convertok "
11091                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11092                                                   "WHERE a.aggfnoid = p.oid "
11093                                                   "AND p.oid = '%u'::pg_catalog.oid",
11094                                                   agginfo->aggfn.dobj.catId.oid);
11095         }
11096         else if (fout->remoteVersion >= 70100)
11097         {
11098                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11099                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
11100                                                   "0 AS aggsortop, "
11101                                                   "agginitval, "
11102                                                   "'t'::boolean AS convertok "
11103                                                   "FROM pg_aggregate "
11104                                                   "WHERE oid = '%u'::oid",
11105                                                   agginfo->aggfn.dobj.catId.oid);
11106         }
11107         else
11108         {
11109                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11110                                                   "aggfinalfn, "
11111                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11112                                                   "0 AS aggsortop, "
11113                                                   "agginitval1 AS agginitval, "
11114                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11115                                                   "FROM pg_aggregate "
11116                                                   "WHERE oid = '%u'::oid",
11117                                                   agginfo->aggfn.dobj.catId.oid);
11118         }
11119
11120         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11121
11122         /* Expecting a single result only */
11123         ntups = PQntuples(res);
11124         if (ntups != 1)
11125         {
11126                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11127                                                            "query returned %d rows instead of one: %s\n",
11128                                                                  ntups),
11129                                   ntups, query->data);
11130                 exit_nicely();
11131         }
11132
11133         i_aggtransfn = PQfnumber(res, "aggtransfn");
11134         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11135         i_aggsortop = PQfnumber(res, "aggsortop");
11136         i_aggtranstype = PQfnumber(res, "aggtranstype");
11137         i_agginitval = PQfnumber(res, "agginitval");
11138         i_convertok = PQfnumber(res, "convertok");
11139
11140         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11141         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11142         aggsortop = PQgetvalue(res, 0, i_aggsortop);
11143         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11144         agginitval = PQgetvalue(res, 0, i_agginitval);
11145         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11146
11147         aggsig = format_aggregate_signature(agginfo, fout, true);
11148         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11149
11150         if (!convertok)
11151         {
11152                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11153                                   aggsig);
11154                 return;
11155         }
11156
11157         if (fout->remoteVersion >= 70300)
11158         {
11159                 /* If using 7.3's regproc or regtype, data is already quoted */
11160                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11161                                                   aggtransfn,
11162                                                   aggtranstype);
11163         }
11164         else if (fout->remoteVersion >= 70100)
11165         {
11166                 /* format_type quotes, regproc does not */
11167                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11168                                                   fmtId(aggtransfn),
11169                                                   aggtranstype);
11170         }
11171         else
11172         {
11173                 /* need quotes all around */
11174                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
11175                                                   fmtId(aggtransfn));
11176                 appendPQExpBuffer(details, "    STYPE = %s",
11177                                                   fmtId(aggtranstype));
11178         }
11179
11180         if (!PQgetisnull(res, 0, i_agginitval))
11181         {
11182                 appendPQExpBuffer(details, ",\n    INITCOND = ");
11183                 appendStringLiteralAH(details, agginitval, fout);
11184         }
11185
11186         if (strcmp(aggfinalfn, "-") != 0)
11187         {
11188                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
11189                                                   aggfinalfn);
11190         }
11191
11192         aggsortop = convertOperatorReference(fout, aggsortop);
11193         if (aggsortop)
11194         {
11195                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
11196                                                   aggsortop);
11197         }
11198
11199         /*
11200          * DROP must be fully qualified in case same name appears in pg_catalog
11201          */
11202         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11203                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11204                                           aggsig);
11205
11206         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11207                                           aggsig, details->data);
11208
11209         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11210
11211         if (binary_upgrade)
11212                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11213
11214         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11215                                  aggsig_tag,
11216                                  agginfo->aggfn.dobj.namespace->dobj.name,
11217                                  NULL,
11218                                  agginfo->aggfn.rolname,
11219                                  false, "AGGREGATE", SECTION_PRE_DATA,
11220                                  q->data, delq->data, NULL,
11221                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
11222                                  NULL, NULL);
11223
11224         /* Dump Aggregate Comments */
11225         dumpComment(fout, labelq->data,
11226                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11227                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11228         dumpSecLabel(fout, labelq->data,
11229                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11230                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11231
11232         /*
11233          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11234          * command look like a function's GRANT; in particular this affects the
11235          * syntax for zero-argument aggregates.
11236          */
11237         free(aggsig);
11238         free(aggsig_tag);
11239
11240         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11241         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11242
11243         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11244                         "FUNCTION",
11245                         aggsig, NULL, aggsig_tag,
11246                         agginfo->aggfn.dobj.namespace->dobj.name,
11247                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11248
11249         free(aggsig);
11250         free(aggsig_tag);
11251
11252         PQclear(res);
11253
11254         destroyPQExpBuffer(query);
11255         destroyPQExpBuffer(q);
11256         destroyPQExpBuffer(delq);
11257         destroyPQExpBuffer(labelq);
11258         destroyPQExpBuffer(details);
11259 }
11260
11261 /*
11262  * dumpTSParser
11263  *        write out a single text search parser
11264  */
11265 static void
11266 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11267 {
11268         PQExpBuffer q;
11269         PQExpBuffer delq;
11270         PQExpBuffer labelq;
11271
11272         /* Skip if not to be dumped */
11273         if (!prsinfo->dobj.dump || dataOnly)
11274                 return;
11275
11276         q = createPQExpBuffer();
11277         delq = createPQExpBuffer();
11278         labelq = createPQExpBuffer();
11279
11280         /* Make sure we are in proper schema */
11281         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11282
11283         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11284                                           fmtId(prsinfo->dobj.name));
11285
11286         appendPQExpBuffer(q, "    START = %s,\n",
11287                                           convertTSFunction(fout, prsinfo->prsstart));
11288         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11289                                           convertTSFunction(fout, prsinfo->prstoken));
11290         appendPQExpBuffer(q, "    END = %s,\n",
11291                                           convertTSFunction(fout, prsinfo->prsend));
11292         if (prsinfo->prsheadline != InvalidOid)
11293                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11294                                                   convertTSFunction(fout, prsinfo->prsheadline));
11295         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11296                                           convertTSFunction(fout, prsinfo->prslextype));
11297
11298         /*
11299          * DROP must be fully qualified in case same name appears in pg_catalog
11300          */
11301         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11302                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11303         appendPQExpBuffer(delq, ".%s;\n",
11304                                           fmtId(prsinfo->dobj.name));
11305
11306         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11307                                           fmtId(prsinfo->dobj.name));
11308
11309         if (binary_upgrade)
11310                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11311
11312         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11313                                  prsinfo->dobj.name,
11314                                  prsinfo->dobj.namespace->dobj.name,
11315                                  NULL,
11316                                  "",
11317                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11318                                  q->data, delq->data, NULL,
11319                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11320                                  NULL, NULL);
11321
11322         /* Dump Parser Comments */
11323         dumpComment(fout, labelq->data,
11324                                 NULL, "",
11325                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11326
11327         destroyPQExpBuffer(q);
11328         destroyPQExpBuffer(delq);
11329         destroyPQExpBuffer(labelq);
11330 }
11331
11332 /*
11333  * dumpTSDictionary
11334  *        write out a single text search dictionary
11335  */
11336 static void
11337 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11338 {
11339         PQExpBuffer q;
11340         PQExpBuffer delq;
11341         PQExpBuffer labelq;
11342         PQExpBuffer query;
11343         PGresult   *res;
11344         int                     ntups;
11345         char       *nspname;
11346         char       *tmplname;
11347
11348         /* Skip if not to be dumped */
11349         if (!dictinfo->dobj.dump || dataOnly)
11350                 return;
11351
11352         q = createPQExpBuffer();
11353         delq = createPQExpBuffer();
11354         labelq = createPQExpBuffer();
11355         query = createPQExpBuffer();
11356
11357         /* Fetch name and namespace of the dictionary's template */
11358         selectSourceSchema(fout, "pg_catalog");
11359         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11360                                           "FROM pg_ts_template p, pg_namespace n "
11361                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11362                                           dictinfo->dicttemplate);
11363         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11364         ntups = PQntuples(res);
11365         if (ntups != 1)
11366         {
11367                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11368                                                            "query returned %d rows instead of one: %s\n",
11369                                                                  ntups),
11370                                   ntups, query->data);
11371                 exit_nicely();
11372         }
11373         nspname = PQgetvalue(res, 0, 0);
11374         tmplname = PQgetvalue(res, 0, 1);
11375
11376         /* Make sure we are in proper schema */
11377         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11378
11379         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11380                                           fmtId(dictinfo->dobj.name));
11381
11382         appendPQExpBuffer(q, "    TEMPLATE = ");
11383         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11384                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11385         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11386
11387         PQclear(res);
11388
11389         /* the dictinitoption can be dumped straight into the command */
11390         if (dictinfo->dictinitoption)
11391                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11392
11393         appendPQExpBuffer(q, " );\n");
11394
11395         /*
11396          * DROP must be fully qualified in case same name appears in pg_catalog
11397          */
11398         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11399                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11400         appendPQExpBuffer(delq, ".%s;\n",
11401                                           fmtId(dictinfo->dobj.name));
11402
11403         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11404                                           fmtId(dictinfo->dobj.name));
11405
11406         if (binary_upgrade)
11407                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11408
11409         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11410                                  dictinfo->dobj.name,
11411                                  dictinfo->dobj.namespace->dobj.name,
11412                                  NULL,
11413                                  dictinfo->rolname,
11414                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11415                                  q->data, delq->data, NULL,
11416                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11417                                  NULL, NULL);
11418
11419         /* Dump Dictionary Comments */
11420         dumpComment(fout, labelq->data,
11421                                 NULL, dictinfo->rolname,
11422                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11423
11424         destroyPQExpBuffer(q);
11425         destroyPQExpBuffer(delq);
11426         destroyPQExpBuffer(labelq);
11427         destroyPQExpBuffer(query);
11428 }
11429
11430 /*
11431  * dumpTSTemplate
11432  *        write out a single text search template
11433  */
11434 static void
11435 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11436 {
11437         PQExpBuffer q;
11438         PQExpBuffer delq;
11439         PQExpBuffer labelq;
11440
11441         /* Skip if not to be dumped */
11442         if (!tmplinfo->dobj.dump || dataOnly)
11443                 return;
11444
11445         q = createPQExpBuffer();
11446         delq = createPQExpBuffer();
11447         labelq = createPQExpBuffer();
11448
11449         /* Make sure we are in proper schema */
11450         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11451
11452         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11453                                           fmtId(tmplinfo->dobj.name));
11454
11455         if (tmplinfo->tmplinit != InvalidOid)
11456                 appendPQExpBuffer(q, "    INIT = %s,\n",
11457                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11458         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11459                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11460
11461         /*
11462          * DROP must be fully qualified in case same name appears in pg_catalog
11463          */
11464         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11465                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11466         appendPQExpBuffer(delq, ".%s;\n",
11467                                           fmtId(tmplinfo->dobj.name));
11468
11469         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11470                                           fmtId(tmplinfo->dobj.name));
11471
11472         if (binary_upgrade)
11473                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11474
11475         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11476                                  tmplinfo->dobj.name,
11477                                  tmplinfo->dobj.namespace->dobj.name,
11478                                  NULL,
11479                                  "",
11480                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11481                                  q->data, delq->data, NULL,
11482                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11483                                  NULL, NULL);
11484
11485         /* Dump Template Comments */
11486         dumpComment(fout, labelq->data,
11487                                 NULL, "",
11488                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11489
11490         destroyPQExpBuffer(q);
11491         destroyPQExpBuffer(delq);
11492         destroyPQExpBuffer(labelq);
11493 }
11494
11495 /*
11496  * dumpTSConfig
11497  *        write out a single text search configuration
11498  */
11499 static void
11500 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11501 {
11502         PQExpBuffer q;
11503         PQExpBuffer delq;
11504         PQExpBuffer labelq;
11505         PQExpBuffer query;
11506         PGresult   *res;
11507         char       *nspname;
11508         char       *prsname;
11509         int                     ntups,
11510                                 i;
11511         int                     i_tokenname;
11512         int                     i_dictname;
11513
11514         /* Skip if not to be dumped */
11515         if (!cfginfo->dobj.dump || dataOnly)
11516                 return;
11517
11518         q = createPQExpBuffer();
11519         delq = createPQExpBuffer();
11520         labelq = createPQExpBuffer();
11521         query = createPQExpBuffer();
11522
11523         /* Fetch name and namespace of the config's parser */
11524         selectSourceSchema(fout, "pg_catalog");
11525         appendPQExpBuffer(query, "SELECT nspname, prsname "
11526                                           "FROM pg_ts_parser p, pg_namespace n "
11527                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11528                                           cfginfo->cfgparser);
11529         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11530         ntups = PQntuples(res);
11531         if (ntups != 1)
11532         {
11533                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11534                                                            "query returned %d rows instead of one: %s\n",
11535                                                                  ntups),
11536                                   ntups, query->data);
11537                 exit_nicely();
11538         }
11539         nspname = PQgetvalue(res, 0, 0);
11540         prsname = PQgetvalue(res, 0, 1);
11541
11542         /* Make sure we are in proper schema */
11543         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11544
11545         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11546                                           fmtId(cfginfo->dobj.name));
11547
11548         appendPQExpBuffer(q, "    PARSER = ");
11549         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11550                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11551         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11552
11553         PQclear(res);
11554
11555         resetPQExpBuffer(query);
11556         appendPQExpBuffer(query,
11557                                           "SELECT \n"
11558                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11559                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11560                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11561                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11562                                           "WHERE m.mapcfg = '%u' \n"
11563                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11564                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11565
11566         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11567         ntups = PQntuples(res);
11568
11569         i_tokenname = PQfnumber(res, "tokenname");
11570         i_dictname = PQfnumber(res, "dictname");
11571
11572         for (i = 0; i < ntups; i++)
11573         {
11574                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11575                 char       *dictname = PQgetvalue(res, i, i_dictname);
11576
11577                 if (i == 0 ||
11578                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11579                 {
11580                         /* starting a new token type, so start a new command */
11581                         if (i > 0)
11582                                 appendPQExpBuffer(q, ";\n");
11583                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11584                                                           fmtId(cfginfo->dobj.name));
11585                         /* tokenname needs quoting, dictname does NOT */
11586                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11587                                                           fmtId(tokenname), dictname);
11588                 }
11589                 else
11590                         appendPQExpBuffer(q, ", %s", dictname);
11591         }
11592
11593         if (ntups > 0)
11594                 appendPQExpBuffer(q, ";\n");
11595
11596         PQclear(res);
11597
11598         /*
11599          * DROP must be fully qualified in case same name appears in pg_catalog
11600          */
11601         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11602                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11603         appendPQExpBuffer(delq, ".%s;\n",
11604                                           fmtId(cfginfo->dobj.name));
11605
11606         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11607                                           fmtId(cfginfo->dobj.name));
11608
11609         if (binary_upgrade)
11610                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11611
11612         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11613                                  cfginfo->dobj.name,
11614                                  cfginfo->dobj.namespace->dobj.name,
11615                                  NULL,
11616                                  cfginfo->rolname,
11617                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11618                                  q->data, delq->data, NULL,
11619                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11620                                  NULL, NULL);
11621
11622         /* Dump Configuration Comments */
11623         dumpComment(fout, labelq->data,
11624                                 NULL, cfginfo->rolname,
11625                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11626
11627         destroyPQExpBuffer(q);
11628         destroyPQExpBuffer(delq);
11629         destroyPQExpBuffer(labelq);
11630         destroyPQExpBuffer(query);
11631 }
11632
11633 /*
11634  * dumpForeignDataWrapper
11635  *        write out a single foreign-data wrapper definition
11636  */
11637 static void
11638 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11639 {
11640         PQExpBuffer q;
11641         PQExpBuffer delq;
11642         PQExpBuffer labelq;
11643         char       *qfdwname;
11644
11645         /* Skip if not to be dumped */
11646         if (!fdwinfo->dobj.dump || dataOnly)
11647                 return;
11648
11649         /*
11650          * FDWs that belong to an extension are dumped based on their "dump"
11651          * field. Otherwise omit them if we are only dumping some specific object.
11652          */
11653         if (!fdwinfo->dobj.ext_member)
11654                 if (!include_everything)
11655                         return;
11656
11657         q = createPQExpBuffer();
11658         delq = createPQExpBuffer();
11659         labelq = createPQExpBuffer();
11660
11661         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11662
11663         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11664                                           qfdwname);
11665
11666         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11667                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11668
11669         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11670                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11671
11672         if (strlen(fdwinfo->fdwoptions) > 0)
11673                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11674
11675         appendPQExpBuffer(q, ";\n");
11676
11677         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11678                                           qfdwname);
11679
11680         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11681                                           qfdwname);
11682
11683         if (binary_upgrade)
11684                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11685
11686         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11687                                  fdwinfo->dobj.name,
11688                                  NULL,
11689                                  NULL,
11690                                  fdwinfo->rolname,
11691                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11692                                  q->data, delq->data, NULL,
11693                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11694                                  NULL, NULL);
11695
11696         /* Handle the ACL */
11697         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11698                         "FOREIGN DATA WRAPPER",
11699                         qfdwname, NULL, fdwinfo->dobj.name,
11700                         NULL, fdwinfo->rolname,
11701                         fdwinfo->fdwacl);
11702
11703         /* Dump Foreign Data Wrapper Comments */
11704         dumpComment(fout, labelq->data,
11705                                 NULL, fdwinfo->rolname,
11706                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11707
11708         free(qfdwname);
11709
11710         destroyPQExpBuffer(q);
11711         destroyPQExpBuffer(delq);
11712         destroyPQExpBuffer(labelq);
11713 }
11714
11715 /*
11716  * dumpForeignServer
11717  *        write out a foreign server definition
11718  */
11719 static void
11720 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11721 {
11722         PQExpBuffer q;
11723         PQExpBuffer delq;
11724         PQExpBuffer labelq;
11725         PQExpBuffer query;
11726         PGresult   *res;
11727         int                     ntups;
11728         char       *qsrvname;
11729         char       *fdwname;
11730
11731         /* Skip if not to be dumped */
11732         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11733                 return;
11734
11735         q = createPQExpBuffer();
11736         delq = createPQExpBuffer();
11737         labelq = createPQExpBuffer();
11738         query = createPQExpBuffer();
11739
11740         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11741
11742         /* look up the foreign-data wrapper */
11743         selectSourceSchema(fout, "pg_catalog");
11744         appendPQExpBuffer(query, "SELECT fdwname "
11745                                           "FROM pg_foreign_data_wrapper w "
11746                                           "WHERE w.oid = '%u'",
11747                                           srvinfo->srvfdw);
11748         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11749         ntups = PQntuples(res);
11750         if (ntups != 1)
11751         {
11752                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11753                                                            "query returned %d rows instead of one: %s\n",
11754                                                                  ntups),
11755                                   ntups, query->data);
11756                 exit_nicely();
11757         }
11758         fdwname = PQgetvalue(res, 0, 0);
11759
11760         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11761         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11762         {
11763                 appendPQExpBuffer(q, " TYPE ");
11764                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11765         }
11766         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11767         {
11768                 appendPQExpBuffer(q, " VERSION ");
11769                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11770         }
11771
11772         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11773         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11774
11775         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11776                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11777
11778         appendPQExpBuffer(q, ";\n");
11779
11780         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11781                                           qsrvname);
11782
11783         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11784
11785         if (binary_upgrade)
11786                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11787
11788         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11789                                  srvinfo->dobj.name,
11790                                  NULL,
11791                                  NULL,
11792                                  srvinfo->rolname,
11793                                  false, "SERVER", SECTION_PRE_DATA,
11794                                  q->data, delq->data, NULL,
11795                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11796                                  NULL, NULL);
11797
11798         /* Handle the ACL */
11799         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11800                         "FOREIGN SERVER",
11801                         qsrvname, NULL, srvinfo->dobj.name,
11802                         NULL, srvinfo->rolname,
11803                         srvinfo->srvacl);
11804
11805         /* Dump user mappings */
11806         dumpUserMappings(fout,
11807                                          srvinfo->dobj.name, NULL,
11808                                          srvinfo->rolname,
11809                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11810
11811         /* Dump Foreign Server Comments */
11812         dumpComment(fout, labelq->data,
11813                                 NULL, srvinfo->rolname,
11814                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11815
11816         free(qsrvname);
11817
11818         destroyPQExpBuffer(q);
11819         destroyPQExpBuffer(delq);
11820         destroyPQExpBuffer(labelq);
11821 }
11822
11823 /*
11824  * dumpUserMappings
11825  *
11826  * This routine is used to dump any user mappings associated with the
11827  * server handed to this routine. Should be called after ArchiveEntry()
11828  * for the server.
11829  */
11830 static void
11831 dumpUserMappings(Archive *fout,
11832                                  const char *servername, const char *namespace,
11833                                  const char *owner,
11834                                  CatalogId catalogId, DumpId dumpId)
11835 {
11836         PQExpBuffer q;
11837         PQExpBuffer delq;
11838         PQExpBuffer query;
11839         PQExpBuffer tag;
11840         PGresult   *res;
11841         int                     ntups;
11842         int                     i_usename;
11843         int                     i_umoptions;
11844         int                     i;
11845
11846         q = createPQExpBuffer();
11847         tag = createPQExpBuffer();
11848         delq = createPQExpBuffer();
11849         query = createPQExpBuffer();
11850
11851         /*
11852          * We read from the publicly accessible view pg_user_mappings, so as not
11853          * to fail if run by a non-superuser.  Note that the view will show
11854          * umoptions as null if the user hasn't got privileges for the associated
11855          * server; this means that pg_dump will dump such a mapping, but with no
11856          * OPTIONS clause.      A possible alternative is to skip such mappings
11857          * altogether, but it's not clear that that's an improvement.
11858          */
11859         selectSourceSchema(fout, "pg_catalog");
11860
11861         appendPQExpBuffer(query,
11862                                           "SELECT usename, "
11863                                           "array_to_string(ARRAY("
11864                                           "SELECT quote_ident(option_name) || ' ' || "
11865                                           "quote_literal(option_value) "
11866                                           "FROM pg_options_to_table(umoptions) "
11867                                           "ORDER BY option_name"
11868                                           "), E',\n    ') AS umoptions "
11869                                           "FROM pg_user_mappings "
11870                                           "WHERE srvid = '%u' "
11871                                           "ORDER BY usename",
11872                                           catalogId.oid);
11873
11874         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11875
11876         ntups = PQntuples(res);
11877         i_usename = PQfnumber(res, "usename");
11878         i_umoptions = PQfnumber(res, "umoptions");
11879
11880         for (i = 0; i < ntups; i++)
11881         {
11882                 char       *usename;
11883                 char       *umoptions;
11884
11885                 usename = PQgetvalue(res, i, i_usename);
11886                 umoptions = PQgetvalue(res, i, i_umoptions);
11887
11888                 resetPQExpBuffer(q);
11889                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11890                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11891
11892                 if (umoptions && strlen(umoptions) > 0)
11893                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11894
11895                 appendPQExpBuffer(q, ";\n");
11896
11897                 resetPQExpBuffer(delq);
11898                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11899                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11900
11901                 resetPQExpBuffer(tag);
11902                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11903                                                   usename, servername);
11904
11905                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11906                                          tag->data,
11907                                          namespace,
11908                                          NULL,
11909                                          owner, false,
11910                                          "USER MAPPING", SECTION_PRE_DATA,
11911                                          q->data, delq->data, NULL,
11912                                          &dumpId, 1,
11913                                          NULL, NULL);
11914         }
11915
11916         PQclear(res);
11917
11918         destroyPQExpBuffer(query);
11919         destroyPQExpBuffer(delq);
11920         destroyPQExpBuffer(q);
11921 }
11922
11923 /*
11924  * Write out default privileges information
11925  */
11926 static void
11927 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11928 {
11929         PQExpBuffer q;
11930         PQExpBuffer tag;
11931         const char *type;
11932
11933         /* Skip if not to be dumped */
11934         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11935                 return;
11936
11937         q = createPQExpBuffer();
11938         tag = createPQExpBuffer();
11939
11940         switch (daclinfo->defaclobjtype)
11941         {
11942                 case DEFACLOBJ_RELATION:
11943                         type = "TABLES";
11944                         break;
11945                 case DEFACLOBJ_SEQUENCE:
11946                         type = "SEQUENCES";
11947                         break;
11948                 case DEFACLOBJ_FUNCTION:
11949                         type = "FUNCTIONS";
11950                         break;
11951                 default:
11952                         /* shouldn't get here */
11953                         write_msg(NULL, "unknown object type (%d) in default privileges\n",
11954                                           (int) daclinfo->defaclobjtype);
11955                         exit_nicely();
11956                         type = "";                      /* keep compiler quiet */
11957         }
11958
11959         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11960
11961         /* build the actual command(s) for this tuple */
11962         if (!buildDefaultACLCommands(type,
11963                                                                  daclinfo->dobj.namespace != NULL ?
11964                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11965                                                                  daclinfo->defaclacl,
11966                                                                  daclinfo->defaclrole,
11967                                                                  fout->remoteVersion,
11968                                                                  q))
11969         {
11970                 write_msg(NULL, "could not parse default ACL list (%s)\n",
11971                                   daclinfo->defaclacl);
11972                 exit_nicely();
11973         }
11974
11975         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11976                                  tag->data,
11977            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11978                                  NULL,
11979                                  daclinfo->defaclrole,
11980                                  false, "DEFAULT ACL", SECTION_NONE,
11981                                  q->data, "", NULL,
11982                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11983                                  NULL, NULL);
11984
11985         destroyPQExpBuffer(tag);
11986         destroyPQExpBuffer(q);
11987 }
11988
11989 /*----------
11990  * Write out grant/revoke information
11991  *
11992  * 'objCatId' is the catalog ID of the underlying object.
11993  * 'objDumpId' is the dump ID of the underlying object.
11994  * 'type' must be one of
11995  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11996  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11997  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11998  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11999  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12000  * 'nspname' is the namespace the object is in (NULL if none).
12001  * 'owner' is the owner, NULL if there is no owner (for languages).
12002  * 'acls' is the string read out of the fooacl system catalog field;
12003  *              it will be parsed here.
12004  *----------
12005  */
12006 static void
12007 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12008                 const char *type, const char *name, const char *subname,
12009                 const char *tag, const char *nspname, const char *owner,
12010                 const char *acls)
12011 {
12012         PQExpBuffer sql;
12013
12014         /* Do nothing if ACL dump is not enabled */
12015         if (aclsSkip)
12016                 return;
12017
12018         /* --data-only skips ACLs *except* BLOB ACLs */
12019         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12020                 return;
12021
12022         sql = createPQExpBuffer();
12023
12024         if (!buildACLCommands(name, subname, type, acls, owner,
12025                                                   "", fout->remoteVersion, sql))
12026         {
12027                 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12028                                   acls, name, type);
12029                 exit_nicely();
12030         }
12031
12032         if (sql->len > 0)
12033                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12034                                          tag, nspname,
12035                                          NULL,
12036                                          owner ? owner : "",
12037                                          false, "ACL", SECTION_NONE,
12038                                          sql->data, "", NULL,
12039                                          &(objDumpId), 1,
12040                                          NULL, NULL);
12041
12042         destroyPQExpBuffer(sql);
12043 }
12044
12045 /*
12046  * dumpSecLabel
12047  *
12048  * This routine is used to dump any security labels associated with the
12049  * object handed to this routine. The routine takes a constant character
12050  * string for the target part of the security-label command, plus
12051  * the namespace and owner of the object (for labeling the ArchiveEntry),
12052  * plus catalog ID and subid which are the lookup key for pg_seclabel,
12053  * plus the dump ID for the object (for setting a dependency).
12054  * If a matching pg_seclabel entry is found, it is dumped.
12055  *
12056  * Note: although this routine takes a dumpId for dependency purposes,
12057  * that purpose is just to mark the dependency in the emitted dump file
12058  * for possible future use by pg_restore.  We do NOT use it for determining
12059  * ordering of the label in the dump file, because this routine is called
12060  * after dependency sorting occurs.  This routine should be called just after
12061  * calling ArchiveEntry() for the specified object.
12062  */
12063 static void
12064 dumpSecLabel(Archive *fout, const char *target,
12065                          const char *namespace, const char *owner,
12066                          CatalogId catalogId, int subid, DumpId dumpId)
12067 {
12068         SecLabelItem *labels;
12069         int                     nlabels;
12070         int                     i;
12071         PQExpBuffer query;
12072
12073         /* do nothing, if --no-security-labels is supplied */
12074         if (no_security_labels)
12075                 return;
12076
12077         /* Comments are schema not data ... except blob comments are data */
12078         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12079         {
12080                 if (dataOnly)
12081                         return;
12082         }
12083         else
12084         {
12085                 if (schemaOnly)
12086                         return;
12087         }
12088
12089         /* Search for security labels associated with catalogId, using table */
12090         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12091
12092         query = createPQExpBuffer();
12093
12094         for (i = 0; i < nlabels; i++)
12095         {
12096                 /*
12097                  * Ignore label entries for which the subid doesn't match.
12098                  */
12099                 if (labels[i].objsubid != subid)
12100                         continue;
12101
12102                 appendPQExpBuffer(query,
12103                                                   "SECURITY LABEL FOR %s ON %s IS ",
12104                                                   fmtId(labels[i].provider), target);
12105                 appendStringLiteralAH(query, labels[i].label, fout);
12106                 appendPQExpBuffer(query, ";\n");
12107         }
12108
12109         if (query->len > 0)
12110         {
12111                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12112                                          target, namespace, NULL, owner,
12113                                          false, "SECURITY LABEL", SECTION_NONE,
12114                                          query->data, "", NULL,
12115                                          &(dumpId), 1,
12116                                          NULL, NULL);
12117         }
12118         destroyPQExpBuffer(query);
12119 }
12120
12121 /*
12122  * dumpTableSecLabel
12123  *
12124  * As above, but dump security label for both the specified table (or view)
12125  * and its columns.
12126  */
12127 static void
12128 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12129 {
12130         SecLabelItem *labels;
12131         int                     nlabels;
12132         int                     i;
12133         PQExpBuffer query;
12134         PQExpBuffer target;
12135
12136         /* do nothing, if --no-security-labels is supplied */
12137         if (no_security_labels)
12138                 return;
12139
12140         /* SecLabel are SCHEMA not data */
12141         if (dataOnly)
12142                 return;
12143
12144         /* Search for comments associated with relation, using table */
12145         nlabels = findSecLabels(fout,
12146                                                         tbinfo->dobj.catId.tableoid,
12147                                                         tbinfo->dobj.catId.oid,
12148                                                         &labels);
12149
12150         /* If security labels exist, build SECURITY LABEL statements */
12151         if (nlabels <= 0)
12152                 return;
12153
12154         query = createPQExpBuffer();
12155         target = createPQExpBuffer();
12156
12157         for (i = 0; i < nlabels; i++)
12158         {
12159                 const char *colname;
12160                 const char *provider = labels[i].provider;
12161                 const char *label = labels[i].label;
12162                 int                     objsubid = labels[i].objsubid;
12163
12164                 resetPQExpBuffer(target);
12165                 if (objsubid == 0)
12166                 {
12167                         appendPQExpBuffer(target, "%s %s", reltypename,
12168                                                           fmtId(tbinfo->dobj.name));
12169                 }
12170                 else
12171                 {
12172                         colname = getAttrName(objsubid, tbinfo);
12173                         /* first fmtId result must be consumed before calling it again */
12174                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12175                         appendPQExpBuffer(target, ".%s", fmtId(colname));
12176                 }
12177                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12178                                                   fmtId(provider), target->data);
12179                 appendStringLiteralAH(query, label, fout);
12180                 appendPQExpBuffer(query, ";\n");
12181         }
12182         if (query->len > 0)
12183         {
12184                 resetPQExpBuffer(target);
12185                 appendPQExpBuffer(target, "%s %s", reltypename,
12186                                                   fmtId(tbinfo->dobj.name));
12187                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12188                                          target->data,
12189                                          tbinfo->dobj.namespace->dobj.name,
12190                                          NULL, tbinfo->rolname,
12191                                          false, "SECURITY LABEL", SECTION_NONE,
12192                                          query->data, "", NULL,
12193                                          &(tbinfo->dobj.dumpId), 1,
12194                                          NULL, NULL);
12195         }
12196         destroyPQExpBuffer(query);
12197         destroyPQExpBuffer(target);
12198 }
12199
12200 /*
12201  * findSecLabels
12202  *
12203  * Find the security label(s), if any, associated with the given object.
12204  * All the objsubid values associated with the given classoid/objoid are
12205  * found with one search.
12206  */
12207 static int
12208 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12209 {
12210         /* static storage for table of security labels */
12211         static SecLabelItem *labels = NULL;
12212         static int      nlabels = -1;
12213
12214         SecLabelItem *middle = NULL;
12215         SecLabelItem *low;
12216         SecLabelItem *high;
12217         int                     nmatch;
12218
12219         /* Get security labels if we didn't already */
12220         if (nlabels < 0)
12221                 nlabels = collectSecLabels(fout, &labels);
12222
12223         if (nlabels <= 0)                       /* no labels, so no match is possible */
12224         {
12225                 *items = NULL;
12226                 return 0;
12227         }
12228
12229         /*
12230          * Do binary search to find some item matching the object.
12231          */
12232         low = &labels[0];
12233         high = &labels[nlabels - 1];
12234         while (low <= high)
12235         {
12236                 middle = low + (high - low) / 2;
12237
12238                 if (classoid < middle->classoid)
12239                         high = middle - 1;
12240                 else if (classoid > middle->classoid)
12241                         low = middle + 1;
12242                 else if (objoid < middle->objoid)
12243                         high = middle - 1;
12244                 else if (objoid > middle->objoid)
12245                         low = middle + 1;
12246                 else
12247                         break;                          /* found a match */
12248         }
12249
12250         if (low > high)                         /* no matches */
12251         {
12252                 *items = NULL;
12253                 return 0;
12254         }
12255
12256         /*
12257          * Now determine how many items match the object.  The search loop
12258          * invariant still holds: only items between low and high inclusive could
12259          * match.
12260          */
12261         nmatch = 1;
12262         while (middle > low)
12263         {
12264                 if (classoid != middle[-1].classoid ||
12265                         objoid != middle[-1].objoid)
12266                         break;
12267                 middle--;
12268                 nmatch++;
12269         }
12270
12271         *items = middle;
12272
12273         middle += nmatch;
12274         while (middle <= high)
12275         {
12276                 if (classoid != middle->classoid ||
12277                         objoid != middle->objoid)
12278                         break;
12279                 middle++;
12280                 nmatch++;
12281         }
12282
12283         return nmatch;
12284 }
12285
12286 /*
12287  * collectSecLabels
12288  *
12289  * Construct a table of all security labels available for database objects.
12290  * It's much faster to pull them all at once.
12291  *
12292  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12293  */
12294 static int
12295 collectSecLabels(Archive *fout, SecLabelItem **items)
12296 {
12297         PGresult   *res;
12298         PQExpBuffer query;
12299         int                     i_label;
12300         int                     i_provider;
12301         int                     i_classoid;
12302         int                     i_objoid;
12303         int                     i_objsubid;
12304         int                     ntups;
12305         int                     i;
12306         SecLabelItem *labels;
12307
12308         query = createPQExpBuffer();
12309
12310         appendPQExpBuffer(query,
12311                                           "SELECT label, provider, classoid, objoid, objsubid "
12312                                           "FROM pg_catalog.pg_seclabel "
12313                                           "ORDER BY classoid, objoid, objsubid");
12314
12315         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12316
12317         /* Construct lookup table containing OIDs in numeric form */
12318         i_label = PQfnumber(res, "label");
12319         i_provider = PQfnumber(res, "provider");
12320         i_classoid = PQfnumber(res, "classoid");
12321         i_objoid = PQfnumber(res, "objoid");
12322         i_objsubid = PQfnumber(res, "objsubid");
12323
12324         ntups = PQntuples(res);
12325
12326         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12327
12328         for (i = 0; i < ntups; i++)
12329         {
12330                 labels[i].label = PQgetvalue(res, i, i_label);
12331                 labels[i].provider = PQgetvalue(res, i, i_provider);
12332                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12333                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12334                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12335         }
12336
12337         /* Do NOT free the PGresult since we are keeping pointers into it */
12338         destroyPQExpBuffer(query);
12339
12340         *items = labels;
12341         return ntups;
12342 }
12343
12344 /*
12345  * dumpTable
12346  *        write out to fout the declarations (not data) of a user-defined table
12347  */
12348 static void
12349 dumpTable(Archive *fout, TableInfo *tbinfo)
12350 {
12351         if (tbinfo->dobj.dump)
12352         {
12353                 char       *namecopy;
12354
12355                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12356                         dumpSequence(fout, tbinfo);
12357                 else if (!dataOnly)
12358                         dumpTableSchema(fout, tbinfo);
12359
12360                 /* Handle the ACL here */
12361                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12362                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12363                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12364                                 "TABLE",
12365                                 namecopy, NULL, tbinfo->dobj.name,
12366                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12367                                 tbinfo->relacl);
12368
12369                 /*
12370                  * Handle column ACLs, if any.  Note: we pull these with a separate
12371                  * query rather than trying to fetch them during getTableAttrs, so
12372                  * that we won't miss ACLs on system columns.
12373                  */
12374                 if (fout->remoteVersion >= 80400)
12375                 {
12376                         PQExpBuffer query = createPQExpBuffer();
12377                         PGresult   *res;
12378                         int                     i;
12379
12380                         appendPQExpBuffer(query,
12381                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12382                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12383                                                           "ORDER BY attnum",
12384                                                           tbinfo->dobj.catId.oid);
12385                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12386
12387                         for (i = 0; i < PQntuples(res); i++)
12388                         {
12389                                 char       *attname = PQgetvalue(res, i, 0);
12390                                 char       *attacl = PQgetvalue(res, i, 1);
12391                                 char       *attnamecopy;
12392                                 char       *acltag;
12393
12394                                 attnamecopy = pg_strdup(fmtId(attname));
12395                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12396                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12397                                 /* Column's GRANT type is always TABLE */
12398                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12399                                                 namecopy, attnamecopy, acltag,
12400                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12401                                                 attacl);
12402                                 free(attnamecopy);
12403                                 free(acltag);
12404                         }
12405                         PQclear(res);
12406                         destroyPQExpBuffer(query);
12407                 }
12408
12409                 free(namecopy);
12410         }
12411 }
12412
12413 /*
12414  * dumpTableSchema
12415  *        write the declaration (not data) of one user-defined table or view
12416  */
12417 static void
12418 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12419 {
12420         PQExpBuffer query = createPQExpBuffer();
12421         PQExpBuffer q = createPQExpBuffer();
12422         PQExpBuffer delq = createPQExpBuffer();
12423         PQExpBuffer labelq = createPQExpBuffer();
12424         PGresult   *res;
12425         int                     numParents;
12426         TableInfo **parents;
12427         int                     actual_atts;    /* number of attrs in this CREATE statment */
12428         const char *reltypename;
12429         char       *storage;
12430         char       *srvname;
12431         char       *ftoptions;
12432         int                     j,
12433                                 k;
12434
12435         /* Make sure we are in proper schema */
12436         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12437
12438         if (binary_upgrade)
12439                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12440                                                                                                 tbinfo->dobj.catId.oid);
12441
12442         /* Is it a table or a view? */
12443         if (tbinfo->relkind == RELKIND_VIEW)
12444         {
12445                 char       *viewdef;
12446
12447                 reltypename = "VIEW";
12448
12449                 /* Fetch the view definition */
12450                 if (fout->remoteVersion >= 70300)
12451                 {
12452                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12453                         appendPQExpBuffer(query,
12454                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12455                                                           tbinfo->dobj.catId.oid);
12456                 }
12457                 else
12458                 {
12459                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12460                                                           "FROM pg_views WHERE viewname = ");
12461                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12462                         appendPQExpBuffer(query, ";");
12463                 }
12464
12465                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12466
12467                 if (PQntuples(res) != 1)
12468                 {
12469                         if (PQntuples(res) < 1)
12470                                 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12471                                                   tbinfo->dobj.name);
12472                         else
12473                                 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12474                                                   tbinfo->dobj.name);
12475                         exit_nicely();
12476                 }
12477
12478                 viewdef = PQgetvalue(res, 0, 0);
12479
12480                 if (strlen(viewdef) == 0)
12481                 {
12482                         write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12483                                           tbinfo->dobj.name);
12484                         exit_nicely();
12485                 }
12486
12487                 /*
12488                  * DROP must be fully qualified in case same name appears in
12489                  * pg_catalog
12490                  */
12491                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12492                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12493                 appendPQExpBuffer(delq, "%s;\n",
12494                                                   fmtId(tbinfo->dobj.name));
12495
12496                 if (binary_upgrade)
12497                         binary_upgrade_set_pg_class_oids(fout, q,
12498                                                                                          tbinfo->dobj.catId.oid, false);
12499
12500                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12501                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12502                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12503                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12504
12505                 appendPQExpBuffer(labelq, "VIEW %s",
12506                                                   fmtId(tbinfo->dobj.name));
12507
12508                 PQclear(res);
12509         }
12510         else
12511         {
12512                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12513                 {
12514                         int                     i_srvname;
12515                         int                     i_ftoptions;
12516
12517                         reltypename = "FOREIGN TABLE";
12518
12519                         /* retrieve name of foreign server and generic options */
12520                         appendPQExpBuffer(query,
12521                                                           "SELECT fs.srvname, "
12522                                                           "pg_catalog.array_to_string(ARRAY("
12523                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12524                                                           "' ' || pg_catalog.quote_literal(option_value) "
12525                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
12526                                                           "ORDER BY option_name"
12527                                                           "), E',\n    ') AS ftoptions "
12528                                                           "FROM pg_catalog.pg_foreign_table ft "
12529                                                           "JOIN pg_catalog.pg_foreign_server fs "
12530                                                           "ON (fs.oid = ft.ftserver) "
12531                                                           "WHERE ft.ftrelid = '%u'",
12532                                                           tbinfo->dobj.catId.oid);
12533                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12534                         if (PQntuples(res) != 1)
12535                         {
12536                                 write_msg(NULL, ngettext("query returned %d foreign server entry for foreign table \"%s\"\n",
12537                                                                                  "query returned %d foreign server entries for foreign table \"%s\"\n",
12538                                                                                  PQntuples(res)),
12539                                                   PQntuples(res), tbinfo->dobj.name);
12540                                 exit_nicely();
12541                         }
12542                         i_srvname = PQfnumber(res, "srvname");
12543                         i_ftoptions = PQfnumber(res, "ftoptions");
12544                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12545                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12546                         PQclear(res);
12547                 }
12548                 else
12549                 {
12550                         reltypename = "TABLE";
12551                         srvname = NULL;
12552                         ftoptions = NULL;
12553                 }
12554                 numParents = tbinfo->numParents;
12555                 parents = tbinfo->parents;
12556
12557                 /*
12558                  * DROP must be fully qualified in case same name appears in
12559                  * pg_catalog
12560                  */
12561                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12562                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12563                 appendPQExpBuffer(delq, "%s;\n",
12564                                                   fmtId(tbinfo->dobj.name));
12565
12566                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12567                                                   fmtId(tbinfo->dobj.name));
12568
12569                 if (binary_upgrade)
12570                         binary_upgrade_set_pg_class_oids(fout, q,
12571                                                                                          tbinfo->dobj.catId.oid, false);
12572
12573                 appendPQExpBuffer(q, "CREATE %s%s %s",
12574                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12575                                                   "UNLOGGED " : "",
12576                                                   reltypename,
12577                                                   fmtId(tbinfo->dobj.name));
12578
12579                 /*
12580                  * Attach to type, if reloftype; except in case of a binary upgrade,
12581                  * we dump the table normally and attach it to the type afterward.
12582                  */
12583                 if (tbinfo->reloftype && !binary_upgrade)
12584                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12585
12586                 /* Dump the attributes */
12587                 actual_atts = 0;
12588                 for (j = 0; j < tbinfo->numatts; j++)
12589                 {
12590                         /*
12591                          * Normally, dump if it's locally defined in this table, and not
12592                          * dropped.  But for binary upgrade, we'll dump all the columns,
12593                          * and then fix up the dropped and nonlocal cases below.
12594                          */
12595                         if (shouldPrintColumn(tbinfo, j))
12596                         {
12597                                 /*
12598                                  * Default value --- suppress if to be printed separately.
12599                                  */
12600                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12601                                                                                    !tbinfo->attrdefs[j]->separate);
12602
12603                                 /*
12604                                  * Not Null constraint --- suppress if inherited, except in
12605                                  * binary-upgrade case where that won't work.
12606                                  */
12607                                 bool            has_notnull = (tbinfo->notnull[j] &&
12608                                                                                    (!tbinfo->inhNotNull[j] ||
12609                                                                                         binary_upgrade));
12610
12611                                 /* Skip column if fully defined by reloftype */
12612                                 if (tbinfo->reloftype &&
12613                                         !has_default && !has_notnull && !binary_upgrade)
12614                                         continue;
12615
12616                                 /* Format properly if not first attr */
12617                                 if (actual_atts == 0)
12618                                         appendPQExpBuffer(q, " (");
12619                                 else
12620                                         appendPQExpBuffer(q, ",");
12621                                 appendPQExpBuffer(q, "\n    ");
12622                                 actual_atts++;
12623
12624                                 /* Attribute name */
12625                                 appendPQExpBuffer(q, "%s ",
12626                                                                   fmtId(tbinfo->attnames[j]));
12627
12628                                 if (tbinfo->attisdropped[j])
12629                                 {
12630                                         /*
12631                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12632                                          * so we will not have gotten a valid type name; insert
12633                                          * INTEGER as a stopgap.  We'll clean things up later.
12634                                          */
12635                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12636                                         /* Skip all the rest, too */
12637                                         continue;
12638                                 }
12639
12640                                 /* Attribute type */
12641                                 if (tbinfo->reloftype && !binary_upgrade)
12642                                 {
12643                                         appendPQExpBuffer(q, "WITH OPTIONS");
12644                                 }
12645                                 else if (fout->remoteVersion >= 70100)
12646                                 {
12647                                         appendPQExpBuffer(q, "%s",
12648                                                                           tbinfo->atttypnames[j]);
12649                                 }
12650                                 else
12651                                 {
12652                                         /* If no format_type, fake it */
12653                                         appendPQExpBuffer(q, "%s",
12654                                                                           myFormatType(tbinfo->atttypnames[j],
12655                                                                                                    tbinfo->atttypmod[j]));
12656                                 }
12657
12658                                 /* Add collation if not default for the type */
12659                                 if (OidIsValid(tbinfo->attcollation[j]))
12660                                 {
12661                                         CollInfo   *coll;
12662
12663                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12664                                         if (coll)
12665                                         {
12666                                                 /* always schema-qualify, don't try to be smart */
12667                                                 appendPQExpBuffer(q, " COLLATE %s.",
12668                                                                          fmtId(coll->dobj.namespace->dobj.name));
12669                                                 appendPQExpBuffer(q, "%s",
12670                                                                                   fmtId(coll->dobj.name));
12671                                         }
12672                                 }
12673
12674                                 if (has_default)
12675                                         appendPQExpBuffer(q, " DEFAULT %s",
12676                                                                           tbinfo->attrdefs[j]->adef_expr);
12677
12678                                 if (has_notnull)
12679                                         appendPQExpBuffer(q, " NOT NULL");
12680                         }
12681                 }
12682
12683                 /*
12684                  * Add non-inherited CHECK constraints, if any.
12685                  */
12686                 for (j = 0; j < tbinfo->ncheck; j++)
12687                 {
12688                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12689
12690                         if (constr->separate || !constr->conislocal)
12691                                 continue;
12692
12693                         if (actual_atts == 0)
12694                                 appendPQExpBuffer(q, " (\n    ");
12695                         else
12696                                 appendPQExpBuffer(q, ",\n    ");
12697
12698                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12699                                                           fmtId(constr->dobj.name));
12700                         appendPQExpBuffer(q, "%s", constr->condef);
12701
12702                         actual_atts++;
12703                 }
12704
12705                 if (actual_atts)
12706                         appendPQExpBuffer(q, "\n)");
12707                 else if (!(tbinfo->reloftype && !binary_upgrade))
12708                 {
12709                         /*
12710                          * We must have a parenthesized attribute list, even though empty,
12711                          * when not using the OF TYPE syntax.
12712                          */
12713                         appendPQExpBuffer(q, " (\n)");
12714                 }
12715
12716                 if (numParents > 0 && !binary_upgrade)
12717                 {
12718                         appendPQExpBuffer(q, "\nINHERITS (");
12719                         for (k = 0; k < numParents; k++)
12720                         {
12721                                 TableInfo  *parentRel = parents[k];
12722
12723                                 if (k > 0)
12724                                         appendPQExpBuffer(q, ", ");
12725                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12726                                         appendPQExpBuffer(q, "%s.",
12727                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12728                                 appendPQExpBuffer(q, "%s",
12729                                                                   fmtId(parentRel->dobj.name));
12730                         }
12731                         appendPQExpBuffer(q, ")");
12732                 }
12733
12734                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12735                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12736
12737                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12738                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12739                 {
12740                         bool            addcomma = false;
12741
12742                         appendPQExpBuffer(q, "\nWITH (");
12743                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12744                         {
12745                                 addcomma = true;
12746                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12747                         }
12748                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12749                         {
12750                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12751                                                                   tbinfo->toast_reloptions);
12752                         }
12753                         appendPQExpBuffer(q, ")");
12754                 }
12755
12756                 /* Dump generic options if any */
12757                 if (ftoptions && ftoptions[0])
12758                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12759
12760                 appendPQExpBuffer(q, ";\n");
12761
12762                 /*
12763                  * To create binary-compatible heap files, we have to ensure the same
12764                  * physical column order, including dropped columns, as in the
12765                  * original.  Therefore, we create dropped columns above and drop them
12766                  * here, also updating their attlen/attalign values so that the
12767                  * dropped column can be skipped properly.      (We do not bother with
12768                  * restoring the original attbyval setting.)  Also, inheritance
12769                  * relationships are set up by doing ALTER INHERIT rather than using
12770                  * an INHERITS clause --- the latter would possibly mess up the column
12771                  * order.  That also means we have to take care about setting
12772                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12773                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12774                  */
12775                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12776                 {
12777                         for (j = 0; j < tbinfo->numatts; j++)
12778                         {
12779                                 if (tbinfo->attisdropped[j])
12780                                 {
12781                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12782                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12783                                                                           "SET attlen = %d, "
12784                                                                           "attalign = '%c', attbyval = false\n"
12785                                                                           "WHERE attname = ",
12786                                                                           tbinfo->attlen[j],
12787                                                                           tbinfo->attalign[j]);
12788                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12789                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12790                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12791                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12792
12793                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12794                                                                           fmtId(tbinfo->dobj.name));
12795                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12796                                                                           fmtId(tbinfo->attnames[j]));
12797                                 }
12798                                 else if (!tbinfo->attislocal[j])
12799                                 {
12800                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12801                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12802                                                                           "SET attislocal = false\n"
12803                                                                           "WHERE attname = ");
12804                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12805                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12806                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12807                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12808                                 }
12809                         }
12810
12811                         for (k = 0; k < tbinfo->ncheck; k++)
12812                         {
12813                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12814
12815                                 if (constr->separate || constr->conislocal)
12816                                         continue;
12817
12818                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12819                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12820                                                                   fmtId(tbinfo->dobj.name));
12821                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12822                                                                   fmtId(constr->dobj.name));
12823                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12824                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12825                                                                   "SET conislocal = false\n"
12826                                                                   "WHERE contype = 'c' AND conname = ");
12827                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12828                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12829                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12830                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12831                         }
12832
12833                         if (numParents > 0)
12834                         {
12835                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12836                                 for (k = 0; k < numParents; k++)
12837                                 {
12838                                         TableInfo  *parentRel = parents[k];
12839
12840                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12841                                                                           fmtId(tbinfo->dobj.name));
12842                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12843                                                 appendPQExpBuffer(q, "%s.",
12844                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12845                                         appendPQExpBuffer(q, "%s;\n",
12846                                                                           fmtId(parentRel->dobj.name));
12847                                 }
12848                         }
12849
12850                         if (tbinfo->reloftype)
12851                         {
12852                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12853                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12854                                                                   fmtId(tbinfo->dobj.name),
12855                                                                   tbinfo->reloftype);
12856                         }
12857
12858                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12859                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12860                                                           "SET relfrozenxid = '%u'\n"
12861                                                           "WHERE oid = ",
12862                                                           tbinfo->frozenxid);
12863                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12864                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12865
12866                         if (tbinfo->toast_oid)
12867                         {
12868                                 /* We preserve the toast oids, so we can use it during restore */
12869                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12870                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12871                                                                   "SET relfrozenxid = '%u'\n"
12872                                                                   "WHERE oid = '%u';\n",
12873                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12874                         }
12875                 }
12876
12877                 /*
12878                  * Dump additional per-column properties that we can't handle in the
12879                  * main CREATE TABLE command.
12880                  */
12881                 for (j = 0; j < tbinfo->numatts; j++)
12882                 {
12883                         /* None of this applies to dropped columns */
12884                         if (tbinfo->attisdropped[j])
12885                                 continue;
12886
12887                         /*
12888                          * If we didn't dump the column definition explicitly above, and
12889                          * it is NOT NULL and did not inherit that property from a parent,
12890                          * we have to mark it separately.
12891                          */
12892                         if (!shouldPrintColumn(tbinfo, j) &&
12893                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12894                         {
12895                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12896                                                                   fmtId(tbinfo->dobj.name));
12897                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12898                                                                   fmtId(tbinfo->attnames[j]));
12899                         }
12900
12901                         /*
12902                          * Dump per-column statistics information. We only issue an ALTER
12903                          * TABLE statement if the attstattarget entry for this column is
12904                          * non-negative (i.e. it's not the default value)
12905                          */
12906                         if (tbinfo->attstattarget[j] >= 0)
12907                         {
12908                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12909                                                                   fmtId(tbinfo->dobj.name));
12910                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12911                                                                   fmtId(tbinfo->attnames[j]));
12912                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12913                                                                   tbinfo->attstattarget[j]);
12914                         }
12915
12916                         /*
12917                          * Dump per-column storage information.  The statement is only
12918                          * dumped if the storage has been changed from the type's default.
12919                          */
12920                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12921                         {
12922                                 switch (tbinfo->attstorage[j])
12923                                 {
12924                                         case 'p':
12925                                                 storage = "PLAIN";
12926                                                 break;
12927                                         case 'e':
12928                                                 storage = "EXTERNAL";
12929                                                 break;
12930                                         case 'm':
12931                                                 storage = "MAIN";
12932                                                 break;
12933                                         case 'x':
12934                                                 storage = "EXTENDED";
12935                                                 break;
12936                                         default:
12937                                                 storage = NULL;
12938                                 }
12939
12940                                 /*
12941                                  * Only dump the statement if it's a storage type we recognize
12942                                  */
12943                                 if (storage != NULL)
12944                                 {
12945                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12946                                                                           fmtId(tbinfo->dobj.name));
12947                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12948                                                                           fmtId(tbinfo->attnames[j]));
12949                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12950                                                                           storage);
12951                                 }
12952                         }
12953
12954                         /*
12955                          * Dump per-column attributes.
12956                          */
12957                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12958                         {
12959                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12960                                                                   fmtId(tbinfo->dobj.name));
12961                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12962                                                                   fmtId(tbinfo->attnames[j]));
12963                                 appendPQExpBuffer(q, "SET (%s);\n",
12964                                                                   tbinfo->attoptions[j]);
12965                         }
12966
12967                         /*
12968                          * Dump per-column fdw options.
12969                          */
12970                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12971                                 tbinfo->attfdwoptions[j] &&
12972                                 tbinfo->attfdwoptions[j][0] != '\0')
12973                         {
12974                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12975                                                                   fmtId(tbinfo->dobj.name));
12976                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12977                                                                   fmtId(tbinfo->attnames[j]));
12978                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12979                                                                   tbinfo->attfdwoptions[j]);
12980                         }
12981                 }
12982         }
12983
12984         if (binary_upgrade)
12985                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12986
12987         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12988                                  tbinfo->dobj.name,
12989                                  tbinfo->dobj.namespace->dobj.name,
12990                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12991                                  tbinfo->rolname,
12992                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12993                                  reltypename, SECTION_PRE_DATA,
12994                                  q->data, delq->data, NULL,
12995                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12996                                  NULL, NULL);
12997
12998
12999         /* Dump Table Comments */
13000         dumpTableComment(fout, tbinfo, reltypename);
13001
13002         /* Dump Table Security Labels */
13003         dumpTableSecLabel(fout, tbinfo, reltypename);
13004
13005         /* Dump comments on inlined table constraints */
13006         for (j = 0; j < tbinfo->ncheck; j++)
13007         {
13008                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13009
13010                 if (constr->separate || !constr->conislocal)
13011                         continue;
13012
13013                 dumpTableConstraintComment(fout, constr);
13014         }
13015
13016         destroyPQExpBuffer(query);
13017         destroyPQExpBuffer(q);
13018         destroyPQExpBuffer(delq);
13019         destroyPQExpBuffer(labelq);
13020 }
13021
13022 /*
13023  * dumpAttrDef --- dump an attribute's default-value declaration
13024  */
13025 static void
13026 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13027 {
13028         TableInfo  *tbinfo = adinfo->adtable;
13029         int                     adnum = adinfo->adnum;
13030         PQExpBuffer q;
13031         PQExpBuffer delq;
13032
13033         /* Skip if table definition not to be dumped */
13034         if (!tbinfo->dobj.dump || dataOnly)
13035                 return;
13036
13037         /* Skip if not "separate"; it was dumped in the table's definition */
13038         if (!adinfo->separate)
13039                 return;
13040
13041         q = createPQExpBuffer();
13042         delq = createPQExpBuffer();
13043
13044         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13045                                           fmtId(tbinfo->dobj.name));
13046         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13047                                           fmtId(tbinfo->attnames[adnum - 1]),
13048                                           adinfo->adef_expr);
13049
13050         /*
13051          * DROP must be fully qualified in case same name appears in pg_catalog
13052          */
13053         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13054                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13055         appendPQExpBuffer(delq, "%s ",
13056                                           fmtId(tbinfo->dobj.name));
13057         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13058                                           fmtId(tbinfo->attnames[adnum - 1]));
13059
13060         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13061                                  tbinfo->attnames[adnum - 1],
13062                                  tbinfo->dobj.namespace->dobj.name,
13063                                  NULL,
13064                                  tbinfo->rolname,
13065                                  false, "DEFAULT", SECTION_PRE_DATA,
13066                                  q->data, delq->data, NULL,
13067                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
13068                                  NULL, NULL);
13069
13070         destroyPQExpBuffer(q);
13071         destroyPQExpBuffer(delq);
13072 }
13073
13074 /*
13075  * getAttrName: extract the correct name for an attribute
13076  *
13077  * The array tblInfo->attnames[] only provides names of user attributes;
13078  * if a system attribute number is supplied, we have to fake it.
13079  * We also do a little bit of bounds checking for safety's sake.
13080  */
13081 static const char *
13082 getAttrName(int attrnum, TableInfo *tblInfo)
13083 {
13084         if (attrnum > 0 && attrnum <= tblInfo->numatts)
13085                 return tblInfo->attnames[attrnum - 1];
13086         switch (attrnum)
13087         {
13088                 case SelfItemPointerAttributeNumber:
13089                         return "ctid";
13090                 case ObjectIdAttributeNumber:
13091                         return "oid";
13092                 case MinTransactionIdAttributeNumber:
13093                         return "xmin";
13094                 case MinCommandIdAttributeNumber:
13095                         return "cmin";
13096                 case MaxTransactionIdAttributeNumber:
13097                         return "xmax";
13098                 case MaxCommandIdAttributeNumber:
13099                         return "cmax";
13100                 case TableOidAttributeNumber:
13101                         return "tableoid";
13102         }
13103         write_msg(NULL, "invalid column number %d for table \"%s\"\n",
13104                           attrnum, tblInfo->dobj.name);
13105         exit_nicely();
13106         return NULL;                            /* keep compiler quiet */
13107 }
13108
13109 /*
13110  * dumpIndex
13111  *        write out to fout a user-defined index
13112  */
13113 static void
13114 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13115 {
13116         TableInfo  *tbinfo = indxinfo->indextable;
13117         PQExpBuffer q;
13118         PQExpBuffer delq;
13119         PQExpBuffer labelq;
13120
13121         if (dataOnly)
13122                 return;
13123
13124         q = createPQExpBuffer();
13125         delq = createPQExpBuffer();
13126         labelq = createPQExpBuffer();
13127
13128         appendPQExpBuffer(labelq, "INDEX %s",
13129                                           fmtId(indxinfo->dobj.name));
13130
13131         /*
13132          * If there's an associated constraint, don't dump the index per se, but
13133          * do dump any comment for it.  (This is safe because dependency ordering
13134          * will have ensured the constraint is emitted first.)
13135          */
13136         if (indxinfo->indexconstraint == 0)
13137         {
13138                 if (binary_upgrade)
13139                         binary_upgrade_set_pg_class_oids(fout, q,
13140                                                                                          indxinfo->dobj.catId.oid, true);
13141
13142                 /* Plain secondary index */
13143                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13144
13145                 /* If the index is clustered, we need to record that. */
13146                 if (indxinfo->indisclustered)
13147                 {
13148                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13149                                                           fmtId(tbinfo->dobj.name));
13150                         appendPQExpBuffer(q, " ON %s;\n",
13151                                                           fmtId(indxinfo->dobj.name));
13152                 }
13153
13154                 /*
13155                  * DROP must be fully qualified in case same name appears in
13156                  * pg_catalog
13157                  */
13158                 appendPQExpBuffer(delq, "DROP INDEX %s.",
13159                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13160                 appendPQExpBuffer(delq, "%s;\n",
13161                                                   fmtId(indxinfo->dobj.name));
13162
13163                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13164                                          indxinfo->dobj.name,
13165                                          tbinfo->dobj.namespace->dobj.name,
13166                                          indxinfo->tablespace,
13167                                          tbinfo->rolname, false,
13168                                          "INDEX", SECTION_POST_DATA,
13169                                          q->data, delq->data, NULL,
13170                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
13171                                          NULL, NULL);
13172         }
13173
13174         /* Dump Index Comments */
13175         dumpComment(fout, labelq->data,
13176                                 tbinfo->dobj.namespace->dobj.name,
13177                                 tbinfo->rolname,
13178                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13179
13180         destroyPQExpBuffer(q);
13181         destroyPQExpBuffer(delq);
13182         destroyPQExpBuffer(labelq);
13183 }
13184
13185 /*
13186  * dumpConstraint
13187  *        write out to fout a user-defined constraint
13188  */
13189 static void
13190 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13191 {
13192         TableInfo  *tbinfo = coninfo->contable;
13193         PQExpBuffer q;
13194         PQExpBuffer delq;
13195
13196         /* Skip if not to be dumped */
13197         if (!coninfo->dobj.dump || dataOnly)
13198                 return;
13199
13200         q = createPQExpBuffer();
13201         delq = createPQExpBuffer();
13202
13203         if (coninfo->contype == 'p' ||
13204                 coninfo->contype == 'u' ||
13205                 coninfo->contype == 'x')
13206         {
13207                 /* Index-related constraint */
13208                 IndxInfo   *indxinfo;
13209                 int                     k;
13210
13211                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13212
13213                 if (indxinfo == NULL)
13214                 {
13215                         write_msg(NULL, "missing index for constraint \"%s\"\n",
13216                                           coninfo->dobj.name);
13217                         exit_nicely();
13218                 }
13219
13220                 if (binary_upgrade)
13221                         binary_upgrade_set_pg_class_oids(fout, q,
13222                                                                                          indxinfo->dobj.catId.oid, true);
13223
13224                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13225                                                   fmtId(tbinfo->dobj.name));
13226                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
13227                                                   fmtId(coninfo->dobj.name));
13228
13229                 if (coninfo->condef)
13230                 {
13231                         /* pg_get_constraintdef should have provided everything */
13232                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13233                 }
13234                 else
13235                 {
13236                         appendPQExpBuffer(q, "%s (",
13237                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13238                         for (k = 0; k < indxinfo->indnkeys; k++)
13239                         {
13240                                 int                     indkey = (int) indxinfo->indkeys[k];
13241                                 const char *attname;
13242
13243                                 if (indkey == InvalidAttrNumber)
13244                                         break;
13245                                 attname = getAttrName(indkey, tbinfo);
13246
13247                                 appendPQExpBuffer(q, "%s%s",
13248                                                                   (k == 0) ? "" : ", ",
13249                                                                   fmtId(attname));
13250                         }
13251
13252                         appendPQExpBuffer(q, ")");
13253
13254                         if (indxinfo->options && strlen(indxinfo->options) > 0)
13255                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13256
13257                         if (coninfo->condeferrable)
13258                         {
13259                                 appendPQExpBuffer(q, " DEFERRABLE");
13260                                 if (coninfo->condeferred)
13261                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
13262                         }
13263
13264                         appendPQExpBuffer(q, ";\n");
13265                 }
13266
13267                 /* If the index is clustered, we need to record that. */
13268                 if (indxinfo->indisclustered)
13269                 {
13270                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13271                                                           fmtId(tbinfo->dobj.name));
13272                         appendPQExpBuffer(q, " ON %s;\n",
13273                                                           fmtId(indxinfo->dobj.name));
13274                 }
13275
13276                 /*
13277                  * DROP must be fully qualified in case same name appears in
13278                  * pg_catalog
13279                  */
13280                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13281                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13282                 appendPQExpBuffer(delq, "%s ",
13283                                                   fmtId(tbinfo->dobj.name));
13284                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13285                                                   fmtId(coninfo->dobj.name));
13286
13287                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13288                                          coninfo->dobj.name,
13289                                          tbinfo->dobj.namespace->dobj.name,
13290                                          indxinfo->tablespace,
13291                                          tbinfo->rolname, false,
13292                                          "CONSTRAINT", SECTION_POST_DATA,
13293                                          q->data, delq->data, NULL,
13294                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13295                                          NULL, NULL);
13296         }
13297         else if (coninfo->contype == 'f')
13298         {
13299                 /*
13300                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13301                  * current table data is not processed
13302                  */
13303                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13304                                                   fmtId(tbinfo->dobj.name));
13305                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13306                                                   fmtId(coninfo->dobj.name),
13307                                                   coninfo->condef);
13308
13309                 /*
13310                  * DROP must be fully qualified in case same name appears in
13311                  * pg_catalog
13312                  */
13313                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13314                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13315                 appendPQExpBuffer(delq, "%s ",
13316                                                   fmtId(tbinfo->dobj.name));
13317                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13318                                                   fmtId(coninfo->dobj.name));
13319
13320                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13321                                          coninfo->dobj.name,
13322                                          tbinfo->dobj.namespace->dobj.name,
13323                                          NULL,
13324                                          tbinfo->rolname, false,
13325                                          "FK CONSTRAINT", SECTION_POST_DATA,
13326                                          q->data, delq->data, NULL,
13327                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13328                                          NULL, NULL);
13329         }
13330         else if (coninfo->contype == 'c' && tbinfo)
13331         {
13332                 /* CHECK constraint on a table */
13333
13334                 /* Ignore if not to be dumped separately */
13335                 if (coninfo->separate)
13336                 {
13337                         /* add ONLY if we do not want it to propagate to children */
13338                         appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13339                                                          coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13340                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13341                                                           fmtId(coninfo->dobj.name),
13342                                                           coninfo->condef);
13343
13344                         /*
13345                          * DROP must be fully qualified in case same name appears in
13346                          * pg_catalog
13347                          */
13348                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13349                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13350                         appendPQExpBuffer(delq, "%s ",
13351                                                           fmtId(tbinfo->dobj.name));
13352                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13353                                                           fmtId(coninfo->dobj.name));
13354
13355                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13356                                                  coninfo->dobj.name,
13357                                                  tbinfo->dobj.namespace->dobj.name,
13358                                                  NULL,
13359                                                  tbinfo->rolname, false,
13360                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13361                                                  q->data, delq->data, NULL,
13362                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13363                                                  NULL, NULL);
13364                 }
13365         }
13366         else if (coninfo->contype == 'c' && tbinfo == NULL)
13367         {
13368                 /* CHECK constraint on a domain */
13369                 TypeInfo   *tyinfo = coninfo->condomain;
13370
13371                 /* Ignore if not to be dumped separately */
13372                 if (coninfo->separate)
13373                 {
13374                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13375                                                           fmtId(tyinfo->dobj.name));
13376                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13377                                                           fmtId(coninfo->dobj.name),
13378                                                           coninfo->condef);
13379
13380                         /*
13381                          * DROP must be fully qualified in case same name appears in
13382                          * pg_catalog
13383                          */
13384                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13385                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13386                         appendPQExpBuffer(delq, "%s ",
13387                                                           fmtId(tyinfo->dobj.name));
13388                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13389                                                           fmtId(coninfo->dobj.name));
13390
13391                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13392                                                  coninfo->dobj.name,
13393                                                  tyinfo->dobj.namespace->dobj.name,
13394                                                  NULL,
13395                                                  tyinfo->rolname, false,
13396                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13397                                                  q->data, delq->data, NULL,
13398                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13399                                                  NULL, NULL);
13400                 }
13401         }
13402         else
13403         {
13404                 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
13405                 exit_nicely();
13406         }
13407
13408         /* Dump Constraint Comments --- only works for table constraints */
13409         if (tbinfo && coninfo->separate)
13410                 dumpTableConstraintComment(fout, coninfo);
13411
13412         destroyPQExpBuffer(q);
13413         destroyPQExpBuffer(delq);
13414 }
13415
13416 /*
13417  * dumpTableConstraintComment --- dump a constraint's comment if any
13418  *
13419  * This is split out because we need the function in two different places
13420  * depending on whether the constraint is dumped as part of CREATE TABLE
13421  * or as a separate ALTER command.
13422  */
13423 static void
13424 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13425 {
13426         TableInfo  *tbinfo = coninfo->contable;
13427         PQExpBuffer labelq = createPQExpBuffer();
13428
13429         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13430                                           fmtId(coninfo->dobj.name));
13431         appendPQExpBuffer(labelq, "ON %s",
13432                                           fmtId(tbinfo->dobj.name));
13433         dumpComment(fout, labelq->data,
13434                                 tbinfo->dobj.namespace->dobj.name,
13435                                 tbinfo->rolname,
13436                                 coninfo->dobj.catId, 0,
13437                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13438
13439         destroyPQExpBuffer(labelq);
13440 }
13441
13442 /*
13443  * findLastBuiltInOid -
13444  * find the last built in oid
13445  *
13446  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13447  * pg_database entry for the current database
13448  */
13449 static Oid
13450 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13451 {
13452         PGresult   *res;
13453         int                     ntups;
13454         Oid                     last_oid;
13455         PQExpBuffer query = createPQExpBuffer();
13456
13457         resetPQExpBuffer(query);
13458         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13459         appendStringLiteralAH(query, dbname, fout);
13460
13461         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13462
13463         ntups = PQntuples(res);
13464         if (ntups < 1)
13465         {
13466                 write_msg(NULL, "missing pg_database entry for this database\n");
13467                 exit_nicely();
13468         }
13469         if (ntups > 1)
13470         {
13471                 write_msg(NULL, "found more than one pg_database entry for this database\n");
13472                 exit_nicely();
13473         }
13474         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13475         PQclear(res);
13476         destroyPQExpBuffer(query);
13477         return last_oid;
13478 }
13479
13480 /*
13481  * findLastBuiltInOid -
13482  * find the last built in oid
13483  *
13484  * For 7.0, we do this by assuming that the last thing that initdb does is to
13485  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13486  * initdb won't be changing anymore, it'll do.
13487  */
13488 static Oid
13489 findLastBuiltinOid_V70(Archive *fout)
13490 {
13491         PGresult   *res;
13492         int                     ntups;
13493         int                     last_oid;
13494
13495         res = ExecuteSqlQuery(fout,
13496                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
13497                                         PGRES_TUPLES_OK);
13498         ntups = PQntuples(res);
13499         if (ntups < 1)
13500         {
13501                 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
13502                 exit_nicely();
13503         }
13504         if (ntups > 1)
13505         {
13506                 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
13507                 exit_nicely();
13508         }
13509         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13510         PQclear(res);
13511         return last_oid;
13512 }
13513
13514 static void
13515 dumpSequence(Archive *fout, TableInfo *tbinfo)
13516 {
13517         PGresult   *res;
13518         char       *startv,
13519                            *last,
13520                            *incby,
13521                            *maxv = NULL,
13522                            *minv = NULL,
13523                            *cache;
13524         char            bufm[100],
13525                                 bufx[100];
13526         bool            cycled,
13527                                 called;
13528         PQExpBuffer query = createPQExpBuffer();
13529         PQExpBuffer delqry = createPQExpBuffer();
13530         PQExpBuffer labelq = createPQExpBuffer();
13531
13532         /* Make sure we are in proper schema */
13533         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13534
13535         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13536         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13537
13538         if (fout->remoteVersion >= 80400)
13539         {
13540                 appendPQExpBuffer(query,
13541                                                   "SELECT sequence_name, "
13542                                                   "start_value, last_value, increment_by, "
13543                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13544                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13545                                                   "     ELSE max_value "
13546                                                   "END AS max_value, "
13547                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13548                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13549                                                   "     ELSE min_value "
13550                                                   "END AS min_value, "
13551                                                   "cache_value, is_cycled, is_called from %s",
13552                                                   bufx, bufm,
13553                                                   fmtId(tbinfo->dobj.name));
13554         }
13555         else
13556         {
13557                 appendPQExpBuffer(query,
13558                                                   "SELECT sequence_name, "
13559                                                   "0 AS start_value, last_value, increment_by, "
13560                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13561                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13562                                                   "     ELSE max_value "
13563                                                   "END AS max_value, "
13564                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13565                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13566                                                   "     ELSE min_value "
13567                                                   "END AS min_value, "
13568                                                   "cache_value, is_cycled, is_called from %s",
13569                                                   bufx, bufm,
13570                                                   fmtId(tbinfo->dobj.name));
13571         }
13572
13573         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13574
13575         if (PQntuples(res) != 1)
13576         {
13577                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13578                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13579                                                                  PQntuples(res)),
13580                                   tbinfo->dobj.name, PQntuples(res));
13581                 exit_nicely();
13582         }
13583
13584         /* Disable this check: it fails if sequence has been renamed */
13585 #ifdef NOT_USED
13586         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13587         {
13588                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13589                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13590                 exit_nicely();
13591         }
13592 #endif
13593
13594         startv = PQgetvalue(res, 0, 1);
13595         last = PQgetvalue(res, 0, 2);
13596         incby = PQgetvalue(res, 0, 3);
13597         if (!PQgetisnull(res, 0, 4))
13598                 maxv = PQgetvalue(res, 0, 4);
13599         if (!PQgetisnull(res, 0, 5))
13600                 minv = PQgetvalue(res, 0, 5);
13601         cache = PQgetvalue(res, 0, 6);
13602         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13603         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13604
13605         /*
13606          * The logic we use for restoring sequences is as follows:
13607          *
13608          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13609          * last_val for start if called is false, else use min_val for start_val).
13610          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13611          * BY command for it.
13612          *
13613          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13614          */
13615         if (!dataOnly)
13616         {
13617                 /*
13618                  * DROP must be fully qualified in case same name appears in
13619                  * pg_catalog
13620                  */
13621                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13622                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13623                 appendPQExpBuffer(delqry, "%s;\n",
13624                                                   fmtId(tbinfo->dobj.name));
13625
13626                 resetPQExpBuffer(query);
13627
13628                 if (binary_upgrade)
13629                 {
13630                         binary_upgrade_set_pg_class_oids(fout, query,
13631                                                                                          tbinfo->dobj.catId.oid, false);
13632                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13633                                                                                                         tbinfo->dobj.catId.oid);
13634                 }
13635
13636                 appendPQExpBuffer(query,
13637                                                   "CREATE SEQUENCE %s\n",
13638                                                   fmtId(tbinfo->dobj.name));
13639
13640                 if (fout->remoteVersion >= 80400)
13641                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13642                 else
13643                 {
13644                         /*
13645                          * Versions before 8.4 did not remember the true start value.  If
13646                          * is_called is false then the sequence has never been incremented
13647                          * so we can use last_val.      Otherwise punt and let it default.
13648                          */
13649                         if (!called)
13650                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13651                 }
13652
13653                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13654
13655                 if (minv)
13656                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13657                 else
13658                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13659
13660                 if (maxv)
13661                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13662                 else
13663                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13664
13665                 appendPQExpBuffer(query,
13666                                                   "    CACHE %s%s",
13667                                                   cache, (cycled ? "\n    CYCLE" : ""));
13668
13669                 appendPQExpBuffer(query, ";\n");
13670
13671                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13672
13673                 /* binary_upgrade:      no need to clear TOAST table oid */
13674
13675                 if (binary_upgrade)
13676                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13677                                                                                         labelq->data);
13678
13679                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13680                                          tbinfo->dobj.name,
13681                                          tbinfo->dobj.namespace->dobj.name,
13682                                          NULL,
13683                                          tbinfo->rolname,
13684                                          false, "SEQUENCE", SECTION_PRE_DATA,
13685                                          query->data, delqry->data, NULL,
13686                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13687                                          NULL, NULL);
13688
13689                 /*
13690                  * If the sequence is owned by a table column, emit the ALTER for it
13691                  * as a separate TOC entry immediately following the sequence's own
13692                  * entry.  It's OK to do this rather than using full sorting logic,
13693                  * because the dependency that tells us it's owned will have forced
13694                  * the table to be created first.  We can't just include the ALTER in
13695                  * the TOC entry because it will fail if we haven't reassigned the
13696                  * sequence owner to match the table's owner.
13697                  *
13698                  * We need not schema-qualify the table reference because both
13699                  * sequence and table must be in the same schema.
13700                  */
13701                 if (OidIsValid(tbinfo->owning_tab))
13702                 {
13703                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13704
13705                         if (owning_tab && owning_tab->dobj.dump)
13706                         {
13707                                 resetPQExpBuffer(query);
13708                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13709                                                                   fmtId(tbinfo->dobj.name));
13710                                 appendPQExpBuffer(query, " OWNED BY %s",
13711                                                                   fmtId(owning_tab->dobj.name));
13712                                 appendPQExpBuffer(query, ".%s;\n",
13713                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13714
13715                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13716                                                          tbinfo->dobj.name,
13717                                                          tbinfo->dobj.namespace->dobj.name,
13718                                                          NULL,
13719                                                          tbinfo->rolname,
13720                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13721                                                          query->data, "", NULL,
13722                                                          &(tbinfo->dobj.dumpId), 1,
13723                                                          NULL, NULL);
13724                         }
13725                 }
13726
13727                 /* Dump Sequence Comments and Security Labels */
13728                 dumpComment(fout, labelq->data,
13729                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13730                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13731                 dumpSecLabel(fout, labelq->data,
13732                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13733                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13734         }
13735
13736         if (!schemaOnly)
13737         {
13738                 resetPQExpBuffer(query);
13739                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13740                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13741                 appendPQExpBuffer(query, ", %s, %s);\n",
13742                                                   last, (called ? "true" : "false"));
13743
13744                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13745                                          tbinfo->dobj.name,
13746                                          tbinfo->dobj.namespace->dobj.name,
13747                                          NULL,
13748                                          tbinfo->rolname,
13749                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13750                                          query->data, "", NULL,
13751                                          &(tbinfo->dobj.dumpId), 1,
13752                                          NULL, NULL);
13753         }
13754
13755         PQclear(res);
13756
13757         destroyPQExpBuffer(query);
13758         destroyPQExpBuffer(delqry);
13759         destroyPQExpBuffer(labelq);
13760 }
13761
13762 static void
13763 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13764 {
13765         TableInfo  *tbinfo = tginfo->tgtable;
13766         PQExpBuffer query;
13767         PQExpBuffer delqry;
13768         PQExpBuffer labelq;
13769         char       *tgargs;
13770         size_t          lentgargs;
13771         const char *p;
13772         int                     findx;
13773
13774         if (dataOnly)
13775                 return;
13776
13777         query = createPQExpBuffer();
13778         delqry = createPQExpBuffer();
13779         labelq = createPQExpBuffer();
13780
13781         /*
13782          * DROP must be fully qualified in case same name appears in pg_catalog
13783          */
13784         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13785                                           fmtId(tginfo->dobj.name));
13786         appendPQExpBuffer(delqry, "ON %s.",
13787                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13788         appendPQExpBuffer(delqry, "%s;\n",
13789                                           fmtId(tbinfo->dobj.name));
13790
13791         if (tginfo->tgdef)
13792         {
13793                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13794         }
13795         else
13796         {
13797                 if (tginfo->tgisconstraint)
13798                 {
13799                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13800                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13801                 }
13802                 else
13803                 {
13804                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13805                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13806                 }
13807                 appendPQExpBuffer(query, "\n    ");
13808
13809                 /* Trigger type */
13810                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13811                         appendPQExpBuffer(query, "BEFORE");
13812                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13813                         appendPQExpBuffer(query, "AFTER");
13814                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13815                         appendPQExpBuffer(query, "INSTEAD OF");
13816                 else
13817                 {
13818                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13819                         exit_nicely();
13820                 }
13821
13822                 findx = 0;
13823                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13824                 {
13825                         appendPQExpBuffer(query, " INSERT");
13826                         findx++;
13827                 }
13828                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13829                 {
13830                         if (findx > 0)
13831                                 appendPQExpBuffer(query, " OR DELETE");
13832                         else
13833                                 appendPQExpBuffer(query, " DELETE");
13834                         findx++;
13835                 }
13836                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13837                 {
13838                         if (findx > 0)
13839                                 appendPQExpBuffer(query, " OR UPDATE");
13840                         else
13841                                 appendPQExpBuffer(query, " UPDATE");
13842                         findx++;
13843                 }
13844                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13845                 {
13846                         if (findx > 0)
13847                                 appendPQExpBuffer(query, " OR TRUNCATE");
13848                         else
13849                                 appendPQExpBuffer(query, " TRUNCATE");
13850                         findx++;
13851                 }
13852                 appendPQExpBuffer(query, " ON %s\n",
13853                                                   fmtId(tbinfo->dobj.name));
13854
13855                 if (tginfo->tgisconstraint)
13856                 {
13857                         if (OidIsValid(tginfo->tgconstrrelid))
13858                         {
13859                                 /* If we are using regclass, name is already quoted */
13860                                 if (fout->remoteVersion >= 70300)
13861                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13862                                                                           tginfo->tgconstrrelname);
13863                                 else
13864                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13865                                                                           fmtId(tginfo->tgconstrrelname));
13866                         }
13867                         if (!tginfo->tgdeferrable)
13868                                 appendPQExpBuffer(query, "NOT ");
13869                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13870                         if (tginfo->tginitdeferred)
13871                                 appendPQExpBuffer(query, "DEFERRED\n");
13872                         else
13873                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13874                 }
13875
13876                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13877                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13878                 else
13879                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13880
13881                 /* In 7.3, result of regproc is already quoted */
13882                 if (fout->remoteVersion >= 70300)
13883                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13884                                                           tginfo->tgfname);
13885                 else
13886                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13887                                                           fmtId(tginfo->tgfname));
13888
13889                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13890                                                                                   &lentgargs);
13891                 p = tgargs;
13892                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13893                 {
13894                         /* find the embedded null that terminates this trigger argument */
13895                         size_t          tlen = strlen(p);
13896
13897                         if (p + tlen >= tgargs + lentgargs)
13898                         {
13899                                 /* hm, not found before end of bytea value... */
13900                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13901                                                   tginfo->tgargs,
13902                                                   tginfo->dobj.name,
13903                                                   tbinfo->dobj.name);
13904                                 exit_nicely();
13905                         }
13906
13907                         if (findx > 0)
13908                                 appendPQExpBuffer(query, ", ");
13909                         appendStringLiteralAH(query, p, fout);
13910                         p += tlen + 1;
13911                 }
13912                 free(tgargs);
13913                 appendPQExpBuffer(query, ");\n");
13914         }
13915
13916         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13917         {
13918                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13919                                                   fmtId(tbinfo->dobj.name));
13920                 switch (tginfo->tgenabled)
13921                 {
13922                         case 'D':
13923                         case 'f':
13924                                 appendPQExpBuffer(query, "DISABLE");
13925                                 break;
13926                         case 'A':
13927                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13928                                 break;
13929                         case 'R':
13930                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13931                                 break;
13932                         default:
13933                                 appendPQExpBuffer(query, "ENABLE");
13934                                 break;
13935                 }
13936                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13937                                                   fmtId(tginfo->dobj.name));
13938         }
13939
13940         appendPQExpBuffer(labelq, "TRIGGER %s ",
13941                                           fmtId(tginfo->dobj.name));
13942         appendPQExpBuffer(labelq, "ON %s",
13943                                           fmtId(tbinfo->dobj.name));
13944
13945         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13946                                  tginfo->dobj.name,
13947                                  tbinfo->dobj.namespace->dobj.name,
13948                                  NULL,
13949                                  tbinfo->rolname, false,
13950                                  "TRIGGER", SECTION_POST_DATA,
13951                                  query->data, delqry->data, NULL,
13952                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13953                                  NULL, NULL);
13954
13955         dumpComment(fout, labelq->data,
13956                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13957                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13958
13959         destroyPQExpBuffer(query);
13960         destroyPQExpBuffer(delqry);
13961         destroyPQExpBuffer(labelq);
13962 }
13963
13964 /*
13965  * dumpRule
13966  *              Dump a rule
13967  */
13968 static void
13969 dumpRule(Archive *fout, RuleInfo *rinfo)
13970 {
13971         TableInfo  *tbinfo = rinfo->ruletable;
13972         PQExpBuffer query;
13973         PQExpBuffer cmd;
13974         PQExpBuffer delcmd;
13975         PQExpBuffer labelq;
13976         PGresult   *res;
13977
13978         /* Skip if not to be dumped */
13979         if (!rinfo->dobj.dump || dataOnly)
13980                 return;
13981
13982         /*
13983          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13984          * we do not want to dump it as a separate object.
13985          */
13986         if (!rinfo->separate)
13987                 return;
13988
13989         /*
13990          * Make sure we are in proper schema.
13991          */
13992         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13993
13994         query = createPQExpBuffer();
13995         cmd = createPQExpBuffer();
13996         delcmd = createPQExpBuffer();
13997         labelq = createPQExpBuffer();
13998
13999         if (fout->remoteVersion >= 70300)
14000         {
14001                 appendPQExpBuffer(query,
14002                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14003                                                   rinfo->dobj.catId.oid);
14004         }
14005         else
14006         {
14007                 /* Rule name was unique before 7.3 ... */
14008                 appendPQExpBuffer(query,
14009                                                   "SELECT pg_get_ruledef('%s') AS definition",
14010                                                   rinfo->dobj.name);
14011         }
14012
14013         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14014
14015         if (PQntuples(res) != 1)
14016         {
14017                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14018                                   rinfo->dobj.name, tbinfo->dobj.name);
14019                 exit_nicely();
14020         }
14021
14022         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14023
14024         /*
14025          * Add the command to alter the rules replication firing semantics if it
14026          * differs from the default.
14027          */
14028         if (rinfo->ev_enabled != 'O')
14029         {
14030                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
14031                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
14032                 appendPQExpBuffer(cmd, "%s ",
14033                                                   fmtId(tbinfo->dobj.name));
14034                 switch (rinfo->ev_enabled)
14035                 {
14036                         case 'A':
14037                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14038                                                                   fmtId(rinfo->dobj.name));
14039                                 break;
14040                         case 'R':
14041                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14042                                                                   fmtId(rinfo->dobj.name));
14043                                 break;
14044                         case 'D':
14045                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14046                                                                   fmtId(rinfo->dobj.name));
14047                                 break;
14048                 }
14049         }
14050
14051         /*
14052          * DROP must be fully qualified in case same name appears in pg_catalog
14053          */
14054         appendPQExpBuffer(delcmd, "DROP RULE %s ",
14055                                           fmtId(rinfo->dobj.name));
14056         appendPQExpBuffer(delcmd, "ON %s.",
14057                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14058         appendPQExpBuffer(delcmd, "%s;\n",
14059                                           fmtId(tbinfo->dobj.name));
14060
14061         appendPQExpBuffer(labelq, "RULE %s",
14062                                           fmtId(rinfo->dobj.name));
14063         appendPQExpBuffer(labelq, " ON %s",
14064                                           fmtId(tbinfo->dobj.name));
14065
14066         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14067                                  rinfo->dobj.name,
14068                                  tbinfo->dobj.namespace->dobj.name,
14069                                  NULL,
14070                                  tbinfo->rolname, false,
14071                                  "RULE", SECTION_POST_DATA,
14072                                  cmd->data, delcmd->data, NULL,
14073                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
14074                                  NULL, NULL);
14075
14076         /* Dump rule comments */
14077         dumpComment(fout, labelq->data,
14078                                 tbinfo->dobj.namespace->dobj.name,
14079                                 tbinfo->rolname,
14080                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14081
14082         PQclear(res);
14083
14084         destroyPQExpBuffer(query);
14085         destroyPQExpBuffer(cmd);
14086         destroyPQExpBuffer(delcmd);
14087         destroyPQExpBuffer(labelq);
14088 }
14089
14090 /*
14091  * getExtensionMembership --- obtain extension membership data
14092  */
14093 void
14094 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14095                                            int numExtensions)
14096 {
14097         PQExpBuffer query;
14098         PGresult   *res;
14099         int                     ntups,
14100                                 i;
14101         int                     i_classid,
14102                                 i_objid,
14103                                 i_refclassid,
14104                                 i_refobjid;
14105         DumpableObject *dobj,
14106                            *refdobj;
14107
14108         /* Nothing to do if no extensions */
14109         if (numExtensions == 0)
14110                 return;
14111
14112         /* Make sure we are in proper schema */
14113         selectSourceSchema(fout, "pg_catalog");
14114
14115         query = createPQExpBuffer();
14116
14117         /* refclassid constraint is redundant but may speed the search */
14118         appendPQExpBuffer(query, "SELECT "
14119                                           "classid, objid, refclassid, refobjid "
14120                                           "FROM pg_depend "
14121                                           "WHERE refclassid = 'pg_extension'::regclass "
14122                                           "AND deptype = 'e' "
14123                                           "ORDER BY 3,4");
14124
14125         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14126
14127         ntups = PQntuples(res);
14128
14129         i_classid = PQfnumber(res, "classid");
14130         i_objid = PQfnumber(res, "objid");
14131         i_refclassid = PQfnumber(res, "refclassid");
14132         i_refobjid = PQfnumber(res, "refobjid");
14133
14134         /*
14135          * Since we ordered the SELECT by referenced ID, we can expect that
14136          * multiple entries for the same extension will appear together; this
14137          * saves on searches.
14138          */
14139         refdobj = NULL;
14140
14141         for (i = 0; i < ntups; i++)
14142         {
14143                 CatalogId       objId;
14144                 CatalogId       refobjId;
14145
14146                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14147                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14148                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14149                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14150
14151                 if (refdobj == NULL ||
14152                         refdobj->catId.tableoid != refobjId.tableoid ||
14153                         refdobj->catId.oid != refobjId.oid)
14154                         refdobj = findObjectByCatalogId(refobjId);
14155
14156                 /*
14157                  * Failure to find objects mentioned in pg_depend is not unexpected,
14158                  * since for example we don't collect info about TOAST tables.
14159                  */
14160                 if (refdobj == NULL)
14161                 {
14162 #ifdef NOT_USED
14163                         fprintf(stderr, "no referenced object %u %u\n",
14164                                         refobjId.tableoid, refobjId.oid);
14165 #endif
14166                         continue;
14167                 }
14168
14169                 dobj = findObjectByCatalogId(objId);
14170
14171                 if (dobj == NULL)
14172                 {
14173 #ifdef NOT_USED
14174                         fprintf(stderr, "no referencing object %u %u\n",
14175                                         objId.tableoid, objId.oid);
14176 #endif
14177                         continue;
14178                 }
14179
14180                 /* Record dependency so that getDependencies needn't repeat this */
14181                 addObjectDependency(dobj, refdobj->dumpId);
14182
14183                 dobj->ext_member = true;
14184
14185                 /*
14186                  * Normally, mark the member object as not to be dumped.  But in
14187                  * binary upgrades, we still dump the members individually, since the
14188                  * idea is to exactly reproduce the database contents rather than
14189                  * replace the extension contents with something different.
14190                  */
14191                 if (!binary_upgrade)
14192                         dobj->dump = false;
14193                 else
14194                         dobj->dump = refdobj->dump;
14195         }
14196
14197         PQclear(res);
14198
14199         /*
14200          * Now identify extension configuration tables and create TableDataInfo
14201          * objects for them, ensuring their data will be dumped even though the
14202          * tables themselves won't be.
14203          *
14204          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14205          * user data in a configuration table is treated like schema data. This
14206          * seems appropriate since system data in a config table would get
14207          * reloaded by CREATE EXTENSION.
14208          */
14209         for (i = 0; i < numExtensions; i++)
14210         {
14211                 ExtensionInfo *curext = &(extinfo[i]);
14212                 char       *extconfig = curext->extconfig;
14213                 char       *extcondition = curext->extcondition;
14214                 char      **extconfigarray = NULL;
14215                 char      **extconditionarray = NULL;
14216                 int                     nconfigitems;
14217                 int                     nconditionitems;
14218
14219                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14220                 if (!curext->dobj.dump)
14221                         continue;
14222
14223                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14224                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14225                         nconfigitems == nconditionitems)
14226                 {
14227                         int                     j;
14228
14229                         for (j = 0; j < nconfigitems; j++)
14230                         {
14231                                 TableInfo  *configtbl;
14232
14233                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
14234                                 if (configtbl == NULL)
14235                                         continue;
14236
14237                                 /*
14238                                  * Note: config tables are dumped without OIDs regardless
14239                                  * of the --oids setting.  This is because row filtering
14240                                  * conditions aren't compatible with dumping OIDs.
14241                                  */
14242                                 makeTableDataInfo(configtbl, false);
14243                                 if (configtbl->dataObj != NULL)
14244                                 {
14245                                         if (strlen(extconditionarray[j]) > 0)
14246                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14247                                 }
14248                         }
14249                 }
14250                 if (extconfigarray)
14251                         free(extconfigarray);
14252                 if (extconditionarray)
14253                         free(extconditionarray);
14254         }
14255
14256         destroyPQExpBuffer(query);
14257 }
14258
14259 /*
14260  * getDependencies --- obtain available dependency data
14261  */
14262 static void
14263 getDependencies(Archive *fout)
14264 {
14265         PQExpBuffer query;
14266         PGresult   *res;
14267         int                     ntups,
14268                                 i;
14269         int                     i_classid,
14270                                 i_objid,
14271                                 i_refclassid,
14272                                 i_refobjid,
14273                                 i_deptype;
14274         DumpableObject *dobj,
14275                            *refdobj;
14276
14277         /* No dependency info available before 7.3 */
14278         if (fout->remoteVersion < 70300)
14279                 return;
14280
14281         if (g_verbose)
14282                 write_msg(NULL, "reading dependency data\n");
14283
14284         /* Make sure we are in proper schema */
14285         selectSourceSchema(fout, "pg_catalog");
14286
14287         query = createPQExpBuffer();
14288
14289         /*
14290          * PIN dependencies aren't interesting, and EXTENSION dependencies were
14291          * already processed by getExtensionMembership.
14292          */
14293         appendPQExpBuffer(query, "SELECT "
14294                                           "classid, objid, refclassid, refobjid, deptype "
14295                                           "FROM pg_depend "
14296                                           "WHERE deptype != 'p' AND deptype != 'e' "
14297                                           "ORDER BY 1,2");
14298
14299         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14300
14301         ntups = PQntuples(res);
14302
14303         i_classid = PQfnumber(res, "classid");
14304         i_objid = PQfnumber(res, "objid");
14305         i_refclassid = PQfnumber(res, "refclassid");
14306         i_refobjid = PQfnumber(res, "refobjid");
14307         i_deptype = PQfnumber(res, "deptype");
14308
14309         /*
14310          * Since we ordered the SELECT by referencing ID, we can expect that
14311          * multiple entries for the same object will appear together; this saves
14312          * on searches.
14313          */
14314         dobj = NULL;
14315
14316         for (i = 0; i < ntups; i++)
14317         {
14318                 CatalogId       objId;
14319                 CatalogId       refobjId;
14320                 char            deptype;
14321
14322                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14323                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14324                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14325                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14326                 deptype = *(PQgetvalue(res, i, i_deptype));
14327
14328                 if (dobj == NULL ||
14329                         dobj->catId.tableoid != objId.tableoid ||
14330                         dobj->catId.oid != objId.oid)
14331                         dobj = findObjectByCatalogId(objId);
14332
14333                 /*
14334                  * Failure to find objects mentioned in pg_depend is not unexpected,
14335                  * since for example we don't collect info about TOAST tables.
14336                  */
14337                 if (dobj == NULL)
14338                 {
14339 #ifdef NOT_USED
14340                         fprintf(stderr, "no referencing object %u %u\n",
14341                                         objId.tableoid, objId.oid);
14342 #endif
14343                         continue;
14344                 }
14345
14346                 refdobj = findObjectByCatalogId(refobjId);
14347
14348                 if (refdobj == NULL)
14349                 {
14350 #ifdef NOT_USED
14351                         fprintf(stderr, "no referenced object %u %u\n",
14352                                         refobjId.tableoid, refobjId.oid);
14353 #endif
14354                         continue;
14355                 }
14356
14357                 /*
14358                  * Ordinarily, table rowtypes have implicit dependencies on their
14359                  * tables.      However, for a composite type the implicit dependency goes
14360                  * the other way in pg_depend; which is the right thing for DROP but
14361                  * it doesn't produce the dependency ordering we need. So in that one
14362                  * case, we reverse the direction of the dependency.
14363                  */
14364                 if (deptype == 'i' &&
14365                         dobj->objType == DO_TABLE &&
14366                         refdobj->objType == DO_TYPE)
14367                         addObjectDependency(refdobj, dobj->dumpId);
14368                 else
14369                         /* normal case */
14370                         addObjectDependency(dobj, refdobj->dumpId);
14371         }
14372
14373         PQclear(res);
14374
14375         destroyPQExpBuffer(query);
14376 }
14377
14378
14379 /*
14380  * selectSourceSchema - make the specified schema the active search path
14381  * in the source database.
14382  *
14383  * NB: pg_catalog is explicitly searched after the specified schema;
14384  * so user names are only qualified if they are cross-schema references,
14385  * and system names are only qualified if they conflict with a user name
14386  * in the current schema.
14387  *
14388  * Whenever the selected schema is not pg_catalog, be careful to qualify
14389  * references to system catalogs and types in our emitted commands!
14390  */
14391 static void
14392 selectSourceSchema(Archive *fout, const char *schemaName)
14393 {
14394         static char *curSchemaName = NULL;
14395         PQExpBuffer query;
14396
14397         /* Not relevant if fetching from pre-7.3 DB */
14398         if (fout->remoteVersion < 70300)
14399                 return;
14400         /* Ignore null schema names */
14401         if (schemaName == NULL || *schemaName == '\0')
14402                 return;
14403         /* Optimize away repeated selection of same schema */
14404         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14405                 return;
14406
14407         query = createPQExpBuffer();
14408         appendPQExpBuffer(query, "SET search_path = %s",
14409                                           fmtId(schemaName));
14410         if (strcmp(schemaName, "pg_catalog") != 0)
14411                 appendPQExpBuffer(query, ", pg_catalog");
14412
14413         ExecuteSqlStatement(fout, query->data);
14414
14415         destroyPQExpBuffer(query);
14416         if (curSchemaName)
14417                 free(curSchemaName);
14418         curSchemaName = pg_strdup(schemaName);
14419 }
14420
14421 /*
14422  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14423  * given type name.
14424  *
14425  * NB: in 7.3 and up the result may depend on the currently-selected
14426  * schema; this is why we don't try to cache the names.
14427  */
14428 static char *
14429 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14430 {
14431         char       *result;
14432         PQExpBuffer query;
14433         PGresult   *res;
14434         int                     ntups;
14435
14436         if (oid == 0)
14437         {
14438                 if ((opts & zeroAsOpaque) != 0)
14439                         return pg_strdup(g_opaque_type);
14440                 else if ((opts & zeroAsAny) != 0)
14441                         return pg_strdup("'any'");
14442                 else if ((opts & zeroAsStar) != 0)
14443                         return pg_strdup("*");
14444                 else if ((opts & zeroAsNone) != 0)
14445                         return pg_strdup("NONE");
14446         }
14447
14448         query = createPQExpBuffer();
14449         if (fout->remoteVersion >= 70300)
14450         {
14451                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14452                                                   oid);
14453         }
14454         else if (fout->remoteVersion >= 70100)
14455         {
14456                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14457                                                   oid);
14458         }
14459         else
14460         {
14461                 appendPQExpBuffer(query, "SELECT typname "
14462                                                   "FROM pg_type "
14463                                                   "WHERE oid = '%u'::oid",
14464                                                   oid);
14465         }
14466
14467         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14468
14469         /* Expecting a single result only */
14470         ntups = PQntuples(res);
14471         if (ntups != 1)
14472         {
14473                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
14474                                                            "query returned %d rows instead of one: %s\n",
14475                                                                  ntups),
14476                                   ntups, query->data);
14477                 exit_nicely();
14478         }
14479
14480         if (fout->remoteVersion >= 70100)
14481         {
14482                 /* already quoted */
14483                 result = pg_strdup(PQgetvalue(res, 0, 0));
14484         }
14485         else
14486         {
14487                 /* may need to quote it */
14488                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14489         }
14490
14491         PQclear(res);
14492         destroyPQExpBuffer(query);
14493
14494         return result;
14495 }
14496
14497 /*
14498  * myFormatType --- local implementation of format_type for use with 7.0.
14499  */
14500 static char *
14501 myFormatType(const char *typname, int32 typmod)
14502 {
14503         char       *result;
14504         bool            isarray = false;
14505         PQExpBuffer buf = createPQExpBuffer();
14506
14507         /* Handle array types */
14508         if (typname[0] == '_')
14509         {
14510                 isarray = true;
14511                 typname++;
14512         }
14513
14514         /* Show lengths on bpchar and varchar */
14515         if (strcmp(typname, "bpchar") == 0)
14516         {
14517                 int                     len = (typmod - VARHDRSZ);
14518
14519                 appendPQExpBuffer(buf, "character");
14520                 if (len > 1)
14521                         appendPQExpBuffer(buf, "(%d)",
14522                                                           typmod - VARHDRSZ);
14523         }
14524         else if (strcmp(typname, "varchar") == 0)
14525         {
14526                 appendPQExpBuffer(buf, "character varying");
14527                 if (typmod != -1)
14528                         appendPQExpBuffer(buf, "(%d)",
14529                                                           typmod - VARHDRSZ);
14530         }
14531         else if (strcmp(typname, "numeric") == 0)
14532         {
14533                 appendPQExpBuffer(buf, "numeric");
14534                 if (typmod != -1)
14535                 {
14536                         int32           tmp_typmod;
14537                         int                     precision;
14538                         int                     scale;
14539
14540                         tmp_typmod = typmod - VARHDRSZ;
14541                         precision = (tmp_typmod >> 16) & 0xffff;
14542                         scale = tmp_typmod & 0xffff;
14543                         appendPQExpBuffer(buf, "(%d,%d)",
14544                                                           precision, scale);
14545                 }
14546         }
14547
14548         /*
14549          * char is an internal single-byte data type; Let's make sure we force it
14550          * through with quotes. - thomas 1998-12-13
14551          */
14552         else if (strcmp(typname, "char") == 0)
14553                 appendPQExpBuffer(buf, "\"char\"");
14554         else
14555                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14556
14557         /* Append array qualifier for array types */
14558         if (isarray)
14559                 appendPQExpBuffer(buf, "[]");
14560
14561         result = pg_strdup(buf->data);
14562         destroyPQExpBuffer(buf);
14563
14564         return result;
14565 }
14566
14567 /*
14568  * fmtQualifiedId - convert a qualified name to the proper format for
14569  * the source database.
14570  *
14571  * Like fmtId, use the result before calling again.
14572  */
14573 static const char *
14574 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14575 {
14576         static PQExpBuffer id_return = NULL;
14577
14578         if (id_return)                          /* first time through? */
14579                 resetPQExpBuffer(id_return);
14580         else
14581                 id_return = createPQExpBuffer();
14582
14583         /* Suppress schema name if fetching from pre-7.3 DB */
14584         if (fout->remoteVersion >= 70300 && schema && *schema)
14585         {
14586                 appendPQExpBuffer(id_return, "%s.",
14587                                                   fmtId(schema));
14588         }
14589         appendPQExpBuffer(id_return, "%s",
14590                                           fmtId(id));
14591
14592         return id_return->data;
14593 }
14594
14595 /*
14596  * Return a column list clause for the given relation.
14597  *
14598  * Special case: if there are no undropped columns in the relation, return
14599  * "", not an invalid "()" column list.
14600  */
14601 static const char *
14602 fmtCopyColumnList(const TableInfo *ti)
14603 {
14604         static PQExpBuffer q = NULL;
14605         int                     numatts = ti->numatts;
14606         char      **attnames = ti->attnames;
14607         bool       *attisdropped = ti->attisdropped;
14608         bool            needComma;
14609         int                     i;
14610
14611         if (q)                                          /* first time through? */
14612                 resetPQExpBuffer(q);
14613         else
14614                 q = createPQExpBuffer();
14615
14616         appendPQExpBuffer(q, "(");
14617         needComma = false;
14618         for (i = 0; i < numatts; i++)
14619         {
14620                 if (attisdropped[i])
14621                         continue;
14622                 if (needComma)
14623                         appendPQExpBuffer(q, ", ");
14624                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14625                 needComma = true;
14626         }
14627
14628         if (!needComma)
14629                 return "";                              /* no undropped columns */
14630
14631         appendPQExpBuffer(q, ")");
14632         return q->data;
14633 }