]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Make documentation of --help and --version options more consistent
[postgresql] / src / bin / pg_dump / pg_dump.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_dump.c
4  *        pg_dump is a utility for dumping out a postgres database
5  *        into a script file.
6  *
7  * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *      pg_dump will read the system catalogs in a database and dump out a
11  *      script that reproduces the schema in terms of SQL that is understood
12  *      by PostgreSQL
13  *
14  *      Note that pg_dump runs in a transaction-snapshot mode transaction,
15  *      so it sees a consistent snapshot of the database including system
16  *      catalogs. However, it relies in part on various specialized backend
17  *      functions like pg_get_indexdef(), and those things tend to run on
18  *      SnapshotNow time, ie they look at the currently committed state.  So
19  *      it is possible to get 'cache lookup failed' error if someone
20  *      performs DDL changes while a dump is happening. The window for this
21  *      sort of thing is from the acquisition of the transaction snapshot to
22  *      getSchemaData() (when pg_dump acquires AccessShareLock on every
23  *      table it intends to dump). It isn't very large, but it can happen.
24  *
25  *      http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
26  *
27  * IDENTIFICATION
28  *        src/bin/pg_dump/pg_dump.c
29  *
30  *-------------------------------------------------------------------------
31  */
32
33 #include "postgres_fe.h"
34
35 #include <unistd.h>
36 #include <ctype.h>
37 #ifdef ENABLE_NLS
38 #include <locale.h>
39 #endif
40 #ifdef HAVE_TERMIOS_H
41 #include <termios.h>
42 #endif
43
44 #include "getopt_long.h"
45
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_largeobject.h"
53 #include "catalog/pg_largeobject_metadata.h"
54 #include "catalog/pg_proc.h"
55 #include "catalog/pg_trigger.h"
56 #include "catalog/pg_type.h"
57 #include "libpq/libpq-fs.h"
58
59 #include "pg_backup_archiver.h"
60 #include "pg_backup_db.h"
61 #include "dumpmem.h"
62 #include "dumputils.h"
63
64 extern char *optarg;
65 extern int      optind,
66                         opterr;
67
68
69 typedef struct
70 {
71         const char *descr;                      /* comment for an object */
72         Oid                     classoid;               /* object class (catalog OID) */
73         Oid                     objoid;                 /* object OID */
74         int                     objsubid;               /* subobject (table column #) */
75 } CommentItem;
76
77 typedef struct
78 {
79         const char *provider;           /* label provider of this security label */
80         const char *label;                      /* security label for an object */
81         Oid                     classoid;               /* object class (catalog OID) */
82         Oid                     objoid;                 /* object OID */
83         int                     objsubid;               /* subobject (table column #) */
84 } SecLabelItem;
85
86 /* global decls */
87 bool            g_verbose;                      /* User wants verbose narration of our
88                                                                  * activities. */
89
90 /* various user-settable parameters */
91 bool            schemaOnly;
92 bool            dataOnly;
93 int                     dumpSections;           /* bitmask of chosen sections */
94 bool            aclsSkip;
95 const char *lockWaitTimeout;
96
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
99
100 /* obsolete as of 7.3: */
101 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
102
103 /*
104  * Object inclusion/exclusion lists
105  *
106  * The string lists record the patterns given by command-line switches,
107  * which we then convert to lists of OIDs of matching objects.
108  */
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
113
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
120
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
123
124 char            g_opaque_type[10];      /* name for the opaque type */
125
126 /* placeholders for the delimiters for comments */
127 char            g_comment_start[10];
128 char            g_comment_end[10];
129
130 static const CatalogId nilCatalogId = {0, 0};
131
132 /* flags for various command-line long options */
133 static int      binary_upgrade = 0;
134 static int      disable_dollar_quoting = 0;
135 static int      dump_inserts = 0;
136 static int      column_inserts = 0;
137 static int      no_security_labels = 0;
138 static int      no_unlogged_table_data = 0;
139 static int      serializable_deferrable = 0;
140
141
142 static void help(const char *progname);
143 static void setup_connection(Archive *AH, const char *dumpencoding,
144                                  char *use_role);
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(Archive *fout,
147                                                         SimpleStringList *patterns,
148                                                         SimpleOidList *oids);
149 static void expand_table_name_patterns(Archive *fout,
150                                                    SimpleStringList *patterns,
151                                                    SimpleOidList *oids);
152 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
153 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
154 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
155 static void dumpComment(Archive *fout, const char *target,
156                         const char *namespace, const char *owner,
157                         CatalogId catalogId, int subid, DumpId dumpId);
158 static int findComments(Archive *fout, Oid classoid, Oid objoid,
159                          CommentItem **items);
160 static int      collectComments(Archive *fout, CommentItem **items);
161 static void dumpSecLabel(Archive *fout, const char *target,
162                          const char *namespace, const char *owner,
163                          CatalogId catalogId, int subid, DumpId dumpId);
164 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
165                           SecLabelItem **items);
166 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
167 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
168 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
169 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
170 static void dumpType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
175 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
177 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
178 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
179 static void dumpFunc(Archive *fout, FuncInfo *finfo);
180 static void dumpCast(Archive *fout, CastInfo *cast);
181 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *convinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpTable(Archive *fout, TableInfo *tbinfo);
190 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
191 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
192 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
193 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
194 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
195 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
196 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
197 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
198 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
199 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
200 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
201 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
202 static void dumpUserMappings(Archive *fout,
203                                  const char *servername, const char *namespace,
204                                  const char *owner, CatalogId catalogId, DumpId dumpId);
205 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
206
207 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
208                 const char *type, const char *name, const char *subname,
209                 const char *tag, const char *nspname, const char *owner,
210                 const char *acls);
211
212 static void getDependencies(Archive *fout);
213 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
214 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
215 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
216 static void getTableDataFKConstraints(void);
217 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
218 static char *format_function_arguments_old(Archive *fout,
219                                                           FuncInfo *finfo, int nallargs,
220                                                           char **allargtypes,
221                                                           char **argmodes,
222                                                           char **argnames);
223 static char *format_function_signature(Archive *fout,
224                                                   FuncInfo *finfo, bool honor_quotes);
225 static const char *convertRegProcReference(Archive *fout,
226                                                 const char *proc);
227 static const char *convertOperatorReference(Archive *fout, const char *opr);
228 static const char *convertTSFunction(Archive *fout, Oid funcOid);
229 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
230 static Oid      findLastBuiltinOid_V70(Archive *fout);
231 static void selectSourceSchema(Archive *fout, const char *schemaName);
232 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
233 static char *myFormatType(const char *typname, int32 typmod);
234 static const char *fmtQualifiedId(Archive *fout,
235                            const char *schema, const char *id);
236 static void getBlobs(Archive *fout);
237 static void dumpBlob(Archive *fout, BlobInfo *binfo);
238 static int      dumpBlobs(Archive *fout, void *arg);
239 static void dumpDatabase(Archive *AH);
240 static void dumpEncoding(Archive *AH);
241 static void dumpStdStrings(Archive *AH);
242 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
243                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
244 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
245                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
246 static void binary_upgrade_set_pg_class_oids(Archive *fout,
247                                                                  PQExpBuffer upgrade_buffer,
248                                                                  Oid pg_class_oid, bool is_index);
249 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
250                                                                 DumpableObject *dobj,
251                                                                 const char *objlabel);
252 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
253 static const char *fmtCopyColumnList(const TableInfo *ti);
254 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
255
256
257 int
258 main(int argc, char **argv)
259 {
260         int                     c;
261         const char *filename = NULL;
262         const char *format = "p";
263         const char *dbname = NULL;
264         const char *pghost = NULL;
265         const char *pgport = NULL;
266         const char *username = NULL;
267         const char *dumpencoding = NULL;
268         bool            oids = false;
269         TableInfo  *tblinfo;
270         int                     numTables;
271         DumpableObject **dobjs;
272         int                     numObjs;
273         int                     i;
274         enum trivalue prompt_password = TRI_DEFAULT;
275         int                     compressLevel = -1;
276         int                     plainText = 0;
277         int                     outputClean = 0;
278         int                     outputCreateDB = 0;
279         bool            outputBlobs = false;
280         int                     outputNoOwner = 0;
281         char       *outputSuperuser = NULL;
282         char       *use_role = NULL;
283         int                     my_version;
284         int                     optindex;
285         RestoreOptions *ropt;
286         ArchiveFormat archiveFormat = archUnknown;
287         ArchiveMode archiveMode;
288         Archive    *fout;                       /* the script file */
289
290         static int      disable_triggers = 0;
291         static int      outputNoTablespaces = 0;
292         static int      use_setsessauth = 0;
293
294         static struct option long_options[] = {
295                 {"data-only", no_argument, NULL, 'a'},
296                 {"blobs", no_argument, NULL, 'b'},
297                 {"clean", no_argument, NULL, 'c'},
298                 {"create", no_argument, NULL, 'C'},
299                 {"file", required_argument, NULL, 'f'},
300                 {"format", required_argument, NULL, 'F'},
301                 {"host", required_argument, NULL, 'h'},
302                 {"ignore-version", no_argument, NULL, 'i'},
303                 {"no-reconnect", no_argument, NULL, 'R'},
304                 {"oids", no_argument, NULL, 'o'},
305                 {"no-owner", no_argument, NULL, 'O'},
306                 {"port", required_argument, NULL, 'p'},
307                 {"schema", required_argument, NULL, 'n'},
308                 {"exclude-schema", required_argument, NULL, 'N'},
309                 {"schema-only", no_argument, NULL, 's'},
310                 {"superuser", required_argument, NULL, 'S'},
311                 {"table", required_argument, NULL, 't'},
312                 {"exclude-table", required_argument, NULL, 'T'},
313                 {"no-password", no_argument, NULL, 'w'},
314                 {"password", no_argument, NULL, 'W'},
315                 {"username", required_argument, NULL, 'U'},
316                 {"verbose", no_argument, NULL, 'v'},
317                 {"no-privileges", no_argument, NULL, 'x'},
318                 {"no-acl", no_argument, NULL, 'x'},
319                 {"compress", required_argument, NULL, 'Z'},
320                 {"encoding", required_argument, NULL, 'E'},
321                 {"help", no_argument, NULL, '?'},
322                 {"version", no_argument, NULL, 'V'},
323
324                 /*
325                  * the following options don't have an equivalent short option letter
326                  */
327                 {"attribute-inserts", no_argument, &column_inserts, 1},
328                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
329                 {"column-inserts", no_argument, &column_inserts, 1},
330                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
331                 {"disable-triggers", no_argument, &disable_triggers, 1},
332                 {"exclude-table-data", required_argument, NULL, 4},
333                 {"inserts", no_argument, &dump_inserts, 1},
334                 {"lock-wait-timeout", required_argument, NULL, 2},
335                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
336                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
337                 {"role", required_argument, NULL, 3},
338                 {"section", required_argument, NULL, 5},
339                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
340                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
341                 {"no-security-labels", no_argument, &no_security_labels, 1},
342                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
343
344                 {NULL, 0, NULL, 0}
345         };
346
347         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
348
349         g_verbose = false;
350
351         strcpy(g_comment_start, "-- ");
352         g_comment_end[0] = '\0';
353         strcpy(g_opaque_type, "opaque");
354
355         dataOnly = schemaOnly = false;
356         dumpSections = DUMP_UNSECTIONED;
357         lockWaitTimeout = NULL;
358
359         progname = get_progname(argv[0]);
360
361         /* Set default options based on progname */
362         if (strcmp(progname, "pg_backup") == 0)
363                 format = "c";
364
365         if (argc > 1)
366         {
367                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
368                 {
369                         help(progname);
370                         exit_nicely(0);
371                 }
372                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
373                 {
374                         puts("pg_dump (PostgreSQL) " PG_VERSION);
375                         exit_nicely(0);
376                 }
377         }
378
379         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
380                                                         long_options, &optindex)) != -1)
381         {
382                 switch (c)
383                 {
384                         case 'a':                       /* Dump data only */
385                                 dataOnly = true;
386                                 break;
387
388                         case 'b':                       /* Dump blobs */
389                                 outputBlobs = true;
390                                 break;
391
392                         case 'c':                       /* clean (i.e., drop) schema prior to create */
393                                 outputClean = 1;
394                                 break;
395
396                         case 'C':                       /* Create DB */
397                                 outputCreateDB = 1;
398                                 break;
399
400                         case 'E':                       /* Dump encoding */
401                                 dumpencoding = optarg;
402                                 break;
403
404                         case 'f':
405                                 filename = optarg;
406                                 break;
407
408                         case 'F':
409                                 format = optarg;
410                                 break;
411
412                         case 'h':                       /* server host */
413                                 pghost = optarg;
414                                 break;
415
416                         case 'i':
417                                 /* ignored, deprecated option */
418                                 break;
419
420                         case 'n':                       /* include schema(s) */
421                                 simple_string_list_append(&schema_include_patterns, optarg);
422                                 include_everything = false;
423                                 break;
424
425                         case 'N':                       /* exclude schema(s) */
426                                 simple_string_list_append(&schema_exclude_patterns, optarg);
427                                 break;
428
429                         case 'o':                       /* Dump oids */
430                                 oids = true;
431                                 break;
432
433                         case 'O':                       /* Don't reconnect to match owner */
434                                 outputNoOwner = 1;
435                                 break;
436
437                         case 'p':                       /* server port */
438                                 pgport = optarg;
439                                 break;
440
441                         case 'R':
442                                 /* no-op, still accepted for backwards compatibility */
443                                 break;
444
445                         case 's':                       /* dump schema only */
446                                 schemaOnly = true;
447                                 break;
448
449                         case 'S':                       /* Username for superuser in plain text output */
450                                 outputSuperuser = pg_strdup(optarg);
451                                 break;
452
453                         case 't':                       /* include table(s) */
454                                 simple_string_list_append(&table_include_patterns, optarg);
455                                 include_everything = false;
456                                 break;
457
458                         case 'T':                       /* exclude table(s) */
459                                 simple_string_list_append(&table_exclude_patterns, optarg);
460                                 break;
461
462                         case 'U':
463                                 username = optarg;
464                                 break;
465
466                         case 'v':                       /* verbose */
467                                 g_verbose = true;
468                                 break;
469
470                         case 'w':
471                                 prompt_password = TRI_NO;
472                                 break;
473
474                         case 'W':
475                                 prompt_password = TRI_YES;
476                                 break;
477
478                         case 'x':                       /* skip ACL dump */
479                                 aclsSkip = true;
480                                 break;
481
482                         case 'Z':                       /* Compression Level */
483                                 compressLevel = atoi(optarg);
484                                 break;
485
486                         case 0:
487                                 /* This covers the long options. */
488                                 break;
489
490                         case 2:                         /* lock-wait-timeout */
491                                 lockWaitTimeout = optarg;
492                                 break;
493
494                         case 3:                         /* SET ROLE */
495                                 use_role = optarg;
496                                 break;
497
498                         case 4:                         /* exclude table(s) data */
499                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
500                                 break;
501
502                         case 5:                         /* section */
503                                 set_dump_section(optarg, &dumpSections);
504                                 break;
505
506                         default:
507                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
508                                 exit_nicely(1);
509                 }
510         }
511
512         /* Get database name from command line */
513         if (optind < argc)
514                 dbname = argv[optind++];
515
516         /* Complain if any arguments remain */
517         if (optind < argc)
518         {
519                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
520                                 progname, argv[optind]);
521                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
522                                 progname);
523                 exit_nicely(1);
524         }
525
526         /* --column-inserts implies --inserts */
527         if (column_inserts)
528                 dump_inserts = 1;
529
530         if (dataOnly && schemaOnly)
531                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
532
533         if (dataOnly && outputClean)
534                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
535
536         if (dump_inserts && oids)
537         {
538                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
539                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
540                 exit_nicely(1);
541         }
542
543         /* Identify archive format to emit */
544         archiveFormat = parseArchiveFormat(format, &archiveMode);
545
546         /* archiveFormat specific setup */
547         if (archiveFormat == archNull)
548                 plainText = 1;
549
550         /* Custom and directory formats are compressed by default, others not */
551         if (compressLevel == -1)
552         {
553                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
554                         compressLevel = Z_DEFAULT_COMPRESSION;
555                 else
556                         compressLevel = 0;
557         }
558
559         /* Open the output file */
560         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
561
562         /* Register the cleanup hook */
563         on_exit_close_archive(fout);
564
565         if (fout == NULL)
566                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
567
568         /* Let the archiver know how noisy to be */
569         fout->verbose = g_verbose;
570
571         my_version = parse_version(PG_VERSION);
572         if (my_version < 0)
573                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
574
575         /*
576          * We allow the server to be back to 7.0, and up to any minor release of
577          * our own major version.  (See also version check in pg_dumpall.c.)
578          */
579         fout->minRemoteVersion = 70000;
580         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
581
582         /*
583          * Open the database using the Archiver, so it knows about it. Errors mean
584          * death.
585          */
586         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
587         setup_connection(fout, dumpencoding, use_role);
588
589         /*
590          * Disable security label support if server version < v9.1.x (prevents
591          * access to nonexistent pg_seclabel catalog)
592          */
593         if (fout->remoteVersion < 90100)
594                 no_security_labels = 1;
595
596         /*
597          * Start transaction-snapshot mode transaction to dump consistent data.
598          */
599         ExecuteSqlStatement(fout, "BEGIN");
600         if (fout->remoteVersion >= 90100)
601         {
602                 if (serializable_deferrable)
603                         ExecuteSqlStatement(fout,
604                                                                 "SET TRANSACTION ISOLATION LEVEL "
605                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
606                 else
607                         ExecuteSqlStatement(fout,
608                                                                 "SET TRANSACTION ISOLATION LEVEL "
609                                                                 "REPEATABLE READ");
610         }
611         else
612                 ExecuteSqlStatement(fout,
613                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
614
615         /* Select the appropriate subquery to convert user IDs to names */
616         if (fout->remoteVersion >= 80100)
617                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
618         else if (fout->remoteVersion >= 70300)
619                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
620         else
621                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
622
623         /* Find the last built-in OID, if needed */
624         if (fout->remoteVersion < 70300)
625         {
626                 if (fout->remoteVersion >= 70100)
627                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
628                                                                                                   PQdb(GetConnection(fout)));
629                 else
630                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
631                 if (g_verbose)
632                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
633         }
634
635         /* Expand schema selection patterns into OID lists */
636         if (schema_include_patterns.head != NULL)
637         {
638                 expand_schema_name_patterns(fout, &schema_include_patterns,
639                                                                         &schema_include_oids);
640                 if (schema_include_oids.head == NULL)
641                         exit_horribly(NULL, "No matching schemas were found\n");
642         }
643         expand_schema_name_patterns(fout, &schema_exclude_patterns,
644                                                                 &schema_exclude_oids);
645         /* non-matching exclusion patterns aren't an error */
646
647         /* Expand table selection patterns into OID lists */
648         if (table_include_patterns.head != NULL)
649         {
650                 expand_table_name_patterns(fout, &table_include_patterns,
651                                                                    &table_include_oids);
652                 if (table_include_oids.head == NULL)
653                         exit_horribly(NULL, "No matching tables were found\n");
654         }
655         expand_table_name_patterns(fout, &table_exclude_patterns,
656                                                            &table_exclude_oids);
657
658         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
659                                                            &tabledata_exclude_oids);
660
661         /* non-matching exclusion patterns aren't an error */
662
663         /*
664          * Dumping blobs is now default unless we saw an inclusion switch or -s
665          * ... but even if we did see one of these, -b turns it back on.
666          */
667         if (include_everything && !schemaOnly)
668                 outputBlobs = true;
669
670         /*
671          * Now scan the database and create DumpableObject structs for all the
672          * objects we intend to dump.
673          */
674         tblinfo = getSchemaData(fout, &numTables);
675
676         if (fout->remoteVersion < 80400)
677                 guessConstraintInheritance(tblinfo, numTables);
678
679         if (!schemaOnly)
680         {
681                 getTableData(tblinfo, numTables, oids);
682                 if (dataOnly)
683                         getTableDataFKConstraints();
684         }
685
686         if (outputBlobs)
687                 getBlobs(fout);
688
689         /*
690          * Collect dependency data to assist in ordering the objects.
691          */
692         getDependencies(fout);
693
694         /*
695          * Sort the objects into a safe dump order (no forward references).
696          *
697          * In 7.3 or later, we can rely on dependency information to help us
698          * determine a safe order, so the initial sort is mostly for cosmetic
699          * purposes: we sort by name to ensure that logically identical schemas
700          * will dump identically.  Before 7.3 we don't have dependencies and we
701          * use OID ordering as an (unreliable) guide to creation order.
702          */
703         getDumpableObjects(&dobjs, &numObjs);
704
705         if (fout->remoteVersion >= 70300)
706                 sortDumpableObjectsByTypeName(dobjs, numObjs);
707         else
708                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
709
710         sortDumpableObjects(dobjs, numObjs);
711
712         /*
713          * Create archive TOC entries for all the objects to be dumped, in a safe
714          * order.
715          */
716
717         /* First the special ENCODING and STDSTRINGS entries. */
718         dumpEncoding(fout);
719         dumpStdStrings(fout);
720
721         /* The database item is always next, unless we don't want it at all */
722         if (include_everything && !dataOnly)
723                 dumpDatabase(fout);
724
725         /* Now the rearrangeable objects. */
726         for (i = 0; i < numObjs; i++)
727                 dumpDumpableObject(fout, dobjs[i]);
728
729         /*
730          * Set up options info to ensure we dump what we want.
731          */
732         ropt = NewRestoreOptions();
733         ropt->filename = filename;
734         ropt->dropSchema = outputClean;
735         ropt->dataOnly = dataOnly;
736         ropt->schemaOnly = schemaOnly;
737         ropt->dumpSections = dumpSections;
738         ropt->aclsSkip = aclsSkip;
739         ropt->superuser = outputSuperuser;
740         ropt->createDB = outputCreateDB;
741         ropt->noOwner = outputNoOwner;
742         ropt->noTablespace = outputNoTablespaces;
743         ropt->disable_triggers = disable_triggers;
744         ropt->use_setsessauth = use_setsessauth;
745
746         if (compressLevel == -1)
747                 ropt->compression = 0;
748         else
749                 ropt->compression = compressLevel;
750
751         ropt->suppressDumpWarnings = true;      /* We've already shown them */
752
753         SetArchiveRestoreOptions(fout, ropt);
754
755         /*
756          * And finally we can do the actual output.
757          *
758          * Note: for non-plain-text output formats, the output file is written
759          * inside CloseArchive().  This is, um, bizarre; but not worth changing
760          * right now.
761          */
762         if (plainText)
763                 RestoreArchive(fout);
764
765         CloseArchive(fout);
766
767         exit_nicely(0);
768 }
769
770
771 static void
772 help(const char *progname)
773 {
774         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
775         printf(_("Usage:\n"));
776         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
777
778         printf(_("\nGeneral options:\n"));
779         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
780         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
781                          "                               plain text (default))\n"));
782         printf(_("  -v, --verbose                verbose mode\n"));
783         printf(_("  -V, --version                output version information, then exit\n"));
784         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
785         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
786         printf(_("  -?, --help                   show this help, then exit\n"));
787
788         printf(_("\nOptions controlling the output content:\n"));
789         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
790         printf(_("  -b, --blobs                  include large objects in dump\n"));
791         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
792         printf(_("  -C, --create                 include commands to create database in dump\n"));
793         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
794         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
795         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
796         printf(_("  -o, --oids                   include OIDs in dump\n"));
797         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
798                          "                               plain-text format\n"));
799         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
800         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
801         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
802         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
803         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
804         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
805         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
806         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
807         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
808         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
809         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
810         printf(_("  --no-security-labels         do not dump security label assignments\n"));
811         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
812         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
813         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
814         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
815         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
816         printf(_("  --use-set-session-authorization\n"
817                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
818                          "                               ALTER OWNER commands to set ownership\n"));
819
820         printf(_("\nConnection options:\n"));
821         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
822         printf(_("  -p, --port=PORT          database server port number\n"));
823         printf(_("  -U, --username=NAME      connect as specified database user\n"));
824         printf(_("  -w, --no-password        never prompt for password\n"));
825         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
826         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
827
828         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
829                          "variable value is used.\n\n"));
830         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
831 }
832
833 static void
834 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
835 {
836         PGconn     *conn = GetConnection(AH);
837         const char *std_strings;
838
839         /* Set the client encoding if requested */
840         if (dumpencoding)
841         {
842                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
843                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
844                                                   dumpencoding);
845         }
846
847         /*
848          * Get the active encoding and the standard_conforming_strings setting, so
849          * we know how to escape strings.
850          */
851         AH->encoding = PQclientEncoding(conn);
852
853         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
854         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
855
856         /* Set the role if requested */
857         if (use_role && AH->remoteVersion >= 80100)
858         {
859                 PQExpBuffer query = createPQExpBuffer();
860
861                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
862                 ExecuteSqlStatement(AH, query->data);
863                 destroyPQExpBuffer(query);
864         }
865
866         /* Set the datestyle to ISO to ensure the dump's portability */
867         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
868
869         /* Likewise, avoid using sql_standard intervalstyle */
870         if (AH->remoteVersion >= 80400)
871                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
872
873         /*
874          * If supported, set extra_float_digits so that we can dump float data
875          * exactly (given correctly implemented float I/O code, anyway)
876          */
877         if (AH->remoteVersion >= 90000)
878                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
879         else if (AH->remoteVersion >= 70400)
880                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
881
882         /*
883          * If synchronized scanning is supported, disable it, to prevent
884          * unpredictable changes in row ordering across a dump and reload.
885          */
886         if (AH->remoteVersion >= 80300)
887                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
888
889         /*
890          * Disable timeouts if supported.
891          */
892         if (AH->remoteVersion >= 70300)
893                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
894
895         /*
896          * Quote all identifiers, if requested.
897          */
898         if (quote_all_identifiers && AH->remoteVersion >= 90100)
899                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
900 }
901
902 static ArchiveFormat
903 parseArchiveFormat(const char *format, ArchiveMode *mode)
904 {
905         ArchiveFormat archiveFormat;
906
907         *mode = archModeWrite;
908
909         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
910         {
911                 /* This is used by pg_dumpall, and is not documented */
912                 archiveFormat = archNull;
913                 *mode = archModeAppend;
914         }
915         else if (pg_strcasecmp(format, "c") == 0)
916                 archiveFormat = archCustom;
917         else if (pg_strcasecmp(format, "custom") == 0)
918                 archiveFormat = archCustom;
919         else if (pg_strcasecmp(format, "d") == 0)
920                 archiveFormat = archDirectory;
921         else if (pg_strcasecmp(format, "directory") == 0)
922                 archiveFormat = archDirectory;
923         else if (pg_strcasecmp(format, "p") == 0)
924                 archiveFormat = archNull;
925         else if (pg_strcasecmp(format, "plain") == 0)
926                 archiveFormat = archNull;
927         else if (pg_strcasecmp(format, "t") == 0)
928                 archiveFormat = archTar;
929         else if (pg_strcasecmp(format, "tar") == 0)
930                 archiveFormat = archTar;
931         else
932                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
933         return archiveFormat;
934 }
935
936 /*
937  * Find the OIDs of all schemas matching the given list of patterns,
938  * and append them to the given OID list.
939  */
940 static void
941 expand_schema_name_patterns(Archive *fout,
942                                                         SimpleStringList *patterns,
943                                                         SimpleOidList *oids)
944 {
945         PQExpBuffer query;
946         PGresult   *res;
947         SimpleStringListCell *cell;
948         int                     i;
949
950         if (patterns->head == NULL)
951                 return;                                 /* nothing to do */
952
953         if (fout->remoteVersion < 70300)
954                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
955
956         query = createPQExpBuffer();
957
958         /*
959          * We use UNION ALL rather than UNION; this might sometimes result in
960          * duplicate entries in the OID list, but we don't care.
961          */
962
963         for (cell = patterns->head; cell; cell = cell->next)
964         {
965                 if (cell != patterns->head)
966                         appendPQExpBuffer(query, "UNION ALL\n");
967                 appendPQExpBuffer(query,
968                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
969                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
970                                                           false, NULL, "n.nspname", NULL, NULL);
971         }
972
973         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
974
975         for (i = 0; i < PQntuples(res); i++)
976         {
977                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
978         }
979
980         PQclear(res);
981         destroyPQExpBuffer(query);
982 }
983
984 /*
985  * Find the OIDs of all tables matching the given list of patterns,
986  * and append them to the given OID list.
987  */
988 static void
989 expand_table_name_patterns(Archive *fout,
990                                                    SimpleStringList *patterns, SimpleOidList *oids)
991 {
992         PQExpBuffer query;
993         PGresult   *res;
994         SimpleStringListCell *cell;
995         int                     i;
996
997         if (patterns->head == NULL)
998                 return;                                 /* nothing to do */
999
1000         query = createPQExpBuffer();
1001
1002         /*
1003          * We use UNION ALL rather than UNION; this might sometimes result in
1004          * duplicate entries in the OID list, but we don't care.
1005          */
1006
1007         for (cell = patterns->head; cell; cell = cell->next)
1008         {
1009                 if (cell != patterns->head)
1010                         appendPQExpBuffer(query, "UNION ALL\n");
1011                 appendPQExpBuffer(query,
1012                                                   "SELECT c.oid"
1013                                                   "\nFROM pg_catalog.pg_class c"
1014                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1015                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1016                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1017                                                   RELKIND_FOREIGN_TABLE);
1018                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1019                                                           false, "n.nspname", "c.relname", NULL,
1020                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1021         }
1022
1023         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1024
1025         for (i = 0; i < PQntuples(res); i++)
1026         {
1027                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1028         }
1029
1030         PQclear(res);
1031         destroyPQExpBuffer(query);
1032 }
1033
1034 /*
1035  * selectDumpableNamespace: policy-setting subroutine
1036  *              Mark a namespace as to be dumped or not
1037  */
1038 static void
1039 selectDumpableNamespace(NamespaceInfo *nsinfo)
1040 {
1041         /*
1042          * If specific tables are being dumped, do not dump any complete
1043          * namespaces. If specific namespaces are being dumped, dump just those
1044          * namespaces. Otherwise, dump all non-system namespaces.
1045          */
1046         if (table_include_oids.head != NULL)
1047                 nsinfo->dobj.dump = false;
1048         else if (schema_include_oids.head != NULL)
1049                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1050                                                                                                    nsinfo->dobj.catId.oid);
1051         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1052                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1053                 nsinfo->dobj.dump = false;
1054         else
1055                 nsinfo->dobj.dump = true;
1056
1057         /*
1058          * In any case, a namespace can be excluded by an exclusion switch
1059          */
1060         if (nsinfo->dobj.dump &&
1061                 simple_oid_list_member(&schema_exclude_oids,
1062                                                            nsinfo->dobj.catId.oid))
1063                 nsinfo->dobj.dump = false;
1064 }
1065
1066 /*
1067  * selectDumpableTable: policy-setting subroutine
1068  *              Mark a table as to be dumped or not
1069  */
1070 static void
1071 selectDumpableTable(TableInfo *tbinfo)
1072 {
1073         /*
1074          * If specific tables are being dumped, dump just those tables; else, dump
1075          * according to the parent namespace's dump flag.
1076          */
1077         if (table_include_oids.head != NULL)
1078                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1079                                                                                                    tbinfo->dobj.catId.oid);
1080         else
1081                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1082
1083         /*
1084          * In any case, a table can be excluded by an exclusion switch
1085          */
1086         if (tbinfo->dobj.dump &&
1087                 simple_oid_list_member(&table_exclude_oids,
1088                                                            tbinfo->dobj.catId.oid))
1089                 tbinfo->dobj.dump = false;
1090 }
1091
1092 /*
1093  * selectDumpableType: policy-setting subroutine
1094  *              Mark a type as to be dumped or not
1095  *
1096  * If it's a table's rowtype or an autogenerated array type, we also apply a
1097  * special type code to facilitate sorting into the desired order.      (We don't
1098  * want to consider those to be ordinary types because that would bring tables
1099  * up into the datatype part of the dump order.)  We still set the object's
1100  * dump flag; that's not going to cause the dummy type to be dumped, but we
1101  * need it so that casts involving such types will be dumped correctly -- see
1102  * dumpCast.  This means the flag should be set the same as for the underlying
1103  * object (the table or base type).
1104  */
1105 static void
1106 selectDumpableType(TypeInfo *tyinfo)
1107 {
1108         /* skip complex types, except for standalone composite types */
1109         if (OidIsValid(tyinfo->typrelid) &&
1110                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1111         {
1112                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1113
1114                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1115                 if (tytable != NULL)
1116                         tyinfo->dobj.dump = tytable->dobj.dump;
1117                 else
1118                         tyinfo->dobj.dump = false;
1119                 return;
1120         }
1121
1122         /* skip auto-generated array types */
1123         if (tyinfo->isArray)
1124         {
1125                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1126
1127                 /*
1128                  * Fall through to set the dump flag; we assume that the subsequent
1129                  * rules will do the same thing as they would for the array's base
1130                  * type.  (We cannot reliably look up the base type here, since
1131                  * getTypes may not have processed it yet.)
1132                  */
1133         }
1134
1135         /* dump only types in dumpable namespaces */
1136         if (!tyinfo->dobj.namespace->dobj.dump)
1137                 tyinfo->dobj.dump = false;
1138
1139         /* skip undefined placeholder types */
1140         else if (!tyinfo->isDefined)
1141                 tyinfo->dobj.dump = false;
1142
1143         else
1144                 tyinfo->dobj.dump = true;
1145 }
1146
1147 /*
1148  * selectDumpableDefaultACL: policy-setting subroutine
1149  *              Mark a default ACL as to be dumped or not
1150  *
1151  * For per-schema default ACLs, dump if the schema is to be dumped.
1152  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1153  * and aclsSkip are checked separately.
1154  */
1155 static void
1156 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1157 {
1158         if (dinfo->dobj.namespace)
1159                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1160         else
1161                 dinfo->dobj.dump = include_everything;
1162 }
1163
1164 /*
1165  * selectDumpableExtension: policy-setting subroutine
1166  *              Mark an extension as to be dumped or not
1167  *
1168  * Normally, we dump all extensions, or none of them if include_everything
1169  * is false (i.e., a --schema or --table switch was given).  However, in
1170  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1171  * assume those will already be installed in the target database.  We identify
1172  * such extensions by their having OIDs in the range reserved for initdb.
1173  */
1174 static void
1175 selectDumpableExtension(ExtensionInfo *extinfo)
1176 {
1177         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1178                 extinfo->dobj.dump = false;
1179         else
1180                 extinfo->dobj.dump = include_everything;
1181 }
1182
1183 /*
1184  * selectDumpableObject: policy-setting subroutine
1185  *              Mark a generic dumpable object as to be dumped or not
1186  *
1187  * Use this only for object types without a special-case routine above.
1188  */
1189 static void
1190 selectDumpableObject(DumpableObject *dobj)
1191 {
1192         /*
1193          * Default policy is to dump if parent namespace is dumpable, or always
1194          * for non-namespace-associated items.
1195          */
1196         if (dobj->namespace)
1197                 dobj->dump = dobj->namespace->dobj.dump;
1198         else
1199                 dobj->dump = true;
1200 }
1201
1202 /*
1203  *      Dump a table's contents for loading using the COPY command
1204  *      - this routine is called by the Archiver when it wants the table
1205  *        to be dumped.
1206  */
1207
1208 static int
1209 dumpTableData_copy(Archive *fout, void *dcontext)
1210 {
1211         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1212         TableInfo  *tbinfo = tdinfo->tdtable;
1213         const char *classname = tbinfo->dobj.name;
1214         const bool      hasoids = tbinfo->hasoids;
1215         const bool      oids = tdinfo->oids;
1216         PQExpBuffer q = createPQExpBuffer();
1217         PGconn     *conn = GetConnection(fout);
1218         PGresult   *res;
1219         int                     ret;
1220         char       *copybuf;
1221         const char *column_list;
1222
1223         if (g_verbose)
1224                 write_msg(NULL, "dumping contents of table %s\n", classname);
1225
1226         /*
1227          * Make sure we are in proper schema.  We will qualify the table name
1228          * below anyway (in case its name conflicts with a pg_catalog table); but
1229          * this ensures reproducible results in case the table contains regproc,
1230          * regclass, etc columns.
1231          */
1232         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1233
1234         /*
1235          * If possible, specify the column list explicitly so that we have no
1236          * possibility of retrieving data in the wrong column order.  (The default
1237          * column ordering of COPY will not be what we want in certain corner
1238          * cases involving ADD COLUMN and inheritance.)
1239          */
1240         if (fout->remoteVersion >= 70300)
1241                 column_list = fmtCopyColumnList(tbinfo);
1242         else
1243                 column_list = "";               /* can't select columns in COPY */
1244
1245         if (oids && hasoids)
1246         {
1247                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1248                                                   fmtQualifiedId(fout,
1249                                                                                  tbinfo->dobj.namespace->dobj.name,
1250                                                                                  classname),
1251                                                   column_list);
1252         }
1253         else if (tdinfo->filtercond)
1254         {
1255                 /* Note: this syntax is only supported in 8.2 and up */
1256                 appendPQExpBufferStr(q, "COPY (SELECT ");
1257                 /* klugery to get rid of parens in column list */
1258                 if (strlen(column_list) > 2)
1259                 {
1260                         appendPQExpBufferStr(q, column_list + 1);
1261                         q->data[q->len - 1] = ' ';
1262                 }
1263                 else
1264                         appendPQExpBufferStr(q, "* ");
1265                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1266                                                   fmtQualifiedId(fout,
1267                                                                                  tbinfo->dobj.namespace->dobj.name,
1268                                                                                  classname),
1269                                                   tdinfo->filtercond);
1270         }
1271         else
1272         {
1273                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1274                                                   fmtQualifiedId(fout,
1275                                                                                  tbinfo->dobj.namespace->dobj.name,
1276                                                                                  classname),
1277                                                   column_list);
1278         }
1279         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1280         PQclear(res);
1281
1282         for (;;)
1283         {
1284                 ret = PQgetCopyData(conn, &copybuf, 0);
1285
1286                 if (ret < 0)
1287                         break;                          /* done or error */
1288
1289                 if (copybuf)
1290                 {
1291                         WriteData(fout, copybuf, ret);
1292                         PQfreemem(copybuf);
1293                 }
1294
1295                 /* ----------
1296                  * THROTTLE:
1297                  *
1298                  * There was considerable discussion in late July, 2000 regarding
1299                  * slowing down pg_dump when backing up large tables. Users with both
1300                  * slow & fast (multi-processor) machines experienced performance
1301                  * degradation when doing a backup.
1302                  *
1303                  * Initial attempts based on sleeping for a number of ms for each ms
1304                  * of work were deemed too complex, then a simple 'sleep in each loop'
1305                  * implementation was suggested. The latter failed because the loop
1306                  * was too tight. Finally, the following was implemented:
1307                  *
1308                  * If throttle is non-zero, then
1309                  *              See how long since the last sleep.
1310                  *              Work out how long to sleep (based on ratio).
1311                  *              If sleep is more than 100ms, then
1312                  *                      sleep
1313                  *                      reset timer
1314                  *              EndIf
1315                  * EndIf
1316                  *
1317                  * where the throttle value was the number of ms to sleep per ms of
1318                  * work. The calculation was done in each loop.
1319                  *
1320                  * Most of the hard work is done in the backend, and this solution
1321                  * still did not work particularly well: on slow machines, the ratio
1322                  * was 50:1, and on medium paced machines, 1:1, and on fast
1323                  * multi-processor machines, it had little or no effect, for reasons
1324                  * that were unclear.
1325                  *
1326                  * Further discussion ensued, and the proposal was dropped.
1327                  *
1328                  * For those people who want this feature, it can be implemented using
1329                  * gettimeofday in each loop, calculating the time since last sleep,
1330                  * multiplying that by the sleep ratio, then if the result is more
1331                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1332                  * function to sleep for a subsecond period ie.
1333                  *
1334                  * select(0, NULL, NULL, NULL, &tvi);
1335                  *
1336                  * This will return after the interval specified in the structure tvi.
1337                  * Finally, call gettimeofday again to save the 'last sleep time'.
1338                  * ----------
1339                  */
1340         }
1341         archprintf(fout, "\\.\n\n\n");
1342
1343         if (ret == -2)
1344         {
1345                 /* copy data transfer failed */
1346                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1347                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1348                 write_msg(NULL, "The command was: %s\n", q->data);
1349                 exit_nicely(1);
1350         }
1351
1352         /* Check command status and return to normal libpq state */
1353         res = PQgetResult(conn);
1354         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1355         {
1356                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1357                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1358                 write_msg(NULL, "The command was: %s\n", q->data);
1359                 exit_nicely(1);
1360         }
1361         PQclear(res);
1362
1363         destroyPQExpBuffer(q);
1364         return 1;
1365 }
1366
1367 /*
1368  * Dump table data using INSERT commands.
1369  *
1370  * Caution: when we restore from an archive file direct to database, the
1371  * INSERT commands emitted by this function have to be parsed by
1372  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1373  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1374  */
1375 static int
1376 dumpTableData_insert(Archive *fout, void *dcontext)
1377 {
1378         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1379         TableInfo  *tbinfo = tdinfo->tdtable;
1380         const char *classname = tbinfo->dobj.name;
1381         PQExpBuffer q = createPQExpBuffer();
1382         PGresult   *res;
1383         int                     tuple;
1384         int                     nfields;
1385         int                     field;
1386
1387         /*
1388          * Make sure we are in proper schema.  We will qualify the table name
1389          * below anyway (in case its name conflicts with a pg_catalog table); but
1390          * this ensures reproducible results in case the table contains regproc,
1391          * regclass, etc columns.
1392          */
1393         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1394
1395         if (fout->remoteVersion >= 70100)
1396         {
1397                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1398                                                   "SELECT * FROM ONLY %s",
1399                                                   fmtQualifiedId(fout,
1400                                                                                  tbinfo->dobj.namespace->dobj.name,
1401                                                                                  classname));
1402         }
1403         else
1404         {
1405                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1406                                                   "SELECT * FROM %s",
1407                                                   fmtQualifiedId(fout,
1408                                                                                  tbinfo->dobj.namespace->dobj.name,
1409                                                                                  classname));
1410         }
1411         if (tdinfo->filtercond)
1412                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1413
1414         ExecuteSqlStatement(fout, q->data);
1415
1416         while (1)
1417         {
1418                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1419                                                           PGRES_TUPLES_OK);
1420                 nfields = PQnfields(res);
1421                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1422                 {
1423                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1424                         if (nfields == 0)
1425                         {
1426                                 /* corner case for zero-column table */
1427                                 archprintf(fout, "DEFAULT VALUES;\n");
1428                                 continue;
1429                         }
1430                         if (column_inserts)
1431                         {
1432                                 resetPQExpBuffer(q);
1433                                 appendPQExpBuffer(q, "(");
1434                                 for (field = 0; field < nfields; field++)
1435                                 {
1436                                         if (field > 0)
1437                                                 appendPQExpBuffer(q, ", ");
1438                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1439                                 }
1440                                 appendPQExpBuffer(q, ") ");
1441                                 archputs(q->data, fout);
1442                         }
1443                         archprintf(fout, "VALUES (");
1444                         for (field = 0; field < nfields; field++)
1445                         {
1446                                 if (field > 0)
1447                                         archprintf(fout, ", ");
1448                                 if (PQgetisnull(res, tuple, field))
1449                                 {
1450                                         archprintf(fout, "NULL");
1451                                         continue;
1452                                 }
1453
1454                                 /* XXX This code is partially duplicated in ruleutils.c */
1455                                 switch (PQftype(res, field))
1456                                 {
1457                                         case INT2OID:
1458                                         case INT4OID:
1459                                         case INT8OID:
1460                                         case OIDOID:
1461                                         case FLOAT4OID:
1462                                         case FLOAT8OID:
1463                                         case NUMERICOID:
1464                                                 {
1465                                                         /*
1466                                                          * These types are printed without quotes unless
1467                                                          * they contain values that aren't accepted by the
1468                                                          * scanner unquoted (e.g., 'NaN').      Note that
1469                                                          * strtod() and friends might accept NaN, so we
1470                                                          * can't use that to test.
1471                                                          *
1472                                                          * In reality we only need to defend against
1473                                                          * infinity and NaN, so we need not get too crazy
1474                                                          * about pattern matching here.
1475                                                          */
1476                                                         const char *s = PQgetvalue(res, tuple, field);
1477
1478                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1479                                                                 archprintf(fout, "%s", s);
1480                                                         else
1481                                                                 archprintf(fout, "'%s'", s);
1482                                                 }
1483                                                 break;
1484
1485                                         case BITOID:
1486                                         case VARBITOID:
1487                                                 archprintf(fout, "B'%s'",
1488                                                                    PQgetvalue(res, tuple, field));
1489                                                 break;
1490
1491                                         case BOOLOID:
1492                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1493                                                         archprintf(fout, "true");
1494                                                 else
1495                                                         archprintf(fout, "false");
1496                                                 break;
1497
1498                                         default:
1499                                                 /* All other types are printed as string literals. */
1500                                                 resetPQExpBuffer(q);
1501                                                 appendStringLiteralAH(q,
1502                                                                                           PQgetvalue(res, tuple, field),
1503                                                                                           fout);
1504                                                 archputs(q->data, fout);
1505                                                 break;
1506                                 }
1507                         }
1508                         archprintf(fout, ");\n");
1509                 }
1510
1511                 if (PQntuples(res) <= 0)
1512                 {
1513                         PQclear(res);
1514                         break;
1515                 }
1516                 PQclear(res);
1517         }
1518
1519         archprintf(fout, "\n\n");
1520
1521         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1522
1523         destroyPQExpBuffer(q);
1524         return 1;
1525 }
1526
1527
1528 /*
1529  * dumpTableData -
1530  *        dump the contents of a single table
1531  *
1532  * Actually, this just makes an ArchiveEntry for the table contents.
1533  */
1534 static void
1535 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1536 {
1537         TableInfo  *tbinfo = tdinfo->tdtable;
1538         PQExpBuffer copyBuf = createPQExpBuffer();
1539         DataDumperPtr dumpFn;
1540         char       *copyStmt;
1541
1542         if (!dump_inserts)
1543         {
1544                 /* Dump/restore using COPY */
1545                 dumpFn = dumpTableData_copy;
1546                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1547                 appendPQExpBuffer(copyBuf, "COPY %s ",
1548                                                   fmtId(tbinfo->dobj.name));
1549                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1550                                                   fmtCopyColumnList(tbinfo),
1551                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1552                 copyStmt = copyBuf->data;
1553         }
1554         else
1555         {
1556                 /* Restore using INSERT */
1557                 dumpFn = dumpTableData_insert;
1558                 copyStmt = NULL;
1559         }
1560
1561         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1562                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1563                                  NULL, tbinfo->rolname,
1564                                  false, "TABLE DATA", SECTION_DATA,
1565                                  "", "", copyStmt,
1566                                  tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1567                                  dumpFn, tdinfo);
1568
1569         destroyPQExpBuffer(copyBuf);
1570 }
1571
1572 /*
1573  * getTableData -
1574  *        set up dumpable objects representing the contents of tables
1575  */
1576 static void
1577 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1578 {
1579         int                     i;
1580
1581         for (i = 0; i < numTables; i++)
1582         {
1583                 if (tblinfo[i].dobj.dump)
1584                         makeTableDataInfo(&(tblinfo[i]), oids);
1585         }
1586 }
1587
1588 /*
1589  * Make a dumpable object for the data of this specific table
1590  *
1591  * Note: we make a TableDataInfo if and only if we are going to dump the
1592  * table data; the "dump" flag in such objects isn't used.
1593  */
1594 static void
1595 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1596 {
1597         TableDataInfo *tdinfo;
1598
1599         /*
1600          * Nothing to do if we already decided to dump the table.  This will
1601          * happen for "config" tables.
1602          */
1603         if (tbinfo->dataObj != NULL)
1604                 return;
1605
1606         /* Skip VIEWs (no data to dump) */
1607         if (tbinfo->relkind == RELKIND_VIEW)
1608                 return;
1609         /* Skip SEQUENCEs (handled elsewhere) */
1610         if (tbinfo->relkind == RELKIND_SEQUENCE)
1611                 return;
1612         /* Skip FOREIGN TABLEs (no data to dump) */
1613         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1614                 return;
1615
1616         /* Don't dump data in unlogged tables, if so requested */
1617         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1618                 no_unlogged_table_data)
1619                 return;
1620
1621         /* Check that the data is not explicitly excluded */
1622         if (simple_oid_list_member(&tabledata_exclude_oids,
1623                                                            tbinfo->dobj.catId.oid))
1624                 return;
1625
1626         /* OK, let's dump it */
1627         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1628
1629         tdinfo->dobj.objType = DO_TABLE_DATA;
1630
1631         /*
1632          * Note: use tableoid 0 so that this object won't be mistaken for
1633          * something that pg_depend entries apply to.
1634          */
1635         tdinfo->dobj.catId.tableoid = 0;
1636         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1637         AssignDumpId(&tdinfo->dobj);
1638         tdinfo->dobj.name = tbinfo->dobj.name;
1639         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1640         tdinfo->tdtable = tbinfo;
1641         tdinfo->oids = oids;
1642         tdinfo->filtercond = NULL;      /* might get set later */
1643         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1644
1645         tbinfo->dataObj = tdinfo;
1646 }
1647
1648 /*
1649  * getTableDataFKConstraints -
1650  *        add dump-order dependencies reflecting foreign key constraints
1651  *
1652  * This code is executed only in a data-only dump --- in schema+data dumps
1653  * we handle foreign key issues by not creating the FK constraints until
1654  * after the data is loaded.  In a data-only dump, however, we want to
1655  * order the table data objects in such a way that a table's referenced
1656  * tables are restored first.  (In the presence of circular references or
1657  * self-references this may be impossible; we'll detect and complain about
1658  * that during the dependency sorting step.)
1659  */
1660 static void
1661 getTableDataFKConstraints(void)
1662 {
1663         DumpableObject **dobjs;
1664         int                     numObjs;
1665         int                     i;
1666
1667         /* Search through all the dumpable objects for FK constraints */
1668         getDumpableObjects(&dobjs, &numObjs);
1669         for (i = 0; i < numObjs; i++)
1670         {
1671                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1672                 {
1673                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1674                         TableInfo  *ftable;
1675
1676                         /* Not interesting unless both tables are to be dumped */
1677                         if (cinfo->contable == NULL ||
1678                                 cinfo->contable->dataObj == NULL)
1679                                 continue;
1680                         ftable = findTableByOid(cinfo->confrelid);
1681                         if (ftable == NULL ||
1682                                 ftable->dataObj == NULL)
1683                                 continue;
1684
1685                         /*
1686                          * Okay, make referencing table's TABLE_DATA object depend on the
1687                          * referenced table's TABLE_DATA object.
1688                          */
1689                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1690                                                                 ftable->dataObj->dobj.dumpId);
1691                 }
1692         }
1693         free(dobjs);
1694 }
1695
1696
1697 /*
1698  * guessConstraintInheritance:
1699  *      In pre-8.4 databases, we can't tell for certain which constraints
1700  *      are inherited.  We assume a CHECK constraint is inherited if its name
1701  *      matches the name of any constraint in the parent.  Originally this code
1702  *      tried to compare the expression texts, but that can fail for various
1703  *      reasons --- for example, if the parent and child tables are in different
1704  *      schemas, reverse-listing of function calls may produce different text
1705  *      (schema-qualified or not) depending on search path.
1706  *
1707  *      In 8.4 and up we can rely on the conislocal field to decide which
1708  *      constraints must be dumped; much safer.
1709  *
1710  *      This function assumes all conislocal flags were initialized to TRUE.
1711  *      It clears the flag on anything that seems to be inherited.
1712  */
1713 static void
1714 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1715 {
1716         int                     i,
1717                                 j,
1718                                 k;
1719
1720         for (i = 0; i < numTables; i++)
1721         {
1722                 TableInfo  *tbinfo = &(tblinfo[i]);
1723                 int                     numParents;
1724                 TableInfo **parents;
1725                 TableInfo  *parent;
1726
1727                 /* Sequences and views never have parents */
1728                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1729                         tbinfo->relkind == RELKIND_VIEW)
1730                         continue;
1731
1732                 /* Don't bother computing anything for non-target tables, either */
1733                 if (!tbinfo->dobj.dump)
1734                         continue;
1735
1736                 numParents = tbinfo->numParents;
1737                 parents = tbinfo->parents;
1738
1739                 if (numParents == 0)
1740                         continue;                       /* nothing to see here, move along */
1741
1742                 /* scan for inherited CHECK constraints */
1743                 for (j = 0; j < tbinfo->ncheck; j++)
1744                 {
1745                         ConstraintInfo *constr;
1746
1747                         constr = &(tbinfo->checkexprs[j]);
1748
1749                         for (k = 0; k < numParents; k++)
1750                         {
1751                                 int                     l;
1752
1753                                 parent = parents[k];
1754                                 for (l = 0; l < parent->ncheck; l++)
1755                                 {
1756                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1757
1758                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1759                                         {
1760                                                 constr->conislocal = false;
1761                                                 break;
1762                                         }
1763                                 }
1764                                 if (!constr->conislocal)
1765                                         break;
1766                         }
1767                 }
1768         }
1769 }
1770
1771
1772 /*
1773  * dumpDatabase:
1774  *      dump the database definition
1775  */
1776 static void
1777 dumpDatabase(Archive *fout)
1778 {
1779         PQExpBuffer dbQry = createPQExpBuffer();
1780         PQExpBuffer delQry = createPQExpBuffer();
1781         PQExpBuffer creaQry = createPQExpBuffer();
1782         PGconn     *conn = GetConnection(fout);
1783         PGresult   *res;
1784         int                     i_tableoid,
1785                                 i_oid,
1786                                 i_dba,
1787                                 i_encoding,
1788                                 i_collate,
1789                                 i_ctype,
1790                                 i_frozenxid,
1791                                 i_tablespace;
1792         CatalogId       dbCatId;
1793         DumpId          dbDumpId;
1794         const char *datname,
1795                            *dba,
1796                            *encoding,
1797                            *collate,
1798                            *ctype,
1799                            *tablespace;
1800         uint32          frozenxid;
1801
1802         datname = PQdb(conn);
1803
1804         if (g_verbose)
1805                 write_msg(NULL, "saving database definition\n");
1806
1807         /* Make sure we are in proper schema */
1808         selectSourceSchema(fout, "pg_catalog");
1809
1810         /* Get the database owner and parameters from pg_database */
1811         if (fout->remoteVersion >= 80400)
1812         {
1813                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1814                                                   "(%s datdba) AS dba, "
1815                                                   "pg_encoding_to_char(encoding) AS encoding, "
1816                                                   "datcollate, datctype, datfrozenxid, "
1817                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1818                                           "shobj_description(oid, 'pg_database') AS description "
1819
1820                                                   "FROM pg_database "
1821                                                   "WHERE datname = ",
1822                                                   username_subquery);
1823                 appendStringLiteralAH(dbQry, datname, fout);
1824         }
1825         else if (fout->remoteVersion >= 80200)
1826         {
1827                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1828                                                   "(%s datdba) AS dba, "
1829                                                   "pg_encoding_to_char(encoding) AS encoding, "
1830                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1831                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1832                                           "shobj_description(oid, 'pg_database') AS description "
1833
1834                                                   "FROM pg_database "
1835                                                   "WHERE datname = ",
1836                                                   username_subquery);
1837                 appendStringLiteralAH(dbQry, datname, fout);
1838         }
1839         else if (fout->remoteVersion >= 80000)
1840         {
1841                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1842                                                   "(%s datdba) AS dba, "
1843                                                   "pg_encoding_to_char(encoding) AS encoding, "
1844                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1845                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1846                                                   "FROM pg_database "
1847                                                   "WHERE datname = ",
1848                                                   username_subquery);
1849                 appendStringLiteralAH(dbQry, datname, fout);
1850         }
1851         else if (fout->remoteVersion >= 70100)
1852         {
1853                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1854                                                   "(%s datdba) AS dba, "
1855                                                   "pg_encoding_to_char(encoding) AS encoding, "
1856                                                   "NULL AS datcollate, NULL AS datctype, "
1857                                                   "0 AS datfrozenxid, "
1858                                                   "NULL AS tablespace "
1859                                                   "FROM pg_database "
1860                                                   "WHERE datname = ",
1861                                                   username_subquery);
1862                 appendStringLiteralAH(dbQry, datname, fout);
1863         }
1864         else
1865         {
1866                 appendPQExpBuffer(dbQry, "SELECT "
1867                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1868                                                   "oid, "
1869                                                   "(%s datdba) AS dba, "
1870                                                   "pg_encoding_to_char(encoding) AS encoding, "
1871                                                   "NULL AS datcollate, NULL AS datctype, "
1872                                                   "0 AS datfrozenxid, "
1873                                                   "NULL AS tablespace "
1874                                                   "FROM pg_database "
1875                                                   "WHERE datname = ",
1876                                                   username_subquery);
1877                 appendStringLiteralAH(dbQry, datname, fout);
1878         }
1879
1880         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1881
1882         i_tableoid = PQfnumber(res, "tableoid");
1883         i_oid = PQfnumber(res, "oid");
1884         i_dba = PQfnumber(res, "dba");
1885         i_encoding = PQfnumber(res, "encoding");
1886         i_collate = PQfnumber(res, "datcollate");
1887         i_ctype = PQfnumber(res, "datctype");
1888         i_frozenxid = PQfnumber(res, "datfrozenxid");
1889         i_tablespace = PQfnumber(res, "tablespace");
1890
1891         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1892         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1893         dba = PQgetvalue(res, 0, i_dba);
1894         encoding = PQgetvalue(res, 0, i_encoding);
1895         collate = PQgetvalue(res, 0, i_collate);
1896         ctype = PQgetvalue(res, 0, i_ctype);
1897         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1898         tablespace = PQgetvalue(res, 0, i_tablespace);
1899
1900         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1901                                           fmtId(datname));
1902         if (strlen(encoding) > 0)
1903         {
1904                 appendPQExpBuffer(creaQry, " ENCODING = ");
1905                 appendStringLiteralAH(creaQry, encoding, fout);
1906         }
1907         if (strlen(collate) > 0)
1908         {
1909                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1910                 appendStringLiteralAH(creaQry, collate, fout);
1911         }
1912         if (strlen(ctype) > 0)
1913         {
1914                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1915                 appendStringLiteralAH(creaQry, ctype, fout);
1916         }
1917         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1918                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1919                                                   fmtId(tablespace));
1920         appendPQExpBuffer(creaQry, ";\n");
1921
1922         if (binary_upgrade)
1923         {
1924                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1925                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1926                                                   "SET datfrozenxid = '%u'\n"
1927                                                   "WHERE        datname = ",
1928                                                   frozenxid);
1929                 appendStringLiteralAH(creaQry, datname, fout);
1930                 appendPQExpBuffer(creaQry, ";\n");
1931
1932         }
1933
1934         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1935                                           fmtId(datname));
1936
1937         dbDumpId = createDumpId();
1938
1939         ArchiveEntry(fout,
1940                                  dbCatId,               /* catalog ID */
1941                                  dbDumpId,              /* dump ID */
1942                                  datname,               /* Name */
1943                                  NULL,                  /* Namespace */
1944                                  NULL,                  /* Tablespace */
1945                                  dba,                   /* Owner */
1946                                  false,                 /* with oids */
1947                                  "DATABASE",    /* Desc */
1948                                  SECTION_PRE_DATA,              /* Section */
1949                                  creaQry->data, /* Create */
1950                                  delQry->data,  /* Del */
1951                                  NULL,                  /* Copy */
1952                                  NULL,                  /* Deps */
1953                                  0,                             /* # Deps */
1954                                  NULL,                  /* Dumper */
1955                                  NULL);                 /* Dumper Arg */
1956
1957         /*
1958          * pg_largeobject and pg_largeobject_metadata come from the old system
1959          * intact, so set their relfrozenxids.
1960          */
1961         if (binary_upgrade)
1962         {
1963                 PGresult   *lo_res;
1964                 PQExpBuffer loFrozenQry = createPQExpBuffer();
1965                 PQExpBuffer loOutQry = createPQExpBuffer();
1966                 int                     i_relfrozenxid;
1967
1968                 /*
1969                  * pg_largeobject
1970                  */
1971                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1972                                                   "FROM pg_catalog.pg_class\n"
1973                                                   "WHERE oid = %u;\n",
1974                                                   LargeObjectRelationId);
1975
1976                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1977
1978                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1979
1980                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
1981                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1982                                                   "SET relfrozenxid = '%u'\n"
1983                                                   "WHERE oid = %u;\n",
1984                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1985                                                   LargeObjectRelationId);
1986                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
1987                                          "pg_largeobject", NULL, NULL, "",
1988                                          false, "pg_largeobject", SECTION_PRE_DATA,
1989                                          loOutQry->data, "", NULL,
1990                                          NULL, 0,
1991                                          NULL, NULL);
1992
1993                 PQclear(lo_res);
1994
1995                 /*
1996                  * pg_largeobject_metadata
1997                  */
1998                 if (fout->remoteVersion >= 90000)
1999                 {
2000                         resetPQExpBuffer(loFrozenQry);
2001                         resetPQExpBuffer(loOutQry);
2002
2003                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2004                                                           "FROM pg_catalog.pg_class\n"
2005                                                           "WHERE oid = %u;\n",
2006                                                           LargeObjectMetadataRelationId);
2007
2008                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2009
2010                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2011
2012                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2013                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2014                                                           "SET relfrozenxid = '%u'\n"
2015                                                           "WHERE oid = %u;\n",
2016                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2017                                                           LargeObjectMetadataRelationId);
2018                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2019                                                  "pg_largeobject_metadata", NULL, NULL, "",
2020                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2021                                                  loOutQry->data, "", NULL,
2022                                                  NULL, 0,
2023                                                  NULL, NULL);
2024
2025                         PQclear(lo_res);
2026                 }
2027
2028                 destroyPQExpBuffer(loFrozenQry);
2029                 destroyPQExpBuffer(loOutQry);
2030         }
2031
2032         /* Dump DB comment if any */
2033         if (fout->remoteVersion >= 80200)
2034         {
2035                 /*
2036                  * 8.2 keeps comments on shared objects in a shared table, so we
2037                  * cannot use the dumpComment used for other database objects.
2038                  */
2039                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2040
2041                 if (comment && strlen(comment))
2042                 {
2043                         resetPQExpBuffer(dbQry);
2044
2045                         /*
2046                          * Generates warning when loaded into a differently-named
2047                          * database.
2048                          */
2049                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2050                         appendStringLiteralAH(dbQry, comment, fout);
2051                         appendPQExpBuffer(dbQry, ";\n");
2052
2053                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2054                                                  dba, false, "COMMENT", SECTION_NONE,
2055                                                  dbQry->data, "", NULL,
2056                                                  &dbDumpId, 1, NULL, NULL);
2057                 }
2058         }
2059         else
2060         {
2061                 resetPQExpBuffer(dbQry);
2062                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2063                 dumpComment(fout, dbQry->data, NULL, "",
2064                                         dbCatId, 0, dbDumpId);
2065         }
2066
2067         PQclear(res);
2068
2069         /* Dump shared security label. */
2070         if (!no_security_labels && fout->remoteVersion >= 90200)
2071         {
2072                 PQExpBuffer seclabelQry = createPQExpBuffer();
2073
2074                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2075                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2076                 resetPQExpBuffer(seclabelQry);
2077                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2078                 if (strlen(seclabelQry->data))
2079                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2080                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2081                                                  seclabelQry->data, "", NULL,
2082                                                  &dbDumpId, 1, NULL, NULL);
2083                 destroyPQExpBuffer(seclabelQry);
2084         }
2085
2086         destroyPQExpBuffer(dbQry);
2087         destroyPQExpBuffer(delQry);
2088         destroyPQExpBuffer(creaQry);
2089 }
2090
2091
2092 /*
2093  * dumpEncoding: put the correct encoding into the archive
2094  */
2095 static void
2096 dumpEncoding(Archive *AH)
2097 {
2098         const char *encname = pg_encoding_to_char(AH->encoding);
2099         PQExpBuffer qry = createPQExpBuffer();
2100
2101         if (g_verbose)
2102                 write_msg(NULL, "saving encoding = %s\n", encname);
2103
2104         appendPQExpBuffer(qry, "SET client_encoding = ");
2105         appendStringLiteralAH(qry, encname, AH);
2106         appendPQExpBuffer(qry, ";\n");
2107
2108         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2109                                  "ENCODING", NULL, NULL, "",
2110                                  false, "ENCODING", SECTION_PRE_DATA,
2111                                  qry->data, "", NULL,
2112                                  NULL, 0,
2113                                  NULL, NULL);
2114
2115         destroyPQExpBuffer(qry);
2116 }
2117
2118
2119 /*
2120  * dumpStdStrings: put the correct escape string behavior into the archive
2121  */
2122 static void
2123 dumpStdStrings(Archive *AH)
2124 {
2125         const char *stdstrings = AH->std_strings ? "on" : "off";
2126         PQExpBuffer qry = createPQExpBuffer();
2127
2128         if (g_verbose)
2129                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2130                                   stdstrings);
2131
2132         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2133                                           stdstrings);
2134
2135         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2136                                  "STDSTRINGS", NULL, NULL, "",
2137                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2138                                  qry->data, "", NULL,
2139                                  NULL, 0,
2140                                  NULL, NULL);
2141
2142         destroyPQExpBuffer(qry);
2143 }
2144
2145
2146 /*
2147  * getBlobs:
2148  *      Collect schema-level data about large objects
2149  */
2150 static void
2151 getBlobs(Archive *fout)
2152 {
2153         PQExpBuffer blobQry = createPQExpBuffer();
2154         BlobInfo   *binfo;
2155         DumpableObject *bdata;
2156         PGresult   *res;
2157         int                     ntups;
2158         int                     i;
2159
2160         /* Verbose message */
2161         if (g_verbose)
2162                 write_msg(NULL, "reading large objects\n");
2163
2164         /* Make sure we are in proper schema */
2165         selectSourceSchema(fout, "pg_catalog");
2166
2167         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2168         if (fout->remoteVersion >= 90000)
2169                 appendPQExpBuffer(blobQry,
2170                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2171                                                   " FROM pg_largeobject_metadata",
2172                                                   username_subquery);
2173         else if (fout->remoteVersion >= 70100)
2174                 appendPQExpBuffer(blobQry,
2175                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2176                                                   " FROM pg_largeobject");
2177         else
2178                 appendPQExpBuffer(blobQry,
2179                                                   "SELECT oid, NULL::oid, NULL::oid"
2180                                                   " FROM pg_class WHERE relkind = 'l'");
2181
2182         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2183
2184         ntups = PQntuples(res);
2185         if (ntups > 0)
2186         {
2187                 /*
2188                  * Each large object has its own BLOB archive entry.
2189                  */
2190                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2191
2192                 for (i = 0; i < ntups; i++)
2193                 {
2194                         binfo[i].dobj.objType = DO_BLOB;
2195                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2196                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2197                         AssignDumpId(&binfo[i].dobj);
2198
2199                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2200                         if (!PQgetisnull(res, i, 1))
2201                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2202                         else
2203                                 binfo[i].rolname = "";
2204                         if (!PQgetisnull(res, i, 2))
2205                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2206                         else
2207                                 binfo[i].blobacl = NULL;
2208                 }
2209
2210                 /*
2211                  * If we have any large objects, a "BLOBS" archive entry is needed.
2212                  * This is just a placeholder for sorting; it carries no data now.
2213                  */
2214                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2215                 bdata->objType = DO_BLOB_DATA;
2216                 bdata->catId = nilCatalogId;
2217                 AssignDumpId(bdata);
2218                 bdata->name = pg_strdup("BLOBS");
2219         }
2220
2221         PQclear(res);
2222         destroyPQExpBuffer(blobQry);
2223 }
2224
2225 /*
2226  * dumpBlob
2227  *
2228  * dump the definition (metadata) of the given large object
2229  */
2230 static void
2231 dumpBlob(Archive *fout, BlobInfo *binfo)
2232 {
2233         PQExpBuffer cquery = createPQExpBuffer();
2234         PQExpBuffer dquery = createPQExpBuffer();
2235
2236         appendPQExpBuffer(cquery,
2237                                           "SELECT pg_catalog.lo_create('%s');\n",
2238                                           binfo->dobj.name);
2239
2240         appendPQExpBuffer(dquery,
2241                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2242                                           binfo->dobj.name);
2243
2244         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2245                                  binfo->dobj.name,
2246                                  NULL, NULL,
2247                                  binfo->rolname, false,
2248                                  "BLOB", SECTION_PRE_DATA,
2249                                  cquery->data, dquery->data, NULL,
2250                                  binfo->dobj.dependencies, binfo->dobj.nDeps,
2251                                  NULL, NULL);
2252
2253         /* set up tag for comment and/or ACL */
2254         resetPQExpBuffer(cquery);
2255         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2256
2257         /* Dump comment if any */
2258         dumpComment(fout, cquery->data,
2259                                 NULL, binfo->rolname,
2260                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2261
2262         /* Dump security label if any */
2263         dumpSecLabel(fout, cquery->data,
2264                                  NULL, binfo->rolname,
2265                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2266
2267         /* Dump ACL if any */
2268         if (binfo->blobacl)
2269                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2270                                 binfo->dobj.name, NULL, cquery->data,
2271                                 NULL, binfo->rolname, binfo->blobacl);
2272
2273         destroyPQExpBuffer(cquery);
2274         destroyPQExpBuffer(dquery);
2275 }
2276
2277 /*
2278  * dumpBlobs:
2279  *      dump the data contents of all large objects
2280  */
2281 static int
2282 dumpBlobs(Archive *fout, void *arg)
2283 {
2284         const char *blobQry;
2285         const char *blobFetchQry;
2286         PGconn     *conn = GetConnection(fout);
2287         PGresult   *res;
2288         char            buf[LOBBUFSIZE];
2289         int                     ntups;
2290         int                     i;
2291         int                     cnt;
2292
2293         if (g_verbose)
2294                 write_msg(NULL, "saving large objects\n");
2295
2296         /* Make sure we are in proper schema */
2297         selectSourceSchema(fout, "pg_catalog");
2298
2299         /*
2300          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2301          * the already-in-memory dumpable objects instead...
2302          */
2303         if (fout->remoteVersion >= 90000)
2304                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2305         else if (fout->remoteVersion >= 70100)
2306                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2307         else
2308                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2309
2310         ExecuteSqlStatement(fout, blobQry);
2311
2312         /* Command to fetch from cursor */
2313         blobFetchQry = "FETCH 1000 IN bloboid";
2314
2315         do
2316         {
2317                 /* Do a fetch */
2318                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2319
2320                 /* Process the tuples, if any */
2321                 ntups = PQntuples(res);
2322                 for (i = 0; i < ntups; i++)
2323                 {
2324                         Oid                     blobOid;
2325                         int                     loFd;
2326
2327                         blobOid = atooid(PQgetvalue(res, i, 0));
2328                         /* Open the BLOB */
2329                         loFd = lo_open(conn, blobOid, INV_READ);
2330                         if (loFd == -1)
2331                                 exit_horribly(NULL, "could not open large object %u: %s",
2332                                                           blobOid, PQerrorMessage(conn));
2333
2334                         StartBlob(fout, blobOid);
2335
2336                         /* Now read it in chunks, sending data to archive */
2337                         do
2338                         {
2339                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2340                                 if (cnt < 0)
2341                                         exit_horribly(NULL, "error reading large object %u: %s",
2342                                                                   blobOid, PQerrorMessage(conn));
2343
2344                                 WriteData(fout, buf, cnt);
2345                         } while (cnt > 0);
2346
2347                         lo_close(conn, loFd);
2348
2349                         EndBlob(fout, blobOid);
2350                 }
2351
2352                 PQclear(res);
2353         } while (ntups > 0);
2354
2355         return 1;
2356 }
2357
2358 static void
2359 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2360                                                                                  PQExpBuffer upgrade_buffer,
2361                                                                                  Oid pg_type_oid)
2362 {
2363         PQExpBuffer upgrade_query = createPQExpBuffer();
2364         PGresult   *upgrade_res;
2365         Oid                     pg_type_array_oid;
2366
2367         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2368         appendPQExpBuffer(upgrade_buffer,
2369          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2370                                           pg_type_oid);
2371
2372         /* we only support old >= 8.3 for binary upgrades */
2373         appendPQExpBuffer(upgrade_query,
2374                                           "SELECT typarray "
2375                                           "FROM pg_catalog.pg_type "
2376                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2377                                           pg_type_oid);
2378
2379         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2380
2381         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2382
2383         if (OidIsValid(pg_type_array_oid))
2384         {
2385                 appendPQExpBuffer(upgrade_buffer,
2386                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2387                 appendPQExpBuffer(upgrade_buffer,
2388                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2389                                                   pg_type_array_oid);
2390         }
2391
2392         PQclear(upgrade_res);
2393         destroyPQExpBuffer(upgrade_query);
2394 }
2395
2396 static bool
2397 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2398                                                                                 PQExpBuffer upgrade_buffer,
2399                                                                                 Oid pg_rel_oid)
2400 {
2401         PQExpBuffer upgrade_query = createPQExpBuffer();
2402         PGresult   *upgrade_res;
2403         Oid                     pg_type_oid;
2404         bool            toast_set = false;
2405
2406         /* we only support old >= 8.3 for binary upgrades */
2407         appendPQExpBuffer(upgrade_query,
2408                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2409                                           "FROM pg_catalog.pg_class c "
2410                                           "LEFT JOIN pg_catalog.pg_class t ON "
2411                                           "  (c.reltoastrelid = t.oid) "
2412                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2413                                           pg_rel_oid);
2414
2415         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2416
2417         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2418
2419         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2420                                                                                          pg_type_oid);
2421
2422         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2423         {
2424                 /* Toast tables do not have pg_type array rows */
2425                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2426                                                                                         PQfnumber(upgrade_res, "trel")));
2427
2428                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2429                 appendPQExpBuffer(upgrade_buffer,
2430                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2431                                                   pg_type_toast_oid);
2432
2433                 toast_set = true;
2434         }
2435
2436         PQclear(upgrade_res);
2437         destroyPQExpBuffer(upgrade_query);
2438
2439         return toast_set;
2440 }
2441
2442 static void
2443 binary_upgrade_set_pg_class_oids(Archive *fout,
2444                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2445                                                                  bool is_index)
2446 {
2447         PQExpBuffer upgrade_query = createPQExpBuffer();
2448         PGresult   *upgrade_res;
2449         Oid                     pg_class_reltoastrelid;
2450         Oid                     pg_class_reltoastidxid;
2451
2452         appendPQExpBuffer(upgrade_query,
2453                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2454                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2455                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2456                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2457                                           pg_class_oid);
2458
2459         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2460
2461         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2462         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2463
2464         appendPQExpBuffer(upgrade_buffer,
2465                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2466
2467         if (!is_index)
2468         {
2469                 appendPQExpBuffer(upgrade_buffer,
2470                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2471                                                   pg_class_oid);
2472                 /* only tables have toast tables, not indexes */
2473                 if (OidIsValid(pg_class_reltoastrelid))
2474                 {
2475                         /*
2476                          * One complexity is that the table definition might not require
2477                          * the creation of a TOAST table, and the TOAST table might have
2478                          * been created long after table creation, when the table was
2479                          * loaded with wide data.  By setting the TOAST oid we force
2480                          * creation of the TOAST heap and TOAST index by the backend so we
2481                          * can cleanly copy the files during binary upgrade.
2482                          */
2483
2484                         appendPQExpBuffer(upgrade_buffer,
2485                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2486                                                           pg_class_reltoastrelid);
2487
2488                         /* every toast table has an index */
2489                         appendPQExpBuffer(upgrade_buffer,
2490                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2491                                                           pg_class_reltoastidxid);
2492                 }
2493         }
2494         else
2495                 appendPQExpBuffer(upgrade_buffer,
2496                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2497                                                   pg_class_oid);
2498
2499         appendPQExpBuffer(upgrade_buffer, "\n");
2500
2501         PQclear(upgrade_res);
2502         destroyPQExpBuffer(upgrade_query);
2503 }
2504
2505 /*
2506  * If the DumpableObject is a member of an extension, add a suitable
2507  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2508  */
2509 static void
2510 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2511                                                                 DumpableObject *dobj,
2512                                                                 const char *objlabel)
2513 {
2514         DumpableObject *extobj = NULL;
2515         int                     i;
2516
2517         if (!dobj->ext_member)
2518                 return;
2519
2520         /*
2521          * Find the parent extension.  We could avoid this search if we wanted to
2522          * add a link field to DumpableObject, but the space costs of that would
2523          * be considerable.  We assume that member objects could only have a
2524          * direct dependency on their own extension, not any others.
2525          */
2526         for (i = 0; i < dobj->nDeps; i++)
2527         {
2528                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2529                 if (extobj && extobj->objType == DO_EXTENSION)
2530                         break;
2531                 extobj = NULL;
2532         }
2533         if (extobj == NULL)
2534                 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2535
2536         appendPQExpBuffer(upgrade_buffer,
2537           "\n-- For binary upgrade, handle extension membership the hard way\n");
2538         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2539                                           fmtId(extobj->name),
2540                                           objlabel);
2541 }
2542
2543 /*
2544  * getNamespaces:
2545  *        read all namespaces in the system catalogs and return them in the
2546  * NamespaceInfo* structure
2547  *
2548  *      numNamespaces is set to the number of namespaces read in
2549  */
2550 NamespaceInfo *
2551 getNamespaces(Archive *fout, int *numNamespaces)
2552 {
2553         PGresult   *res;
2554         int                     ntups;
2555         int                     i;
2556         PQExpBuffer query;
2557         NamespaceInfo *nsinfo;
2558         int                     i_tableoid;
2559         int                     i_oid;
2560         int                     i_nspname;
2561         int                     i_rolname;
2562         int                     i_nspacl;
2563
2564         /*
2565          * Before 7.3, there are no real namespaces; create two dummy entries, one
2566          * for user stuff and one for system stuff.
2567          */
2568         if (fout->remoteVersion < 70300)
2569         {
2570                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2571
2572                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2573                 nsinfo[0].dobj.catId.tableoid = 0;
2574                 nsinfo[0].dobj.catId.oid = 0;
2575                 AssignDumpId(&nsinfo[0].dobj);
2576                 nsinfo[0].dobj.name = pg_strdup("public");
2577                 nsinfo[0].rolname = pg_strdup("");
2578                 nsinfo[0].nspacl = pg_strdup("");
2579
2580                 selectDumpableNamespace(&nsinfo[0]);
2581
2582                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2583                 nsinfo[1].dobj.catId.tableoid = 0;
2584                 nsinfo[1].dobj.catId.oid = 1;
2585                 AssignDumpId(&nsinfo[1].dobj);
2586                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2587                 nsinfo[1].rolname = pg_strdup("");
2588                 nsinfo[1].nspacl = pg_strdup("");
2589
2590                 selectDumpableNamespace(&nsinfo[1]);
2591
2592                 *numNamespaces = 2;
2593
2594                 return nsinfo;
2595         }
2596
2597         query = createPQExpBuffer();
2598
2599         /* Make sure we are in proper schema */
2600         selectSourceSchema(fout, "pg_catalog");
2601
2602         /*
2603          * we fetch all namespaces including system ones, so that every object we
2604          * read in can be linked to a containing namespace.
2605          */
2606         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2607                                           "(%s nspowner) AS rolname, "
2608                                           "nspacl FROM pg_namespace",
2609                                           username_subquery);
2610
2611         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2612
2613         ntups = PQntuples(res);
2614
2615         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2616
2617         i_tableoid = PQfnumber(res, "tableoid");
2618         i_oid = PQfnumber(res, "oid");
2619         i_nspname = PQfnumber(res, "nspname");
2620         i_rolname = PQfnumber(res, "rolname");
2621         i_nspacl = PQfnumber(res, "nspacl");
2622
2623         for (i = 0; i < ntups; i++)
2624         {
2625                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2626                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2627                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2628                 AssignDumpId(&nsinfo[i].dobj);
2629                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2630                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2631                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2632
2633                 /* Decide whether to dump this namespace */
2634                 selectDumpableNamespace(&nsinfo[i]);
2635
2636                 if (strlen(nsinfo[i].rolname) == 0)
2637                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2638                                           nsinfo[i].dobj.name);
2639         }
2640
2641         PQclear(res);
2642         destroyPQExpBuffer(query);
2643
2644         *numNamespaces = ntups;
2645
2646         return nsinfo;
2647 }
2648
2649 /*
2650  * findNamespace:
2651  *              given a namespace OID and an object OID, look up the info read by
2652  *              getNamespaces
2653  *
2654  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2655  * a system object or not.      In 7.3 and later there is no guessing, and we
2656  * don't use objoid at all.
2657  */
2658 static NamespaceInfo *
2659 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2660 {
2661         NamespaceInfo *nsinfo;
2662
2663         if (fout->remoteVersion >= 70300)
2664         {
2665                 nsinfo = findNamespaceByOid(nsoid);
2666         }
2667         else
2668         {
2669                 /* This code depends on the dummy objects set up by getNamespaces. */
2670                 Oid                     i;
2671
2672                 if (objoid > g_last_builtin_oid)
2673                         i = 0;                          /* user object */
2674                 else
2675                         i = 1;                          /* system object */
2676                 nsinfo = findNamespaceByOid(i);
2677         }
2678
2679         if (nsinfo == NULL)
2680                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2681
2682         return nsinfo;
2683 }
2684
2685 /*
2686  * getExtensions:
2687  *        read all extensions in the system catalogs and return them in the
2688  * ExtensionInfo* structure
2689  *
2690  *      numExtensions is set to the number of extensions read in
2691  */
2692 ExtensionInfo *
2693 getExtensions(Archive *fout, int *numExtensions)
2694 {
2695         PGresult   *res;
2696         int                     ntups;
2697         int                     i;
2698         PQExpBuffer query;
2699         ExtensionInfo *extinfo;
2700         int                     i_tableoid;
2701         int                     i_oid;
2702         int                     i_extname;
2703         int                     i_nspname;
2704         int                     i_extrelocatable;
2705         int                     i_extversion;
2706         int                     i_extconfig;
2707         int                     i_extcondition;
2708
2709         /*
2710          * Before 9.1, there are no extensions.
2711          */
2712         if (fout->remoteVersion < 90100)
2713         {
2714                 *numExtensions = 0;
2715                 return NULL;
2716         }
2717
2718         query = createPQExpBuffer();
2719
2720         /* Make sure we are in proper schema */
2721         selectSourceSchema(fout, "pg_catalog");
2722
2723         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2724                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2725                                           "FROM pg_extension x "
2726                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2727
2728         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2729
2730         ntups = PQntuples(res);
2731
2732         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2733
2734         i_tableoid = PQfnumber(res, "tableoid");
2735         i_oid = PQfnumber(res, "oid");
2736         i_extname = PQfnumber(res, "extname");
2737         i_nspname = PQfnumber(res, "nspname");
2738         i_extrelocatable = PQfnumber(res, "extrelocatable");
2739         i_extversion = PQfnumber(res, "extversion");
2740         i_extconfig = PQfnumber(res, "extconfig");
2741         i_extcondition = PQfnumber(res, "extcondition");
2742
2743         for (i = 0; i < ntups; i++)
2744         {
2745                 extinfo[i].dobj.objType = DO_EXTENSION;
2746                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2747                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2748                 AssignDumpId(&extinfo[i].dobj);
2749                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2750                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2751                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2752                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2753                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2754                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2755
2756                 /* Decide whether we want to dump it */
2757                 selectDumpableExtension(&(extinfo[i]));
2758         }
2759
2760         PQclear(res);
2761         destroyPQExpBuffer(query);
2762
2763         *numExtensions = ntups;
2764
2765         return extinfo;
2766 }
2767
2768 /*
2769  * getTypes:
2770  *        read all types in the system catalogs and return them in the
2771  * TypeInfo* structure
2772  *
2773  *      numTypes is set to the number of types read in
2774  *
2775  * NB: this must run after getFuncs() because we assume we can do
2776  * findFuncByOid().
2777  */
2778 TypeInfo *
2779 getTypes(Archive *fout, int *numTypes)
2780 {
2781         PGresult   *res;
2782         int                     ntups;
2783         int                     i;
2784         PQExpBuffer query = createPQExpBuffer();
2785         TypeInfo   *tyinfo;
2786         ShellTypeInfo *stinfo;
2787         int                     i_tableoid;
2788         int                     i_oid;
2789         int                     i_typname;
2790         int                     i_typnamespace;
2791         int                     i_rolname;
2792         int                     i_typinput;
2793         int                     i_typoutput;
2794         int                     i_typelem;
2795         int                     i_typrelid;
2796         int                     i_typrelkind;
2797         int                     i_typtype;
2798         int                     i_typisdefined;
2799         int                     i_isarray;
2800
2801         /*
2802          * we include even the built-in types because those may be used as array
2803          * elements by user-defined types
2804          *
2805          * we filter out the built-in types when we dump out the types
2806          *
2807          * same approach for undefined (shell) types and array types
2808          *
2809          * Note: as of 8.3 we can reliably detect whether a type is an
2810          * auto-generated array type by checking the element type's typarray.
2811          * (Before that the test is capable of generating false positives.) We
2812          * still check for name beginning with '_', though, so as to avoid the
2813          * cost of the subselect probe for all standard types.  This would have to
2814          * be revisited if the backend ever allows renaming of array types.
2815          */
2816
2817         /* Make sure we are in proper schema */
2818         selectSourceSchema(fout, "pg_catalog");
2819
2820         if (fout->remoteVersion >= 80300)
2821         {
2822                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2823                                                   "typnamespace, "
2824                                                   "(%s typowner) AS rolname, "
2825                                                   "typinput::oid AS typinput, "
2826                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2827                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2828                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2829                                                   "typtype, typisdefined, "
2830                                                   "typname[0] = '_' AND typelem != 0 AND "
2831                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2832                                                   "FROM pg_type",
2833                                                   username_subquery);
2834         }
2835         else if (fout->remoteVersion >= 70300)
2836         {
2837                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2838                                                   "typnamespace, "
2839                                                   "(%s typowner) AS rolname, "
2840                                                   "typinput::oid AS typinput, "
2841                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2842                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2843                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2844                                                   "typtype, typisdefined, "
2845                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2846                                                   "FROM pg_type",
2847                                                   username_subquery);
2848         }
2849         else if (fout->remoteVersion >= 70100)
2850         {
2851                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2852                                                   "0::oid AS typnamespace, "
2853                                                   "(%s typowner) AS rolname, "
2854                                                   "typinput::oid AS typinput, "
2855                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2856                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2857                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2858                                                   "typtype, typisdefined, "
2859                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2860                                                   "FROM pg_type",
2861                                                   username_subquery);
2862         }
2863         else
2864         {
2865                 appendPQExpBuffer(query, "SELECT "
2866                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2867                                                   "oid, typname, "
2868                                                   "0::oid AS typnamespace, "
2869                                                   "(%s typowner) AS rolname, "
2870                                                   "typinput::oid AS typinput, "
2871                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2872                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2873                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2874                                                   "typtype, typisdefined, "
2875                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2876                                                   "FROM pg_type",
2877                                                   username_subquery);
2878         }
2879
2880         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2881
2882         ntups = PQntuples(res);
2883
2884         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2885
2886         i_tableoid = PQfnumber(res, "tableoid");
2887         i_oid = PQfnumber(res, "oid");
2888         i_typname = PQfnumber(res, "typname");
2889         i_typnamespace = PQfnumber(res, "typnamespace");
2890         i_rolname = PQfnumber(res, "rolname");
2891         i_typinput = PQfnumber(res, "typinput");
2892         i_typoutput = PQfnumber(res, "typoutput");
2893         i_typelem = PQfnumber(res, "typelem");
2894         i_typrelid = PQfnumber(res, "typrelid");
2895         i_typrelkind = PQfnumber(res, "typrelkind");
2896         i_typtype = PQfnumber(res, "typtype");
2897         i_typisdefined = PQfnumber(res, "typisdefined");
2898         i_isarray = PQfnumber(res, "isarray");
2899
2900         for (i = 0; i < ntups; i++)
2901         {
2902                 tyinfo[i].dobj.objType = DO_TYPE;
2903                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2904                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2905                 AssignDumpId(&tyinfo[i].dobj);
2906                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2907                 tyinfo[i].dobj.namespace =
2908                         findNamespace(fout,
2909                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2910                                                   tyinfo[i].dobj.catId.oid);
2911                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2912                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2913                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2914                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2915                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2916                 tyinfo[i].shellType = NULL;
2917
2918                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2919                         tyinfo[i].isDefined = true;
2920                 else
2921                         tyinfo[i].isDefined = false;
2922
2923                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2924                         tyinfo[i].isArray = true;
2925                 else
2926                         tyinfo[i].isArray = false;
2927
2928                 /* Decide whether we want to dump it */
2929                 selectDumpableType(&tyinfo[i]);
2930
2931                 /*
2932                  * If it's a domain, fetch info about its constraints, if any
2933                  */
2934                 tyinfo[i].nDomChecks = 0;
2935                 tyinfo[i].domChecks = NULL;
2936                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2937                         getDomainConstraints(fout, &(tyinfo[i]));
2938
2939                 /*
2940                  * If it's a base type, make a DumpableObject representing a shell
2941                  * definition of the type.      We will need to dump that ahead of the I/O
2942                  * functions for the type.      Similarly, range types need a shell
2943                  * definition in case they have a canonicalize function.
2944                  *
2945                  * Note: the shell type doesn't have a catId.  You might think it
2946                  * should copy the base type's catId, but then it might capture the
2947                  * pg_depend entries for the type, which we don't want.
2948                  */
2949                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2950                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
2951                 {
2952                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2953                         stinfo->dobj.objType = DO_SHELL_TYPE;
2954                         stinfo->dobj.catId = nilCatalogId;
2955                         AssignDumpId(&stinfo->dobj);
2956                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2957                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2958                         stinfo->baseType = &(tyinfo[i]);
2959                         tyinfo[i].shellType = stinfo;
2960
2961                         /*
2962                          * Initially mark the shell type as not to be dumped.  We'll only
2963                          * dump it if the I/O or canonicalize functions need to be dumped;
2964                          * this is taken care of while sorting dependencies.
2965                          */
2966                         stinfo->dobj.dump = false;
2967
2968                         /*
2969                          * However, if dumping from pre-7.3, there will be no dependency
2970                          * info so we have to fake it here.  We only need to worry about
2971                          * typinput and typoutput since the other functions only exist
2972                          * post-7.3.
2973                          */
2974                         if (fout->remoteVersion < 70300)
2975                         {
2976                                 Oid                     typinput;
2977                                 Oid                     typoutput;
2978                                 FuncInfo   *funcInfo;
2979
2980                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
2981                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
2982
2983                                 funcInfo = findFuncByOid(typinput);
2984                                 if (funcInfo && funcInfo->dobj.dump)
2985                                 {
2986                                         /* base type depends on function */
2987                                         addObjectDependency(&tyinfo[i].dobj,
2988                                                                                 funcInfo->dobj.dumpId);
2989                                         /* function depends on shell type */
2990                                         addObjectDependency(&funcInfo->dobj,
2991                                                                                 stinfo->dobj.dumpId);
2992                                         /* mark shell type as to be dumped */
2993                                         stinfo->dobj.dump = true;
2994                                 }
2995
2996                                 funcInfo = findFuncByOid(typoutput);
2997                                 if (funcInfo && funcInfo->dobj.dump)
2998                                 {
2999                                         /* base type depends on function */
3000                                         addObjectDependency(&tyinfo[i].dobj,
3001                                                                                 funcInfo->dobj.dumpId);
3002                                         /* function depends on shell type */
3003                                         addObjectDependency(&funcInfo->dobj,
3004                                                                                 stinfo->dobj.dumpId);
3005                                         /* mark shell type as to be dumped */
3006                                         stinfo->dobj.dump = true;
3007                                 }
3008                         }
3009                 }
3010
3011                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3012                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3013                                           tyinfo[i].dobj.name);
3014         }
3015
3016         *numTypes = ntups;
3017
3018         PQclear(res);
3019
3020         destroyPQExpBuffer(query);
3021
3022         return tyinfo;
3023 }
3024
3025 /*
3026  * getOperators:
3027  *        read all operators in the system catalogs and return them in the
3028  * OprInfo* structure
3029  *
3030  *      numOprs is set to the number of operators read in
3031  */
3032 OprInfo *
3033 getOperators(Archive *fout, int *numOprs)
3034 {
3035         PGresult   *res;
3036         int                     ntups;
3037         int                     i;
3038         PQExpBuffer query = createPQExpBuffer();
3039         OprInfo    *oprinfo;
3040         int                     i_tableoid;
3041         int                     i_oid;
3042         int                     i_oprname;
3043         int                     i_oprnamespace;
3044         int                     i_rolname;
3045         int                     i_oprkind;
3046         int                     i_oprcode;
3047
3048         /*
3049          * find all operators, including builtin operators; we filter out
3050          * system-defined operators at dump-out time.
3051          */
3052
3053         /* Make sure we are in proper schema */
3054         selectSourceSchema(fout, "pg_catalog");
3055
3056         if (fout->remoteVersion >= 70300)
3057         {
3058                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3059                                                   "oprnamespace, "
3060                                                   "(%s oprowner) AS rolname, "
3061                                                   "oprkind, "
3062                                                   "oprcode::oid AS oprcode "
3063                                                   "FROM pg_operator",
3064                                                   username_subquery);
3065         }
3066         else if (fout->remoteVersion >= 70100)
3067         {
3068                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3069                                                   "0::oid AS oprnamespace, "
3070                                                   "(%s oprowner) AS rolname, "
3071                                                   "oprkind, "
3072                                                   "oprcode::oid AS oprcode "
3073                                                   "FROM pg_operator",
3074                                                   username_subquery);
3075         }
3076         else
3077         {
3078                 appendPQExpBuffer(query, "SELECT "
3079                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3080                                                   "oid, oprname, "
3081                                                   "0::oid AS oprnamespace, "
3082                                                   "(%s oprowner) AS rolname, "
3083                                                   "oprkind, "
3084                                                   "oprcode::oid AS oprcode "
3085                                                   "FROM pg_operator",
3086                                                   username_subquery);
3087         }
3088
3089         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3090
3091         ntups = PQntuples(res);
3092         *numOprs = ntups;
3093
3094         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3095
3096         i_tableoid = PQfnumber(res, "tableoid");
3097         i_oid = PQfnumber(res, "oid");
3098         i_oprname = PQfnumber(res, "oprname");
3099         i_oprnamespace = PQfnumber(res, "oprnamespace");
3100         i_rolname = PQfnumber(res, "rolname");
3101         i_oprkind = PQfnumber(res, "oprkind");
3102         i_oprcode = PQfnumber(res, "oprcode");
3103
3104         for (i = 0; i < ntups; i++)
3105         {
3106                 oprinfo[i].dobj.objType = DO_OPERATOR;
3107                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3108                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3109                 AssignDumpId(&oprinfo[i].dobj);
3110                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3111                 oprinfo[i].dobj.namespace =
3112                         findNamespace(fout,
3113                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3114                                                   oprinfo[i].dobj.catId.oid);
3115                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3116                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3117                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3118
3119                 /* Decide whether we want to dump it */
3120                 selectDumpableObject(&(oprinfo[i].dobj));
3121
3122                 if (strlen(oprinfo[i].rolname) == 0)
3123                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3124                                           oprinfo[i].dobj.name);
3125         }
3126
3127         PQclear(res);
3128
3129         destroyPQExpBuffer(query);
3130
3131         return oprinfo;
3132 }
3133
3134 /*
3135  * getCollations:
3136  *        read all collations in the system catalogs and return them in the
3137  * CollInfo* structure
3138  *
3139  *      numCollations is set to the number of collations read in
3140  */
3141 CollInfo *
3142 getCollations(Archive *fout, int *numCollations)
3143 {
3144         PGresult   *res;
3145         int                     ntups;
3146         int                     i;
3147         PQExpBuffer query;
3148         CollInfo   *collinfo;
3149         int                     i_tableoid;
3150         int                     i_oid;
3151         int                     i_collname;
3152         int                     i_collnamespace;
3153         int                     i_rolname;
3154
3155         /* Collations didn't exist pre-9.1 */
3156         if (fout->remoteVersion < 90100)
3157         {
3158                 *numCollations = 0;
3159                 return NULL;
3160         }
3161
3162         query = createPQExpBuffer();
3163
3164         /*
3165          * find all collations, including builtin collations; we filter out
3166          * system-defined collations at dump-out time.
3167          */
3168
3169         /* Make sure we are in proper schema */
3170         selectSourceSchema(fout, "pg_catalog");
3171
3172         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3173                                           "collnamespace, "
3174                                           "(%s collowner) AS rolname "
3175                                           "FROM pg_collation",
3176                                           username_subquery);
3177
3178         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3179
3180         ntups = PQntuples(res);
3181         *numCollations = ntups;
3182
3183         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3184
3185         i_tableoid = PQfnumber(res, "tableoid");
3186         i_oid = PQfnumber(res, "oid");
3187         i_collname = PQfnumber(res, "collname");
3188         i_collnamespace = PQfnumber(res, "collnamespace");
3189         i_rolname = PQfnumber(res, "rolname");
3190
3191         for (i = 0; i < ntups; i++)
3192         {
3193                 collinfo[i].dobj.objType = DO_COLLATION;
3194                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3195                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3196                 AssignDumpId(&collinfo[i].dobj);
3197                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3198                 collinfo[i].dobj.namespace =
3199                         findNamespace(fout,
3200                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3201                                                   collinfo[i].dobj.catId.oid);
3202                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3203
3204                 /* Decide whether we want to dump it */
3205                 selectDumpableObject(&(collinfo[i].dobj));
3206         }
3207
3208         PQclear(res);
3209
3210         destroyPQExpBuffer(query);
3211
3212         return collinfo;
3213 }
3214
3215 /*
3216  * getConversions:
3217  *        read all conversions in the system catalogs and return them in the
3218  * ConvInfo* structure
3219  *
3220  *      numConversions is set to the number of conversions read in
3221  */
3222 ConvInfo *
3223 getConversions(Archive *fout, int *numConversions)
3224 {
3225         PGresult   *res;
3226         int                     ntups;
3227         int                     i;
3228         PQExpBuffer query = createPQExpBuffer();
3229         ConvInfo   *convinfo;
3230         int                     i_tableoid;
3231         int                     i_oid;
3232         int                     i_conname;
3233         int                     i_connamespace;
3234         int                     i_rolname;
3235
3236         /* Conversions didn't exist pre-7.3 */
3237         if (fout->remoteVersion < 70300)
3238         {
3239                 *numConversions = 0;
3240                 return NULL;
3241         }
3242
3243         /*
3244          * find all conversions, including builtin conversions; we filter out
3245          * system-defined conversions at dump-out time.
3246          */
3247
3248         /* Make sure we are in proper schema */
3249         selectSourceSchema(fout, "pg_catalog");
3250
3251         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3252                                           "connamespace, "
3253                                           "(%s conowner) AS rolname "
3254                                           "FROM pg_conversion",
3255                                           username_subquery);
3256
3257         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3258
3259         ntups = PQntuples(res);
3260         *numConversions = ntups;
3261
3262         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3263
3264         i_tableoid = PQfnumber(res, "tableoid");
3265         i_oid = PQfnumber(res, "oid");
3266         i_conname = PQfnumber(res, "conname");
3267         i_connamespace = PQfnumber(res, "connamespace");
3268         i_rolname = PQfnumber(res, "rolname");
3269
3270         for (i = 0; i < ntups; i++)
3271         {
3272                 convinfo[i].dobj.objType = DO_CONVERSION;
3273                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3274                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3275                 AssignDumpId(&convinfo[i].dobj);
3276                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3277                 convinfo[i].dobj.namespace =
3278                         findNamespace(fout,
3279                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3280                                                   convinfo[i].dobj.catId.oid);
3281                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3282
3283                 /* Decide whether we want to dump it */
3284                 selectDumpableObject(&(convinfo[i].dobj));
3285         }
3286
3287         PQclear(res);
3288
3289         destroyPQExpBuffer(query);
3290
3291         return convinfo;
3292 }
3293
3294 /*
3295  * getOpclasses:
3296  *        read all opclasses in the system catalogs and return them in the
3297  * OpclassInfo* structure
3298  *
3299  *      numOpclasses is set to the number of opclasses read in
3300  */
3301 OpclassInfo *
3302 getOpclasses(Archive *fout, int *numOpclasses)
3303 {
3304         PGresult   *res;
3305         int                     ntups;
3306         int                     i;
3307         PQExpBuffer query = createPQExpBuffer();
3308         OpclassInfo *opcinfo;
3309         int                     i_tableoid;
3310         int                     i_oid;
3311         int                     i_opcname;
3312         int                     i_opcnamespace;
3313         int                     i_rolname;
3314
3315         /*
3316          * find all opclasses, including builtin opclasses; we filter out
3317          * system-defined opclasses at dump-out time.
3318          */
3319
3320         /* Make sure we are in proper schema */
3321         selectSourceSchema(fout, "pg_catalog");
3322
3323         if (fout->remoteVersion >= 70300)
3324         {
3325                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3326                                                   "opcnamespace, "
3327                                                   "(%s opcowner) AS rolname "
3328                                                   "FROM pg_opclass",
3329                                                   username_subquery);
3330         }
3331         else if (fout->remoteVersion >= 70100)
3332         {
3333                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3334                                                   "0::oid AS opcnamespace, "
3335                                                   "''::name AS rolname "
3336                                                   "FROM pg_opclass");
3337         }
3338         else
3339         {
3340                 appendPQExpBuffer(query, "SELECT "
3341                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3342                                                   "oid, opcname, "
3343                                                   "0::oid AS opcnamespace, "
3344                                                   "''::name AS rolname "
3345                                                   "FROM pg_opclass");
3346         }
3347
3348         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3349
3350         ntups = PQntuples(res);
3351         *numOpclasses = ntups;
3352
3353         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3354
3355         i_tableoid = PQfnumber(res, "tableoid");
3356         i_oid = PQfnumber(res, "oid");
3357         i_opcname = PQfnumber(res, "opcname");
3358         i_opcnamespace = PQfnumber(res, "opcnamespace");
3359         i_rolname = PQfnumber(res, "rolname");
3360
3361         for (i = 0; i < ntups; i++)
3362         {
3363                 opcinfo[i].dobj.objType = DO_OPCLASS;
3364                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3365                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3366                 AssignDumpId(&opcinfo[i].dobj);
3367                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3368                 opcinfo[i].dobj.namespace =
3369                         findNamespace(fout,
3370                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3371                                                   opcinfo[i].dobj.catId.oid);
3372                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3373
3374                 /* Decide whether we want to dump it */
3375                 selectDumpableObject(&(opcinfo[i].dobj));
3376
3377                 if (fout->remoteVersion >= 70300)
3378                 {
3379                         if (strlen(opcinfo[i].rolname) == 0)
3380                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3381                                                   opcinfo[i].dobj.name);
3382                 }
3383         }
3384
3385         PQclear(res);
3386
3387         destroyPQExpBuffer(query);
3388
3389         return opcinfo;
3390 }
3391
3392 /*
3393  * getOpfamilies:
3394  *        read all opfamilies in the system catalogs and return them in the
3395  * OpfamilyInfo* structure
3396  *
3397  *      numOpfamilies is set to the number of opfamilies read in
3398  */
3399 OpfamilyInfo *
3400 getOpfamilies(Archive *fout, int *numOpfamilies)
3401 {
3402         PGresult   *res;
3403         int                     ntups;
3404         int                     i;
3405         PQExpBuffer query;
3406         OpfamilyInfo *opfinfo;
3407         int                     i_tableoid;
3408         int                     i_oid;
3409         int                     i_opfname;
3410         int                     i_opfnamespace;
3411         int                     i_rolname;
3412
3413         /* Before 8.3, there is no separate concept of opfamilies */
3414         if (fout->remoteVersion < 80300)
3415         {
3416                 *numOpfamilies = 0;
3417                 return NULL;
3418         }
3419
3420         query = createPQExpBuffer();
3421
3422         /*
3423          * find all opfamilies, including builtin opfamilies; we filter out
3424          * system-defined opfamilies at dump-out time.
3425          */
3426
3427         /* Make sure we are in proper schema */
3428         selectSourceSchema(fout, "pg_catalog");
3429
3430         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3431                                           "opfnamespace, "
3432                                           "(%s opfowner) AS rolname "
3433                                           "FROM pg_opfamily",
3434                                           username_subquery);
3435
3436         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3437
3438         ntups = PQntuples(res);
3439         *numOpfamilies = ntups;
3440
3441         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3442
3443         i_tableoid = PQfnumber(res, "tableoid");
3444         i_oid = PQfnumber(res, "oid");
3445         i_opfname = PQfnumber(res, "opfname");
3446         i_opfnamespace = PQfnumber(res, "opfnamespace");
3447         i_rolname = PQfnumber(res, "rolname");
3448
3449         for (i = 0; i < ntups; i++)
3450         {
3451                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3452                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3453                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3454                 AssignDumpId(&opfinfo[i].dobj);
3455                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3456                 opfinfo[i].dobj.namespace =
3457                         findNamespace(fout,
3458                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3459                                                   opfinfo[i].dobj.catId.oid);
3460                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3461
3462                 /* Decide whether we want to dump it */
3463                 selectDumpableObject(&(opfinfo[i].dobj));
3464
3465                 if (fout->remoteVersion >= 70300)
3466                 {
3467                         if (strlen(opfinfo[i].rolname) == 0)
3468                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3469                                                   opfinfo[i].dobj.name);
3470                 }
3471         }
3472
3473         PQclear(res);
3474
3475         destroyPQExpBuffer(query);
3476
3477         return opfinfo;
3478 }
3479
3480 /*
3481  * getAggregates:
3482  *        read all the user-defined aggregates in the system catalogs and
3483  * return them in the AggInfo* structure
3484  *
3485  * numAggs is set to the number of aggregates read in
3486  */
3487 AggInfo *
3488 getAggregates(Archive *fout, int *numAggs)
3489 {
3490         PGresult   *res;
3491         int                     ntups;
3492         int                     i;
3493         PQExpBuffer query = createPQExpBuffer();
3494         AggInfo    *agginfo;
3495         int                     i_tableoid;
3496         int                     i_oid;
3497         int                     i_aggname;
3498         int                     i_aggnamespace;
3499         int                     i_pronargs;
3500         int                     i_proargtypes;
3501         int                     i_rolname;
3502         int                     i_aggacl;
3503
3504         /* Make sure we are in proper schema */
3505         selectSourceSchema(fout, "pg_catalog");
3506
3507         /*
3508          * Find all user-defined aggregates.  See comment in getFuncs() for the
3509          * rationale behind the filtering logic.
3510          */
3511
3512         if (fout->remoteVersion >= 80200)
3513         {
3514                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3515                                                   "pronamespace AS aggnamespace, "
3516                                                   "pronargs, proargtypes, "
3517                                                   "(%s proowner) AS rolname, "
3518                                                   "proacl AS aggacl "
3519                                                   "FROM pg_proc p "
3520                                                   "WHERE proisagg AND ("
3521                                                   "pronamespace != "
3522                                                   "(SELECT oid FROM pg_namespace "
3523                                                   "WHERE nspname = 'pg_catalog')",
3524                                                   username_subquery);
3525                 if (binary_upgrade && fout->remoteVersion >= 90100)
3526                         appendPQExpBuffer(query,
3527                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3528                                                           "classid = 'pg_proc'::regclass AND "
3529                                                           "objid = p.oid AND "
3530                                                           "refclassid = 'pg_extension'::regclass AND "
3531                                                           "deptype = 'e')");
3532                 appendPQExpBuffer(query, ")");
3533         }
3534         else if (fout->remoteVersion >= 70300)
3535         {
3536                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3537                                                   "pronamespace AS aggnamespace, "
3538                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3539                                                   "proargtypes, "
3540                                                   "(%s proowner) AS rolname, "
3541                                                   "proacl AS aggacl "
3542                                                   "FROM pg_proc "
3543                                                   "WHERE proisagg "
3544                                                   "AND pronamespace != "
3545                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3546                                                   username_subquery);
3547         }
3548         else if (fout->remoteVersion >= 70100)
3549         {
3550                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3551                                                   "0::oid AS aggnamespace, "
3552                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3553                                                   "aggbasetype AS proargtypes, "
3554                                                   "(%s aggowner) AS rolname, "
3555                                                   "'{=X}' AS aggacl "
3556                                                   "FROM pg_aggregate "
3557                                                   "where oid > '%u'::oid",
3558                                                   username_subquery,
3559                                                   g_last_builtin_oid);
3560         }
3561         else
3562         {
3563                 appendPQExpBuffer(query, "SELECT "
3564                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3565                                                   "oid, aggname, "
3566                                                   "0::oid AS aggnamespace, "
3567                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3568                                                   "aggbasetype AS proargtypes, "
3569                                                   "(%s aggowner) AS rolname, "
3570                                                   "'{=X}' AS aggacl "
3571                                                   "FROM pg_aggregate "
3572                                                   "where oid > '%u'::oid",
3573                                                   username_subquery,
3574                                                   g_last_builtin_oid);
3575         }
3576
3577         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3578
3579         ntups = PQntuples(res);
3580         *numAggs = ntups;
3581
3582         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3583
3584         i_tableoid = PQfnumber(res, "tableoid");
3585         i_oid = PQfnumber(res, "oid");
3586         i_aggname = PQfnumber(res, "aggname");
3587         i_aggnamespace = PQfnumber(res, "aggnamespace");
3588         i_pronargs = PQfnumber(res, "pronargs");
3589         i_proargtypes = PQfnumber(res, "proargtypes");
3590         i_rolname = PQfnumber(res, "rolname");
3591         i_aggacl = PQfnumber(res, "aggacl");
3592
3593         for (i = 0; i < ntups; i++)
3594         {
3595                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3596                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3597                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3598                 AssignDumpId(&agginfo[i].aggfn.dobj);
3599                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3600                 agginfo[i].aggfn.dobj.namespace =
3601                         findNamespace(fout,
3602                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3603                                                   agginfo[i].aggfn.dobj.catId.oid);
3604                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3605                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3606                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3607                                           agginfo[i].aggfn.dobj.name);
3608                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3609                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3610                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3611                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3612                 if (agginfo[i].aggfn.nargs == 0)
3613                         agginfo[i].aggfn.argtypes = NULL;
3614                 else
3615                 {
3616                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3617                         if (fout->remoteVersion >= 70300)
3618                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3619                                                           agginfo[i].aggfn.argtypes,
3620                                                           agginfo[i].aggfn.nargs);
3621                         else
3622                                 /* it's just aggbasetype */
3623                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3624                 }
3625
3626                 /* Decide whether we want to dump it */
3627                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3628         }
3629
3630         PQclear(res);
3631
3632         destroyPQExpBuffer(query);
3633
3634         return agginfo;
3635 }
3636
3637 /*
3638  * getFuncs:
3639  *        read all the user-defined functions in the system catalogs and
3640  * return them in the FuncInfo* structure
3641  *
3642  * numFuncs is set to the number of functions read in
3643  */
3644 FuncInfo *
3645 getFuncs(Archive *fout, int *numFuncs)
3646 {
3647         PGresult   *res;
3648         int                     ntups;
3649         int                     i;
3650         PQExpBuffer query = createPQExpBuffer();
3651         FuncInfo   *finfo;
3652         int                     i_tableoid;
3653         int                     i_oid;
3654         int                     i_proname;
3655         int                     i_pronamespace;
3656         int                     i_rolname;
3657         int                     i_prolang;
3658         int                     i_pronargs;
3659         int                     i_proargtypes;
3660         int                     i_prorettype;
3661         int                     i_proacl;
3662
3663         /* Make sure we are in proper schema */
3664         selectSourceSchema(fout, "pg_catalog");
3665
3666         /*
3667          * Find all user-defined functions.  Normally we can exclude functions in
3668          * pg_catalog, which is worth doing since there are several thousand of
3669          * 'em.  However, there are some extensions that create functions in
3670          * pg_catalog.  In normal dumps we can still ignore those --- but in
3671          * binary-upgrade mode, we must dump the member objects of the extension,
3672          * so be sure to fetch any such functions.
3673          *
3674          * Also, in 9.2 and up, exclude functions that are internally dependent on
3675          * something else, since presumably those will be created as a result of
3676          * creating the something else.  This currently only acts to suppress
3677          * constructor functions for range types.  Note that this is OK only
3678          * because the constructors don't have any dependencies the range type
3679          * doesn't have; otherwise we might not get creation ordering correct.
3680          */
3681
3682         if (fout->remoteVersion >= 70300)
3683         {
3684                 appendPQExpBuffer(query,
3685                                                   "SELECT tableoid, oid, proname, prolang, "
3686                                                   "pronargs, proargtypes, prorettype, proacl, "
3687                                                   "pronamespace, "
3688                                                   "(%s proowner) AS rolname "
3689                                                   "FROM pg_proc p "
3690                                                   "WHERE NOT proisagg AND ("
3691                                                   "pronamespace != "
3692                                                   "(SELECT oid FROM pg_namespace "
3693                                                   "WHERE nspname = 'pg_catalog')",
3694                                                   username_subquery);
3695                 if (fout->remoteVersion >= 90200)
3696                         appendPQExpBuffer(query,
3697                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3698                                                           "WHERE classid = 'pg_proc'::regclass AND "
3699                                                           "objid = p.oid AND deptype = 'i')");
3700                 if (binary_upgrade && fout->remoteVersion >= 90100)
3701                         appendPQExpBuffer(query,
3702                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3703                                                           "classid = 'pg_proc'::regclass AND "
3704                                                           "objid = p.oid AND "
3705                                                           "refclassid = 'pg_extension'::regclass AND "
3706                                                           "deptype = 'e')");
3707                 appendPQExpBuffer(query, ")");
3708         }
3709         else if (fout->remoteVersion >= 70100)
3710         {
3711                 appendPQExpBuffer(query,
3712                                                   "SELECT tableoid, oid, proname, prolang, "
3713                                                   "pronargs, proargtypes, prorettype, "
3714                                                   "'{=X}' AS proacl, "
3715                                                   "0::oid AS pronamespace, "
3716                                                   "(%s proowner) AS rolname "
3717                                                   "FROM pg_proc "
3718                                                   "WHERE pg_proc.oid > '%u'::oid",
3719                                                   username_subquery,
3720                                                   g_last_builtin_oid);
3721         }
3722         else
3723         {
3724                 appendPQExpBuffer(query,
3725                                                   "SELECT "
3726                                                   "(SELECT oid FROM pg_class "
3727                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3728                                                   "oid, proname, prolang, "
3729                                                   "pronargs, proargtypes, prorettype, "
3730                                                   "'{=X}' AS proacl, "
3731                                                   "0::oid AS pronamespace, "
3732                                                   "(%s proowner) AS rolname "
3733                                                   "FROM pg_proc "
3734                                                   "where pg_proc.oid > '%u'::oid",
3735                                                   username_subquery,
3736                                                   g_last_builtin_oid);
3737         }
3738
3739         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3740
3741         ntups = PQntuples(res);
3742
3743         *numFuncs = ntups;
3744
3745         finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3746
3747         i_tableoid = PQfnumber(res, "tableoid");
3748         i_oid = PQfnumber(res, "oid");
3749         i_proname = PQfnumber(res, "proname");
3750         i_pronamespace = PQfnumber(res, "pronamespace");
3751         i_rolname = PQfnumber(res, "rolname");
3752         i_prolang = PQfnumber(res, "prolang");
3753         i_pronargs = PQfnumber(res, "pronargs");
3754         i_proargtypes = PQfnumber(res, "proargtypes");
3755         i_prorettype = PQfnumber(res, "prorettype");
3756         i_proacl = PQfnumber(res, "proacl");
3757
3758         for (i = 0; i < ntups; i++)
3759         {
3760                 finfo[i].dobj.objType = DO_FUNC;
3761                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3762                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3763                 AssignDumpId(&finfo[i].dobj);
3764                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3765                 finfo[i].dobj.namespace =
3766                         findNamespace(fout,
3767                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3768                                                   finfo[i].dobj.catId.oid);
3769                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3770                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3771                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3772                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3773                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3774                 if (finfo[i].nargs == 0)
3775                         finfo[i].argtypes = NULL;
3776                 else
3777                 {
3778                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3779                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3780                                                   finfo[i].argtypes, finfo[i].nargs);
3781                 }
3782
3783                 /* Decide whether we want to dump it */
3784                 selectDumpableObject(&(finfo[i].dobj));
3785
3786                 if (strlen(finfo[i].rolname) == 0)
3787                         write_msg(NULL,
3788                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3789                                           finfo[i].dobj.name);
3790         }
3791
3792         PQclear(res);
3793
3794         destroyPQExpBuffer(query);
3795
3796         return finfo;
3797 }
3798
3799 /*
3800  * getTables
3801  *        read all the user-defined tables (no indexes, no catalogs)
3802  * in the system catalogs return them in the TableInfo* structure
3803  *
3804  * numTables is set to the number of tables read in
3805  */
3806 TableInfo *
3807 getTables(Archive *fout, int *numTables)
3808 {
3809         PGresult   *res;
3810         int                     ntups;
3811         int                     i;
3812         PQExpBuffer query = createPQExpBuffer();
3813         TableInfo  *tblinfo;
3814         int                     i_reltableoid;
3815         int                     i_reloid;
3816         int                     i_relname;
3817         int                     i_relnamespace;
3818         int                     i_relkind;
3819         int                     i_relacl;
3820         int                     i_rolname;
3821         int                     i_relchecks;
3822         int                     i_relhastriggers;
3823         int                     i_relhasindex;
3824         int                     i_relhasrules;
3825         int                     i_relhasoids;
3826         int                     i_relfrozenxid;
3827         int                     i_toastoid;
3828         int                     i_toastfrozenxid;
3829         int                     i_relpersistence;
3830         int                     i_owning_tab;
3831         int                     i_owning_col;
3832         int                     i_reltablespace;
3833         int                     i_reloptions;
3834         int                     i_toastreloptions;
3835         int                     i_reloftype;
3836
3837         /* Make sure we are in proper schema */
3838         selectSourceSchema(fout, "pg_catalog");
3839
3840         /*
3841          * Find all the tables and table-like objects.
3842          *
3843          * We include system catalogs, so that we can work if a user table is
3844          * defined to inherit from a system catalog (pretty weird, but...)
3845          *
3846          * We ignore relations that are not ordinary tables, sequences, views,
3847          * composite types, or foreign tables.
3848          *
3849          * Composite-type table entries won't be dumped as such, but we have to
3850          * make a DumpableObject for them so that we can track dependencies of the
3851          * composite type (pg_depend entries for columns of the composite type
3852          * link to the pg_class entry not the pg_type entry).
3853          *
3854          * Note: in this phase we should collect only a minimal amount of
3855          * information about each table, basically just enough to decide if it is
3856          * interesting. We must fetch all tables in this phase because otherwise
3857          * we cannot correctly identify inherited columns, owned sequences, etc.
3858          */
3859
3860         if (fout->remoteVersion >= 90100)
3861         {
3862                 /*
3863                  * Left join to pick up dependency info linking sequences to their
3864                  * owning column, if any (note this dependency is AUTO as of 8.2)
3865                  */
3866                 appendPQExpBuffer(query,
3867                                                   "SELECT c.tableoid, c.oid, c.relname, "
3868                                                   "c.relacl, c.relkind, c.relnamespace, "
3869                                                   "(%s c.relowner) AS rolname, "
3870                                                   "c.relchecks, c.relhastriggers, "
3871                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3872                                                   "c.relfrozenxid, tc.oid AS toid, "
3873                                                   "tc.relfrozenxid AS tfrozenxid, "
3874                                                   "c.relpersistence, "
3875                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3876                                                   "d.refobjid AS owning_tab, "
3877                                                   "d.refobjsubid AS owning_col, "
3878                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3879                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3880                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3881                                                   "FROM pg_class c "
3882                                                   "LEFT JOIN pg_depend d ON "
3883                                                   "(c.relkind = '%c' AND "
3884                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3885                                                   "d.objsubid = 0 AND "
3886                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3887                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3888                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3889                                                   "ORDER BY c.oid",
3890                                                   username_subquery,
3891                                                   RELKIND_SEQUENCE,
3892                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3893                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3894                                                   RELKIND_FOREIGN_TABLE);
3895         }
3896         else if (fout->remoteVersion >= 90000)
3897         {
3898                 /*
3899                  * Left join to pick up dependency info linking sequences to their
3900                  * owning column, if any (note this dependency is AUTO as of 8.2)
3901                  */
3902                 appendPQExpBuffer(query,
3903                                                   "SELECT c.tableoid, c.oid, c.relname, "
3904                                                   "c.relacl, c.relkind, c.relnamespace, "
3905                                                   "(%s c.relowner) AS rolname, "
3906                                                   "c.relchecks, c.relhastriggers, "
3907                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3908                                                   "c.relfrozenxid, tc.oid AS toid, "
3909                                                   "tc.relfrozenxid AS tfrozenxid, "
3910                                                   "'p' AS relpersistence, "
3911                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3912                                                   "d.refobjid AS owning_tab, "
3913                                                   "d.refobjsubid AS owning_col, "
3914                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3915                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3916                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3917                                                   "FROM pg_class c "
3918                                                   "LEFT JOIN pg_depend d ON "
3919                                                   "(c.relkind = '%c' AND "
3920                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3921                                                   "d.objsubid = 0 AND "
3922                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3923                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3924                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3925                                                   "ORDER BY c.oid",
3926                                                   username_subquery,
3927                                                   RELKIND_SEQUENCE,
3928                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3929                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3930         }
3931         else if (fout->remoteVersion >= 80400)
3932         {
3933                 /*
3934                  * Left join to pick up dependency info linking sequences to their
3935                  * owning column, if any (note this dependency is AUTO as of 8.2)
3936                  */
3937                 appendPQExpBuffer(query,
3938                                                   "SELECT c.tableoid, c.oid, c.relname, "
3939                                                   "c.relacl, c.relkind, c.relnamespace, "
3940                                                   "(%s c.relowner) AS rolname, "
3941                                                   "c.relchecks, c.relhastriggers, "
3942                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3943                                                   "c.relfrozenxid, tc.oid AS toid, "
3944                                                   "tc.relfrozenxid AS tfrozenxid, "
3945                                                   "'p' AS relpersistence, "
3946                                                   "NULL AS reloftype, "
3947                                                   "d.refobjid AS owning_tab, "
3948                                                   "d.refobjsubid AS owning_col, "
3949                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3950                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3951                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3952                                                   "FROM pg_class c "
3953                                                   "LEFT JOIN pg_depend d ON "
3954                                                   "(c.relkind = '%c' AND "
3955                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3956                                                   "d.objsubid = 0 AND "
3957                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3958                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3959                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3960                                                   "ORDER BY c.oid",
3961                                                   username_subquery,
3962                                                   RELKIND_SEQUENCE,
3963                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3964                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3965         }
3966         else if (fout->remoteVersion >= 80200)
3967         {
3968                 /*
3969                  * Left join to pick up dependency info linking sequences to their
3970                  * owning column, if any (note this dependency is AUTO as of 8.2)
3971                  */
3972                 appendPQExpBuffer(query,
3973                                                   "SELECT c.tableoid, c.oid, c.relname, "
3974                                                   "c.relacl, c.relkind, c.relnamespace, "
3975                                                   "(%s c.relowner) AS rolname, "
3976                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
3977                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3978                                                   "c.relfrozenxid, tc.oid AS toid, "
3979                                                   "tc.relfrozenxid AS tfrozenxid, "
3980                                                   "'p' AS relpersistence, "
3981                                                   "NULL AS reloftype, "
3982                                                   "d.refobjid AS owning_tab, "
3983                                                   "d.refobjsubid AS owning_col, "
3984                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3985                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3986                                                   "NULL AS toast_reloptions "
3987                                                   "FROM pg_class c "
3988                                                   "LEFT JOIN pg_depend d ON "
3989                                                   "(c.relkind = '%c' AND "
3990                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3991                                                   "d.objsubid = 0 AND "
3992                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3993                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3994                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3995                                                   "ORDER BY c.oid",
3996                                                   username_subquery,
3997                                                   RELKIND_SEQUENCE,
3998                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3999                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4000         }
4001         else if (fout->remoteVersion >= 80000)
4002         {
4003                 /*
4004                  * Left join to pick up dependency info linking sequences to their
4005                  * owning column, if any
4006                  */
4007                 appendPQExpBuffer(query,
4008                                                   "SELECT c.tableoid, c.oid, relname, "
4009                                                   "relacl, relkind, relnamespace, "
4010                                                   "(%s relowner) AS rolname, "
4011                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4012                                                   "relhasindex, relhasrules, relhasoids, "
4013                                                   "0 AS relfrozenxid, "
4014                                                   "0 AS toid, "
4015                                                   "0 AS tfrozenxid, "
4016                                                   "'p' AS relpersistence, "
4017                                                   "NULL AS reloftype, "
4018                                                   "d.refobjid AS owning_tab, "
4019                                                   "d.refobjsubid AS owning_col, "
4020                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4021                                                   "NULL AS reloptions, "
4022                                                   "NULL AS toast_reloptions "
4023                                                   "FROM pg_class c "
4024                                                   "LEFT JOIN pg_depend d ON "
4025                                                   "(c.relkind = '%c' AND "
4026                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4027                                                   "d.objsubid = 0 AND "
4028                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4029                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4030                                                   "ORDER BY c.oid",
4031                                                   username_subquery,
4032                                                   RELKIND_SEQUENCE,
4033                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4034                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4035         }
4036         else if (fout->remoteVersion >= 70300)
4037         {
4038                 /*
4039                  * Left join to pick up dependency info linking sequences to their
4040                  * owning column, if any
4041                  */
4042                 appendPQExpBuffer(query,
4043                                                   "SELECT c.tableoid, c.oid, relname, "
4044                                                   "relacl, relkind, relnamespace, "
4045                                                   "(%s relowner) AS rolname, "
4046                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4047                                                   "relhasindex, relhasrules, relhasoids, "
4048                                                   "0 AS relfrozenxid, "
4049                                                   "0 AS toid, "
4050                                                   "0 AS tfrozenxid, "
4051                                                   "'p' AS relpersistence, "
4052                                                   "NULL AS reloftype, "
4053                                                   "d.refobjid AS owning_tab, "
4054                                                   "d.refobjsubid AS owning_col, "
4055                                                   "NULL AS reltablespace, "
4056                                                   "NULL AS reloptions, "
4057                                                   "NULL AS toast_reloptions "
4058                                                   "FROM pg_class c "
4059                                                   "LEFT JOIN pg_depend d ON "
4060                                                   "(c.relkind = '%c' AND "
4061                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4062                                                   "d.objsubid = 0 AND "
4063                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4064                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4065                                                   "ORDER BY c.oid",
4066                                                   username_subquery,
4067                                                   RELKIND_SEQUENCE,
4068                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4069                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4070         }
4071         else if (fout->remoteVersion >= 70200)
4072         {
4073                 appendPQExpBuffer(query,
4074                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4075                                                   "0::oid AS relnamespace, "
4076                                                   "(%s relowner) AS rolname, "
4077                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4078                                                   "relhasindex, relhasrules, relhasoids, "
4079                                                   "0 AS relfrozenxid, "
4080                                                   "0 AS toid, "
4081                                                   "0 AS tfrozenxid, "
4082                                                   "'p' AS relpersistence, "
4083                                                   "NULL AS reloftype, "
4084                                                   "NULL::oid AS owning_tab, "
4085                                                   "NULL::int4 AS owning_col, "
4086                                                   "NULL AS reltablespace, "
4087                                                   "NULL AS reloptions, "
4088                                                   "NULL AS toast_reloptions "
4089                                                   "FROM pg_class "
4090                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4091                                                   "ORDER BY oid",
4092                                                   username_subquery,
4093                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4094         }
4095         else if (fout->remoteVersion >= 70100)
4096         {
4097                 /* all tables have oids in 7.1 */
4098                 appendPQExpBuffer(query,
4099                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4100                                                   "0::oid AS relnamespace, "
4101                                                   "(%s relowner) AS rolname, "
4102                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4103                                                   "relhasindex, relhasrules, "
4104                                                   "'t'::bool AS relhasoids, "
4105                                                   "0 AS relfrozenxid, "
4106                                                   "0 AS toid, "
4107                                                   "0 AS tfrozenxid, "
4108                                                   "'p' AS relpersistence, "
4109                                                   "NULL AS reloftype, "
4110                                                   "NULL::oid AS owning_tab, "
4111                                                   "NULL::int4 AS owning_col, "
4112                                                   "NULL AS reltablespace, "
4113                                                   "NULL AS reloptions, "
4114                                                   "NULL AS toast_reloptions "
4115                                                   "FROM pg_class "
4116                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4117                                                   "ORDER BY oid",
4118                                                   username_subquery,
4119                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4120         }
4121         else
4122         {
4123                 /*
4124                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4125                  * have a view by looking for a rule in pg_rewrite.
4126                  */
4127                 appendPQExpBuffer(query,
4128                                                   "SELECT "
4129                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4130                                                   "oid, relname, relacl, "
4131                                                   "CASE WHEN relhasrules and relkind = 'r' "
4132                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4133                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4134                                                   "THEN '%c'::\"char\" "
4135                                                   "ELSE relkind END AS relkind,"
4136                                                   "0::oid AS relnamespace, "
4137                                                   "(%s relowner) AS rolname, "
4138                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4139                                                   "relhasindex, relhasrules, "
4140                                                   "'t'::bool AS relhasoids, "
4141                                                   "0 as relfrozenxid, "
4142                                                   "0 AS toid, "
4143                                                   "0 AS tfrozenxid, "
4144                                                   "'p' AS relpersistence, "
4145                                                   "NULL AS reloftype, "
4146                                                   "NULL::oid AS owning_tab, "
4147                                                   "NULL::int4 AS owning_col, "
4148                                                   "NULL AS reltablespace, "
4149                                                   "NULL AS reloptions, "
4150                                                   "NULL AS toast_reloptions "
4151                                                   "FROM pg_class c "
4152                                                   "WHERE relkind IN ('%c', '%c') "
4153                                                   "ORDER BY oid",
4154                                                   RELKIND_VIEW,
4155                                                   username_subquery,
4156                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4157         }
4158
4159         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4160
4161         ntups = PQntuples(res);
4162
4163         *numTables = ntups;
4164
4165         /*
4166          * Extract data from result and lock dumpable tables.  We do the locking
4167          * before anything else, to minimize the window wherein a table could
4168          * disappear under us.
4169          *
4170          * Note that we have to save info about all tables here, even when dumping
4171          * only one, because we don't yet know which tables might be inheritance
4172          * ancestors of the target table.
4173          */
4174         tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4175
4176         i_reltableoid = PQfnumber(res, "tableoid");
4177         i_reloid = PQfnumber(res, "oid");
4178         i_relname = PQfnumber(res, "relname");
4179         i_relnamespace = PQfnumber(res, "relnamespace");
4180         i_relacl = PQfnumber(res, "relacl");
4181         i_relkind = PQfnumber(res, "relkind");
4182         i_rolname = PQfnumber(res, "rolname");
4183         i_relchecks = PQfnumber(res, "relchecks");
4184         i_relhastriggers = PQfnumber(res, "relhastriggers");
4185         i_relhasindex = PQfnumber(res, "relhasindex");
4186         i_relhasrules = PQfnumber(res, "relhasrules");
4187         i_relhasoids = PQfnumber(res, "relhasoids");
4188         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4189         i_toastoid = PQfnumber(res, "toid");
4190         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4191         i_relpersistence = PQfnumber(res, "relpersistence");
4192         i_owning_tab = PQfnumber(res, "owning_tab");
4193         i_owning_col = PQfnumber(res, "owning_col");
4194         i_reltablespace = PQfnumber(res, "reltablespace");
4195         i_reloptions = PQfnumber(res, "reloptions");
4196         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4197         i_reloftype = PQfnumber(res, "reloftype");
4198
4199         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4200         {
4201                 /*
4202                  * Arrange to fail instead of waiting forever for a table lock.
4203                  *
4204                  * NB: this coding assumes that the only queries issued within the
4205                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4206                  * applied to other things too.
4207                  */
4208                 resetPQExpBuffer(query);
4209                 appendPQExpBuffer(query, "SET statement_timeout = ");
4210                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4211                 ExecuteSqlStatement(fout, query->data);
4212         }
4213
4214         for (i = 0; i < ntups; i++)
4215         {
4216                 tblinfo[i].dobj.objType = DO_TABLE;
4217                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4218                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4219                 AssignDumpId(&tblinfo[i].dobj);
4220                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4221                 tblinfo[i].dobj.namespace =
4222                         findNamespace(fout,
4223                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4224                                                   tblinfo[i].dobj.catId.oid);
4225                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4226                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4227                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4228                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4229                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4230                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4231                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4232                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4233                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4234                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4235                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4236                 if (PQgetisnull(res, i, i_reloftype))
4237                         tblinfo[i].reloftype = NULL;
4238                 else
4239                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4240                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4241                 if (PQgetisnull(res, i, i_owning_tab))
4242                 {
4243                         tblinfo[i].owning_tab = InvalidOid;
4244                         tblinfo[i].owning_col = 0;
4245                 }
4246                 else
4247                 {
4248                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4249                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4250                 }
4251                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4252                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4253                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4254
4255                 /* other fields were zeroed above */
4256
4257                 /*
4258                  * Decide whether we want to dump this table.
4259                  */
4260                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4261                         tblinfo[i].dobj.dump = false;
4262                 else
4263                         selectDumpableTable(&tblinfo[i]);
4264                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4265
4266                 /*
4267                  * Read-lock target tables to make sure they aren't DROPPED or altered
4268                  * in schema before we get around to dumping them.
4269                  *
4270                  * Note that we don't explicitly lock parents of the target tables; we
4271                  * assume our lock on the child is enough to prevent schema
4272                  * alterations to parent tables.
4273                  *
4274                  * NOTE: it'd be kinda nice to lock other relations too, not only
4275                  * plain tables, but the backend doesn't presently allow that.
4276                  */
4277                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4278                 {
4279                         resetPQExpBuffer(query);
4280                         appendPQExpBuffer(query,
4281                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4282                                                           fmtQualifiedId(fout,
4283                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4284                                                                                          tblinfo[i].dobj.name));
4285                         ExecuteSqlStatement(fout, query->data);
4286                 }
4287
4288                 /* Emit notice if join for owner failed */
4289                 if (strlen(tblinfo[i].rolname) == 0)
4290                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4291                                           tblinfo[i].dobj.name);
4292         }
4293
4294         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4295         {
4296                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4297         }
4298
4299         PQclear(res);
4300
4301         destroyPQExpBuffer(query);
4302
4303         return tblinfo;
4304 }
4305
4306 /*
4307  * getOwnedSeqs
4308  *        identify owned sequences and mark them as dumpable if owning table is
4309  *
4310  * We used to do this in getTables(), but it's better to do it after the
4311  * index used by findTableByOid() has been set up.
4312  */
4313 void
4314 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4315 {
4316         int                     i;
4317
4318         /*
4319          * Force sequences that are "owned" by table columns to be dumped whenever
4320          * their owning table is being dumped.
4321          */
4322         for (i = 0; i < numTables; i++)
4323         {
4324                 TableInfo  *seqinfo = &tblinfo[i];
4325                 TableInfo  *owning_tab;
4326
4327                 if (!OidIsValid(seqinfo->owning_tab))
4328                         continue;                       /* not an owned sequence */
4329                 if (seqinfo->dobj.dump)
4330                         continue;                       /* no need to search */
4331                 owning_tab = findTableByOid(seqinfo->owning_tab);
4332                 if (owning_tab && owning_tab->dobj.dump)
4333                 {
4334                         seqinfo->interesting = true;
4335                         seqinfo->dobj.dump = true;
4336                 }
4337         }
4338 }
4339
4340 /*
4341  * getInherits
4342  *        read all the inheritance information
4343  * from the system catalogs return them in the InhInfo* structure
4344  *
4345  * numInherits is set to the number of pairs read in
4346  */
4347 InhInfo *
4348 getInherits(Archive *fout, int *numInherits)
4349 {
4350         PGresult   *res;
4351         int                     ntups;
4352         int                     i;
4353         PQExpBuffer query = createPQExpBuffer();
4354         InhInfo    *inhinfo;
4355
4356         int                     i_inhrelid;
4357         int                     i_inhparent;
4358
4359         /* Make sure we are in proper schema */
4360         selectSourceSchema(fout, "pg_catalog");
4361
4362         /* find all the inheritance information */
4363
4364         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4365
4366         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4367
4368         ntups = PQntuples(res);
4369
4370         *numInherits = ntups;
4371
4372         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4373
4374         i_inhrelid = PQfnumber(res, "inhrelid");
4375         i_inhparent = PQfnumber(res, "inhparent");
4376
4377         for (i = 0; i < ntups; i++)
4378         {
4379                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4380                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4381         }
4382
4383         PQclear(res);
4384
4385         destroyPQExpBuffer(query);
4386
4387         return inhinfo;
4388 }
4389
4390 /*
4391  * getIndexes
4392  *        get information about every index on a dumpable table
4393  *
4394  * Note: index data is not returned directly to the caller, but it
4395  * does get entered into the DumpableObject tables.
4396  */
4397 void
4398 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4399 {
4400         int                     i,
4401                                 j;
4402         PQExpBuffer query = createPQExpBuffer();
4403         PGresult   *res;
4404         IndxInfo   *indxinfo;
4405         ConstraintInfo *constrinfo;
4406         int                     i_tableoid,
4407                                 i_oid,
4408                                 i_indexname,
4409                                 i_indexdef,
4410                                 i_indnkeys,
4411                                 i_indkey,
4412                                 i_indisclustered,
4413                                 i_contype,
4414                                 i_conname,
4415                                 i_condeferrable,
4416                                 i_condeferred,
4417                                 i_contableoid,
4418                                 i_conoid,
4419                                 i_condef,
4420                                 i_tablespace,
4421                                 i_options;
4422         int                     ntups;
4423
4424         for (i = 0; i < numTables; i++)
4425         {
4426                 TableInfo  *tbinfo = &tblinfo[i];
4427
4428                 /* Only plain tables have indexes */
4429                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4430                         continue;
4431
4432                 /* Ignore indexes of tables not to be dumped */
4433                 if (!tbinfo->dobj.dump)
4434                         continue;
4435
4436                 if (g_verbose)
4437                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4438                                           tbinfo->dobj.name);
4439
4440                 /* Make sure we are in proper schema so indexdef is right */
4441                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4442
4443                 /*
4444                  * The point of the messy-looking outer join is to find a constraint
4445                  * that is related by an internal dependency link to the index. If we
4446                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4447                  * assume an index won't have more than one internal dependency.
4448                  *
4449                  * As of 9.0 we don't need to look at pg_depend but can check for a
4450                  * match to pg_constraint.conindid.  The check on conrelid is
4451                  * redundant but useful because that column is indexed while conindid
4452                  * is not.
4453                  */
4454                 resetPQExpBuffer(query);
4455                 if (fout->remoteVersion >= 90000)
4456                 {
4457                         appendPQExpBuffer(query,
4458                                                           "SELECT t.tableoid, t.oid, "
4459                                                           "t.relname AS indexname, "
4460                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4461                                                           "t.relnatts AS indnkeys, "
4462                                                           "i.indkey, i.indisclustered, "
4463                                                           "c.contype, c.conname, "
4464                                                           "c.condeferrable, c.condeferred, "
4465                                                           "c.tableoid AS contableoid, "
4466                                                           "c.oid AS conoid, "
4467                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4468                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4469                                                         "array_to_string(t.reloptions, ', ') AS options "
4470                                                           "FROM pg_catalog.pg_index i "
4471                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4472                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4473                                                           "ON (i.indrelid = c.conrelid AND "
4474                                                           "i.indexrelid = c.conindid AND "
4475                                                           "c.contype IN ('p','u','x')) "
4476                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4477                                                           "ORDER BY indexname",
4478                                                           tbinfo->dobj.catId.oid);
4479                 }
4480                 else if (fout->remoteVersion >= 80200)
4481                 {
4482                         appendPQExpBuffer(query,
4483                                                           "SELECT t.tableoid, t.oid, "
4484                                                           "t.relname AS indexname, "
4485                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4486                                                           "t.relnatts AS indnkeys, "
4487                                                           "i.indkey, i.indisclustered, "
4488                                                           "c.contype, c.conname, "
4489                                                           "c.condeferrable, c.condeferred, "
4490                                                           "c.tableoid AS contableoid, "
4491                                                           "c.oid AS conoid, "
4492                                                           "null AS condef, "
4493                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4494                                                         "array_to_string(t.reloptions, ', ') AS options "
4495                                                           "FROM pg_catalog.pg_index i "
4496                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4497                                                           "LEFT JOIN pg_catalog.pg_depend d "
4498                                                           "ON (d.classid = t.tableoid "
4499                                                           "AND d.objid = t.oid "
4500                                                           "AND d.deptype = 'i') "
4501                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4502                                                           "ON (d.refclassid = c.tableoid "
4503                                                           "AND d.refobjid = c.oid) "
4504                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4505                                                           "ORDER BY indexname",
4506                                                           tbinfo->dobj.catId.oid);
4507                 }
4508                 else if (fout->remoteVersion >= 80000)
4509                 {
4510                         appendPQExpBuffer(query,
4511                                                           "SELECT t.tableoid, t.oid, "
4512                                                           "t.relname AS indexname, "
4513                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4514                                                           "t.relnatts AS indnkeys, "
4515                                                           "i.indkey, i.indisclustered, "
4516                                                           "c.contype, c.conname, "
4517                                                           "c.condeferrable, c.condeferred, "
4518                                                           "c.tableoid AS contableoid, "
4519                                                           "c.oid AS conoid, "
4520                                                           "null AS condef, "
4521                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4522                                                           "null AS options "
4523                                                           "FROM pg_catalog.pg_index i "
4524                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4525                                                           "LEFT JOIN pg_catalog.pg_depend d "
4526                                                           "ON (d.classid = t.tableoid "
4527                                                           "AND d.objid = t.oid "
4528                                                           "AND d.deptype = 'i') "
4529                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4530                                                           "ON (d.refclassid = c.tableoid "
4531                                                           "AND d.refobjid = c.oid) "
4532                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4533                                                           "ORDER BY indexname",
4534                                                           tbinfo->dobj.catId.oid);
4535                 }
4536                 else if (fout->remoteVersion >= 70300)
4537                 {
4538                         appendPQExpBuffer(query,
4539                                                           "SELECT t.tableoid, t.oid, "
4540                                                           "t.relname AS indexname, "
4541                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4542                                                           "t.relnatts AS indnkeys, "
4543                                                           "i.indkey, i.indisclustered, "
4544                                                           "c.contype, c.conname, "
4545                                                           "c.condeferrable, c.condeferred, "
4546                                                           "c.tableoid AS contableoid, "
4547                                                           "c.oid AS conoid, "
4548                                                           "null AS condef, "
4549                                                           "NULL AS tablespace, "
4550                                                           "null AS options "
4551                                                           "FROM pg_catalog.pg_index i "
4552                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4553                                                           "LEFT JOIN pg_catalog.pg_depend d "
4554                                                           "ON (d.classid = t.tableoid "
4555                                                           "AND d.objid = t.oid "
4556                                                           "AND d.deptype = 'i') "
4557                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4558                                                           "ON (d.refclassid = c.tableoid "
4559                                                           "AND d.refobjid = c.oid) "
4560                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4561                                                           "ORDER BY indexname",
4562                                                           tbinfo->dobj.catId.oid);
4563                 }
4564                 else if (fout->remoteVersion >= 70100)
4565                 {
4566                         appendPQExpBuffer(query,
4567                                                           "SELECT t.tableoid, t.oid, "
4568                                                           "t.relname AS indexname, "
4569                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4570                                                           "t.relnatts AS indnkeys, "
4571                                                           "i.indkey, false AS indisclustered, "
4572                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4573                                                           "ELSE '0'::char END AS contype, "
4574                                                           "t.relname AS conname, "
4575                                                           "false AS condeferrable, "
4576                                                           "false AS condeferred, "
4577                                                           "0::oid AS contableoid, "
4578                                                           "t.oid AS conoid, "
4579                                                           "null AS condef, "
4580                                                           "NULL AS tablespace, "
4581                                                           "null AS options "
4582                                                           "FROM pg_index i, pg_class t "
4583                                                           "WHERE t.oid = i.indexrelid "
4584                                                           "AND i.indrelid = '%u'::oid "
4585                                                           "ORDER BY indexname",
4586                                                           tbinfo->dobj.catId.oid);
4587                 }
4588                 else
4589                 {
4590                         appendPQExpBuffer(query,
4591                                                           "SELECT "
4592                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4593                                                           "t.oid, "
4594                                                           "t.relname AS indexname, "
4595                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4596                                                           "t.relnatts AS indnkeys, "
4597                                                           "i.indkey, false AS indisclustered, "
4598                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4599                                                           "ELSE '0'::char END AS contype, "
4600                                                           "t.relname AS conname, "
4601                                                           "false AS condeferrable, "
4602                                                           "false AS condeferred, "
4603                                                           "0::oid AS contableoid, "
4604                                                           "t.oid AS conoid, "
4605                                                           "null AS condef, "
4606                                                           "NULL AS tablespace, "
4607                                                           "null AS options "
4608                                                           "FROM pg_index i, pg_class t "
4609                                                           "WHERE t.oid = i.indexrelid "
4610                                                           "AND i.indrelid = '%u'::oid "
4611                                                           "ORDER BY indexname",
4612                                                           tbinfo->dobj.catId.oid);
4613                 }
4614
4615                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4616
4617                 ntups = PQntuples(res);
4618
4619                 i_tableoid = PQfnumber(res, "tableoid");
4620                 i_oid = PQfnumber(res, "oid");
4621                 i_indexname = PQfnumber(res, "indexname");
4622                 i_indexdef = PQfnumber(res, "indexdef");
4623                 i_indnkeys = PQfnumber(res, "indnkeys");
4624                 i_indkey = PQfnumber(res, "indkey");
4625                 i_indisclustered = PQfnumber(res, "indisclustered");
4626                 i_contype = PQfnumber(res, "contype");
4627                 i_conname = PQfnumber(res, "conname");
4628                 i_condeferrable = PQfnumber(res, "condeferrable");
4629                 i_condeferred = PQfnumber(res, "condeferred");
4630                 i_contableoid = PQfnumber(res, "contableoid");
4631                 i_conoid = PQfnumber(res, "conoid");
4632                 i_condef = PQfnumber(res, "condef");
4633                 i_tablespace = PQfnumber(res, "tablespace");
4634                 i_options = PQfnumber(res, "options");
4635
4636                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4637                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4638
4639                 for (j = 0; j < ntups; j++)
4640                 {
4641                         char            contype;
4642
4643                         indxinfo[j].dobj.objType = DO_INDEX;
4644                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4645                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4646                         AssignDumpId(&indxinfo[j].dobj);
4647                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4648                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4649                         indxinfo[j].indextable = tbinfo;
4650                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4651                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4652                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4653                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4654
4655                         /*
4656                          * In pre-7.4 releases, indkeys may contain more entries than
4657                          * indnkeys says (since indnkeys will be 1 for a functional
4658                          * index).      We don't actually care about this case since we don't
4659                          * examine indkeys except for indexes associated with PRIMARY and
4660                          * UNIQUE constraints, which are never functional indexes. But we
4661                          * have to allocate enough space to keep parseOidArray from
4662                          * complaining.
4663                          */
4664                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4665                         parseOidArray(PQgetvalue(res, j, i_indkey),
4666                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4667                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4668                         contype = *(PQgetvalue(res, j, i_contype));
4669
4670                         if (contype == 'p' || contype == 'u' || contype == 'x')
4671                         {
4672                                 /*
4673                                  * If we found a constraint matching the index, create an
4674                                  * entry for it.
4675                                  *
4676                                  * In a pre-7.3 database, we take this path iff the index was
4677                                  * marked indisprimary.
4678                                  */
4679                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4680                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4681                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4682                                 AssignDumpId(&constrinfo[j].dobj);
4683                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4684                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4685                                 constrinfo[j].contable = tbinfo;
4686                                 constrinfo[j].condomain = NULL;
4687                                 constrinfo[j].contype = contype;
4688                                 if (contype == 'x')
4689                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4690                                 else
4691                                         constrinfo[j].condef = NULL;
4692                                 constrinfo[j].confrelid = InvalidOid;
4693                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4694                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4695                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4696                                 constrinfo[j].conislocal = true;
4697                                 constrinfo[j].separate = true;
4698
4699                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4700
4701                                 /* If pre-7.3 DB, better make sure table comes first */
4702                                 addObjectDependency(&constrinfo[j].dobj,
4703                                                                         tbinfo->dobj.dumpId);
4704                         }
4705                         else
4706                         {
4707                                 /* Plain secondary index */
4708                                 indxinfo[j].indexconstraint = 0;
4709                         }
4710                 }
4711
4712                 PQclear(res);
4713         }
4714
4715         destroyPQExpBuffer(query);
4716 }
4717
4718 /*
4719  * getConstraints
4720  *
4721  * Get info about constraints on dumpable tables.
4722  *
4723  * Currently handles foreign keys only.
4724  * Unique and primary key constraints are handled with indexes,
4725  * while check constraints are processed in getTableAttrs().
4726  */
4727 void
4728 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4729 {
4730         int                     i,
4731                                 j;
4732         ConstraintInfo *constrinfo;
4733         PQExpBuffer query;
4734         PGresult   *res;
4735         int                     i_contableoid,
4736                                 i_conoid,
4737                                 i_conname,
4738                                 i_confrelid,
4739                                 i_condef;
4740         int                     ntups;
4741
4742         /* pg_constraint was created in 7.3, so nothing to do if older */
4743         if (fout->remoteVersion < 70300)
4744                 return;
4745
4746         query = createPQExpBuffer();
4747
4748         for (i = 0; i < numTables; i++)
4749         {
4750                 TableInfo  *tbinfo = &tblinfo[i];
4751
4752                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4753                         continue;
4754
4755                 if (g_verbose)
4756                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4757                                           tbinfo->dobj.name);
4758
4759                 /*
4760                  * select table schema to ensure constraint expr is qualified if
4761                  * needed
4762                  */
4763                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4764
4765                 resetPQExpBuffer(query);
4766                 appendPQExpBuffer(query,
4767                                                   "SELECT tableoid, oid, conname, confrelid, "
4768                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4769                                                   "FROM pg_catalog.pg_constraint "
4770                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4771                                                   "AND contype = 'f'",
4772                                                   tbinfo->dobj.catId.oid);
4773                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4774
4775                 ntups = PQntuples(res);
4776
4777                 i_contableoid = PQfnumber(res, "tableoid");
4778                 i_conoid = PQfnumber(res, "oid");
4779                 i_conname = PQfnumber(res, "conname");
4780                 i_confrelid = PQfnumber(res, "confrelid");
4781                 i_condef = PQfnumber(res, "condef");
4782
4783                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4784
4785                 for (j = 0; j < ntups; j++)
4786                 {
4787                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4788                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4789                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4790                         AssignDumpId(&constrinfo[j].dobj);
4791                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4792                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4793                         constrinfo[j].contable = tbinfo;
4794                         constrinfo[j].condomain = NULL;
4795                         constrinfo[j].contype = 'f';
4796                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4797                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4798                         constrinfo[j].conindex = 0;
4799                         constrinfo[j].condeferrable = false;
4800                         constrinfo[j].condeferred = false;
4801                         constrinfo[j].conislocal = true;
4802                         constrinfo[j].separate = true;
4803                 }
4804
4805                 PQclear(res);
4806         }
4807
4808         destroyPQExpBuffer(query);
4809 }
4810
4811 /*
4812  * getDomainConstraints
4813  *
4814  * Get info about constraints on a domain.
4815  */
4816 static void
4817 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4818 {
4819         int                     i;
4820         ConstraintInfo *constrinfo;
4821         PQExpBuffer query;
4822         PGresult   *res;
4823         int                     i_tableoid,
4824                                 i_oid,
4825                                 i_conname,
4826                                 i_consrc;
4827         int                     ntups;
4828
4829         /* pg_constraint was created in 7.3, so nothing to do if older */
4830         if (fout->remoteVersion < 70300)
4831                 return;
4832
4833         /*
4834          * select appropriate schema to ensure names in constraint are properly
4835          * qualified
4836          */
4837         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4838
4839         query = createPQExpBuffer();
4840
4841         if (fout->remoteVersion >= 90100)
4842                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4843                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4844                                                   "convalidated "
4845                                                   "FROM pg_catalog.pg_constraint "
4846                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4847                                                   "ORDER BY conname",
4848                                                   tyinfo->dobj.catId.oid);
4849
4850         else if (fout->remoteVersion >= 70400)
4851                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4852                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4853                                                   "true as convalidated "
4854                                                   "FROM pg_catalog.pg_constraint "
4855                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4856                                                   "ORDER BY conname",
4857                                                   tyinfo->dobj.catId.oid);
4858         else
4859                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4860                                                   "'CHECK (' || consrc || ')' AS consrc, "
4861                                                   "true as convalidated "
4862                                                   "FROM pg_catalog.pg_constraint "
4863                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4864                                                   "ORDER BY conname",
4865                                                   tyinfo->dobj.catId.oid);
4866
4867         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4868
4869         ntups = PQntuples(res);
4870
4871         i_tableoid = PQfnumber(res, "tableoid");
4872         i_oid = PQfnumber(res, "oid");
4873         i_conname = PQfnumber(res, "conname");
4874         i_consrc = PQfnumber(res, "consrc");
4875
4876         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4877
4878         tyinfo->nDomChecks = ntups;
4879         tyinfo->domChecks = constrinfo;
4880
4881         for (i = 0; i < ntups; i++)
4882         {
4883                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
4884
4885                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4886                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4887                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4888                 AssignDumpId(&constrinfo[i].dobj);
4889                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4890                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4891                 constrinfo[i].contable = NULL;
4892                 constrinfo[i].condomain = tyinfo;
4893                 constrinfo[i].contype = 'c';
4894                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4895                 constrinfo[i].confrelid = InvalidOid;
4896                 constrinfo[i].conindex = 0;
4897                 constrinfo[i].condeferrable = false;
4898                 constrinfo[i].condeferred = false;
4899                 constrinfo[i].conislocal = true;
4900
4901                 constrinfo[i].separate = !validated;
4902
4903                 /*
4904                  * Make the domain depend on the constraint, ensuring it won't be
4905                  * output till any constraint dependencies are OK.      If the constraint
4906                  * has not been validated, it's going to be dumped after the domain
4907                  * anyway, so this doesn't matter.
4908                  */
4909                 if (validated)
4910                         addObjectDependency(&tyinfo->dobj,
4911                                                                 constrinfo[i].dobj.dumpId);
4912         }
4913
4914         PQclear(res);
4915
4916         destroyPQExpBuffer(query);
4917 }
4918
4919 /*
4920  * getRules
4921  *        get basic information about every rule in the system
4922  *
4923  * numRules is set to the number of rules read in
4924  */
4925 RuleInfo *
4926 getRules(Archive *fout, int *numRules)
4927 {
4928         PGresult   *res;
4929         int                     ntups;
4930         int                     i;
4931         PQExpBuffer query = createPQExpBuffer();
4932         RuleInfo   *ruleinfo;
4933         int                     i_tableoid;
4934         int                     i_oid;
4935         int                     i_rulename;
4936         int                     i_ruletable;
4937         int                     i_ev_type;
4938         int                     i_is_instead;
4939         int                     i_ev_enabled;
4940
4941         /* Make sure we are in proper schema */
4942         selectSourceSchema(fout, "pg_catalog");
4943
4944         if (fout->remoteVersion >= 80300)
4945         {
4946                 appendPQExpBuffer(query, "SELECT "
4947                                                   "tableoid, oid, rulename, "
4948                                                   "ev_class AS ruletable, ev_type, is_instead, "
4949                                                   "ev_enabled "
4950                                                   "FROM pg_rewrite "
4951                                                   "ORDER BY oid");
4952         }
4953         else if (fout->remoteVersion >= 70100)
4954         {
4955                 appendPQExpBuffer(query, "SELECT "
4956                                                   "tableoid, oid, rulename, "
4957                                                   "ev_class AS ruletable, ev_type, is_instead, "
4958                                                   "'O'::char AS ev_enabled "
4959                                                   "FROM pg_rewrite "
4960                                                   "ORDER BY oid");
4961         }
4962         else
4963         {
4964                 appendPQExpBuffer(query, "SELECT "
4965                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4966                                                   "oid, rulename, "
4967                                                   "ev_class AS ruletable, ev_type, is_instead, "
4968                                                   "'O'::char AS ev_enabled "
4969                                                   "FROM pg_rewrite "
4970                                                   "ORDER BY oid");
4971         }
4972
4973         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4974
4975         ntups = PQntuples(res);
4976
4977         *numRules = ntups;
4978
4979         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
4980
4981         i_tableoid = PQfnumber(res, "tableoid");
4982         i_oid = PQfnumber(res, "oid");
4983         i_rulename = PQfnumber(res, "rulename");
4984         i_ruletable = PQfnumber(res, "ruletable");
4985         i_ev_type = PQfnumber(res, "ev_type");
4986         i_is_instead = PQfnumber(res, "is_instead");
4987         i_ev_enabled = PQfnumber(res, "ev_enabled");
4988
4989         for (i = 0; i < ntups; i++)
4990         {
4991                 Oid                     ruletableoid;
4992
4993                 ruleinfo[i].dobj.objType = DO_RULE;
4994                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4995                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4996                 AssignDumpId(&ruleinfo[i].dobj);
4997                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
4998                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
4999                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5000                 if (ruleinfo[i].ruletable == NULL)
5001                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5002                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5003                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5004                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5005                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5006                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5007                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5008                 if (ruleinfo[i].ruletable)
5009                 {
5010                         /*
5011                          * If the table is a view, force its ON SELECT rule to be sorted
5012                          * before the view itself --- this ensures that any dependencies
5013                          * for the rule affect the table's positioning. Other rules are
5014                          * forced to appear after their table.
5015                          */
5016                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5017                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5018                         {
5019                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5020                                                                         ruleinfo[i].dobj.dumpId);
5021                                 /* We'll merge the rule into CREATE VIEW, if possible */
5022                                 ruleinfo[i].separate = false;
5023                         }
5024                         else
5025                         {
5026                                 addObjectDependency(&ruleinfo[i].dobj,
5027                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5028                                 ruleinfo[i].separate = true;
5029                         }
5030                 }
5031                 else
5032                         ruleinfo[i].separate = true;
5033         }
5034
5035         PQclear(res);
5036
5037         destroyPQExpBuffer(query);
5038
5039         return ruleinfo;
5040 }
5041
5042 /*
5043  * getTriggers
5044  *        get information about every trigger on a dumpable table
5045  *
5046  * Note: trigger data is not returned directly to the caller, but it
5047  * does get entered into the DumpableObject tables.
5048  */
5049 void
5050 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5051 {
5052         int                     i,
5053                                 j;
5054         PQExpBuffer query = createPQExpBuffer();
5055         PGresult   *res;
5056         TriggerInfo *tginfo;
5057         int                     i_tableoid,
5058                                 i_oid,
5059                                 i_tgname,
5060                                 i_tgfname,
5061                                 i_tgtype,
5062                                 i_tgnargs,
5063                                 i_tgargs,
5064                                 i_tgisconstraint,
5065                                 i_tgconstrname,
5066                                 i_tgconstrrelid,
5067                                 i_tgconstrrelname,
5068                                 i_tgenabled,
5069                                 i_tgdeferrable,
5070                                 i_tginitdeferred,
5071                                 i_tgdef;
5072         int                     ntups;
5073
5074         for (i = 0; i < numTables; i++)
5075         {
5076                 TableInfo  *tbinfo = &tblinfo[i];
5077
5078                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5079                         continue;
5080
5081                 if (g_verbose)
5082                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5083                                           tbinfo->dobj.name);
5084
5085                 /*
5086                  * select table schema to ensure regproc name is qualified if needed
5087                  */
5088                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5089
5090                 resetPQExpBuffer(query);
5091                 if (fout->remoteVersion >= 90000)
5092                 {
5093                         /*
5094                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5095                          * could result in non-forward-compatible dumps of WHEN clauses
5096                          * due to under-parenthesization.
5097                          */
5098                         appendPQExpBuffer(query,
5099                                                           "SELECT tgname, "
5100                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5101                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5102                                                           "tgenabled, tableoid, oid "
5103                                                           "FROM pg_catalog.pg_trigger t "
5104                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5105                                                           "AND NOT tgisinternal",
5106                                                           tbinfo->dobj.catId.oid);
5107                 }
5108                 else if (fout->remoteVersion >= 80300)
5109                 {
5110                         /*
5111                          * We ignore triggers that are tied to a foreign-key constraint
5112                          */
5113                         appendPQExpBuffer(query,
5114                                                           "SELECT tgname, "
5115                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5116                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5117                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5118                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5119                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5120                                                           "FROM pg_catalog.pg_trigger t "
5121                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5122                                                           "AND tgconstraint = 0",
5123                                                           tbinfo->dobj.catId.oid);
5124                 }
5125                 else if (fout->remoteVersion >= 70300)
5126                 {
5127                         /*
5128                          * We ignore triggers that are tied to a foreign-key constraint,
5129                          * but in these versions we have to grovel through pg_constraint
5130                          * to find out
5131                          */
5132                         appendPQExpBuffer(query,
5133                                                           "SELECT tgname, "
5134                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5135                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5136                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5137                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5138                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5139                                                           "FROM pg_catalog.pg_trigger t "
5140                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5141                                                           "AND (NOT tgisconstraint "
5142                                                           " OR NOT EXISTS"
5143                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5144                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5145                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5146                                                           tbinfo->dobj.catId.oid);
5147                 }
5148                 else if (fout->remoteVersion >= 70100)
5149                 {
5150                         appendPQExpBuffer(query,
5151                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5152                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5153                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5154                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5155                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5156                                                           "             AS tgconstrrelname "
5157                                                           "FROM pg_trigger "
5158                                                           "WHERE tgrelid = '%u'::oid",
5159                                                           tbinfo->dobj.catId.oid);
5160                 }
5161                 else
5162                 {
5163                         appendPQExpBuffer(query,
5164                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5165                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5166                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5167                                                           "tgconstrrelid, tginitdeferred, "
5168                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5169                                                           "oid, "
5170                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5171                                                           "             AS tgconstrrelname "
5172                                                           "FROM pg_trigger "
5173                                                           "WHERE tgrelid = '%u'::oid",
5174                                                           tbinfo->dobj.catId.oid);
5175                 }
5176                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5177
5178                 ntups = PQntuples(res);
5179
5180                 i_tableoid = PQfnumber(res, "tableoid");
5181                 i_oid = PQfnumber(res, "oid");
5182                 i_tgname = PQfnumber(res, "tgname");
5183                 i_tgfname = PQfnumber(res, "tgfname");
5184                 i_tgtype = PQfnumber(res, "tgtype");
5185                 i_tgnargs = PQfnumber(res, "tgnargs");
5186                 i_tgargs = PQfnumber(res, "tgargs");
5187                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5188                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5189                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5190                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5191                 i_tgenabled = PQfnumber(res, "tgenabled");
5192                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5193                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5194                 i_tgdef = PQfnumber(res, "tgdef");
5195
5196                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5197
5198                 for (j = 0; j < ntups; j++)
5199                 {
5200                         tginfo[j].dobj.objType = DO_TRIGGER;
5201                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5202                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5203                         AssignDumpId(&tginfo[j].dobj);
5204                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5205                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5206                         tginfo[j].tgtable = tbinfo;
5207                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5208                         if (i_tgdef >= 0)
5209                         {
5210                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5211
5212                                 /* remaining fields are not valid if we have tgdef */
5213                                 tginfo[j].tgfname = NULL;
5214                                 tginfo[j].tgtype = 0;
5215                                 tginfo[j].tgnargs = 0;
5216                                 tginfo[j].tgargs = NULL;
5217                                 tginfo[j].tgisconstraint = false;
5218                                 tginfo[j].tgdeferrable = false;
5219                                 tginfo[j].tginitdeferred = false;
5220                                 tginfo[j].tgconstrname = NULL;
5221                                 tginfo[j].tgconstrrelid = InvalidOid;
5222                                 tginfo[j].tgconstrrelname = NULL;
5223                         }
5224                         else
5225                         {
5226                                 tginfo[j].tgdef = NULL;
5227
5228                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5229                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5230                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5231                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5232                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5233                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5234                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5235
5236                                 if (tginfo[j].tgisconstraint)
5237                                 {
5238                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5239                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5240                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5241                                         {
5242                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5243                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5244                                                                                   tginfo[j].dobj.name,
5245                                                                                   tbinfo->dobj.name,
5246                                                                                   tginfo[j].tgconstrrelid);
5247                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5248                                         }
5249                                         else
5250                                                 tginfo[j].tgconstrrelname = NULL;
5251                                 }
5252                                 else
5253                                 {
5254                                         tginfo[j].tgconstrname = NULL;
5255                                         tginfo[j].tgconstrrelid = InvalidOid;
5256                                         tginfo[j].tgconstrrelname = NULL;
5257                                 }
5258                         }
5259                 }
5260
5261                 PQclear(res);
5262         }
5263
5264         destroyPQExpBuffer(query);
5265 }
5266
5267 /*
5268  * getProcLangs
5269  *        get basic information about every procedural language in the system
5270  *
5271  * numProcLangs is set to the number of langs read in
5272  *
5273  * NB: this must run after getFuncs() because we assume we can do
5274  * findFuncByOid().
5275  */
5276 ProcLangInfo *
5277 getProcLangs(Archive *fout, int *numProcLangs)
5278 {
5279         PGresult   *res;
5280         int                     ntups;
5281         int                     i;
5282         PQExpBuffer query = createPQExpBuffer();
5283         ProcLangInfo *planginfo;
5284         int                     i_tableoid;
5285         int                     i_oid;
5286         int                     i_lanname;
5287         int                     i_lanpltrusted;
5288         int                     i_lanplcallfoid;
5289         int                     i_laninline;
5290         int                     i_lanvalidator;
5291         int                     i_lanacl;
5292         int                     i_lanowner;
5293
5294         /* Make sure we are in proper schema */
5295         selectSourceSchema(fout, "pg_catalog");
5296
5297         if (fout->remoteVersion >= 90000)
5298         {
5299                 /* pg_language has a laninline column */
5300                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5301                                                   "lanname, lanpltrusted, lanplcallfoid, "
5302                                                   "laninline, lanvalidator,  lanacl, "
5303                                                   "(%s lanowner) AS lanowner "
5304                                                   "FROM pg_language "
5305                                                   "WHERE lanispl "
5306                                                   "ORDER BY oid",
5307                                                   username_subquery);
5308         }
5309         else if (fout->remoteVersion >= 80300)
5310         {
5311                 /* pg_language has a lanowner column */
5312                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5313                                                   "lanname, lanpltrusted, lanplcallfoid, "
5314                                                   "lanvalidator,  lanacl, "
5315                                                   "(%s lanowner) AS lanowner "
5316                                                   "FROM pg_language "
5317                                                   "WHERE lanispl "
5318                                                   "ORDER BY oid",
5319                                                   username_subquery);
5320         }
5321         else if (fout->remoteVersion >= 80100)
5322         {
5323                 /* Languages are owned by the bootstrap superuser, OID 10 */
5324                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5325                                                   "(%s '10') AS lanowner "
5326                                                   "FROM pg_language "
5327                                                   "WHERE lanispl "
5328                                                   "ORDER BY oid",
5329                                                   username_subquery);
5330         }
5331         else if (fout->remoteVersion >= 70400)
5332         {
5333                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5334                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5335                                                   "(%s '1') AS lanowner "
5336                                                   "FROM pg_language "
5337                                                   "WHERE lanispl "
5338                                                   "ORDER BY oid",
5339                                                   username_subquery);
5340         }
5341         else if (fout->remoteVersion >= 70100)
5342         {
5343                 /* No clear notion of an owner at all before 7.4 ... */
5344                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5345                                                   "WHERE lanispl "
5346                                                   "ORDER BY oid");
5347         }
5348         else
5349         {
5350                 appendPQExpBuffer(query, "SELECT "
5351                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5352                                                   "oid, * FROM pg_language "
5353                                                   "WHERE lanispl "
5354                                                   "ORDER BY oid");
5355         }
5356
5357         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5358
5359         ntups = PQntuples(res);
5360
5361         *numProcLangs = ntups;
5362
5363         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5364
5365         i_tableoid = PQfnumber(res, "tableoid");
5366         i_oid = PQfnumber(res, "oid");
5367         i_lanname = PQfnumber(res, "lanname");
5368         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5369         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5370         /* these may fail and return -1: */
5371         i_laninline = PQfnumber(res, "laninline");
5372         i_lanvalidator = PQfnumber(res, "lanvalidator");
5373         i_lanacl = PQfnumber(res, "lanacl");
5374         i_lanowner = PQfnumber(res, "lanowner");
5375
5376         for (i = 0; i < ntups; i++)
5377         {
5378                 planginfo[i].dobj.objType = DO_PROCLANG;
5379                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5380                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5381                 AssignDumpId(&planginfo[i].dobj);
5382
5383                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5384                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5385                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5386                 if (i_laninline >= 0)
5387                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5388                 else
5389                         planginfo[i].laninline = InvalidOid;
5390                 if (i_lanvalidator >= 0)
5391                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5392                 else
5393                         planginfo[i].lanvalidator = InvalidOid;
5394                 if (i_lanacl >= 0)
5395                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5396                 else
5397                         planginfo[i].lanacl = pg_strdup("{=U}");
5398                 if (i_lanowner >= 0)
5399                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5400                 else
5401                         planginfo[i].lanowner = pg_strdup("");
5402
5403                 if (fout->remoteVersion < 70300)
5404                 {
5405                         /*
5406                          * We need to make a dependency to ensure the function will be
5407                          * dumped first.  (In 7.3 and later the regular dependency
5408                          * mechanism will handle this for us.)
5409                          */
5410                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5411
5412                         if (funcInfo)
5413                                 addObjectDependency(&planginfo[i].dobj,
5414                                                                         funcInfo->dobj.dumpId);
5415                 }
5416         }
5417
5418         PQclear(res);
5419
5420         destroyPQExpBuffer(query);
5421
5422         return planginfo;
5423 }
5424
5425 /*
5426  * getCasts
5427  *        get basic information about every cast in the system
5428  *
5429  * numCasts is set to the number of casts read in
5430  */
5431 CastInfo *
5432 getCasts(Archive *fout, int *numCasts)
5433 {
5434         PGresult   *res;
5435         int                     ntups;
5436         int                     i;
5437         PQExpBuffer query = createPQExpBuffer();
5438         CastInfo   *castinfo;
5439         int                     i_tableoid;
5440         int                     i_oid;
5441         int                     i_castsource;
5442         int                     i_casttarget;
5443         int                     i_castfunc;
5444         int                     i_castcontext;
5445         int                     i_castmethod;
5446
5447         /* Make sure we are in proper schema */
5448         selectSourceSchema(fout, "pg_catalog");
5449
5450         if (fout->remoteVersion >= 80400)
5451         {
5452                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5453                                                   "castsource, casttarget, castfunc, castcontext, "
5454                                                   "castmethod "
5455                                                   "FROM pg_cast ORDER BY 3,4");
5456         }
5457         else if (fout->remoteVersion >= 70300)
5458         {
5459                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5460                                                   "castsource, casttarget, castfunc, castcontext, "
5461                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5462                                                   "FROM pg_cast ORDER BY 3,4");
5463         }
5464         else
5465         {
5466                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5467                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5468                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5469                                                   "'f' AS castmethod "
5470                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5471                                                   "WHERE p.pronargs = 1 AND "
5472                                                   "p.proargtypes[0] = t1.oid AND "
5473                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5474                                                   "ORDER BY 3,4");
5475         }
5476
5477         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5478
5479         ntups = PQntuples(res);
5480
5481         *numCasts = ntups;
5482
5483         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5484
5485         i_tableoid = PQfnumber(res, "tableoid");
5486         i_oid = PQfnumber(res, "oid");
5487         i_castsource = PQfnumber(res, "castsource");
5488         i_casttarget = PQfnumber(res, "casttarget");
5489         i_castfunc = PQfnumber(res, "castfunc");
5490         i_castcontext = PQfnumber(res, "castcontext");
5491         i_castmethod = PQfnumber(res, "castmethod");
5492
5493         for (i = 0; i < ntups; i++)
5494         {
5495                 PQExpBufferData namebuf;
5496                 TypeInfo   *sTypeInfo;
5497                 TypeInfo   *tTypeInfo;
5498
5499                 castinfo[i].dobj.objType = DO_CAST;
5500                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5501                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5502                 AssignDumpId(&castinfo[i].dobj);
5503                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5504                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5505                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5506                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5507                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5508
5509                 /*
5510                  * Try to name cast as concatenation of typnames.  This is only used
5511                  * for purposes of sorting.  If we fail to find either type, the name
5512                  * will be an empty string.
5513                  */
5514                 initPQExpBuffer(&namebuf);
5515                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5516                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5517                 if (sTypeInfo && tTypeInfo)
5518                         appendPQExpBuffer(&namebuf, "%s %s",
5519                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5520                 castinfo[i].dobj.name = namebuf.data;
5521
5522                 if (OidIsValid(castinfo[i].castfunc))
5523                 {
5524                         /*
5525                          * We need to make a dependency to ensure the function will be
5526                          * dumped first.  (In 7.3 and later the regular dependency
5527                          * mechanism will handle this for us.)
5528                          */
5529                         FuncInfo   *funcInfo;
5530
5531                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5532                         if (funcInfo)
5533                                 addObjectDependency(&castinfo[i].dobj,
5534                                                                         funcInfo->dobj.dumpId);
5535                 }
5536         }
5537
5538         PQclear(res);
5539
5540         destroyPQExpBuffer(query);
5541
5542         return castinfo;
5543 }
5544
5545 /*
5546  * getTableAttrs -
5547  *        for each interesting table, read info about its attributes
5548  *        (names, types, default values, CHECK constraints, etc)
5549  *
5550  * This is implemented in a very inefficient way right now, looping
5551  * through the tblinfo and doing a join per table to find the attrs and their
5552  * types.  However, because we want type names and so forth to be named
5553  * relative to the schema of each table, we couldn't do it in just one
5554  * query.  (Maybe one query per schema?)
5555  *
5556  *      modifies tblinfo
5557  */
5558 void
5559 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5560 {
5561         int                     i,
5562                                 j;
5563         PQExpBuffer q = createPQExpBuffer();
5564         int                     i_attnum;
5565         int                     i_attname;
5566         int                     i_atttypname;
5567         int                     i_atttypmod;
5568         int                     i_attstattarget;
5569         int                     i_attstorage;
5570         int                     i_typstorage;
5571         int                     i_attnotnull;
5572         int                     i_atthasdef;
5573         int                     i_attisdropped;
5574         int                     i_attlen;
5575         int                     i_attalign;
5576         int                     i_attislocal;
5577         int                     i_attoptions;
5578         int                     i_attcollation;
5579         int                     i_attfdwoptions;
5580         PGresult   *res;
5581         int                     ntups;
5582         bool            hasdefaults;
5583
5584         for (i = 0; i < numTables; i++)
5585         {
5586                 TableInfo  *tbinfo = &tblinfo[i];
5587
5588                 /* Don't bother to collect info for sequences */
5589                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5590                         continue;
5591
5592                 /* Don't bother with uninteresting tables, either */
5593                 if (!tbinfo->interesting)
5594                         continue;
5595
5596                 /*
5597                  * Make sure we are in proper schema for this table; this allows
5598                  * correct retrieval of formatted type names and default exprs
5599                  */
5600                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5601
5602                 /* find all the user attributes and their types */
5603
5604                 /*
5605                  * we must read the attribute names in attribute number order! because
5606                  * we will use the attnum to index into the attnames array later.  We
5607                  * actually ask to order by "attrelid, attnum" because (at least up to
5608                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5609                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5610                  */
5611                 if (g_verbose)
5612                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5613                                           tbinfo->dobj.name);
5614
5615                 resetPQExpBuffer(q);
5616
5617                 if (fout->remoteVersion >= 90200)
5618                 {
5619                         /*
5620                          * attfdwoptions is new in 9.2.
5621                          */
5622                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5623                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5624                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5625                                                           "a.attlen, a.attalign, a.attislocal, "
5626                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5627                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5628                                                           "CASE WHEN a.attcollation <> t.typcollation "
5629                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5630                                                           "pg_catalog.array_to_string(ARRAY("
5631                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5632                                                           "' ' || pg_catalog.quote_literal(option_value) "
5633                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5634                                                           "ORDER BY option_name"
5635                                                           "), E',\n    ') AS attfdwoptions "
5636                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5637                                                           "ON a.atttypid = t.oid "
5638                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5639                                                           "AND a.attnum > 0::pg_catalog.int2 "
5640                                                           "ORDER BY a.attrelid, a.attnum",
5641                                                           tbinfo->dobj.catId.oid);
5642                 }
5643                 else if (fout->remoteVersion >= 90100)
5644                 {
5645                         /*
5646                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5647                          * clauses for attributes whose collation is different from their
5648                          * type's default, we use a CASE here to suppress uninteresting
5649                          * attcollations cheaply.
5650                          */
5651                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5652                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5653                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5654                                                           "a.attlen, a.attalign, a.attislocal, "
5655                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5656                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5657                                                           "CASE WHEN a.attcollation <> t.typcollation "
5658                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5659                                                           "NULL AS attfdwoptions "
5660                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5661                                                           "ON a.atttypid = t.oid "
5662                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5663                                                           "AND a.attnum > 0::pg_catalog.int2 "
5664                                                           "ORDER BY a.attrelid, a.attnum",
5665                                                           tbinfo->dobj.catId.oid);
5666                 }
5667                 else if (fout->remoteVersion >= 90000)
5668                 {
5669                         /* attoptions is new in 9.0 */
5670                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5671                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5672                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5673                                                           "a.attlen, a.attalign, a.attislocal, "
5674                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5675                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5676                                                           "0 AS attcollation, "
5677                                                           "NULL AS attfdwoptions "
5678                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5679                                                           "ON a.atttypid = t.oid "
5680                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5681                                                           "AND a.attnum > 0::pg_catalog.int2 "
5682                                                           "ORDER BY a.attrelid, a.attnum",
5683                                                           tbinfo->dobj.catId.oid);
5684                 }
5685                 else if (fout->remoteVersion >= 70300)
5686                 {
5687                         /* need left join here to not fail on dropped columns ... */
5688                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5689                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5690                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5691                                                           "a.attlen, a.attalign, a.attislocal, "
5692                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5693                                                           "'' AS attoptions, 0 AS attcollation, "
5694                                                           "NULL AS attfdwoptions "
5695                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5696                                                           "ON a.atttypid = t.oid "
5697                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5698                                                           "AND a.attnum > 0::pg_catalog.int2 "
5699                                                           "ORDER BY a.attrelid, a.attnum",
5700                                                           tbinfo->dobj.catId.oid);
5701                 }
5702                 else if (fout->remoteVersion >= 70100)
5703                 {
5704                         /*
5705                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5706                          * we don't dump it because we can't tell whether it's been
5707                          * explicitly set or was just a default.
5708                          *
5709                          * attislocal doesn't exist before 7.3, either; in older databases
5710                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5711                          */
5712                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5713                                                           "-1 AS attstattarget, a.attstorage, "
5714                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5715                                                           "false AS attisdropped, a.attlen, "
5716                                                           "a.attalign, true AS attislocal, "
5717                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5718                                                           "'' AS attoptions, 0 AS attcollation, "
5719                                                           "NULL AS attfdwoptions "
5720                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5721                                                           "ON a.atttypid = t.oid "
5722                                                           "WHERE a.attrelid = '%u'::oid "
5723                                                           "AND a.attnum > 0::int2 "
5724                                                           "ORDER BY a.attrelid, a.attnum",
5725                                                           tbinfo->dobj.catId.oid);
5726                 }
5727                 else
5728                 {
5729                         /* format_type not available before 7.1 */
5730                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5731                                                           "-1 AS attstattarget, "
5732                                                           "attstorage, attstorage AS typstorage, "
5733                                                           "attnotnull, atthasdef, false AS attisdropped, "
5734                                                           "attlen, attalign, "
5735                                                           "true AS attislocal, "
5736                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5737                                                           "'' AS attoptions, 0 AS attcollation, "
5738                                                           "NULL AS attfdwoptions "
5739                                                           "FROM pg_attribute a "
5740                                                           "WHERE attrelid = '%u'::oid "
5741                                                           "AND attnum > 0::int2 "
5742                                                           "ORDER BY attrelid, attnum",
5743                                                           tbinfo->dobj.catId.oid);
5744                 }
5745
5746                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5747
5748                 ntups = PQntuples(res);
5749
5750                 i_attnum = PQfnumber(res, "attnum");
5751                 i_attname = PQfnumber(res, "attname");
5752                 i_atttypname = PQfnumber(res, "atttypname");
5753                 i_atttypmod = PQfnumber(res, "atttypmod");
5754                 i_attstattarget = PQfnumber(res, "attstattarget");
5755                 i_attstorage = PQfnumber(res, "attstorage");
5756                 i_typstorage = PQfnumber(res, "typstorage");
5757                 i_attnotnull = PQfnumber(res, "attnotnull");
5758                 i_atthasdef = PQfnumber(res, "atthasdef");
5759                 i_attisdropped = PQfnumber(res, "attisdropped");
5760                 i_attlen = PQfnumber(res, "attlen");
5761                 i_attalign = PQfnumber(res, "attalign");
5762                 i_attislocal = PQfnumber(res, "attislocal");
5763                 i_attoptions = PQfnumber(res, "attoptions");
5764                 i_attcollation = PQfnumber(res, "attcollation");
5765                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5766
5767                 tbinfo->numatts = ntups;
5768                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5769                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5770                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5771                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5772                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5773                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5774                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5775                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5776                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5777                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5778                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5779                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5780                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5781                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5782                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5783                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5784                 hasdefaults = false;
5785
5786                 for (j = 0; j < ntups; j++)
5787                 {
5788                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5789                                 exit_horribly(NULL,
5790                                                           "invalid column numbering in table \"%s\"\n",
5791                                                           tbinfo->dobj.name);
5792                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5793                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5794                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5795                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5796                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5797                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5798                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5799                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5800                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5801                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5802                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5803                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5804                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5805                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5806                         tbinfo->attrdefs[j] = NULL; /* fix below */
5807                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5808                                 hasdefaults = true;
5809                         /* these flags will be set in flagInhAttrs() */
5810                         tbinfo->inhNotNull[j] = false;
5811                 }
5812
5813                 PQclear(res);
5814
5815                 /*
5816                  * Get info about column defaults
5817                  */
5818                 if (hasdefaults)
5819                 {
5820                         AttrDefInfo *attrdefs;
5821                         int                     numDefaults;
5822
5823                         if (g_verbose)
5824                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5825                                                   tbinfo->dobj.name);
5826
5827                         resetPQExpBuffer(q);
5828                         if (fout->remoteVersion >= 70300)
5829                         {
5830                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5831                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5832                                                                   "FROM pg_catalog.pg_attrdef "
5833                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5834                                                                   tbinfo->dobj.catId.oid);
5835                         }
5836                         else if (fout->remoteVersion >= 70200)
5837                         {
5838                                 /* 7.2 did not have OIDs in pg_attrdef */
5839                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5840                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5841                                                                   "FROM pg_attrdef "
5842                                                                   "WHERE adrelid = '%u'::oid",
5843                                                                   tbinfo->dobj.catId.oid);
5844                         }
5845                         else if (fout->remoteVersion >= 70100)
5846                         {
5847                                 /* no pg_get_expr, so must rely on adsrc */
5848                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5849                                                                   "FROM pg_attrdef "
5850                                                                   "WHERE adrelid = '%u'::oid",
5851                                                                   tbinfo->dobj.catId.oid);
5852                         }
5853                         else
5854                         {
5855                                 /* no pg_get_expr, no tableoid either */
5856                                 appendPQExpBuffer(q, "SELECT "
5857                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5858                                                                   "oid, adnum, adsrc "
5859                                                                   "FROM pg_attrdef "
5860                                                                   "WHERE adrelid = '%u'::oid",
5861                                                                   tbinfo->dobj.catId.oid);
5862                         }
5863                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5864
5865                         numDefaults = PQntuples(res);
5866                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5867
5868                         for (j = 0; j < numDefaults; j++)
5869                         {
5870                                 int                     adnum;
5871
5872                                 adnum = atoi(PQgetvalue(res, j, 2));
5873
5874                                 if (adnum <= 0 || adnum > ntups)
5875                                         exit_horribly(NULL,
5876                                                                   "invalid adnum value %d for table \"%s\"\n",
5877                                                                   adnum, tbinfo->dobj.name);
5878
5879                                 /*
5880                                  * dropped columns shouldn't have defaults, but just in case,
5881                                  * ignore 'em
5882                                  */
5883                                 if (tbinfo->attisdropped[adnum - 1])
5884                                         continue;
5885
5886                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
5887                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5888                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5889                                 AssignDumpId(&attrdefs[j].dobj);
5890                                 attrdefs[j].adtable = tbinfo;
5891                                 attrdefs[j].adnum = adnum;
5892                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5893
5894                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5895                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5896
5897                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5898
5899                                 /*
5900                                  * Defaults on a VIEW must always be dumped as separate ALTER
5901                                  * TABLE commands.      Defaults on regular tables are dumped as
5902                                  * part of the CREATE TABLE if possible, which it won't be if
5903                                  * the column is not going to be emitted explicitly.
5904                                  */
5905                                 if (tbinfo->relkind == RELKIND_VIEW)
5906                                 {
5907                                         attrdefs[j].separate = true;
5908                                         /* needed in case pre-7.3 DB: */
5909                                         addObjectDependency(&attrdefs[j].dobj,
5910                                                                                 tbinfo->dobj.dumpId);
5911                                 }
5912                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5913                                 {
5914                                         /* column will be suppressed, print default separately */
5915                                         attrdefs[j].separate = true;
5916                                         /* needed in case pre-7.3 DB: */
5917                                         addObjectDependency(&attrdefs[j].dobj,
5918                                                                                 tbinfo->dobj.dumpId);
5919                                 }
5920                                 else
5921                                 {
5922                                         attrdefs[j].separate = false;
5923
5924                                         /*
5925                                          * Mark the default as needing to appear before the table,
5926                                          * so that any dependencies it has must be emitted before
5927                                          * the CREATE TABLE.  If this is not possible, we'll
5928                                          * change to "separate" mode while sorting dependencies.
5929                                          */
5930                                         addObjectDependency(&tbinfo->dobj,
5931                                                                                 attrdefs[j].dobj.dumpId);
5932                                 }
5933
5934                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5935                         }
5936                         PQclear(res);
5937                 }
5938
5939                 /*
5940                  * Get info about table CHECK constraints
5941                  */
5942                 if (tbinfo->ncheck > 0)
5943                 {
5944                         ConstraintInfo *constrs;
5945                         int                     numConstrs;
5946
5947                         if (g_verbose)
5948                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5949                                                   tbinfo->dobj.name);
5950
5951                         resetPQExpBuffer(q);
5952                         if (fout->remoteVersion >= 90200)
5953                         {
5954                                 /*
5955                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
5956                                  * but it wasn't ever false for check constraints until 9.2).
5957                                  */
5958                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5959                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5960                                                                   "conislocal, convalidated "
5961                                                                   "FROM pg_catalog.pg_constraint "
5962                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5963                                                                   "   AND contype = 'c' "
5964                                                                   "ORDER BY conname",
5965                                                                   tbinfo->dobj.catId.oid);
5966                         }
5967                         else if (fout->remoteVersion >= 80400)
5968                         {
5969                                 /* conislocal is new in 8.4 */
5970                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5971                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5972                                                                   "conislocal, true AS convalidated "
5973                                                                   "FROM pg_catalog.pg_constraint "
5974                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5975                                                                   "   AND contype = 'c' "
5976                                                                   "ORDER BY conname",
5977                                                                   tbinfo->dobj.catId.oid);
5978                         }
5979                         else if (fout->remoteVersion >= 70400)
5980                         {
5981                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5982                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5983                                                                   "true AS conislocal, true AS convalidated "
5984                                                                   "FROM pg_catalog.pg_constraint "
5985                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5986                                                                   "   AND contype = 'c' "
5987                                                                   "ORDER BY conname",
5988                                                                   tbinfo->dobj.catId.oid);
5989                         }
5990                         else if (fout->remoteVersion >= 70300)
5991                         {
5992                                 /* no pg_get_constraintdef, must use consrc */
5993                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5994                                                                   "'CHECK (' || consrc || ')' AS consrc, "
5995                                                                   "true AS conislocal, true AS convalidated "
5996                                                                   "FROM pg_catalog.pg_constraint "
5997                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5998                                                                   "   AND contype = 'c' "
5999                                                                   "ORDER BY conname",
6000                                                                   tbinfo->dobj.catId.oid);
6001                         }
6002                         else if (fout->remoteVersion >= 70200)
6003                         {
6004                                 /* 7.2 did not have OIDs in pg_relcheck */
6005                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6006                                                                   "rcname AS conname, "
6007                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6008                                                                   "true AS conislocal, true AS convalidated "
6009                                                                   "FROM pg_relcheck "
6010                                                                   "WHERE rcrelid = '%u'::oid "
6011                                                                   "ORDER BY rcname",
6012                                                                   tbinfo->dobj.catId.oid);
6013                         }
6014                         else if (fout->remoteVersion >= 70100)
6015                         {
6016                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6017                                                                   "rcname AS conname, "
6018                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6019                                                                   "true AS conislocal, true AS convalidated "
6020                                                                   "FROM pg_relcheck "
6021                                                                   "WHERE rcrelid = '%u'::oid "
6022                                                                   "ORDER BY rcname",
6023                                                                   tbinfo->dobj.catId.oid);
6024                         }
6025                         else
6026                         {
6027                                 /* no tableoid in 7.0 */
6028                                 appendPQExpBuffer(q, "SELECT "
6029                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6030                                                                   "oid, rcname AS conname, "
6031                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6032                                                                   "true AS conislocal, true AS convalidated "
6033                                                                   "FROM pg_relcheck "
6034                                                                   "WHERE rcrelid = '%u'::oid "
6035                                                                   "ORDER BY rcname",
6036                                                                   tbinfo->dobj.catId.oid);
6037                         }
6038                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6039
6040                         numConstrs = PQntuples(res);
6041                         if (numConstrs != tbinfo->ncheck)
6042                         {
6043                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6044                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6045                                                                                  tbinfo->ncheck),
6046                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6047                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6048                                 exit_nicely(1);
6049                         }
6050
6051                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6052                         tbinfo->checkexprs = constrs;
6053
6054                         for (j = 0; j < numConstrs; j++)
6055                         {
6056                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6057
6058                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6059                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6060                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6061                                 AssignDumpId(&constrs[j].dobj);
6062                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6063                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6064                                 constrs[j].contable = tbinfo;
6065                                 constrs[j].condomain = NULL;
6066                                 constrs[j].contype = 'c';
6067                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6068                                 constrs[j].confrelid = InvalidOid;
6069                                 constrs[j].conindex = 0;
6070                                 constrs[j].condeferrable = false;
6071                                 constrs[j].condeferred = false;
6072                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6073
6074                                 /*
6075                                  * An unvalidated constraint needs to be dumped separately, so
6076                                  * that potentially-violating existing data is loaded before
6077                                  * the constraint.
6078                                  */
6079                                 constrs[j].separate = !validated;
6080
6081                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6082
6083                                 /*
6084                                  * Mark the constraint as needing to appear before the table
6085                                  * --- this is so that any other dependencies of the
6086                                  * constraint will be emitted before we try to create the
6087                                  * table.  If the constraint is to be dumped separately, it
6088                                  * will be dumped after data is loaded anyway, so don't do it.
6089                                  * (There's an automatic dependency in the opposite direction
6090                                  * anyway, so don't need to add one manually here.)
6091                                  */
6092                                 if (!constrs[j].separate)
6093                                         addObjectDependency(&tbinfo->dobj,
6094                                                                                 constrs[j].dobj.dumpId);
6095
6096                                 /*
6097                                  * If the constraint is inherited, this will be detected later
6098                                  * (in pre-8.4 databases).      We also detect later if the
6099                                  * constraint must be split out from the table definition.
6100                                  */
6101                         }
6102                         PQclear(res);
6103                 }
6104         }
6105
6106         destroyPQExpBuffer(q);
6107 }
6108
6109 /*
6110  * Test whether a column should be printed as part of table's CREATE TABLE.
6111  * Column number is zero-based.
6112  *
6113  * Normally this is always true, but it's false for dropped columns, as well
6114  * as those that were inherited without any local definition.  (If we print
6115  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6116  * However, in binary_upgrade mode, we must print all such columns anyway and
6117  * fix the attislocal/attisdropped state later, so as to keep control of the
6118  * physical column order.
6119  *
6120  * This function exists because there are scattered nonobvious places that
6121  * must be kept in sync with this decision.
6122  */
6123 bool
6124 shouldPrintColumn(TableInfo *tbinfo, int colno)
6125 {
6126         if (binary_upgrade)
6127                 return true;
6128         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6129 }
6130
6131
6132 /*
6133  * getTSParsers:
6134  *        read all text search parsers in the system catalogs and return them
6135  *        in the TSParserInfo* structure
6136  *
6137  *      numTSParsers is set to the number of parsers read in
6138  */
6139 TSParserInfo *
6140 getTSParsers(Archive *fout, int *numTSParsers)
6141 {
6142         PGresult   *res;
6143         int                     ntups;
6144         int                     i;
6145         PQExpBuffer query;
6146         TSParserInfo *prsinfo;
6147         int                     i_tableoid;
6148         int                     i_oid;
6149         int                     i_prsname;
6150         int                     i_prsnamespace;
6151         int                     i_prsstart;
6152         int                     i_prstoken;
6153         int                     i_prsend;
6154         int                     i_prsheadline;
6155         int                     i_prslextype;
6156
6157         /* Before 8.3, there is no built-in text search support */
6158         if (fout->remoteVersion < 80300)
6159         {
6160                 *numTSParsers = 0;
6161                 return NULL;
6162         }
6163
6164         query = createPQExpBuffer();
6165
6166         /*
6167          * find all text search objects, including builtin ones; we filter out
6168          * system-defined objects at dump-out time.
6169          */
6170
6171         /* Make sure we are in proper schema */
6172         selectSourceSchema(fout, "pg_catalog");
6173
6174         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6175                                           "prsstart::oid, prstoken::oid, "
6176                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6177                                           "FROM pg_ts_parser");
6178
6179         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6180
6181         ntups = PQntuples(res);
6182         *numTSParsers = ntups;
6183
6184         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6185
6186         i_tableoid = PQfnumber(res, "tableoid");
6187         i_oid = PQfnumber(res, "oid");
6188         i_prsname = PQfnumber(res, "prsname");
6189         i_prsnamespace = PQfnumber(res, "prsnamespace");
6190         i_prsstart = PQfnumber(res, "prsstart");
6191         i_prstoken = PQfnumber(res, "prstoken");
6192         i_prsend = PQfnumber(res, "prsend");
6193         i_prsheadline = PQfnumber(res, "prsheadline");
6194         i_prslextype = PQfnumber(res, "prslextype");
6195
6196         for (i = 0; i < ntups; i++)
6197         {
6198                 prsinfo[i].dobj.objType = DO_TSPARSER;
6199                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6200                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6201                 AssignDumpId(&prsinfo[i].dobj);
6202                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6203                 prsinfo[i].dobj.namespace =
6204                         findNamespace(fout,
6205                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6206                                                   prsinfo[i].dobj.catId.oid);
6207                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6208                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6209                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6210                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6211                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6212
6213                 /* Decide whether we want to dump it */
6214                 selectDumpableObject(&(prsinfo[i].dobj));
6215         }
6216
6217         PQclear(res);
6218
6219         destroyPQExpBuffer(query);
6220
6221         return prsinfo;
6222 }
6223
6224 /*
6225  * getTSDictionaries:
6226  *        read all text search dictionaries in the system catalogs and return them
6227  *        in the TSDictInfo* structure
6228  *
6229  *      numTSDicts is set to the number of dictionaries read in
6230  */
6231 TSDictInfo *
6232 getTSDictionaries(Archive *fout, int *numTSDicts)
6233 {
6234         PGresult   *res;
6235         int                     ntups;
6236         int                     i;
6237         PQExpBuffer query;
6238         TSDictInfo *dictinfo;
6239         int                     i_tableoid;
6240         int                     i_oid;
6241         int                     i_dictname;
6242         int                     i_dictnamespace;
6243         int                     i_rolname;
6244         int                     i_dicttemplate;
6245         int                     i_dictinitoption;
6246
6247         /* Before 8.3, there is no built-in text search support */
6248         if (fout->remoteVersion < 80300)
6249         {
6250                 *numTSDicts = 0;
6251                 return NULL;
6252         }
6253
6254         query = createPQExpBuffer();
6255
6256         /* Make sure we are in proper schema */
6257         selectSourceSchema(fout, "pg_catalog");
6258
6259         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6260                                           "dictnamespace, (%s dictowner) AS rolname, "
6261                                           "dicttemplate, dictinitoption "
6262                                           "FROM pg_ts_dict",
6263                                           username_subquery);
6264
6265         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6266
6267         ntups = PQntuples(res);
6268         *numTSDicts = ntups;
6269
6270         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6271
6272         i_tableoid = PQfnumber(res, "tableoid");
6273         i_oid = PQfnumber(res, "oid");
6274         i_dictname = PQfnumber(res, "dictname");
6275         i_dictnamespace = PQfnumber(res, "dictnamespace");
6276         i_rolname = PQfnumber(res, "rolname");
6277         i_dictinitoption = PQfnumber(res, "dictinitoption");
6278         i_dicttemplate = PQfnumber(res, "dicttemplate");
6279
6280         for (i = 0; i < ntups; i++)
6281         {
6282                 dictinfo[i].dobj.objType = DO_TSDICT;
6283                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6284                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6285                 AssignDumpId(&dictinfo[i].dobj);
6286                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6287                 dictinfo[i].dobj.namespace =
6288                         findNamespace(fout,
6289                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6290                                                   dictinfo[i].dobj.catId.oid);
6291                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6292                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6293                 if (PQgetisnull(res, i, i_dictinitoption))
6294                         dictinfo[i].dictinitoption = NULL;
6295                 else
6296                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6297
6298                 /* Decide whether we want to dump it */
6299                 selectDumpableObject(&(dictinfo[i].dobj));
6300         }
6301
6302         PQclear(res);
6303
6304         destroyPQExpBuffer(query);
6305
6306         return dictinfo;
6307 }
6308
6309 /*
6310  * getTSTemplates:
6311  *        read all text search templates in the system catalogs and return them
6312  *        in the TSTemplateInfo* structure
6313  *
6314  *      numTSTemplates is set to the number of templates read in
6315  */
6316 TSTemplateInfo *
6317 getTSTemplates(Archive *fout, int *numTSTemplates)
6318 {
6319         PGresult   *res;
6320         int                     ntups;
6321         int                     i;
6322         PQExpBuffer query;
6323         TSTemplateInfo *tmplinfo;
6324         int                     i_tableoid;
6325         int                     i_oid;
6326         int                     i_tmplname;
6327         int                     i_tmplnamespace;
6328         int                     i_tmplinit;
6329         int                     i_tmpllexize;
6330
6331         /* Before 8.3, there is no built-in text search support */
6332         if (fout->remoteVersion < 80300)
6333         {
6334                 *numTSTemplates = 0;
6335                 return NULL;
6336         }
6337
6338         query = createPQExpBuffer();
6339
6340         /* Make sure we are in proper schema */
6341         selectSourceSchema(fout, "pg_catalog");
6342
6343         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6344                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6345                                           "FROM pg_ts_template");
6346
6347         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6348
6349         ntups = PQntuples(res);
6350         *numTSTemplates = ntups;
6351
6352         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6353
6354         i_tableoid = PQfnumber(res, "tableoid");
6355         i_oid = PQfnumber(res, "oid");
6356         i_tmplname = PQfnumber(res, "tmplname");
6357         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6358         i_tmplinit = PQfnumber(res, "tmplinit");
6359         i_tmpllexize = PQfnumber(res, "tmpllexize");
6360
6361         for (i = 0; i < ntups; i++)
6362         {
6363                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6364                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6365                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6366                 AssignDumpId(&tmplinfo[i].dobj);
6367                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6368                 tmplinfo[i].dobj.namespace =
6369                         findNamespace(fout,
6370                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6371                                                   tmplinfo[i].dobj.catId.oid);
6372                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6373                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6374
6375                 /* Decide whether we want to dump it */
6376                 selectDumpableObject(&(tmplinfo[i].dobj));
6377         }
6378
6379         PQclear(res);
6380
6381         destroyPQExpBuffer(query);
6382
6383         return tmplinfo;
6384 }
6385
6386 /*
6387  * getTSConfigurations:
6388  *        read all text search configurations in the system catalogs and return
6389  *        them in the TSConfigInfo* structure
6390  *
6391  *      numTSConfigs is set to the number of configurations read in
6392  */
6393 TSConfigInfo *
6394 getTSConfigurations(Archive *fout, int *numTSConfigs)
6395 {
6396         PGresult   *res;
6397         int                     ntups;
6398         int                     i;
6399         PQExpBuffer query;
6400         TSConfigInfo *cfginfo;
6401         int                     i_tableoid;
6402         int                     i_oid;
6403         int                     i_cfgname;
6404         int                     i_cfgnamespace;
6405         int                     i_rolname;
6406         int                     i_cfgparser;
6407
6408         /* Before 8.3, there is no built-in text search support */
6409         if (fout->remoteVersion < 80300)
6410         {
6411                 *numTSConfigs = 0;
6412                 return NULL;
6413         }
6414
6415         query = createPQExpBuffer();
6416
6417         /* Make sure we are in proper schema */
6418         selectSourceSchema(fout, "pg_catalog");
6419
6420         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6421                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6422                                           "FROM pg_ts_config",
6423                                           username_subquery);
6424
6425         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6426
6427         ntups = PQntuples(res);
6428         *numTSConfigs = ntups;
6429
6430         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6431
6432         i_tableoid = PQfnumber(res, "tableoid");
6433         i_oid = PQfnumber(res, "oid");
6434         i_cfgname = PQfnumber(res, "cfgname");
6435         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6436         i_rolname = PQfnumber(res, "rolname");
6437         i_cfgparser = PQfnumber(res, "cfgparser");
6438
6439         for (i = 0; i < ntups; i++)
6440         {
6441                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6442                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6443                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6444                 AssignDumpId(&cfginfo[i].dobj);
6445                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6446                 cfginfo[i].dobj.namespace =
6447                         findNamespace(fout,
6448                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6449                                                   cfginfo[i].dobj.catId.oid);
6450                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6451                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6452
6453                 /* Decide whether we want to dump it */
6454                 selectDumpableObject(&(cfginfo[i].dobj));
6455         }
6456
6457         PQclear(res);
6458
6459         destroyPQExpBuffer(query);
6460
6461         return cfginfo;
6462 }
6463
6464 /*
6465  * getForeignDataWrappers:
6466  *        read all foreign-data wrappers in the system catalogs and return
6467  *        them in the FdwInfo* structure
6468  *
6469  *      numForeignDataWrappers is set to the number of fdws read in
6470  */
6471 FdwInfo *
6472 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6473 {
6474         PGresult   *res;
6475         int                     ntups;
6476         int                     i;
6477         PQExpBuffer query = createPQExpBuffer();
6478         FdwInfo    *fdwinfo;
6479         int                     i_tableoid;
6480         int                     i_oid;
6481         int                     i_fdwname;
6482         int                     i_rolname;
6483         int                     i_fdwhandler;
6484         int                     i_fdwvalidator;
6485         int                     i_fdwacl;
6486         int                     i_fdwoptions;
6487
6488         /* Before 8.4, there are no foreign-data wrappers */
6489         if (fout->remoteVersion < 80400)
6490         {
6491                 *numForeignDataWrappers = 0;
6492                 return NULL;
6493         }
6494
6495         /* Make sure we are in proper schema */
6496         selectSourceSchema(fout, "pg_catalog");
6497
6498         if (fout->remoteVersion >= 90100)
6499         {
6500                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6501                                                   "(%s fdwowner) AS rolname, "
6502                                                   "fdwhandler::pg_catalog.regproc, "
6503                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6504                                                   "array_to_string(ARRAY("
6505                                                   "SELECT quote_ident(option_name) || ' ' || "
6506                                                   "quote_literal(option_value) "
6507                                                   "FROM pg_options_to_table(fdwoptions) "
6508                                                   "ORDER BY option_name"
6509                                                   "), E',\n    ') AS fdwoptions "
6510                                                   "FROM pg_foreign_data_wrapper",
6511                                                   username_subquery);
6512         }
6513         else
6514         {
6515                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6516                                                   "(%s fdwowner) AS rolname, "
6517                                                   "'-' AS fdwhandler, "
6518                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6519                                                   "array_to_string(ARRAY("
6520                                                   "SELECT quote_ident(option_name) || ' ' || "
6521                                                   "quote_literal(option_value) "
6522                                                   "FROM pg_options_to_table(fdwoptions) "
6523                                                   "ORDER BY option_name"
6524                                                   "), E',\n    ') AS fdwoptions "
6525                                                   "FROM pg_foreign_data_wrapper",
6526                                                   username_subquery);
6527         }
6528
6529         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6530
6531         ntups = PQntuples(res);
6532         *numForeignDataWrappers = ntups;
6533
6534         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6535
6536         i_tableoid = PQfnumber(res, "tableoid");
6537         i_oid = PQfnumber(res, "oid");
6538         i_fdwname = PQfnumber(res, "fdwname");
6539         i_rolname = PQfnumber(res, "rolname");
6540         i_fdwhandler = PQfnumber(res, "fdwhandler");
6541         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6542         i_fdwacl = PQfnumber(res, "fdwacl");
6543         i_fdwoptions = PQfnumber(res, "fdwoptions");
6544
6545         for (i = 0; i < ntups; i++)
6546         {
6547                 fdwinfo[i].dobj.objType = DO_FDW;
6548                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6549                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6550                 AssignDumpId(&fdwinfo[i].dobj);
6551                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6552                 fdwinfo[i].dobj.namespace = NULL;
6553                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6554                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6555                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6556                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6557                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6558
6559                 /* Decide whether we want to dump it */
6560                 selectDumpableObject(&(fdwinfo[i].dobj));
6561         }
6562
6563         PQclear(res);
6564
6565         destroyPQExpBuffer(query);
6566
6567         return fdwinfo;
6568 }
6569
6570 /*
6571  * getForeignServers:
6572  *        read all foreign servers in the system catalogs and return
6573  *        them in the ForeignServerInfo * structure
6574  *
6575  *      numForeignServers is set to the number of servers read in
6576  */
6577 ForeignServerInfo *
6578 getForeignServers(Archive *fout, int *numForeignServers)
6579 {
6580         PGresult   *res;
6581         int                     ntups;
6582         int                     i;
6583         PQExpBuffer query = createPQExpBuffer();
6584         ForeignServerInfo *srvinfo;
6585         int                     i_tableoid;
6586         int                     i_oid;
6587         int                     i_srvname;
6588         int                     i_rolname;
6589         int                     i_srvfdw;
6590         int                     i_srvtype;
6591         int                     i_srvversion;
6592         int                     i_srvacl;
6593         int                     i_srvoptions;
6594
6595         /* Before 8.4, there are no foreign servers */
6596         if (fout->remoteVersion < 80400)
6597         {
6598                 *numForeignServers = 0;
6599                 return NULL;
6600         }
6601
6602         /* Make sure we are in proper schema */
6603         selectSourceSchema(fout, "pg_catalog");
6604
6605         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6606                                           "(%s srvowner) AS rolname, "
6607                                           "srvfdw, srvtype, srvversion, srvacl,"
6608                                           "array_to_string(ARRAY("
6609                                           "SELECT quote_ident(option_name) || ' ' || "
6610                                           "quote_literal(option_value) "
6611                                           "FROM pg_options_to_table(srvoptions) "
6612                                           "ORDER BY option_name"
6613                                           "), E',\n    ') AS srvoptions "
6614                                           "FROM pg_foreign_server",
6615                                           username_subquery);
6616
6617         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6618
6619         ntups = PQntuples(res);
6620         *numForeignServers = ntups;
6621
6622         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6623
6624         i_tableoid = PQfnumber(res, "tableoid");
6625         i_oid = PQfnumber(res, "oid");
6626         i_srvname = PQfnumber(res, "srvname");
6627         i_rolname = PQfnumber(res, "rolname");
6628         i_srvfdw = PQfnumber(res, "srvfdw");
6629         i_srvtype = PQfnumber(res, "srvtype");
6630         i_srvversion = PQfnumber(res, "srvversion");
6631         i_srvacl = PQfnumber(res, "srvacl");
6632         i_srvoptions = PQfnumber(res, "srvoptions");
6633
6634         for (i = 0; i < ntups; i++)
6635         {
6636                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6637                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6638                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6639                 AssignDumpId(&srvinfo[i].dobj);
6640                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6641                 srvinfo[i].dobj.namespace = NULL;
6642                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6643                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6644                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6645                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6646                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6647                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6648
6649                 /* Decide whether we want to dump it */
6650                 selectDumpableObject(&(srvinfo[i].dobj));
6651         }
6652
6653         PQclear(res);
6654
6655         destroyPQExpBuffer(query);
6656
6657         return srvinfo;
6658 }
6659
6660 /*
6661  * getDefaultACLs:
6662  *        read all default ACL information in the system catalogs and return
6663  *        them in the DefaultACLInfo structure
6664  *
6665  *      numDefaultACLs is set to the number of ACLs read in
6666  */
6667 DefaultACLInfo *
6668 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6669 {
6670         DefaultACLInfo *daclinfo;
6671         PQExpBuffer query;
6672         PGresult   *res;
6673         int                     i_oid;
6674         int                     i_tableoid;
6675         int                     i_defaclrole;
6676         int                     i_defaclnamespace;
6677         int                     i_defaclobjtype;
6678         int                     i_defaclacl;
6679         int                     i,
6680                                 ntups;
6681
6682         if (fout->remoteVersion < 90000)
6683         {
6684                 *numDefaultACLs = 0;
6685                 return NULL;
6686         }
6687
6688         query = createPQExpBuffer();
6689
6690         /* Make sure we are in proper schema */
6691         selectSourceSchema(fout, "pg_catalog");
6692
6693         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6694                                           "(%s defaclrole) AS defaclrole, "
6695                                           "defaclnamespace, "
6696                                           "defaclobjtype, "
6697                                           "defaclacl "
6698                                           "FROM pg_default_acl",
6699                                           username_subquery);
6700
6701         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6702
6703         ntups = PQntuples(res);
6704         *numDefaultACLs = ntups;
6705
6706         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6707
6708         i_oid = PQfnumber(res, "oid");
6709         i_tableoid = PQfnumber(res, "tableoid");
6710         i_defaclrole = PQfnumber(res, "defaclrole");
6711         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6712         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6713         i_defaclacl = PQfnumber(res, "defaclacl");
6714
6715         for (i = 0; i < ntups; i++)
6716         {
6717                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6718
6719                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6720                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6721                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6722                 AssignDumpId(&daclinfo[i].dobj);
6723                 /* cheesy ... is it worth coming up with a better object name? */
6724                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6725
6726                 if (nspid != InvalidOid)
6727                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6728                                                                                                  daclinfo[i].dobj.catId.oid);
6729                 else
6730                         daclinfo[i].dobj.namespace = NULL;
6731
6732                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6733                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6734                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6735
6736                 /* Decide whether we want to dump it */
6737                 selectDumpableDefaultACL(&(daclinfo[i]));
6738         }
6739
6740         PQclear(res);
6741
6742         destroyPQExpBuffer(query);
6743
6744         return daclinfo;
6745 }
6746
6747 /*
6748  * dumpComment --
6749  *
6750  * This routine is used to dump any comments associated with the
6751  * object handed to this routine. The routine takes a constant character
6752  * string for the target part of the comment-creation command, plus
6753  * the namespace and owner of the object (for labeling the ArchiveEntry),
6754  * plus catalog ID and subid which are the lookup key for pg_description,
6755  * plus the dump ID for the object (for setting a dependency).
6756  * If a matching pg_description entry is found, it is dumped.
6757  *
6758  * Note: although this routine takes a dumpId for dependency purposes,
6759  * that purpose is just to mark the dependency in the emitted dump file
6760  * for possible future use by pg_restore.  We do NOT use it for determining
6761  * ordering of the comment in the dump file, because this routine is called
6762  * after dependency sorting occurs.  This routine should be called just after
6763  * calling ArchiveEntry() for the specified object.
6764  */
6765 static void
6766 dumpComment(Archive *fout, const char *target,
6767                         const char *namespace, const char *owner,
6768                         CatalogId catalogId, int subid, DumpId dumpId)
6769 {
6770         CommentItem *comments;
6771         int                     ncomments;
6772
6773         /* Comments are schema not data ... except blob comments are data */
6774         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6775         {
6776                 if (dataOnly)
6777                         return;
6778         }
6779         else
6780         {
6781                 if (schemaOnly)
6782                         return;
6783         }
6784
6785         /* Search for comments associated with catalogId, using table */
6786         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6787                                                          &comments);
6788
6789         /* Is there one matching the subid? */
6790         while (ncomments > 0)
6791         {
6792                 if (comments->objsubid == subid)
6793                         break;
6794                 comments++;
6795                 ncomments--;
6796         }
6797
6798         /* If a comment exists, build COMMENT ON statement */
6799         if (ncomments > 0)
6800         {
6801                 PQExpBuffer query = createPQExpBuffer();
6802
6803                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6804                 appendStringLiteralAH(query, comments->descr, fout);
6805                 appendPQExpBuffer(query, ";\n");
6806
6807                 /*
6808                  * We mark comments as SECTION_NONE because they really belong in the
6809                  * same section as their parent, whether that is pre-data or
6810                  * post-data.
6811                  */
6812                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6813                                          target, namespace, NULL, owner,
6814                                          false, "COMMENT", SECTION_NONE,
6815                                          query->data, "", NULL,
6816                                          &(dumpId), 1,
6817                                          NULL, NULL);
6818
6819                 destroyPQExpBuffer(query);
6820         }
6821 }
6822
6823 /*
6824  * dumpTableComment --
6825  *
6826  * As above, but dump comments for both the specified table (or view)
6827  * and its columns.
6828  */
6829 static void
6830 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6831                                  const char *reltypename)
6832 {
6833         CommentItem *comments;
6834         int                     ncomments;
6835         PQExpBuffer query;
6836         PQExpBuffer target;
6837
6838         /* Comments are SCHEMA not data */
6839         if (dataOnly)
6840                 return;
6841
6842         /* Search for comments associated with relation, using table */
6843         ncomments = findComments(fout,
6844                                                          tbinfo->dobj.catId.tableoid,
6845                                                          tbinfo->dobj.catId.oid,
6846                                                          &comments);
6847
6848         /* If comments exist, build COMMENT ON statements */
6849         if (ncomments <= 0)
6850                 return;
6851
6852         query = createPQExpBuffer();
6853         target = createPQExpBuffer();
6854
6855         while (ncomments > 0)
6856         {
6857                 const char *descr = comments->descr;
6858                 int                     objsubid = comments->objsubid;
6859
6860                 if (objsubid == 0)
6861                 {
6862                         resetPQExpBuffer(target);
6863                         appendPQExpBuffer(target, "%s %s", reltypename,
6864                                                           fmtId(tbinfo->dobj.name));
6865
6866                         resetPQExpBuffer(query);
6867                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6868                         appendStringLiteralAH(query, descr, fout);
6869                         appendPQExpBuffer(query, ";\n");
6870
6871                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6872                                                  target->data,
6873                                                  tbinfo->dobj.namespace->dobj.name,
6874                                                  NULL, tbinfo->rolname,
6875                                                  false, "COMMENT", SECTION_NONE,
6876                                                  query->data, "", NULL,
6877                                                  &(tbinfo->dobj.dumpId), 1,
6878                                                  NULL, NULL);
6879                 }
6880                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6881                 {
6882                         resetPQExpBuffer(target);
6883                         appendPQExpBuffer(target, "COLUMN %s.",
6884                                                           fmtId(tbinfo->dobj.name));
6885                         appendPQExpBuffer(target, "%s",
6886                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6887
6888                         resetPQExpBuffer(query);
6889                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6890                         appendStringLiteralAH(query, descr, fout);
6891                         appendPQExpBuffer(query, ";\n");
6892
6893                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6894                                                  target->data,
6895                                                  tbinfo->dobj.namespace->dobj.name,
6896                                                  NULL, tbinfo->rolname,
6897                                                  false, "COMMENT", SECTION_NONE,
6898                                                  query->data, "", NULL,
6899                                                  &(tbinfo->dobj.dumpId), 1,
6900                                                  NULL, NULL);
6901                 }
6902
6903                 comments++;
6904                 ncomments--;
6905         }
6906
6907         destroyPQExpBuffer(query);
6908         destroyPQExpBuffer(target);
6909 }
6910
6911 /*
6912  * findComments --
6913  *
6914  * Find the comment(s), if any, associated with the given object.  All the
6915  * objsubid values associated with the given classoid/objoid are found with
6916  * one search.
6917  */
6918 static int
6919 findComments(Archive *fout, Oid classoid, Oid objoid,
6920                          CommentItem **items)
6921 {
6922         /* static storage for table of comments */
6923         static CommentItem *comments = NULL;
6924         static int      ncomments = -1;
6925
6926         CommentItem *middle = NULL;
6927         CommentItem *low;
6928         CommentItem *high;
6929         int                     nmatch;
6930
6931         /* Get comments if we didn't already */
6932         if (ncomments < 0)
6933                 ncomments = collectComments(fout, &comments);
6934
6935         /*
6936          * Pre-7.2, pg_description does not contain classoid, so collectComments
6937          * just stores a zero.  If there's a collision on object OID, well, you
6938          * get duplicate comments.
6939          */
6940         if (fout->remoteVersion < 70200)
6941                 classoid = 0;
6942
6943         /*
6944          * Do binary search to find some item matching the object.
6945          */
6946         low = &comments[0];
6947         high = &comments[ncomments - 1];
6948         while (low <= high)
6949         {
6950                 middle = low + (high - low) / 2;
6951
6952                 if (classoid < middle->classoid)
6953                         high = middle - 1;
6954                 else if (classoid > middle->classoid)
6955                         low = middle + 1;
6956                 else if (objoid < middle->objoid)
6957                         high = middle - 1;
6958                 else if (objoid > middle->objoid)
6959                         low = middle + 1;
6960                 else
6961                         break;                          /* found a match */
6962         }
6963
6964         if (low > high)                         /* no matches */
6965         {
6966                 *items = NULL;
6967                 return 0;
6968         }
6969
6970         /*
6971          * Now determine how many items match the object.  The search loop
6972          * invariant still holds: only items between low and high inclusive could
6973          * match.
6974          */
6975         nmatch = 1;
6976         while (middle > low)
6977         {
6978                 if (classoid != middle[-1].classoid ||
6979                         objoid != middle[-1].objoid)
6980                         break;
6981                 middle--;
6982                 nmatch++;
6983         }
6984
6985         *items = middle;
6986
6987         middle += nmatch;
6988         while (middle <= high)
6989         {
6990                 if (classoid != middle->classoid ||
6991                         objoid != middle->objoid)
6992                         break;
6993                 middle++;
6994                 nmatch++;
6995         }
6996
6997         return nmatch;
6998 }
6999
7000 /*
7001  * collectComments --
7002  *
7003  * Construct a table of all comments available for database objects.
7004  * We used to do per-object queries for the comments, but it's much faster
7005  * to pull them all over at once, and on most databases the memory cost
7006  * isn't high.
7007  *
7008  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7009  */
7010 static int
7011 collectComments(Archive *fout, CommentItem **items)
7012 {
7013         PGresult   *res;
7014         PQExpBuffer query;
7015         int                     i_description;
7016         int                     i_classoid;
7017         int                     i_objoid;
7018         int                     i_objsubid;
7019         int                     ntups;
7020         int                     i;
7021         CommentItem *comments;
7022
7023         /*
7024          * Note we do NOT change source schema here; preserve the caller's
7025          * setting, instead.
7026          */
7027
7028         query = createPQExpBuffer();
7029
7030         if (fout->remoteVersion >= 70300)
7031         {
7032                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7033                                                   "FROM pg_catalog.pg_description "
7034                                                   "ORDER BY classoid, objoid, objsubid");
7035         }
7036         else if (fout->remoteVersion >= 70200)
7037         {
7038                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7039                                                   "FROM pg_description "
7040                                                   "ORDER BY classoid, objoid, objsubid");
7041         }
7042         else
7043         {
7044                 /* Note: this will fail to find attribute comments in pre-7.2... */
7045                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7046                                                   "FROM pg_description "
7047                                                   "ORDER BY objoid");
7048         }
7049
7050         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7051
7052         /* Construct lookup table containing OIDs in numeric form */
7053
7054         i_description = PQfnumber(res, "description");
7055         i_classoid = PQfnumber(res, "classoid");
7056         i_objoid = PQfnumber(res, "objoid");
7057         i_objsubid = PQfnumber(res, "objsubid");
7058
7059         ntups = PQntuples(res);
7060
7061         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7062
7063         for (i = 0; i < ntups; i++)
7064         {
7065                 comments[i].descr = PQgetvalue(res, i, i_description);
7066                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7067                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7068                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7069         }
7070
7071         /* Do NOT free the PGresult since we are keeping pointers into it */
7072         destroyPQExpBuffer(query);
7073
7074         *items = comments;
7075         return ntups;
7076 }
7077
7078 /*
7079  * dumpDumpableObject
7080  *
7081  * This routine and its subsidiaries are responsible for creating
7082  * ArchiveEntries (TOC objects) for each object to be dumped.
7083  */
7084 static void
7085 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7086 {
7087         switch (dobj->objType)
7088         {
7089                 case DO_NAMESPACE:
7090                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7091                         break;
7092                 case DO_EXTENSION:
7093                         dumpExtension(fout, (ExtensionInfo *) dobj);
7094                         break;
7095                 case DO_TYPE:
7096                         dumpType(fout, (TypeInfo *) dobj);
7097                         break;
7098                 case DO_SHELL_TYPE:
7099                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7100                         break;
7101                 case DO_FUNC:
7102                         dumpFunc(fout, (FuncInfo *) dobj);
7103                         break;
7104                 case DO_AGG:
7105                         dumpAgg(fout, (AggInfo *) dobj);
7106                         break;
7107                 case DO_OPERATOR:
7108                         dumpOpr(fout, (OprInfo *) dobj);
7109                         break;
7110                 case DO_OPCLASS:
7111                         dumpOpclass(fout, (OpclassInfo *) dobj);
7112                         break;
7113                 case DO_OPFAMILY:
7114                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7115                         break;
7116                 case DO_COLLATION:
7117                         dumpCollation(fout, (CollInfo *) dobj);
7118                         break;
7119                 case DO_CONVERSION:
7120                         dumpConversion(fout, (ConvInfo *) dobj);
7121                         break;
7122                 case DO_TABLE:
7123                         dumpTable(fout, (TableInfo *) dobj);
7124                         break;
7125                 case DO_ATTRDEF:
7126                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7127                         break;
7128                 case DO_INDEX:
7129                         dumpIndex(fout, (IndxInfo *) dobj);
7130                         break;
7131                 case DO_RULE:
7132                         dumpRule(fout, (RuleInfo *) dobj);
7133                         break;
7134                 case DO_TRIGGER:
7135                         dumpTrigger(fout, (TriggerInfo *) dobj);
7136                         break;
7137                 case DO_CONSTRAINT:
7138                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7139                         break;
7140                 case DO_FK_CONSTRAINT:
7141                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7142                         break;
7143                 case DO_PROCLANG:
7144                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7145                         break;
7146                 case DO_CAST:
7147                         dumpCast(fout, (CastInfo *) dobj);
7148                         break;
7149                 case DO_TABLE_DATA:
7150                         dumpTableData(fout, (TableDataInfo *) dobj);
7151                         break;
7152                 case DO_DUMMY_TYPE:
7153                         /* table rowtypes and array types are never dumped separately */
7154                         break;
7155                 case DO_TSPARSER:
7156                         dumpTSParser(fout, (TSParserInfo *) dobj);
7157                         break;
7158                 case DO_TSDICT:
7159                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7160                         break;
7161                 case DO_TSTEMPLATE:
7162                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7163                         break;
7164                 case DO_TSCONFIG:
7165                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7166                         break;
7167                 case DO_FDW:
7168                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7169                         break;
7170                 case DO_FOREIGN_SERVER:
7171                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7172                         break;
7173                 case DO_DEFAULT_ACL:
7174                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7175                         break;
7176                 case DO_BLOB:
7177                         dumpBlob(fout, (BlobInfo *) dobj);
7178                         break;
7179                 case DO_BLOB_DATA:
7180                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7181                                                  dobj->name, NULL, NULL, "",
7182                                                  false, "BLOBS", SECTION_DATA,
7183                                                  "", "", NULL,
7184                                                  dobj->dependencies, dobj->nDeps,
7185                                                  dumpBlobs, NULL);
7186                         break;
7187         }
7188 }
7189
7190 /*
7191  * dumpNamespace
7192  *        writes out to fout the queries to recreate a user-defined namespace
7193  */
7194 static void
7195 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7196 {
7197         PQExpBuffer q;
7198         PQExpBuffer delq;
7199         PQExpBuffer labelq;
7200         char       *qnspname;
7201
7202         /* Skip if not to be dumped */
7203         if (!nspinfo->dobj.dump || dataOnly)
7204                 return;
7205
7206         /* don't dump dummy namespace from pre-7.3 source */
7207         if (strlen(nspinfo->dobj.name) == 0)
7208                 return;
7209
7210         q = createPQExpBuffer();
7211         delq = createPQExpBuffer();
7212         labelq = createPQExpBuffer();
7213
7214         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7215
7216         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7217
7218         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7219
7220         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7221
7222         if (binary_upgrade)
7223                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7224
7225         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7226                                  nspinfo->dobj.name,
7227                                  NULL, NULL,
7228                                  nspinfo->rolname,
7229                                  false, "SCHEMA", SECTION_PRE_DATA,
7230                                  q->data, delq->data, NULL,
7231                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7232                                  NULL, NULL);
7233
7234         /* Dump Schema Comments and Security Labels */
7235         dumpComment(fout, labelq->data,
7236                                 NULL, nspinfo->rolname,
7237                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7238         dumpSecLabel(fout, labelq->data,
7239                                  NULL, nspinfo->rolname,
7240                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7241
7242         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7243                         qnspname, NULL, nspinfo->dobj.name, NULL,
7244                         nspinfo->rolname, nspinfo->nspacl);
7245
7246         free(qnspname);
7247
7248         destroyPQExpBuffer(q);
7249         destroyPQExpBuffer(delq);
7250         destroyPQExpBuffer(labelq);
7251 }
7252
7253 /*
7254  * dumpExtension
7255  *        writes out to fout the queries to recreate an extension
7256  */
7257 static void
7258 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7259 {
7260         PQExpBuffer q;
7261         PQExpBuffer delq;
7262         PQExpBuffer labelq;
7263         char       *qextname;
7264
7265         /* Skip if not to be dumped */
7266         if (!extinfo->dobj.dump || dataOnly)
7267                 return;
7268
7269         q = createPQExpBuffer();
7270         delq = createPQExpBuffer();
7271         labelq = createPQExpBuffer();
7272
7273         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7274
7275         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7276
7277         if (!binary_upgrade)
7278         {
7279                 /*
7280                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7281                  * problem if the extension already exists in the target database;
7282                  * this is essential for installed-by-default extensions such as
7283                  * plpgsql.
7284                  *
7285                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7286                  * built-in extensions based on their OIDs; see
7287                  * selectDumpableExtension.
7288                  */
7289                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7290                                                   qextname, fmtId(extinfo->namespace));
7291         }
7292         else
7293         {
7294                 int                     i;
7295                 int                     n;
7296
7297                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7298                 appendPQExpBuffer(q,
7299                                                   "SELECT binary_upgrade.create_empty_extension(");
7300                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7301                 appendPQExpBuffer(q, ", ");
7302                 appendStringLiteralAH(q, extinfo->namespace, fout);
7303                 appendPQExpBuffer(q, ", ");
7304                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7305                 appendStringLiteralAH(q, extinfo->extversion, fout);
7306                 appendPQExpBuffer(q, ", ");
7307
7308                 /*
7309                  * Note that we're pushing extconfig (an OID array) back into
7310                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7311                  * preserved in binary upgrade.
7312                  */
7313                 if (strlen(extinfo->extconfig) > 2)
7314                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7315                 else
7316                         appendPQExpBuffer(q, "NULL");
7317                 appendPQExpBuffer(q, ", ");
7318                 if (strlen(extinfo->extcondition) > 2)
7319                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7320                 else
7321                         appendPQExpBuffer(q, "NULL");
7322                 appendPQExpBuffer(q, ", ");
7323                 appendPQExpBuffer(q, "ARRAY[");
7324                 n = 0;
7325                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7326                 {
7327                         DumpableObject *extobj;
7328
7329                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7330                         if (extobj && extobj->objType == DO_EXTENSION)
7331                         {
7332                                 if (n++ > 0)
7333                                         appendPQExpBuffer(q, ",");
7334                                 appendStringLiteralAH(q, extobj->name, fout);
7335                         }
7336                 }
7337                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7338                 appendPQExpBuffer(q, ");\n");
7339         }
7340
7341         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7342
7343         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7344                                  extinfo->dobj.name,
7345                                  NULL, NULL,
7346                                  "",
7347                                  false, "EXTENSION", SECTION_PRE_DATA,
7348                                  q->data, delq->data, NULL,
7349                                  extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7350                                  NULL, NULL);
7351
7352         /* Dump Extension Comments and Security Labels */
7353         dumpComment(fout, labelq->data,
7354                                 NULL, "",
7355                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7356         dumpSecLabel(fout, labelq->data,
7357                                  NULL, "",
7358                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7359
7360         free(qextname);
7361
7362         destroyPQExpBuffer(q);
7363         destroyPQExpBuffer(delq);
7364         destroyPQExpBuffer(labelq);
7365 }
7366
7367 /*
7368  * dumpType
7369  *        writes out to fout the queries to recreate a user-defined type
7370  */
7371 static void
7372 dumpType(Archive *fout, TypeInfo *tyinfo)
7373 {
7374         /* Skip if not to be dumped */
7375         if (!tyinfo->dobj.dump || dataOnly)
7376                 return;
7377
7378         /* Dump out in proper style */
7379         if (tyinfo->typtype == TYPTYPE_BASE)
7380                 dumpBaseType(fout, tyinfo);
7381         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7382                 dumpDomain(fout, tyinfo);
7383         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7384                 dumpCompositeType(fout, tyinfo);
7385         else if (tyinfo->typtype == TYPTYPE_ENUM)
7386                 dumpEnumType(fout, tyinfo);
7387         else if (tyinfo->typtype == TYPTYPE_RANGE)
7388                 dumpRangeType(fout, tyinfo);
7389         else
7390                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7391                                   tyinfo->dobj.name);
7392 }
7393
7394 /*
7395  * dumpEnumType
7396  *        writes out to fout the queries to recreate a user-defined enum type
7397  */
7398 static void
7399 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7400 {
7401         PQExpBuffer q = createPQExpBuffer();
7402         PQExpBuffer delq = createPQExpBuffer();
7403         PQExpBuffer labelq = createPQExpBuffer();
7404         PQExpBuffer query = createPQExpBuffer();
7405         PGresult   *res;
7406         int                     num,
7407                                 i;
7408         Oid                     enum_oid;
7409         char       *label;
7410
7411         /* Set proper schema search path */
7412         selectSourceSchema(fout, "pg_catalog");
7413
7414         if (fout->remoteVersion >= 90100)
7415                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7416                                                   "FROM pg_catalog.pg_enum "
7417                                                   "WHERE enumtypid = '%u'"
7418                                                   "ORDER BY enumsortorder",
7419                                                   tyinfo->dobj.catId.oid);
7420         else
7421                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7422                                                   "FROM pg_catalog.pg_enum "
7423                                                   "WHERE enumtypid = '%u'"
7424                                                   "ORDER BY oid",
7425                                                   tyinfo->dobj.catId.oid);
7426
7427         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7428
7429         num = PQntuples(res);
7430
7431         /*
7432          * DROP must be fully qualified in case same name appears in pg_catalog.
7433          * CASCADE shouldn't be required here as for normal types since the I/O
7434          * functions are generic and do not get dropped.
7435          */
7436         appendPQExpBuffer(delq, "DROP TYPE %s.",
7437                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7438         appendPQExpBuffer(delq, "%s;\n",
7439                                           fmtId(tyinfo->dobj.name));
7440
7441         if (binary_upgrade)
7442                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7443                                                                                                  tyinfo->dobj.catId.oid);
7444
7445         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7446                                           fmtId(tyinfo->dobj.name));
7447
7448         if (!binary_upgrade)
7449         {
7450                 /* Labels with server-assigned oids */
7451                 for (i = 0; i < num; i++)
7452                 {
7453                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7454                         if (i > 0)
7455                                 appendPQExpBuffer(q, ",");
7456                         appendPQExpBuffer(q, "\n    ");
7457                         appendStringLiteralAH(q, label, fout);
7458                 }
7459         }
7460
7461         appendPQExpBuffer(q, "\n);\n");
7462
7463         if (binary_upgrade)
7464         {
7465                 /* Labels with dump-assigned (preserved) oids */
7466                 for (i = 0; i < num; i++)
7467                 {
7468                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7469                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7470
7471                         if (i == 0)
7472                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7473                         appendPQExpBuffer(q,
7474                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7475                                                           enum_oid);
7476                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7477                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7478                         appendPQExpBuffer(q, "%s ADD VALUE ",
7479                                                           fmtId(tyinfo->dobj.name));
7480                         appendStringLiteralAH(q, label, fout);
7481                         appendPQExpBuffer(q, ";\n\n");
7482                 }
7483         }
7484
7485         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7486
7487         if (binary_upgrade)
7488                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7489
7490         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7491                                  tyinfo->dobj.name,
7492                                  tyinfo->dobj.namespace->dobj.name,
7493                                  NULL,
7494                                  tyinfo->rolname, false,
7495                                  "TYPE", SECTION_PRE_DATA,
7496                                  q->data, delq->data, NULL,
7497                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7498                                  NULL, NULL);
7499
7500         /* Dump Type Comments and Security Labels */
7501         dumpComment(fout, labelq->data,
7502                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7503                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7504         dumpSecLabel(fout, labelq->data,
7505                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7506                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7507
7508         PQclear(res);
7509         destroyPQExpBuffer(q);
7510         destroyPQExpBuffer(delq);
7511         destroyPQExpBuffer(labelq);
7512         destroyPQExpBuffer(query);
7513 }
7514
7515 /*
7516  * dumpRangeType
7517  *        writes out to fout the queries to recreate a user-defined range type
7518  */
7519 static void
7520 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7521 {
7522         PQExpBuffer q = createPQExpBuffer();
7523         PQExpBuffer delq = createPQExpBuffer();
7524         PQExpBuffer labelq = createPQExpBuffer();
7525         PQExpBuffer query = createPQExpBuffer();
7526         PGresult   *res;
7527         Oid                     collationOid;
7528         char       *procname;
7529
7530         /*
7531          * select appropriate schema to ensure names in CREATE are properly
7532          * qualified
7533          */
7534         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7535
7536         appendPQExpBuffer(query,
7537                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7538                                           "opc.opcname AS opcname, "
7539                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7540                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7541                                           "opc.opcdefault, "
7542                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7543                                           "     ELSE rngcollation END AS collation, "
7544                                           "rngcanonical, rngsubdiff "
7545                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7546                                           "     pg_catalog.pg_opclass opc "
7547                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7548                                           "rngtypid = '%u'",
7549                                           tyinfo->dobj.catId.oid);
7550
7551         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7552
7553         /*
7554          * DROP must be fully qualified in case same name appears in pg_catalog.
7555          * CASCADE shouldn't be required here as for normal types since the I/O
7556          * functions are generic and do not get dropped.
7557          */
7558         appendPQExpBuffer(delq, "DROP TYPE %s.",
7559                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7560         appendPQExpBuffer(delq, "%s;\n",
7561                                           fmtId(tyinfo->dobj.name));
7562
7563         if (binary_upgrade)
7564                 binary_upgrade_set_type_oids_by_type_oid(fout,
7565                                                                                                  q, tyinfo->dobj.catId.oid);
7566
7567         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7568                                           fmtId(tyinfo->dobj.name));
7569
7570         appendPQExpBuffer(q, "\n    subtype = %s",
7571                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7572
7573         /* print subtype_opclass only if not default for subtype */
7574         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7575         {
7576                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7577                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7578
7579                 /* always schema-qualify, don't try to be smart */
7580                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7581                                                   fmtId(nspname));
7582                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7583         }
7584
7585         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7586         if (OidIsValid(collationOid))
7587         {
7588                 CollInfo   *coll = findCollationByOid(collationOid);
7589
7590                 if (coll)
7591                 {
7592                         /* always schema-qualify, don't try to be smart */
7593                         appendPQExpBuffer(q, ",\n    collation = %s.",
7594                                                           fmtId(coll->dobj.namespace->dobj.name));
7595                         appendPQExpBuffer(q, "%s",
7596                                                           fmtId(coll->dobj.name));
7597                 }
7598         }
7599
7600         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7601         if (strcmp(procname, "-") != 0)
7602                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7603
7604         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7605         if (strcmp(procname, "-") != 0)
7606                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7607
7608         appendPQExpBuffer(q, "\n);\n");
7609
7610         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7611
7612         if (binary_upgrade)
7613                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7614
7615         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7616                                  tyinfo->dobj.name,
7617                                  tyinfo->dobj.namespace->dobj.name,
7618                                  NULL,
7619                                  tyinfo->rolname, false,
7620                                  "TYPE", SECTION_PRE_DATA,
7621                                  q->data, delq->data, NULL,
7622                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7623                                  NULL, NULL);
7624
7625         /* Dump Type Comments and Security Labels */
7626         dumpComment(fout, labelq->data,
7627                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7628                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7629         dumpSecLabel(fout, labelq->data,
7630                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7631                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7632
7633         PQclear(res);
7634         destroyPQExpBuffer(q);
7635         destroyPQExpBuffer(delq);
7636         destroyPQExpBuffer(labelq);
7637         destroyPQExpBuffer(query);
7638 }
7639
7640 /*
7641  * dumpBaseType
7642  *        writes out to fout the queries to recreate a user-defined base type
7643  */
7644 static void
7645 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7646 {
7647         PQExpBuffer q = createPQExpBuffer();
7648         PQExpBuffer delq = createPQExpBuffer();
7649         PQExpBuffer labelq = createPQExpBuffer();
7650         PQExpBuffer query = createPQExpBuffer();
7651         PGresult   *res;
7652         char       *typlen;
7653         char       *typinput;
7654         char       *typoutput;
7655         char       *typreceive;
7656         char       *typsend;
7657         char       *typmodin;
7658         char       *typmodout;
7659         char       *typanalyze;
7660         Oid                     typreceiveoid;
7661         Oid                     typsendoid;
7662         Oid                     typmodinoid;
7663         Oid                     typmodoutoid;
7664         Oid                     typanalyzeoid;
7665         char       *typcategory;
7666         char       *typispreferred;
7667         char       *typdelim;
7668         char       *typbyval;
7669         char       *typalign;
7670         char       *typstorage;
7671         char       *typcollatable;
7672         char       *typdefault;
7673         bool            typdefault_is_literal = false;
7674
7675         /* Set proper schema search path so regproc references list correctly */
7676         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7677
7678         /* Fetch type-specific details */
7679         if (fout->remoteVersion >= 90100)
7680         {
7681                 appendPQExpBuffer(query, "SELECT typlen, "
7682                                                   "typinput, typoutput, typreceive, typsend, "
7683                                                   "typmodin, typmodout, typanalyze, "
7684                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7685                                                   "typsend::pg_catalog.oid AS typsendoid, "
7686                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7687                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7688                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7689                                                   "typcategory, typispreferred, "
7690                                                   "typdelim, typbyval, typalign, typstorage, "
7691                                                   "(typcollation <> 0) AS typcollatable, "
7692                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7693                                                   "FROM pg_catalog.pg_type "
7694                                                   "WHERE oid = '%u'::pg_catalog.oid",
7695                                                   tyinfo->dobj.catId.oid);
7696         }
7697         else if (fout->remoteVersion >= 80400)
7698         {
7699                 appendPQExpBuffer(query, "SELECT typlen, "
7700                                                   "typinput, typoutput, typreceive, typsend, "
7701                                                   "typmodin, typmodout, typanalyze, "
7702                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7703                                                   "typsend::pg_catalog.oid AS typsendoid, "
7704                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7705                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7706                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7707                                                   "typcategory, typispreferred, "
7708                                                   "typdelim, typbyval, typalign, typstorage, "
7709                                                   "false AS typcollatable, "
7710                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7711                                                   "FROM pg_catalog.pg_type "
7712                                                   "WHERE oid = '%u'::pg_catalog.oid",
7713                                                   tyinfo->dobj.catId.oid);
7714         }
7715         else if (fout->remoteVersion >= 80300)
7716         {
7717                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7718                 appendPQExpBuffer(query, "SELECT typlen, "
7719                                                   "typinput, typoutput, typreceive, typsend, "
7720                                                   "typmodin, typmodout, typanalyze, "
7721                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7722                                                   "typsend::pg_catalog.oid AS typsendoid, "
7723                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7724                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7725                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7726                                                   "'U' AS typcategory, false AS typispreferred, "
7727                                                   "typdelim, typbyval, typalign, typstorage, "
7728                                                   "false AS typcollatable, "
7729                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7730                                                   "FROM pg_catalog.pg_type "
7731                                                   "WHERE oid = '%u'::pg_catalog.oid",
7732                                                   tyinfo->dobj.catId.oid);
7733         }
7734         else if (fout->remoteVersion >= 80000)
7735         {
7736                 appendPQExpBuffer(query, "SELECT typlen, "
7737                                                   "typinput, typoutput, typreceive, typsend, "
7738                                                   "'-' AS typmodin, '-' AS typmodout, "
7739                                                   "typanalyze, "
7740                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7741                                                   "typsend::pg_catalog.oid AS typsendoid, "
7742                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7743                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7744                                                   "'U' AS typcategory, false AS typispreferred, "
7745                                                   "typdelim, typbyval, typalign, typstorage, "
7746                                                   "false AS typcollatable, "
7747                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7748                                                   "FROM pg_catalog.pg_type "
7749                                                   "WHERE oid = '%u'::pg_catalog.oid",
7750                                                   tyinfo->dobj.catId.oid);
7751         }
7752         else if (fout->remoteVersion >= 70400)
7753         {
7754                 appendPQExpBuffer(query, "SELECT typlen, "
7755                                                   "typinput, typoutput, typreceive, typsend, "
7756                                                   "'-' AS typmodin, '-' AS typmodout, "
7757                                                   "'-' AS typanalyze, "
7758                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7759                                                   "typsend::pg_catalog.oid AS typsendoid, "
7760                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7761                                                   "0 AS typanalyzeoid, "
7762                                                   "'U' AS typcategory, false AS typispreferred, "
7763                                                   "typdelim, typbyval, typalign, typstorage, "
7764                                                   "false AS typcollatable, "
7765                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7766                                                   "FROM pg_catalog.pg_type "
7767                                                   "WHERE oid = '%u'::pg_catalog.oid",
7768                                                   tyinfo->dobj.catId.oid);
7769         }
7770         else if (fout->remoteVersion >= 70300)
7771         {
7772                 appendPQExpBuffer(query, "SELECT typlen, "
7773                                                   "typinput, typoutput, "
7774                                                   "'-' AS typreceive, '-' AS typsend, "
7775                                                   "'-' AS typmodin, '-' AS typmodout, "
7776                                                   "'-' AS typanalyze, "
7777                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7778                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7779                                                   "0 AS typanalyzeoid, "
7780                                                   "'U' AS typcategory, false AS typispreferred, "
7781                                                   "typdelim, typbyval, typalign, typstorage, "
7782                                                   "false AS typcollatable, "
7783                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7784                                                   "FROM pg_catalog.pg_type "
7785                                                   "WHERE oid = '%u'::pg_catalog.oid",
7786                                                   tyinfo->dobj.catId.oid);
7787         }
7788         else if (fout->remoteVersion >= 70200)
7789         {
7790                 /*
7791                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7792                  * ignore them because they are not right.
7793                  */
7794                 appendPQExpBuffer(query, "SELECT typlen, "
7795                                                   "typinput, typoutput, "
7796                                                   "'-' AS typreceive, '-' AS typsend, "
7797                                                   "'-' AS typmodin, '-' AS typmodout, "
7798                                                   "'-' AS typanalyze, "
7799                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7800                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7801                                                   "0 AS typanalyzeoid, "
7802                                                   "'U' AS typcategory, false AS typispreferred, "
7803                                                   "typdelim, typbyval, typalign, typstorage, "
7804                                                   "false AS typcollatable, "
7805                                                   "NULL AS typdefaultbin, typdefault "
7806                                                   "FROM pg_type "
7807                                                   "WHERE oid = '%u'::oid",
7808                                                   tyinfo->dobj.catId.oid);
7809         }
7810         else if (fout->remoteVersion >= 70100)
7811         {
7812                 /*
7813                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7814                  * representation.
7815                  */
7816                 appendPQExpBuffer(query, "SELECT typlen, "
7817                                                   "typinput, typoutput, "
7818                                                   "'-' AS typreceive, '-' AS typsend, "
7819                                                   "'-' AS typmodin, '-' AS typmodout, "
7820                                                   "'-' AS typanalyze, "
7821                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7822                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7823                                                   "0 AS typanalyzeoid, "
7824                                                   "'U' AS typcategory, false AS typispreferred, "
7825                                                   "typdelim, typbyval, typalign, typstorage, "
7826                                                   "false AS typcollatable, "
7827                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7828                                                   "FROM pg_type "
7829                                                   "WHERE oid = '%u'::oid",
7830                                                   tyinfo->dobj.catId.oid);
7831         }
7832         else
7833         {
7834                 appendPQExpBuffer(query, "SELECT typlen, "
7835                                                   "typinput, typoutput, "
7836                                                   "'-' AS typreceive, '-' AS typsend, "
7837                                                   "'-' AS typmodin, '-' AS typmodout, "
7838                                                   "'-' AS typanalyze, "
7839                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7840                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7841                                                   "0 AS typanalyzeoid, "
7842                                                   "'U' AS typcategory, false AS typispreferred, "
7843                                                   "typdelim, typbyval, typalign, "
7844                                                   "'p'::char AS typstorage, "
7845                                                   "false AS typcollatable, "
7846                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7847                                                   "FROM pg_type "
7848                                                   "WHERE oid = '%u'::oid",
7849                                                   tyinfo->dobj.catId.oid);
7850         }
7851
7852         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7853
7854         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7855         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7856         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7857         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7858         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7859         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7860         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7861         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7862         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7863         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7864         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7865         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7866         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7867         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7868         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7869         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7870         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7871         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7872         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7873         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7874         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7875                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7876         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7877         {
7878                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7879                 typdefault_is_literal = true;   /* it needs quotes */
7880         }
7881         else
7882                 typdefault = NULL;
7883
7884         /*
7885          * DROP must be fully qualified in case same name appears in pg_catalog.
7886          * The reason we include CASCADE is that the circular dependency between
7887          * the type and its I/O functions makes it impossible to drop the type any
7888          * other way.
7889          */
7890         appendPQExpBuffer(delq, "DROP TYPE %s.",
7891                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7892         appendPQExpBuffer(delq, "%s CASCADE;\n",
7893                                           fmtId(tyinfo->dobj.name));
7894
7895         /* We might already have a shell type, but setting pg_type_oid is harmless */
7896         if (binary_upgrade)
7897                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7898                                                                                                  tyinfo->dobj.catId.oid);
7899
7900         appendPQExpBuffer(q,
7901                                           "CREATE TYPE %s (\n"
7902                                           "    INTERNALLENGTH = %s",
7903                                           fmtId(tyinfo->dobj.name),
7904                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7905
7906         if (fout->remoteVersion >= 70300)
7907         {
7908                 /* regproc result is correctly quoted as of 7.3 */
7909                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
7910                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
7911                 if (OidIsValid(typreceiveoid))
7912                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
7913                 if (OidIsValid(typsendoid))
7914                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
7915                 if (OidIsValid(typmodinoid))
7916                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
7917                 if (OidIsValid(typmodoutoid))
7918                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
7919                 if (OidIsValid(typanalyzeoid))
7920                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
7921         }
7922         else
7923         {
7924                 /* regproc delivers an unquoted name before 7.3 */
7925                 /* cannot combine these because fmtId uses static result area */
7926                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
7927                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7928                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7929         }
7930
7931         if (strcmp(typcollatable, "t") == 0)
7932                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
7933
7934         if (typdefault != NULL)
7935         {
7936                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7937                 if (typdefault_is_literal)
7938                         appendStringLiteralAH(q, typdefault, fout);
7939                 else
7940                         appendPQExpBufferStr(q, typdefault);
7941         }
7942
7943         if (OidIsValid(tyinfo->typelem))
7944         {
7945                 char       *elemType;
7946
7947                 /* reselect schema in case changed by function dump */
7948                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7949                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7950                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
7951                 free(elemType);
7952         }
7953
7954         if (strcmp(typcategory, "U") != 0)
7955         {
7956                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
7957                 appendStringLiteralAH(q, typcategory, fout);
7958         }
7959
7960         if (strcmp(typispreferred, "t") == 0)
7961                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
7962
7963         if (typdelim && strcmp(typdelim, ",") != 0)
7964         {
7965                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
7966                 appendStringLiteralAH(q, typdelim, fout);
7967         }
7968
7969         if (strcmp(typalign, "c") == 0)
7970                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
7971         else if (strcmp(typalign, "s") == 0)
7972                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
7973         else if (strcmp(typalign, "i") == 0)
7974                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
7975         else if (strcmp(typalign, "d") == 0)
7976                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
7977
7978         if (strcmp(typstorage, "p") == 0)
7979                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
7980         else if (strcmp(typstorage, "e") == 0)
7981                 appendPQExpBuffer(q, ",\n    STORAGE = external");
7982         else if (strcmp(typstorage, "x") == 0)
7983                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
7984         else if (strcmp(typstorage, "m") == 0)
7985                 appendPQExpBuffer(q, ",\n    STORAGE = main");
7986
7987         if (strcmp(typbyval, "t") == 0)
7988                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
7989
7990         appendPQExpBuffer(q, "\n);\n");
7991
7992         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7993
7994         if (binary_upgrade)
7995                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7996
7997         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7998                                  tyinfo->dobj.name,
7999                                  tyinfo->dobj.namespace->dobj.name,
8000                                  NULL,
8001                                  tyinfo->rolname, false,
8002                                  "TYPE", SECTION_PRE_DATA,
8003                                  q->data, delq->data, NULL,
8004                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8005                                  NULL, NULL);
8006
8007         /* Dump Type Comments and Security Labels */
8008         dumpComment(fout, labelq->data,
8009                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8010                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8011         dumpSecLabel(fout, labelq->data,
8012                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8013                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8014
8015         PQclear(res);
8016         destroyPQExpBuffer(q);
8017         destroyPQExpBuffer(delq);
8018         destroyPQExpBuffer(labelq);
8019         destroyPQExpBuffer(query);
8020 }
8021
8022 /*
8023  * dumpDomain
8024  *        writes out to fout the queries to recreate a user-defined domain
8025  */
8026 static void
8027 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8028 {
8029         PQExpBuffer q = createPQExpBuffer();
8030         PQExpBuffer delq = createPQExpBuffer();
8031         PQExpBuffer labelq = createPQExpBuffer();
8032         PQExpBuffer query = createPQExpBuffer();
8033         PGresult   *res;
8034         int                     i;
8035         char       *typnotnull;
8036         char       *typdefn;
8037         char       *typdefault;
8038         Oid                     typcollation;
8039         bool            typdefault_is_literal = false;
8040
8041         /* Set proper schema search path so type references list correctly */
8042         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8043
8044         /* Fetch domain specific details */
8045         if (fout->remoteVersion >= 90100)
8046         {
8047                 /* typcollation is new in 9.1 */
8048                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8049                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8050                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8051                                                   "t.typdefault, "
8052                                                   "CASE WHEN t.typcollation <> u.typcollation "
8053                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8054                                                   "FROM pg_catalog.pg_type t "
8055                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8056                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8057                                                   tyinfo->dobj.catId.oid);
8058         }
8059         else
8060         {
8061                 /* We assume here that remoteVersion must be at least 70300 */
8062                 appendPQExpBuffer(query, "SELECT typnotnull, "
8063                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8064                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8065                                                   "typdefault, 0 AS typcollation "
8066                                                   "FROM pg_catalog.pg_type "
8067                                                   "WHERE oid = '%u'::pg_catalog.oid",
8068                                                   tyinfo->dobj.catId.oid);
8069         }
8070
8071         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8072
8073         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8074         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8075         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8076                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8077         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8078         {
8079                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8080                 typdefault_is_literal = true;   /* it needs quotes */
8081         }
8082         else
8083                 typdefault = NULL;
8084         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8085
8086         if (binary_upgrade)
8087                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8088                                                                                                  tyinfo->dobj.catId.oid);
8089
8090         appendPQExpBuffer(q,
8091                                           "CREATE DOMAIN %s AS %s",
8092                                           fmtId(tyinfo->dobj.name),
8093                                           typdefn);
8094
8095         /* Print collation only if different from base type's collation */
8096         if (OidIsValid(typcollation))
8097         {
8098                 CollInfo   *coll;
8099
8100                 coll = findCollationByOid(typcollation);
8101                 if (coll)
8102                 {
8103                         /* always schema-qualify, don't try to be smart */
8104                         appendPQExpBuffer(q, " COLLATE %s.",
8105                                                           fmtId(coll->dobj.namespace->dobj.name));
8106                         appendPQExpBuffer(q, "%s",
8107                                                           fmtId(coll->dobj.name));
8108                 }
8109         }
8110
8111         if (typnotnull[0] == 't')
8112                 appendPQExpBuffer(q, " NOT NULL");
8113
8114         if (typdefault != NULL)
8115         {
8116                 appendPQExpBuffer(q, " DEFAULT ");
8117                 if (typdefault_is_literal)
8118                         appendStringLiteralAH(q, typdefault, fout);
8119                 else
8120                         appendPQExpBufferStr(q, typdefault);
8121         }
8122
8123         PQclear(res);
8124
8125         /*
8126          * Add any CHECK constraints for the domain
8127          */
8128         for (i = 0; i < tyinfo->nDomChecks; i++)
8129         {
8130                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8131
8132                 if (!domcheck->separate)
8133                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8134                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8135         }
8136
8137         appendPQExpBuffer(q, ";\n");
8138
8139         /*
8140          * DROP must be fully qualified in case same name appears in pg_catalog
8141          */
8142         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8143                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8144         appendPQExpBuffer(delq, "%s;\n",
8145                                           fmtId(tyinfo->dobj.name));
8146
8147         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8148
8149         if (binary_upgrade)
8150                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8151
8152         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8153                                  tyinfo->dobj.name,
8154                                  tyinfo->dobj.namespace->dobj.name,
8155                                  NULL,
8156                                  tyinfo->rolname, false,
8157                                  "DOMAIN", SECTION_PRE_DATA,
8158                                  q->data, delq->data, NULL,
8159                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8160                                  NULL, NULL);
8161
8162         /* Dump Domain Comments and Security Labels */
8163         dumpComment(fout, labelq->data,
8164                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8165                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8166         dumpSecLabel(fout, labelq->data,
8167                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8168                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8169
8170         destroyPQExpBuffer(q);
8171         destroyPQExpBuffer(delq);
8172         destroyPQExpBuffer(labelq);
8173         destroyPQExpBuffer(query);
8174 }
8175
8176 /*
8177  * dumpCompositeType
8178  *        writes out to fout the queries to recreate a user-defined stand-alone
8179  *        composite type
8180  */
8181 static void
8182 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8183 {
8184         PQExpBuffer q = createPQExpBuffer();
8185         PQExpBuffer dropped = createPQExpBuffer();
8186         PQExpBuffer delq = createPQExpBuffer();
8187         PQExpBuffer labelq = createPQExpBuffer();
8188         PQExpBuffer query = createPQExpBuffer();
8189         PGresult   *res;
8190         int                     ntups;
8191         int                     i_attname;
8192         int                     i_atttypdefn;
8193         int                     i_attlen;
8194         int                     i_attalign;
8195         int                     i_attisdropped;
8196         int                     i_attcollation;
8197         int                     i_typrelid;
8198         int                     i;
8199         int                     actual_atts;
8200
8201         /* Set proper schema search path so type references list correctly */
8202         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8203
8204         /* Fetch type specific details */
8205         if (fout->remoteVersion >= 90100)
8206         {
8207                 /*
8208                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8209                  * clauses for attributes whose collation is different from their
8210                  * type's default, we use a CASE here to suppress uninteresting
8211                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8212                  * collation does not matter for those.
8213                  */
8214                 appendPQExpBuffer(query, "SELECT a.attname, "
8215                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8216                                                   "a.attlen, a.attalign, a.attisdropped, "
8217                                                   "CASE WHEN a.attcollation <> at.typcollation "
8218                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8219                                                   "ct.typrelid "
8220                                                   "FROM pg_catalog.pg_type ct "
8221                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8222                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8223                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8224                                                   "ORDER BY a.attnum ",
8225                                                   tyinfo->dobj.catId.oid);
8226         }
8227         else
8228         {
8229                 /*
8230                  * We assume here that remoteVersion must be at least 70300.  Since
8231                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8232                  * always be false.
8233                  */
8234                 appendPQExpBuffer(query, "SELECT a.attname, "
8235                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8236                                                   "a.attlen, a.attalign, a.attisdropped, "
8237                                                   "0 AS attcollation, "
8238                                                   "ct.typrelid "
8239                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8240                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8241                                                   "AND a.attrelid = ct.typrelid "
8242                                                   "ORDER BY a.attnum ",
8243                                                   tyinfo->dobj.catId.oid);
8244         }
8245
8246         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8247
8248         ntups = PQntuples(res);
8249
8250         i_attname = PQfnumber(res, "attname");
8251         i_atttypdefn = PQfnumber(res, "atttypdefn");
8252         i_attlen = PQfnumber(res, "attlen");
8253         i_attalign = PQfnumber(res, "attalign");
8254         i_attisdropped = PQfnumber(res, "attisdropped");
8255         i_attcollation = PQfnumber(res, "attcollation");
8256         i_typrelid = PQfnumber(res, "typrelid");
8257
8258         if (binary_upgrade)
8259         {
8260                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8261
8262                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8263                                                                                                  tyinfo->dobj.catId.oid);
8264                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8265         }
8266
8267         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8268                                           fmtId(tyinfo->dobj.name));
8269
8270         actual_atts = 0;
8271         for (i = 0; i < ntups; i++)
8272         {
8273                 char       *attname;
8274                 char       *atttypdefn;
8275                 char       *attlen;
8276                 char       *attalign;
8277                 bool            attisdropped;
8278                 Oid                     attcollation;
8279
8280                 attname = PQgetvalue(res, i, i_attname);
8281                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8282                 attlen = PQgetvalue(res, i, i_attlen);
8283                 attalign = PQgetvalue(res, i, i_attalign);
8284                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8285                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8286
8287                 if (attisdropped && !binary_upgrade)
8288                         continue;
8289
8290                 /* Format properly if not first attr */
8291                 if (actual_atts++ > 0)
8292                         appendPQExpBuffer(q, ",");
8293                 appendPQExpBuffer(q, "\n\t");
8294
8295                 if (!attisdropped)
8296                 {
8297                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8298
8299                         /* Add collation if not default for the column type */
8300                         if (OidIsValid(attcollation))
8301                         {
8302                                 CollInfo   *coll;
8303
8304                                 coll = findCollationByOid(attcollation);
8305                                 if (coll)
8306                                 {
8307                                         /* always schema-qualify, don't try to be smart */
8308                                         appendPQExpBuffer(q, " COLLATE %s.",
8309                                                                           fmtId(coll->dobj.namespace->dobj.name));
8310                                         appendPQExpBuffer(q, "%s",
8311                                                                           fmtId(coll->dobj.name));
8312                                 }
8313                         }
8314                 }
8315                 else
8316                 {
8317                         /*
8318                          * This is a dropped attribute and we're in binary_upgrade mode.
8319                          * Insert a placeholder for it in the CREATE TYPE command, and set
8320                          * length and alignment with direct UPDATE to the catalogs
8321                          * afterwards. See similar code in dumpTableSchema().
8322                          */
8323                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8324
8325                         /* stash separately for insertion after the CREATE TYPE */
8326                         appendPQExpBuffer(dropped,
8327                                           "\n-- For binary upgrade, recreate dropped column.\n");
8328                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8329                                                           "SET attlen = %s, "
8330                                                           "attalign = '%s', attbyval = false\n"
8331                                                           "WHERE attname = ", attlen, attalign);
8332                         appendStringLiteralAH(dropped, attname, fout);
8333                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8334                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8335                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8336
8337                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8338                                                           fmtId(tyinfo->dobj.name));
8339                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8340                                                           fmtId(attname));
8341                 }
8342         }
8343         appendPQExpBuffer(q, "\n);\n");
8344         appendPQExpBufferStr(q, dropped->data);
8345
8346         /*
8347          * DROP must be fully qualified in case same name appears in pg_catalog
8348          */
8349         appendPQExpBuffer(delq, "DROP TYPE %s.",
8350                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8351         appendPQExpBuffer(delq, "%s;\n",
8352                                           fmtId(tyinfo->dobj.name));
8353
8354         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8355
8356         if (binary_upgrade)
8357                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8358
8359         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8360                                  tyinfo->dobj.name,
8361                                  tyinfo->dobj.namespace->dobj.name,
8362                                  NULL,
8363                                  tyinfo->rolname, false,
8364                                  "TYPE", SECTION_PRE_DATA,
8365                                  q->data, delq->data, NULL,
8366                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8367                                  NULL, NULL);
8368
8369
8370         /* Dump Type Comments and Security Labels */
8371         dumpComment(fout, labelq->data,
8372                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8373                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8374         dumpSecLabel(fout, labelq->data,
8375                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8376                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8377
8378         PQclear(res);
8379         destroyPQExpBuffer(q);
8380         destroyPQExpBuffer(dropped);
8381         destroyPQExpBuffer(delq);
8382         destroyPQExpBuffer(labelq);
8383         destroyPQExpBuffer(query);
8384
8385         /* Dump any per-column comments */
8386         dumpCompositeTypeColComments(fout, tyinfo);
8387 }
8388
8389 /*
8390  * dumpCompositeTypeColComments
8391  *        writes out to fout the queries to recreate comments on the columns of
8392  *        a user-defined stand-alone composite type
8393  */
8394 static void
8395 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8396 {
8397         CommentItem *comments;
8398         int                     ncomments;
8399         PGresult   *res;
8400         PQExpBuffer query;
8401         PQExpBuffer target;
8402         Oid                     pgClassOid;
8403         int                     i;
8404         int                     ntups;
8405         int                     i_attname;
8406         int                     i_attnum;
8407
8408         query = createPQExpBuffer();
8409
8410         /* We assume here that remoteVersion must be at least 70300 */
8411         appendPQExpBuffer(query,
8412                                           "SELECT c.tableoid, a.attname, a.attnum "
8413                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8414                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8415                                           "  AND NOT a.attisdropped "
8416                                           "ORDER BY a.attnum ",
8417                                           tyinfo->typrelid);
8418
8419         /* Fetch column attnames */
8420         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8421
8422         ntups = PQntuples(res);
8423         if (ntups < 1)
8424         {
8425                 PQclear(res);
8426                 destroyPQExpBuffer(query);
8427                 return;
8428         }
8429
8430         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8431
8432         /* Search for comments associated with type's pg_class OID */
8433         ncomments = findComments(fout,
8434                                                          pgClassOid,
8435                                                          tyinfo->typrelid,
8436                                                          &comments);
8437
8438         /* If no comments exist, we're done */
8439         if (ncomments <= 0)
8440         {
8441                 PQclear(res);
8442                 destroyPQExpBuffer(query);
8443                 return;
8444         }
8445
8446         /* Build COMMENT ON statements */
8447         target = createPQExpBuffer();
8448
8449         i_attnum = PQfnumber(res, "attnum");
8450         i_attname = PQfnumber(res, "attname");
8451         while (ncomments > 0)
8452         {
8453                 const char *attname;
8454
8455                 attname = NULL;
8456                 for (i = 0; i < ntups; i++)
8457                 {
8458                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8459                         {
8460                                 attname = PQgetvalue(res, i, i_attname);
8461                                 break;
8462                         }
8463                 }
8464                 if (attname)                    /* just in case we don't find it */
8465                 {
8466                         const char *descr = comments->descr;
8467
8468                         resetPQExpBuffer(target);
8469                         appendPQExpBuffer(target, "COLUMN %s.",
8470                                                           fmtId(tyinfo->dobj.name));
8471                         appendPQExpBuffer(target, "%s",
8472                                                           fmtId(attname));
8473
8474                         resetPQExpBuffer(query);
8475                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8476                         appendStringLiteralAH(query, descr, fout);
8477                         appendPQExpBuffer(query, ";\n");
8478
8479                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8480                                                  target->data,
8481                                                  tyinfo->dobj.namespace->dobj.name,
8482                                                  NULL, tyinfo->rolname,
8483                                                  false, "COMMENT", SECTION_NONE,
8484                                                  query->data, "", NULL,
8485                                                  &(tyinfo->dobj.dumpId), 1,
8486                                                  NULL, NULL);
8487                 }
8488
8489                 comments++;
8490                 ncomments--;
8491         }
8492
8493         PQclear(res);
8494         destroyPQExpBuffer(query);
8495         destroyPQExpBuffer(target);
8496 }
8497
8498 /*
8499  * dumpShellType
8500  *        writes out to fout the queries to create a shell type
8501  *
8502  * We dump a shell definition in advance of the I/O functions for the type.
8503  */
8504 static void
8505 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8506 {
8507         PQExpBuffer q;
8508
8509         /* Skip if not to be dumped */
8510         if (!stinfo->dobj.dump || dataOnly)
8511                 return;
8512
8513         q = createPQExpBuffer();
8514
8515         /*
8516          * Note the lack of a DROP command for the shell type; any required DROP
8517          * is driven off the base type entry, instead.  This interacts with
8518          * _printTocEntry()'s use of the presence of a DROP command to decide
8519          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8520          * the shell type's owner immediately on creation; that should happen only
8521          * after it's filled in, otherwise the backend complains.
8522          */
8523
8524         if (binary_upgrade)
8525                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8526                                                                                    stinfo->baseType->dobj.catId.oid);
8527
8528         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8529                                           fmtId(stinfo->dobj.name));
8530
8531         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8532                                  stinfo->dobj.name,
8533                                  stinfo->dobj.namespace->dobj.name,
8534                                  NULL,
8535                                  stinfo->baseType->rolname, false,
8536                                  "SHELL TYPE", SECTION_PRE_DATA,
8537                                  q->data, "", NULL,
8538                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8539                                  NULL, NULL);
8540
8541         destroyPQExpBuffer(q);
8542 }
8543
8544 /*
8545  * Determine whether we want to dump definitions for procedural languages.
8546  * Since the languages themselves don't have schemas, we can't rely on
8547  * the normal schema-based selection mechanism.  We choose to dump them
8548  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8549  * the dump flag of the PL's call handler function, but in 8.1 this will
8550  * probably always be false since call handlers are created in pg_catalog.)
8551  *
8552  * For some backwards compatibility with the older behavior, we forcibly
8553  * dump a PL if its handler function (and validator if any) are in a
8554  * dumpable namespace.  That case is not checked here.
8555  *
8556  * Also, if the PL belongs to an extension, we do not use this heuristic.
8557  * That case isn't checked here either.
8558  */
8559 static bool
8560 shouldDumpProcLangs(void)
8561 {
8562         if (!include_everything)
8563                 return false;
8564         /* And they're schema not data */
8565         if (dataOnly)
8566                 return false;
8567         return true;
8568 }
8569
8570 /*
8571  * dumpProcLang
8572  *                writes out to fout the queries to recreate a user-defined
8573  *                procedural language
8574  */
8575 static void
8576 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8577 {
8578         PQExpBuffer defqry;
8579         PQExpBuffer delqry;
8580         PQExpBuffer labelq;
8581         bool            useParams;
8582         char       *qlanname;
8583         char       *lanschema;
8584         FuncInfo   *funcInfo;
8585         FuncInfo   *inlineInfo = NULL;
8586         FuncInfo   *validatorInfo = NULL;
8587
8588         /* Skip if not to be dumped */
8589         if (!plang->dobj.dump || dataOnly)
8590                 return;
8591
8592         /*
8593          * Try to find the support function(s).  It is not an error if we don't
8594          * find them --- if the functions are in the pg_catalog schema, as is
8595          * standard in 8.1 and up, then we won't have loaded them. (In this case
8596          * we will emit a parameterless CREATE LANGUAGE command, which will
8597          * require PL template knowledge in the backend to reload.)
8598          */
8599
8600         funcInfo = findFuncByOid(plang->lanplcallfoid);
8601         if (funcInfo != NULL && !funcInfo->dobj.dump)
8602                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8603
8604         if (OidIsValid(plang->laninline))
8605         {
8606                 inlineInfo = findFuncByOid(plang->laninline);
8607                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8608                         inlineInfo = NULL;
8609         }
8610
8611         if (OidIsValid(plang->lanvalidator))
8612         {
8613                 validatorInfo = findFuncByOid(plang->lanvalidator);
8614                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8615                         validatorInfo = NULL;
8616         }
8617
8618         /*
8619          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8620          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8621          * dump it.
8622          *
8623          * However, for a language that belongs to an extension, we must not use
8624          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8625          * told to (via dobj.dump).  Generally the support functions will belong
8626          * to the same extension and so have the same dump flags ... if they
8627          * don't, this might not work terribly nicely.
8628          */
8629         useParams = (funcInfo != NULL &&
8630                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8631                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8632
8633         if (!plang->dobj.ext_member)
8634         {
8635                 if (!useParams && !shouldDumpProcLangs())
8636                         return;
8637         }
8638
8639         defqry = createPQExpBuffer();
8640         delqry = createPQExpBuffer();
8641         labelq = createPQExpBuffer();
8642
8643         qlanname = pg_strdup(fmtId(plang->dobj.name));
8644
8645         /*
8646          * If dumping a HANDLER clause, treat the language as being in the handler
8647          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8648          * it doesn't really have a schema.
8649          */
8650         if (useParams)
8651                 lanschema = funcInfo->dobj.namespace->dobj.name;
8652         else
8653                 lanschema = NULL;
8654
8655         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8656                                           qlanname);
8657
8658         if (useParams)
8659         {
8660                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8661                                                   plang->lanpltrusted ? "TRUSTED " : "",
8662                                                   qlanname);
8663                 appendPQExpBuffer(defqry, " HANDLER %s",
8664                                                   fmtId(funcInfo->dobj.name));
8665                 if (OidIsValid(plang->laninline))
8666                 {
8667                         appendPQExpBuffer(defqry, " INLINE ");
8668                         /* Cope with possibility that inline is in different schema */
8669                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8670                                 appendPQExpBuffer(defqry, "%s.",
8671                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8672                         appendPQExpBuffer(defqry, "%s",
8673                                                           fmtId(inlineInfo->dobj.name));
8674                 }
8675                 if (OidIsValid(plang->lanvalidator))
8676                 {
8677                         appendPQExpBuffer(defqry, " VALIDATOR ");
8678                         /* Cope with possibility that validator is in different schema */
8679                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8680                                 appendPQExpBuffer(defqry, "%s.",
8681                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8682                         appendPQExpBuffer(defqry, "%s",
8683                                                           fmtId(validatorInfo->dobj.name));
8684                 }
8685         }
8686         else
8687         {
8688                 /*
8689                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8690                  * command will not fail if the language is preinstalled in the target
8691                  * database.  We restrict the use of REPLACE to this case so as to
8692                  * eliminate the risk of replacing a language with incompatible
8693                  * parameter settings: this command will only succeed at all if there
8694                  * is a pg_pltemplate entry, and if there is one, the existing entry
8695                  * must match it too.
8696                  */
8697                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8698                                                   qlanname);
8699         }
8700         appendPQExpBuffer(defqry, ";\n");
8701
8702         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8703
8704         if (binary_upgrade)
8705                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8706
8707         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8708                                  plang->dobj.name,
8709                                  lanschema, NULL, plang->lanowner,
8710                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8711                                  defqry->data, delqry->data, NULL,
8712                                  plang->dobj.dependencies, plang->dobj.nDeps,
8713                                  NULL, NULL);
8714
8715         /* Dump Proc Lang Comments and Security Labels */
8716         dumpComment(fout, labelq->data,
8717                                 NULL, "",
8718                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8719         dumpSecLabel(fout, labelq->data,
8720                                  NULL, "",
8721                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8722
8723         if (plang->lanpltrusted)
8724                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8725                                 qlanname, NULL, plang->dobj.name,
8726                                 lanschema,
8727                                 plang->lanowner, plang->lanacl);
8728
8729         free(qlanname);
8730
8731         destroyPQExpBuffer(defqry);
8732         destroyPQExpBuffer(delqry);
8733         destroyPQExpBuffer(labelq);
8734 }
8735
8736 /*
8737  * format_function_arguments: generate function name and argument list
8738  *
8739  * This is used when we can rely on pg_get_function_arguments to format
8740  * the argument list.
8741  */
8742 static char *
8743 format_function_arguments(FuncInfo *finfo, char *funcargs)
8744 {
8745         PQExpBufferData fn;
8746
8747         initPQExpBuffer(&fn);
8748         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8749         return fn.data;
8750 }
8751
8752 /*
8753  * format_function_arguments_old: generate function name and argument list
8754  *
8755  * The argument type names are qualified if needed.  The function name
8756  * is never qualified.
8757  *
8758  * This is used only with pre-8.4 servers, so we aren't expecting to see
8759  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8760  *
8761  * Any or all of allargtypes, argmodes, argnames may be NULL.
8762  */
8763 static char *
8764 format_function_arguments_old(Archive *fout,
8765                                                           FuncInfo *finfo, int nallargs,
8766                                                           char **allargtypes,
8767                                                           char **argmodes,
8768                                                           char **argnames)
8769 {
8770         PQExpBufferData fn;
8771         int                     j;
8772
8773         initPQExpBuffer(&fn);
8774         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8775         for (j = 0; j < nallargs; j++)
8776         {
8777                 Oid                     typid;
8778                 char       *typname;
8779                 const char *argmode;
8780                 const char *argname;
8781
8782                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8783                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8784
8785                 if (argmodes)
8786                 {
8787                         switch (argmodes[j][0])
8788                         {
8789                                 case PROARGMODE_IN:
8790                                         argmode = "";
8791                                         break;
8792                                 case PROARGMODE_OUT:
8793                                         argmode = "OUT ";
8794                                         break;
8795                                 case PROARGMODE_INOUT:
8796                                         argmode = "INOUT ";
8797                                         break;
8798                                 default:
8799                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8800                                         argmode = "";
8801                                         break;
8802                         }
8803                 }
8804                 else
8805                         argmode = "";
8806
8807                 argname = argnames ? argnames[j] : (char *) NULL;
8808                 if (argname && argname[0] == '\0')
8809                         argname = NULL;
8810
8811                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8812                                                   (j > 0) ? ", " : "",
8813                                                   argmode,
8814                                                   argname ? fmtId(argname) : "",
8815                                                   argname ? " " : "",
8816                                                   typname);
8817                 free(typname);
8818         }
8819         appendPQExpBuffer(&fn, ")");
8820         return fn.data;
8821 }
8822
8823 /*
8824  * format_function_signature: generate function name and argument list
8825  *
8826  * This is like format_function_arguments_old except that only a minimal
8827  * list of input argument types is generated; this is sufficient to
8828  * reference the function, but not to define it.
8829  *
8830  * If honor_quotes is false then the function name is never quoted.
8831  * This is appropriate for use in TOC tags, but not in SQL commands.
8832  */
8833 static char *
8834 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8835 {
8836         PQExpBufferData fn;
8837         int                     j;
8838
8839         initPQExpBuffer(&fn);
8840         if (honor_quotes)
8841                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8842         else
8843                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8844         for (j = 0; j < finfo->nargs; j++)
8845         {
8846                 char       *typname;
8847
8848                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8849                                                                            zeroAsOpaque);
8850
8851                 appendPQExpBuffer(&fn, "%s%s",
8852                                                   (j > 0) ? ", " : "",
8853                                                   typname);
8854                 free(typname);
8855         }
8856         appendPQExpBuffer(&fn, ")");
8857         return fn.data;
8858 }
8859
8860
8861 /*
8862  * dumpFunc:
8863  *        dump out one function
8864  */
8865 static void
8866 dumpFunc(Archive *fout, FuncInfo *finfo)
8867 {
8868         PQExpBuffer query;
8869         PQExpBuffer q;
8870         PQExpBuffer delqry;
8871         PQExpBuffer labelq;
8872         PQExpBuffer asPart;
8873         PGresult   *res;
8874         char       *funcsig;            /* identity signature */
8875         char       *funcfullsig;        /* full signature */
8876         char       *funcsig_tag;
8877         char       *proretset;
8878         char       *prosrc;
8879         char       *probin;
8880         char       *funcargs;
8881         char       *funciargs;
8882         char       *funcresult;
8883         char       *proallargtypes;
8884         char       *proargmodes;
8885         char       *proargnames;
8886         char       *proiswindow;
8887         char       *provolatile;
8888         char       *proisstrict;
8889         char       *prosecdef;
8890         char       *proleakproof;
8891         char       *proconfig;
8892         char       *procost;
8893         char       *prorows;
8894         char       *lanname;
8895         char       *rettypename;
8896         int                     nallargs;
8897         char      **allargtypes = NULL;
8898         char      **argmodes = NULL;
8899         char      **argnames = NULL;
8900         char      **configitems = NULL;
8901         int                     nconfigitems = 0;
8902         int                     i;
8903
8904         /* Skip if not to be dumped */
8905         if (!finfo->dobj.dump || dataOnly)
8906                 return;
8907
8908         query = createPQExpBuffer();
8909         q = createPQExpBuffer();
8910         delqry = createPQExpBuffer();
8911         labelq = createPQExpBuffer();
8912         asPart = createPQExpBuffer();
8913
8914         /* Set proper schema search path so type references list correctly */
8915         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8916
8917         /* Fetch function-specific details */
8918         if (fout->remoteVersion >= 90200)
8919         {
8920                 /*
8921                  * proleakproof was added at v9.2
8922                  */
8923                 appendPQExpBuffer(query,
8924                                                   "SELECT proretset, prosrc, probin, "
8925                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8926                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8927                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8928                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8929                                                   "proleakproof, proconfig, procost, prorows, "
8930                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8931                                                   "FROM pg_catalog.pg_proc "
8932                                                   "WHERE oid = '%u'::pg_catalog.oid",
8933                                                   finfo->dobj.catId.oid);
8934         }
8935         else if (fout->remoteVersion >= 80400)
8936         {
8937                 /*
8938                  * In 8.4 and up we rely on pg_get_function_arguments and
8939                  * pg_get_function_result instead of examining proallargtypes etc.
8940                  */
8941                 appendPQExpBuffer(query,
8942                                                   "SELECT proretset, prosrc, probin, "
8943                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8944                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8945                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8946                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8947                                                   "false AS proleakproof, "
8948                                                   " proconfig, procost, prorows, "
8949                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8950                                                   "FROM pg_catalog.pg_proc "
8951                                                   "WHERE oid = '%u'::pg_catalog.oid",
8952                                                   finfo->dobj.catId.oid);
8953         }
8954         else if (fout->remoteVersion >= 80300)
8955         {
8956                 appendPQExpBuffer(query,
8957                                                   "SELECT proretset, prosrc, probin, "
8958                                                   "proallargtypes, proargmodes, proargnames, "
8959                                                   "false AS proiswindow, "
8960                                                   "provolatile, proisstrict, prosecdef, "
8961                                                   "false AS proleakproof, "
8962                                                   "proconfig, procost, prorows, "
8963                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8964                                                   "FROM pg_catalog.pg_proc "
8965                                                   "WHERE oid = '%u'::pg_catalog.oid",
8966                                                   finfo->dobj.catId.oid);
8967         }
8968         else if (fout->remoteVersion >= 80100)
8969         {
8970                 appendPQExpBuffer(query,
8971                                                   "SELECT proretset, prosrc, probin, "
8972                                                   "proallargtypes, proargmodes, proargnames, "
8973                                                   "false AS proiswindow, "
8974                                                   "provolatile, proisstrict, prosecdef, "
8975                                                   "false AS proleakproof, "
8976                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
8977                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8978                                                   "FROM pg_catalog.pg_proc "
8979                                                   "WHERE oid = '%u'::pg_catalog.oid",
8980                                                   finfo->dobj.catId.oid);
8981         }
8982         else if (fout->remoteVersion >= 80000)
8983         {
8984                 appendPQExpBuffer(query,
8985                                                   "SELECT proretset, prosrc, probin, "
8986                                                   "null AS proallargtypes, "
8987                                                   "null AS proargmodes, "
8988                                                   "proargnames, "
8989                                                   "false AS proiswindow, "
8990                                                   "provolatile, proisstrict, prosecdef, "
8991                                                   "false AS proleakproof, "
8992                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
8993                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8994                                                   "FROM pg_catalog.pg_proc "
8995                                                   "WHERE oid = '%u'::pg_catalog.oid",
8996                                                   finfo->dobj.catId.oid);
8997         }
8998         else if (fout->remoteVersion >= 70300)
8999         {
9000                 appendPQExpBuffer(query,
9001                                                   "SELECT proretset, prosrc, probin, "
9002                                                   "null AS proallargtypes, "
9003                                                   "null AS proargmodes, "
9004                                                   "null AS proargnames, "
9005                                                   "false AS proiswindow, "
9006                                                   "provolatile, proisstrict, prosecdef, "
9007                                                   "false AS proleakproof, "
9008                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9009                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9010                                                   "FROM pg_catalog.pg_proc "
9011                                                   "WHERE oid = '%u'::pg_catalog.oid",
9012                                                   finfo->dobj.catId.oid);
9013         }
9014         else if (fout->remoteVersion >= 70100)
9015         {
9016                 appendPQExpBuffer(query,
9017                                                   "SELECT proretset, prosrc, probin, "
9018                                                   "null AS proallargtypes, "
9019                                                   "null AS proargmodes, "
9020                                                   "null AS proargnames, "
9021                                                   "false AS proiswindow, "
9022                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9023                                                   "proisstrict, "
9024                                                   "false AS prosecdef, "
9025                                                   "false AS proleakproof, "
9026                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9027                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9028                                                   "FROM pg_proc "
9029                                                   "WHERE oid = '%u'::oid",
9030                                                   finfo->dobj.catId.oid);
9031         }
9032         else
9033         {
9034                 appendPQExpBuffer(query,
9035                                                   "SELECT proretset, prosrc, probin, "
9036                                                   "null AS proallargtypes, "
9037                                                   "null AS proargmodes, "
9038                                                   "null AS proargnames, "
9039                                                   "false AS proiswindow, "
9040                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9041                                                   "false AS proisstrict, "
9042                                                   "false AS prosecdef, "
9043                                                   "false AS proleakproof, "
9044                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9045                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9046                                                   "FROM pg_proc "
9047                                                   "WHERE oid = '%u'::oid",
9048                                                   finfo->dobj.catId.oid);
9049         }
9050
9051         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9052
9053         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9054         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9055         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9056         if (fout->remoteVersion >= 80400)
9057         {
9058                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9059                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9060                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9061                 proallargtypes = proargmodes = proargnames = NULL;
9062         }
9063         else
9064         {
9065                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9066                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9067                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9068                 funcargs = funciargs = funcresult = NULL;
9069         }
9070         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9071         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9072         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9073         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9074         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9075         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9076         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9077         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9078         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9079
9080         /*
9081          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9082          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9083          * versions would set it to "-".  There are no known cases in which prosrc
9084          * is unused, so the tests below for "-" are probably useless.
9085          */
9086         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9087         {
9088                 appendPQExpBuffer(asPart, "AS ");
9089                 appendStringLiteralAH(asPart, probin, fout);
9090                 if (strcmp(prosrc, "-") != 0)
9091                 {
9092                         appendPQExpBuffer(asPart, ", ");
9093
9094                         /*
9095                          * where we have bin, use dollar quoting if allowed and src
9096                          * contains quote or backslash; else use regular quoting.
9097                          */
9098                         if (disable_dollar_quoting ||
9099                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9100                                 appendStringLiteralAH(asPart, prosrc, fout);
9101                         else
9102                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9103                 }
9104         }
9105         else
9106         {
9107                 if (strcmp(prosrc, "-") != 0)
9108                 {
9109                         appendPQExpBuffer(asPart, "AS ");
9110                         /* with no bin, dollar quote src unconditionally if allowed */
9111                         if (disable_dollar_quoting)
9112                                 appendStringLiteralAH(asPart, prosrc, fout);
9113                         else
9114                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9115                 }
9116         }
9117
9118         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9119
9120         if (proallargtypes && *proallargtypes)
9121         {
9122                 int                     nitems = 0;
9123
9124                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9125                         nitems < finfo->nargs)
9126                 {
9127                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9128                         if (allargtypes)
9129                                 free(allargtypes);
9130                         allargtypes = NULL;
9131                 }
9132                 else
9133                         nallargs = nitems;
9134         }
9135
9136         if (proargmodes && *proargmodes)
9137         {
9138                 int                     nitems = 0;
9139
9140                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9141                         nitems != nallargs)
9142                 {
9143                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9144                         if (argmodes)
9145                                 free(argmodes);
9146                         argmodes = NULL;
9147                 }
9148         }
9149
9150         if (proargnames && *proargnames)
9151         {
9152                 int                     nitems = 0;
9153
9154                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9155                         nitems != nallargs)
9156                 {
9157                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9158                         if (argnames)
9159                                 free(argnames);
9160                         argnames = NULL;
9161                 }
9162         }
9163
9164         if (proconfig && *proconfig)
9165         {
9166                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9167                 {
9168                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9169                         if (configitems)
9170                                 free(configitems);
9171                         configitems = NULL;
9172                         nconfigitems = 0;
9173                 }
9174         }
9175
9176         if (funcargs)
9177         {
9178                 /* 8.4 or later; we rely on server-side code for most of the work */
9179                 funcfullsig = format_function_arguments(finfo, funcargs);
9180                 funcsig = format_function_arguments(finfo, funciargs);
9181         }
9182         else
9183         {
9184                 /* pre-8.4, do it ourselves */
9185                 funcsig = format_function_arguments_old(fout,
9186                                                                                                 finfo, nallargs, allargtypes,
9187                                                                                                 argmodes, argnames);
9188                 funcfullsig = funcsig;
9189         }
9190
9191         funcsig_tag = format_function_signature(fout, finfo, false);
9192
9193         /*
9194          * DROP must be fully qualified in case same name appears in pg_catalog
9195          */
9196         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9197                                           fmtId(finfo->dobj.namespace->dobj.name),
9198                                           funcsig);
9199
9200         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9201         if (funcresult)
9202                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9203         else
9204         {
9205                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9206                                                                                    zeroAsOpaque);
9207                 appendPQExpBuffer(q, "RETURNS %s%s",
9208                                                   (proretset[0] == 't') ? "SETOF " : "",
9209                                                   rettypename);
9210                 free(rettypename);
9211         }
9212
9213         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9214
9215         if (proiswindow[0] == 't')
9216                 appendPQExpBuffer(q, " WINDOW");
9217
9218         if (provolatile[0] != PROVOLATILE_VOLATILE)
9219         {
9220                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9221                         appendPQExpBuffer(q, " IMMUTABLE");
9222                 else if (provolatile[0] == PROVOLATILE_STABLE)
9223                         appendPQExpBuffer(q, " STABLE");
9224                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9225                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9226                                                   finfo->dobj.name);
9227         }
9228
9229         if (proisstrict[0] == 't')
9230                 appendPQExpBuffer(q, " STRICT");
9231
9232         if (prosecdef[0] == 't')
9233                 appendPQExpBuffer(q, " SECURITY DEFINER");
9234
9235         if (proleakproof[0] == 't')
9236                 appendPQExpBuffer(q, " LEAKPROOF");
9237
9238         /*
9239          * COST and ROWS are emitted only if present and not default, so as not to
9240          * break backwards-compatibility of the dump without need.      Keep this code
9241          * in sync with the defaults in functioncmds.c.
9242          */
9243         if (strcmp(procost, "0") != 0)
9244         {
9245                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9246                 {
9247                         /* default cost is 1 */
9248                         if (strcmp(procost, "1") != 0)
9249                                 appendPQExpBuffer(q, " COST %s", procost);
9250                 }
9251                 else
9252                 {
9253                         /* default cost is 100 */
9254                         if (strcmp(procost, "100") != 0)
9255                                 appendPQExpBuffer(q, " COST %s", procost);
9256                 }
9257         }
9258         if (proretset[0] == 't' &&
9259                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9260                 appendPQExpBuffer(q, " ROWS %s", prorows);
9261
9262         for (i = 0; i < nconfigitems; i++)
9263         {
9264                 /* we feel free to scribble on configitems[] here */
9265                 char       *configitem = configitems[i];
9266                 char       *pos;
9267
9268                 pos = strchr(configitem, '=');
9269                 if (pos == NULL)
9270                         continue;
9271                 *pos++ = '\0';
9272                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9273
9274                 /*
9275                  * Some GUC variable names are 'LIST' type and hence must not be
9276                  * quoted.
9277                  */
9278                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9279                         || pg_strcasecmp(configitem, "search_path") == 0)
9280                         appendPQExpBuffer(q, "%s", pos);
9281                 else
9282                         appendStringLiteralAH(q, pos, fout);
9283         }
9284
9285         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9286
9287         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9288
9289         if (binary_upgrade)
9290                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9291
9292         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9293                                  funcsig_tag,
9294                                  finfo->dobj.namespace->dobj.name,
9295                                  NULL,
9296                                  finfo->rolname, false,
9297                                  "FUNCTION", SECTION_PRE_DATA,
9298                                  q->data, delqry->data, NULL,
9299                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
9300                                  NULL, NULL);
9301
9302         /* Dump Function Comments and Security Labels */
9303         dumpComment(fout, labelq->data,
9304                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9305                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9306         dumpSecLabel(fout, labelq->data,
9307                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9308                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9309
9310         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9311                         funcsig, NULL, funcsig_tag,
9312                         finfo->dobj.namespace->dobj.name,
9313                         finfo->rolname, finfo->proacl);
9314
9315         PQclear(res);
9316
9317         destroyPQExpBuffer(query);
9318         destroyPQExpBuffer(q);
9319         destroyPQExpBuffer(delqry);
9320         destroyPQExpBuffer(labelq);
9321         destroyPQExpBuffer(asPart);
9322         free(funcsig);
9323         free(funcsig_tag);
9324         if (allargtypes)
9325                 free(allargtypes);
9326         if (argmodes)
9327                 free(argmodes);
9328         if (argnames)
9329                 free(argnames);
9330         if (configitems)
9331                 free(configitems);
9332 }
9333
9334
9335 /*
9336  * Dump a user-defined cast
9337  */
9338 static void
9339 dumpCast(Archive *fout, CastInfo *cast)
9340 {
9341         PQExpBuffer defqry;
9342         PQExpBuffer delqry;
9343         PQExpBuffer labelq;
9344         FuncInfo   *funcInfo = NULL;
9345
9346         /* Skip if not to be dumped */
9347         if (!cast->dobj.dump || dataOnly)
9348                 return;
9349
9350         /* Cannot dump if we don't have the cast function's info */
9351         if (OidIsValid(cast->castfunc))
9352         {
9353                 funcInfo = findFuncByOid(cast->castfunc);
9354                 if (funcInfo == NULL)
9355                         return;
9356         }
9357
9358         /*
9359          * As per discussion we dump casts if one or more of the underlying
9360          * objects (the conversion function and the two data types) are not
9361          * builtin AND if all of the non-builtin objects are included in the dump.
9362          * Builtin meaning, the namespace name does not start with "pg_".
9363          *
9364          * However, for a cast that belongs to an extension, we must not use this
9365          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9366          */
9367         if (!cast->dobj.ext_member)
9368         {
9369                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9370                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9371
9372                 if (sourceInfo == NULL || targetInfo == NULL)
9373                         return;
9374
9375                 /*
9376                  * Skip this cast if all objects are from pg_
9377                  */
9378                 if ((funcInfo == NULL ||
9379                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9380                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9381                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9382                         return;
9383
9384                 /*
9385                  * Skip cast if function isn't from pg_ and is not to be dumped.
9386                  */
9387                 if (funcInfo &&
9388                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9389                         !funcInfo->dobj.dump)
9390                         return;
9391
9392                 /*
9393                  * Same for the source type
9394                  */
9395                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9396                         !sourceInfo->dobj.dump)
9397                         return;
9398
9399                 /*
9400                  * and the target type.
9401                  */
9402                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9403                         !targetInfo->dobj.dump)
9404                         return;
9405         }
9406
9407         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9408         selectSourceSchema(fout, "pg_catalog");
9409
9410         defqry = createPQExpBuffer();
9411         delqry = createPQExpBuffer();
9412         labelq = createPQExpBuffer();
9413
9414         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9415                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9416                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9417
9418         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9419                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9420                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9421
9422         switch (cast->castmethod)
9423         {
9424                 case COERCION_METHOD_BINARY:
9425                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9426                         break;
9427                 case COERCION_METHOD_INOUT:
9428                         appendPQExpBuffer(defqry, "WITH INOUT");
9429                         break;
9430                 case COERCION_METHOD_FUNCTION:
9431                         if (funcInfo)
9432                         {
9433                                 char       *fsig = format_function_signature(fout, funcInfo, true);
9434
9435                                 /*
9436                                  * Always qualify the function name, in case it is not in
9437                                  * pg_catalog schema (format_function_signature won't qualify
9438                                  * it).
9439                                  */
9440                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9441                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9442                                 free(fsig);
9443                         }
9444                         else
9445                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9446                         break;
9447                 default:
9448                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9449         }
9450
9451         if (cast->castcontext == 'a')
9452                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9453         else if (cast->castcontext == 'i')
9454                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9455         appendPQExpBuffer(defqry, ";\n");
9456
9457         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9458                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9459                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9460
9461         if (binary_upgrade)
9462                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9463
9464         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9465                                  labelq->data,
9466                                  "pg_catalog", NULL, "",
9467                                  false, "CAST", SECTION_PRE_DATA,
9468                                  defqry->data, delqry->data, NULL,
9469                                  cast->dobj.dependencies, cast->dobj.nDeps,
9470                                  NULL, NULL);
9471
9472         /* Dump Cast Comments */
9473         dumpComment(fout, labelq->data,
9474                                 NULL, "",
9475                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9476
9477         destroyPQExpBuffer(defqry);
9478         destroyPQExpBuffer(delqry);
9479         destroyPQExpBuffer(labelq);
9480 }
9481
9482 /*
9483  * dumpOpr
9484  *        write out a single operator definition
9485  */
9486 static void
9487 dumpOpr(Archive *fout, OprInfo *oprinfo)
9488 {
9489         PQExpBuffer query;
9490         PQExpBuffer q;
9491         PQExpBuffer delq;
9492         PQExpBuffer labelq;
9493         PQExpBuffer oprid;
9494         PQExpBuffer details;
9495         const char *name;
9496         PGresult   *res;
9497         int                     i_oprkind;
9498         int                     i_oprcode;
9499         int                     i_oprleft;
9500         int                     i_oprright;
9501         int                     i_oprcom;
9502         int                     i_oprnegate;
9503         int                     i_oprrest;
9504         int                     i_oprjoin;
9505         int                     i_oprcanmerge;
9506         int                     i_oprcanhash;
9507         char       *oprkind;
9508         char       *oprcode;
9509         char       *oprleft;
9510         char       *oprright;
9511         char       *oprcom;
9512         char       *oprnegate;
9513         char       *oprrest;
9514         char       *oprjoin;
9515         char       *oprcanmerge;
9516         char       *oprcanhash;
9517
9518         /* Skip if not to be dumped */
9519         if (!oprinfo->dobj.dump || dataOnly)
9520                 return;
9521
9522         /*
9523          * some operators are invalid because they were the result of user
9524          * defining operators before commutators exist
9525          */
9526         if (!OidIsValid(oprinfo->oprcode))
9527                 return;
9528
9529         query = createPQExpBuffer();
9530         q = createPQExpBuffer();
9531         delq = createPQExpBuffer();
9532         labelq = createPQExpBuffer();
9533         oprid = createPQExpBuffer();
9534         details = createPQExpBuffer();
9535
9536         /* Make sure we are in proper schema so regoperator works correctly */
9537         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9538
9539         if (fout->remoteVersion >= 80300)
9540         {
9541                 appendPQExpBuffer(query, "SELECT oprkind, "
9542                                                   "oprcode::pg_catalog.regprocedure, "
9543                                                   "oprleft::pg_catalog.regtype, "
9544                                                   "oprright::pg_catalog.regtype, "
9545                                                   "oprcom::pg_catalog.regoperator, "
9546                                                   "oprnegate::pg_catalog.regoperator, "
9547                                                   "oprrest::pg_catalog.regprocedure, "
9548                                                   "oprjoin::pg_catalog.regprocedure, "
9549                                                   "oprcanmerge, oprcanhash "
9550                                                   "FROM pg_catalog.pg_operator "
9551                                                   "WHERE oid = '%u'::pg_catalog.oid",
9552                                                   oprinfo->dobj.catId.oid);
9553         }
9554         else if (fout->remoteVersion >= 70300)
9555         {
9556                 appendPQExpBuffer(query, "SELECT oprkind, "
9557                                                   "oprcode::pg_catalog.regprocedure, "
9558                                                   "oprleft::pg_catalog.regtype, "
9559                                                   "oprright::pg_catalog.regtype, "
9560                                                   "oprcom::pg_catalog.regoperator, "
9561                                                   "oprnegate::pg_catalog.regoperator, "
9562                                                   "oprrest::pg_catalog.regprocedure, "
9563                                                   "oprjoin::pg_catalog.regprocedure, "
9564                                                   "(oprlsortop != 0) AS oprcanmerge, "
9565                                                   "oprcanhash "
9566                                                   "FROM pg_catalog.pg_operator "
9567                                                   "WHERE oid = '%u'::pg_catalog.oid",
9568                                                   oprinfo->dobj.catId.oid);
9569         }
9570         else if (fout->remoteVersion >= 70100)
9571         {
9572                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9573                                                   "CASE WHEN oprleft = 0 THEN '-' "
9574                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9575                                                   "CASE WHEN oprright = 0 THEN '-' "
9576                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9577                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9578                                                   "(oprlsortop != 0) AS oprcanmerge, "
9579                                                   "oprcanhash "
9580                                                   "FROM pg_operator "
9581                                                   "WHERE oid = '%u'::oid",
9582                                                   oprinfo->dobj.catId.oid);
9583         }
9584         else
9585         {
9586                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9587                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9588                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9589                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9590                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9591                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9592                                                   "(oprlsortop != 0) AS oprcanmerge, "
9593                                                   "oprcanhash "
9594                                                   "FROM pg_operator "
9595                                                   "WHERE oid = '%u'::oid",
9596                                                   oprinfo->dobj.catId.oid);
9597         }
9598
9599         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9600
9601         i_oprkind = PQfnumber(res, "oprkind");
9602         i_oprcode = PQfnumber(res, "oprcode");
9603         i_oprleft = PQfnumber(res, "oprleft");
9604         i_oprright = PQfnumber(res, "oprright");
9605         i_oprcom = PQfnumber(res, "oprcom");
9606         i_oprnegate = PQfnumber(res, "oprnegate");
9607         i_oprrest = PQfnumber(res, "oprrest");
9608         i_oprjoin = PQfnumber(res, "oprjoin");
9609         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9610         i_oprcanhash = PQfnumber(res, "oprcanhash");
9611
9612         oprkind = PQgetvalue(res, 0, i_oprkind);
9613         oprcode = PQgetvalue(res, 0, i_oprcode);
9614         oprleft = PQgetvalue(res, 0, i_oprleft);
9615         oprright = PQgetvalue(res, 0, i_oprright);
9616         oprcom = PQgetvalue(res, 0, i_oprcom);
9617         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9618         oprrest = PQgetvalue(res, 0, i_oprrest);
9619         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9620         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9621         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9622
9623         appendPQExpBuffer(details, "    PROCEDURE = %s",
9624                                           convertRegProcReference(fout, oprcode));
9625
9626         appendPQExpBuffer(oprid, "%s (",
9627                                           oprinfo->dobj.name);
9628
9629         /*
9630          * right unary means there's a left arg and left unary means there's a
9631          * right arg
9632          */
9633         if (strcmp(oprkind, "r") == 0 ||
9634                 strcmp(oprkind, "b") == 0)
9635         {
9636                 if (fout->remoteVersion >= 70100)
9637                         name = oprleft;
9638                 else
9639                         name = fmtId(oprleft);
9640                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9641                 appendPQExpBuffer(oprid, "%s", name);
9642         }
9643         else
9644                 appendPQExpBuffer(oprid, "NONE");
9645
9646         if (strcmp(oprkind, "l") == 0 ||
9647                 strcmp(oprkind, "b") == 0)
9648         {
9649                 if (fout->remoteVersion >= 70100)
9650                         name = oprright;
9651                 else
9652                         name = fmtId(oprright);
9653                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9654                 appendPQExpBuffer(oprid, ", %s)", name);
9655         }
9656         else
9657                 appendPQExpBuffer(oprid, ", NONE)");
9658
9659         name = convertOperatorReference(fout, oprcom);
9660         if (name)
9661                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9662
9663         name = convertOperatorReference(fout, oprnegate);
9664         if (name)
9665                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9666
9667         if (strcmp(oprcanmerge, "t") == 0)
9668                 appendPQExpBuffer(details, ",\n    MERGES");
9669
9670         if (strcmp(oprcanhash, "t") == 0)
9671                 appendPQExpBuffer(details, ",\n    HASHES");
9672
9673         name = convertRegProcReference(fout, oprrest);
9674         if (name)
9675                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9676
9677         name = convertRegProcReference(fout, oprjoin);
9678         if (name)
9679                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9680
9681         /*
9682          * DROP must be fully qualified in case same name appears in pg_catalog
9683          */
9684         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9685                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9686                                           oprid->data);
9687
9688         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9689                                           oprinfo->dobj.name, details->data);
9690
9691         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9692
9693         if (binary_upgrade)
9694                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9695
9696         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9697                                  oprinfo->dobj.name,
9698                                  oprinfo->dobj.namespace->dobj.name,
9699                                  NULL,
9700                                  oprinfo->rolname,
9701                                  false, "OPERATOR", SECTION_PRE_DATA,
9702                                  q->data, delq->data, NULL,
9703                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9704                                  NULL, NULL);
9705
9706         /* Dump Operator Comments */
9707         dumpComment(fout, labelq->data,
9708                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9709                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9710
9711         PQclear(res);
9712
9713         destroyPQExpBuffer(query);
9714         destroyPQExpBuffer(q);
9715         destroyPQExpBuffer(delq);
9716         destroyPQExpBuffer(labelq);
9717         destroyPQExpBuffer(oprid);
9718         destroyPQExpBuffer(details);
9719 }
9720
9721 /*
9722  * Convert a function reference obtained from pg_operator
9723  *
9724  * Returns what to print, or NULL if function references is InvalidOid
9725  *
9726  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9727  * argument-types part.  In prior versions, the input is a REGPROC display.
9728  */
9729 static const char *
9730 convertRegProcReference(Archive *fout, const char *proc)
9731 {
9732         /* In all cases "-" means a null reference */
9733         if (strcmp(proc, "-") == 0)
9734                 return NULL;
9735
9736         if (fout->remoteVersion >= 70300)
9737         {
9738                 char       *name;
9739                 char       *paren;
9740                 bool            inquote;
9741
9742                 name = pg_strdup(proc);
9743                 /* find non-double-quoted left paren */
9744                 inquote = false;
9745                 for (paren = name; *paren; paren++)
9746                 {
9747                         if (*paren == '(' && !inquote)
9748                         {
9749                                 *paren = '\0';
9750                                 break;
9751                         }
9752                         if (*paren == '"')
9753                                 inquote = !inquote;
9754                 }
9755                 return name;
9756         }
9757
9758         /* REGPROC before 7.3 does not quote its result */
9759         return fmtId(proc);
9760 }
9761
9762 /*
9763  * Convert an operator cross-reference obtained from pg_operator
9764  *
9765  * Returns what to print, or NULL to print nothing
9766  *
9767  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9768  * argument-types part, and add OPERATOR() decoration if the name is
9769  * schema-qualified.  In older versions, the input is just a numeric OID,
9770  * which we search our operator list for.
9771  */
9772 static const char *
9773 convertOperatorReference(Archive *fout, const char *opr)
9774 {
9775         OprInfo    *oprInfo;
9776
9777         /* In all cases "0" means a null reference */
9778         if (strcmp(opr, "0") == 0)
9779                 return NULL;
9780
9781         if (fout->remoteVersion >= 70300)
9782         {
9783                 char       *name;
9784                 char       *oname;
9785                 char       *ptr;
9786                 bool            inquote;
9787                 bool            sawdot;
9788
9789                 name = pg_strdup(opr);
9790                 /* find non-double-quoted left paren, and check for non-quoted dot */
9791                 inquote = false;
9792                 sawdot = false;
9793                 for (ptr = name; *ptr; ptr++)
9794                 {
9795                         if (*ptr == '"')
9796                                 inquote = !inquote;
9797                         else if (*ptr == '.' && !inquote)
9798                                 sawdot = true;
9799                         else if (*ptr == '(' && !inquote)
9800                         {
9801                                 *ptr = '\0';
9802                                 break;
9803                         }
9804                 }
9805                 /* If not schema-qualified, don't need to add OPERATOR() */
9806                 if (!sawdot)
9807                         return name;
9808                 oname = pg_malloc(strlen(name) + 11);
9809                 sprintf(oname, "OPERATOR(%s)", name);
9810                 free(name);
9811                 return oname;
9812         }
9813
9814         oprInfo = findOprByOid(atooid(opr));
9815         if (oprInfo == NULL)
9816         {
9817                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9818                                   opr);
9819                 return NULL;
9820         }
9821         return oprInfo->dobj.name;
9822 }
9823
9824 /*
9825  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9826  *
9827  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9828  * argument lists of these functions are predetermined.  Note that the
9829  * caller should ensure we are in the proper schema, because the results
9830  * are search path dependent!
9831  */
9832 static const char *
9833 convertTSFunction(Archive *fout, Oid funcOid)
9834 {
9835         char       *result;
9836         char            query[128];
9837         PGresult   *res;
9838
9839         snprintf(query, sizeof(query),
9840                          "SELECT '%u'::pg_catalog.regproc", funcOid);
9841         res = ExecuteSqlQueryForSingleRow(fout, query);
9842
9843         result = pg_strdup(PQgetvalue(res, 0, 0));
9844
9845         PQclear(res);
9846
9847         return result;
9848 }
9849
9850
9851 /*
9852  * dumpOpclass
9853  *        write out a single operator class definition
9854  */
9855 static void
9856 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9857 {
9858         PQExpBuffer query;
9859         PQExpBuffer q;
9860         PQExpBuffer delq;
9861         PQExpBuffer labelq;
9862         PGresult   *res;
9863         int                     ntups;
9864         int                     i_opcintype;
9865         int                     i_opckeytype;
9866         int                     i_opcdefault;
9867         int                     i_opcfamily;
9868         int                     i_opcfamilyname;
9869         int                     i_opcfamilynsp;
9870         int                     i_amname;
9871         int                     i_amopstrategy;
9872         int                     i_amopreqcheck;
9873         int                     i_amopopr;
9874         int                     i_sortfamily;
9875         int                     i_sortfamilynsp;
9876         int                     i_amprocnum;
9877         int                     i_amproc;
9878         int                     i_amproclefttype;
9879         int                     i_amprocrighttype;
9880         char       *opcintype;
9881         char       *opckeytype;
9882         char       *opcdefault;
9883         char       *opcfamily;
9884         char       *opcfamilyname;
9885         char       *opcfamilynsp;
9886         char       *amname;
9887         char       *amopstrategy;
9888         char       *amopreqcheck;
9889         char       *amopopr;
9890         char       *sortfamily;
9891         char       *sortfamilynsp;
9892         char       *amprocnum;
9893         char       *amproc;
9894         char       *amproclefttype;
9895         char       *amprocrighttype;
9896         bool            needComma;
9897         int                     i;
9898
9899         /* Skip if not to be dumped */
9900         if (!opcinfo->dobj.dump || dataOnly)
9901                 return;
9902
9903         /*
9904          * XXX currently we do not implement dumping of operator classes from
9905          * pre-7.3 databases.  This could be done but it seems not worth the
9906          * trouble.
9907          */
9908         if (fout->remoteVersion < 70300)
9909                 return;
9910
9911         query = createPQExpBuffer();
9912         q = createPQExpBuffer();
9913         delq = createPQExpBuffer();
9914         labelq = createPQExpBuffer();
9915
9916         /* Make sure we are in proper schema so regoperator works correctly */
9917         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9918
9919         /* Get additional fields from the pg_opclass row */
9920         if (fout->remoteVersion >= 80300)
9921         {
9922                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9923                                                   "opckeytype::pg_catalog.regtype, "
9924                                                   "opcdefault, opcfamily, "
9925                                                   "opfname AS opcfamilyname, "
9926                                                   "nspname AS opcfamilynsp, "
9927                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9928                                                   "FROM pg_catalog.pg_opclass c "
9929                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9930                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9931                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
9932                                                   opcinfo->dobj.catId.oid);
9933         }
9934         else
9935         {
9936                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9937                                                   "opckeytype::pg_catalog.regtype, "
9938                                                   "opcdefault, NULL AS opcfamily, "
9939                                                   "NULL AS opcfamilyname, "
9940                                                   "NULL AS opcfamilynsp, "
9941                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9942                                                   "FROM pg_catalog.pg_opclass "
9943                                                   "WHERE oid = '%u'::pg_catalog.oid",
9944                                                   opcinfo->dobj.catId.oid);
9945         }
9946
9947         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9948
9949         i_opcintype = PQfnumber(res, "opcintype");
9950         i_opckeytype = PQfnumber(res, "opckeytype");
9951         i_opcdefault = PQfnumber(res, "opcdefault");
9952         i_opcfamily = PQfnumber(res, "opcfamily");
9953         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9954         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9955         i_amname = PQfnumber(res, "amname");
9956
9957         opcintype = PQgetvalue(res, 0, i_opcintype);
9958         opckeytype = PQgetvalue(res, 0, i_opckeytype);
9959         opcdefault = PQgetvalue(res, 0, i_opcdefault);
9960         /* opcfamily will still be needed after we PQclear res */
9961         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9962         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9963         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
9964         /* amname will still be needed after we PQclear res */
9965         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
9966
9967         /*
9968          * DROP must be fully qualified in case same name appears in pg_catalog
9969          */
9970         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
9971                                           fmtId(opcinfo->dobj.namespace->dobj.name));
9972         appendPQExpBuffer(delq, ".%s",
9973                                           fmtId(opcinfo->dobj.name));
9974         appendPQExpBuffer(delq, " USING %s;\n",
9975                                           fmtId(amname));
9976
9977         /* Build the fixed portion of the CREATE command */
9978         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
9979                                           fmtId(opcinfo->dobj.name));
9980         if (strcmp(opcdefault, "t") == 0)
9981                 appendPQExpBuffer(q, "DEFAULT ");
9982         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
9983                                           opcintype,
9984                                           fmtId(amname));
9985         if (strlen(opcfamilyname) > 0 &&
9986                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
9987                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
9988         {
9989                 appendPQExpBuffer(q, " FAMILY ");
9990                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
9991                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
9992                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
9993         }
9994         appendPQExpBuffer(q, " AS\n    ");
9995
9996         needComma = false;
9997
9998         if (strcmp(opckeytype, "-") != 0)
9999         {
10000                 appendPQExpBuffer(q, "STORAGE %s",
10001                                                   opckeytype);
10002                 needComma = true;
10003         }
10004
10005         PQclear(res);
10006
10007         /*
10008          * Now fetch and print the OPERATOR entries (pg_amop rows).
10009          *
10010          * Print only those opfamily members that are tied to the opclass by
10011          * pg_depend entries.
10012          *
10013          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10014          * older server's opclass in which it is used.  This is to avoid
10015          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10016          * older server and then reload into that old version.  This can go away
10017          * once 8.3 is so old as to not be of interest to anyone.
10018          */
10019         resetPQExpBuffer(query);
10020
10021         if (fout->remoteVersion >= 90100)
10022         {
10023                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10024                                                   "amopopr::pg_catalog.regoperator, "
10025                                                   "opfname AS sortfamily, "
10026                                                   "nspname AS sortfamilynsp "
10027                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10028                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10029                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10030                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10031                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10032                                                   "AND refobjid = '%u'::pg_catalog.oid "
10033                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10034                                                   "ORDER BY amopstrategy",
10035                                                   opcinfo->dobj.catId.oid,
10036                                                   opcfamily);
10037         }
10038         else if (fout->remoteVersion >= 80400)
10039         {
10040                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10041                                                   "amopopr::pg_catalog.regoperator, "
10042                                                   "NULL AS sortfamily, "
10043                                                   "NULL AS sortfamilynsp "
10044                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10045                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10046                                                   "AND refobjid = '%u'::pg_catalog.oid "
10047                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10048                                                   "AND objid = ao.oid "
10049                                                   "ORDER BY amopstrategy",
10050                                                   opcinfo->dobj.catId.oid);
10051         }
10052         else if (fout->remoteVersion >= 80300)
10053         {
10054                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10055                                                   "amopopr::pg_catalog.regoperator, "
10056                                                   "NULL AS sortfamily, "
10057                                                   "NULL AS sortfamilynsp "
10058                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10059                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10060                                                   "AND refobjid = '%u'::pg_catalog.oid "
10061                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10062                                                   "AND objid = ao.oid "
10063                                                   "ORDER BY amopstrategy",
10064                                                   opcinfo->dobj.catId.oid);
10065         }
10066         else
10067         {
10068                 /*
10069                  * Here, we print all entries since there are no opfamilies and hence
10070                  * no loose operators to worry about.
10071                  */
10072                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10073                                                   "amopopr::pg_catalog.regoperator, "
10074                                                   "NULL AS sortfamily, "
10075                                                   "NULL AS sortfamilynsp "
10076                                                   "FROM pg_catalog.pg_amop "
10077                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10078                                                   "ORDER BY amopstrategy",
10079                                                   opcinfo->dobj.catId.oid);
10080         }
10081
10082         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10083
10084         ntups = PQntuples(res);
10085
10086         i_amopstrategy = PQfnumber(res, "amopstrategy");
10087         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10088         i_amopopr = PQfnumber(res, "amopopr");
10089         i_sortfamily = PQfnumber(res, "sortfamily");
10090         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10091
10092         for (i = 0; i < ntups; i++)
10093         {
10094                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10095                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10096                 amopopr = PQgetvalue(res, i, i_amopopr);
10097                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10098                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10099
10100                 if (needComma)
10101                         appendPQExpBuffer(q, " ,\n    ");
10102
10103                 appendPQExpBuffer(q, "OPERATOR %s %s",
10104                                                   amopstrategy, amopopr);
10105
10106                 if (strlen(sortfamily) > 0)
10107                 {
10108                         appendPQExpBuffer(q, " FOR ORDER BY ");
10109                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10110                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10111                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10112                 }
10113
10114                 if (strcmp(amopreqcheck, "t") == 0)
10115                         appendPQExpBuffer(q, " RECHECK");
10116
10117                 needComma = true;
10118         }
10119
10120         PQclear(res);
10121
10122         /*
10123          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10124          *
10125          * Print only those opfamily members that are tied to the opclass by
10126          * pg_depend entries.
10127          *
10128          * We print the amproclefttype/amprocrighttype even though in most cases
10129          * the backend could deduce the right values, because of the corner case
10130          * of a btree sort support function for a cross-type comparison.  That's
10131          * only allowed in 9.2 and later, but for simplicity print them in all
10132          * versions that have the columns.
10133          */
10134         resetPQExpBuffer(query);
10135
10136         if (fout->remoteVersion >= 80300)
10137         {
10138                 appendPQExpBuffer(query, "SELECT amprocnum, "
10139                                                   "amproc::pg_catalog.regprocedure, "
10140                                                   "amproclefttype::pg_catalog.regtype, "
10141                                                   "amprocrighttype::pg_catalog.regtype "
10142                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10143                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10144                                                   "AND refobjid = '%u'::pg_catalog.oid "
10145                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10146                                                   "AND objid = ap.oid "
10147                                                   "ORDER BY amprocnum",
10148                                                   opcinfo->dobj.catId.oid);
10149         }
10150         else
10151         {
10152                 appendPQExpBuffer(query, "SELECT amprocnum, "
10153                                                   "amproc::pg_catalog.regprocedure, "
10154                                                   "'' AS amproclefttype, "
10155                                                   "'' AS amprocrighttype "
10156                                                   "FROM pg_catalog.pg_amproc "
10157                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10158                                                   "ORDER BY amprocnum",
10159                                                   opcinfo->dobj.catId.oid);
10160         }
10161
10162         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10163
10164         ntups = PQntuples(res);
10165
10166         i_amprocnum = PQfnumber(res, "amprocnum");
10167         i_amproc = PQfnumber(res, "amproc");
10168         i_amproclefttype = PQfnumber(res, "amproclefttype");
10169         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10170
10171         for (i = 0; i < ntups; i++)
10172         {
10173                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10174                 amproc = PQgetvalue(res, i, i_amproc);
10175                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10176                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10177
10178                 if (needComma)
10179                         appendPQExpBuffer(q, " ,\n    ");
10180
10181                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10182
10183                 if (*amproclefttype && *amprocrighttype)
10184                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10185
10186                 appendPQExpBuffer(q, " %s", amproc);
10187
10188                 needComma = true;
10189         }
10190
10191         PQclear(res);
10192
10193         appendPQExpBuffer(q, ";\n");
10194
10195         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10196                                           fmtId(opcinfo->dobj.name));
10197         appendPQExpBuffer(labelq, " USING %s",
10198                                           fmtId(amname));
10199
10200         if (binary_upgrade)
10201                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10202
10203         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10204                                  opcinfo->dobj.name,
10205                                  opcinfo->dobj.namespace->dobj.name,
10206                                  NULL,
10207                                  opcinfo->rolname,
10208                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10209                                  q->data, delq->data, NULL,
10210                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10211                                  NULL, NULL);
10212
10213         /* Dump Operator Class Comments */
10214         dumpComment(fout, labelq->data,
10215                                 NULL, opcinfo->rolname,
10216                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10217
10218         free(amname);
10219         destroyPQExpBuffer(query);
10220         destroyPQExpBuffer(q);
10221         destroyPQExpBuffer(delq);
10222         destroyPQExpBuffer(labelq);
10223 }
10224
10225 /*
10226  * dumpOpfamily
10227  *        write out a single operator family definition
10228  *
10229  * Note: this also dumps any "loose" operator members that aren't bound to a
10230  * specific opclass within the opfamily.
10231  */
10232 static void
10233 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10234 {
10235         PQExpBuffer query;
10236         PQExpBuffer q;
10237         PQExpBuffer delq;
10238         PQExpBuffer labelq;
10239         PGresult   *res;
10240         PGresult   *res_ops;
10241         PGresult   *res_procs;
10242         int                     ntups;
10243         int                     i_amname;
10244         int                     i_amopstrategy;
10245         int                     i_amopreqcheck;
10246         int                     i_amopopr;
10247         int                     i_sortfamily;
10248         int                     i_sortfamilynsp;
10249         int                     i_amprocnum;
10250         int                     i_amproc;
10251         int                     i_amproclefttype;
10252         int                     i_amprocrighttype;
10253         char       *amname;
10254         char       *amopstrategy;
10255         char       *amopreqcheck;
10256         char       *amopopr;
10257         char       *sortfamily;
10258         char       *sortfamilynsp;
10259         char       *amprocnum;
10260         char       *amproc;
10261         char       *amproclefttype;
10262         char       *amprocrighttype;
10263         bool            needComma;
10264         int                     i;
10265
10266         /* Skip if not to be dumped */
10267         if (!opfinfo->dobj.dump || dataOnly)
10268                 return;
10269
10270         /*
10271          * We want to dump the opfamily only if (1) it contains "loose" operators
10272          * or functions, or (2) it contains an opclass with a different name or
10273          * owner.  Otherwise it's sufficient to let it be created during creation
10274          * of the contained opclass, and not dumping it improves portability of
10275          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10276          * that first.
10277          */
10278
10279         query = createPQExpBuffer();
10280         q = createPQExpBuffer();
10281         delq = createPQExpBuffer();
10282         labelq = createPQExpBuffer();
10283
10284         /* Make sure we are in proper schema so regoperator works correctly */
10285         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10286
10287         /*
10288          * Fetch only those opfamily members that are tied directly to the
10289          * opfamily by pg_depend entries.
10290          *
10291          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10292          * older server's opclass in which it is used.  This is to avoid
10293          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10294          * older server and then reload into that old version.  This can go away
10295          * once 8.3 is so old as to not be of interest to anyone.
10296          */
10297         if (fout->remoteVersion >= 90100)
10298         {
10299                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10300                                                   "amopopr::pg_catalog.regoperator, "
10301                                                   "opfname AS sortfamily, "
10302                                                   "nspname AS sortfamilynsp "
10303                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10304                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10305                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10306                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10307                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10308                                                   "AND refobjid = '%u'::pg_catalog.oid "
10309                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10310                                                   "ORDER BY amopstrategy",
10311                                                   opfinfo->dobj.catId.oid,
10312                                                   opfinfo->dobj.catId.oid);
10313         }
10314         else if (fout->remoteVersion >= 80400)
10315         {
10316                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10317                                                   "amopopr::pg_catalog.regoperator, "
10318                                                   "NULL AS sortfamily, "
10319                                                   "NULL AS sortfamilynsp "
10320                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10321                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10322                                                   "AND refobjid = '%u'::pg_catalog.oid "
10323                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10324                                                   "AND objid = ao.oid "
10325                                                   "ORDER BY amopstrategy",
10326                                                   opfinfo->dobj.catId.oid);
10327         }
10328         else
10329         {
10330                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10331                                                   "amopopr::pg_catalog.regoperator, "
10332                                                   "NULL AS sortfamily, "
10333                                                   "NULL AS sortfamilynsp "
10334                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10335                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10336                                                   "AND refobjid = '%u'::pg_catalog.oid "
10337                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10338                                                   "AND objid = ao.oid "
10339                                                   "ORDER BY amopstrategy",
10340                                                   opfinfo->dobj.catId.oid);
10341         }
10342
10343         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10344
10345         resetPQExpBuffer(query);
10346
10347         appendPQExpBuffer(query, "SELECT amprocnum, "
10348                                           "amproc::pg_catalog.regprocedure, "
10349                                           "amproclefttype::pg_catalog.regtype, "
10350                                           "amprocrighttype::pg_catalog.regtype "
10351                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10352                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10353                                           "AND refobjid = '%u'::pg_catalog.oid "
10354                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10355                                           "AND objid = ap.oid "
10356                                           "ORDER BY amprocnum",
10357                                           opfinfo->dobj.catId.oid);
10358
10359         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10360
10361         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10362         {
10363                 /* No loose members, so check contained opclasses */
10364                 resetPQExpBuffer(query);
10365
10366                 appendPQExpBuffer(query, "SELECT 1 "
10367                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10368                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10369                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10370                                                   "AND refobjid = f.oid "
10371                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10372                                                   "AND objid = c.oid "
10373                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10374                                                   "LIMIT 1",
10375                                                   opfinfo->dobj.catId.oid);
10376
10377                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10378
10379                 if (PQntuples(res) == 0)
10380                 {
10381                         /* no need to dump it, so bail out */
10382                         PQclear(res);
10383                         PQclear(res_ops);
10384                         PQclear(res_procs);
10385                         destroyPQExpBuffer(query);
10386                         destroyPQExpBuffer(q);
10387                         destroyPQExpBuffer(delq);
10388                         destroyPQExpBuffer(labelq);
10389                         return;
10390                 }
10391
10392                 PQclear(res);
10393         }
10394
10395         /* Get additional fields from the pg_opfamily row */
10396         resetPQExpBuffer(query);
10397
10398         appendPQExpBuffer(query, "SELECT "
10399          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10400                                           "FROM pg_catalog.pg_opfamily "
10401                                           "WHERE oid = '%u'::pg_catalog.oid",
10402                                           opfinfo->dobj.catId.oid);
10403
10404         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10405
10406         i_amname = PQfnumber(res, "amname");
10407
10408         /* amname will still be needed after we PQclear res */
10409         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10410
10411         /*
10412          * DROP must be fully qualified in case same name appears in pg_catalog
10413          */
10414         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10415                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10416         appendPQExpBuffer(delq, ".%s",
10417                                           fmtId(opfinfo->dobj.name));
10418         appendPQExpBuffer(delq, " USING %s;\n",
10419                                           fmtId(amname));
10420
10421         /* Build the fixed portion of the CREATE command */
10422         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10423                                           fmtId(opfinfo->dobj.name));
10424         appendPQExpBuffer(q, " USING %s;\n",
10425                                           fmtId(amname));
10426
10427         PQclear(res);
10428
10429         /* Do we need an ALTER to add loose members? */
10430         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10431         {
10432                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10433                                                   fmtId(opfinfo->dobj.name));
10434                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10435                                                   fmtId(amname));
10436
10437                 needComma = false;
10438
10439                 /*
10440                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10441                  */
10442                 ntups = PQntuples(res_ops);
10443
10444                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10445                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10446                 i_amopopr = PQfnumber(res_ops, "amopopr");
10447                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10448                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10449
10450                 for (i = 0; i < ntups; i++)
10451                 {
10452                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10453                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10454                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10455                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10456                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10457
10458                         if (needComma)
10459                                 appendPQExpBuffer(q, " ,\n    ");
10460
10461                         appendPQExpBuffer(q, "OPERATOR %s %s",
10462                                                           amopstrategy, amopopr);
10463
10464                         if (strlen(sortfamily) > 0)
10465                         {
10466                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10467                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10468                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10469                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10470                         }
10471
10472                         if (strcmp(amopreqcheck, "t") == 0)
10473                                 appendPQExpBuffer(q, " RECHECK");
10474
10475                         needComma = true;
10476                 }
10477
10478                 /*
10479                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10480                  */
10481                 ntups = PQntuples(res_procs);
10482
10483                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10484                 i_amproc = PQfnumber(res_procs, "amproc");
10485                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10486                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10487
10488                 for (i = 0; i < ntups; i++)
10489                 {
10490                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10491                         amproc = PQgetvalue(res_procs, i, i_amproc);
10492                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10493                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10494
10495                         if (needComma)
10496                                 appendPQExpBuffer(q, " ,\n    ");
10497
10498                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10499                                                           amprocnum, amproclefttype, amprocrighttype,
10500                                                           amproc);
10501
10502                         needComma = true;
10503                 }
10504
10505                 appendPQExpBuffer(q, ";\n");
10506         }
10507
10508         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10509                                           fmtId(opfinfo->dobj.name));
10510         appendPQExpBuffer(labelq, " USING %s",
10511                                           fmtId(amname));
10512
10513         if (binary_upgrade)
10514                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10515
10516         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10517                                  opfinfo->dobj.name,
10518                                  opfinfo->dobj.namespace->dobj.name,
10519                                  NULL,
10520                                  opfinfo->rolname,
10521                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10522                                  q->data, delq->data, NULL,
10523                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10524                                  NULL, NULL);
10525
10526         /* Dump Operator Family Comments */
10527         dumpComment(fout, labelq->data,
10528                                 NULL, opfinfo->rolname,
10529                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10530
10531         free(amname);
10532         PQclear(res_ops);
10533         PQclear(res_procs);
10534         destroyPQExpBuffer(query);
10535         destroyPQExpBuffer(q);
10536         destroyPQExpBuffer(delq);
10537         destroyPQExpBuffer(labelq);
10538 }
10539
10540 /*
10541  * dumpCollation
10542  *        write out a single collation definition
10543  */
10544 static void
10545 dumpCollation(Archive *fout, CollInfo *collinfo)
10546 {
10547         PQExpBuffer query;
10548         PQExpBuffer q;
10549         PQExpBuffer delq;
10550         PQExpBuffer labelq;
10551         PGresult   *res;
10552         int                     i_collcollate;
10553         int                     i_collctype;
10554         const char *collcollate;
10555         const char *collctype;
10556
10557         /* Skip if not to be dumped */
10558         if (!collinfo->dobj.dump || dataOnly)
10559                 return;
10560
10561         query = createPQExpBuffer();
10562         q = createPQExpBuffer();
10563         delq = createPQExpBuffer();
10564         labelq = createPQExpBuffer();
10565
10566         /* Make sure we are in proper schema */
10567         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10568
10569         /* Get conversion-specific details */
10570         appendPQExpBuffer(query, "SELECT "
10571                                           "collcollate, "
10572                                           "collctype "
10573                                           "FROM pg_catalog.pg_collation c "
10574                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10575                                           collinfo->dobj.catId.oid);
10576
10577         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10578
10579         i_collcollate = PQfnumber(res, "collcollate");
10580         i_collctype = PQfnumber(res, "collctype");
10581
10582         collcollate = PQgetvalue(res, 0, i_collcollate);
10583         collctype = PQgetvalue(res, 0, i_collctype);
10584
10585         /*
10586          * DROP must be fully qualified in case same name appears in pg_catalog
10587          */
10588         appendPQExpBuffer(delq, "DROP COLLATION %s",
10589                                           fmtId(collinfo->dobj.namespace->dobj.name));
10590         appendPQExpBuffer(delq, ".%s;\n",
10591                                           fmtId(collinfo->dobj.name));
10592
10593         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10594                                           fmtId(collinfo->dobj.name));
10595         appendStringLiteralAH(q, collcollate, fout);
10596         appendPQExpBuffer(q, ", lc_ctype = ");
10597         appendStringLiteralAH(q, collctype, fout);
10598         appendPQExpBuffer(q, ");\n");
10599
10600         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10601
10602         if (binary_upgrade)
10603                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10604
10605         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10606                                  collinfo->dobj.name,
10607                                  collinfo->dobj.namespace->dobj.name,
10608                                  NULL,
10609                                  collinfo->rolname,
10610                                  false, "COLLATION", SECTION_PRE_DATA,
10611                                  q->data, delq->data, NULL,
10612                                  collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10613                                  NULL, NULL);
10614
10615         /* Dump Collation Comments */
10616         dumpComment(fout, labelq->data,
10617                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10618                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10619
10620         PQclear(res);
10621
10622         destroyPQExpBuffer(query);
10623         destroyPQExpBuffer(q);
10624         destroyPQExpBuffer(delq);
10625         destroyPQExpBuffer(labelq);
10626 }
10627
10628 /*
10629  * dumpConversion
10630  *        write out a single conversion definition
10631  */
10632 static void
10633 dumpConversion(Archive *fout, ConvInfo *convinfo)
10634 {
10635         PQExpBuffer query;
10636         PQExpBuffer q;
10637         PQExpBuffer delq;
10638         PQExpBuffer labelq;
10639         PGresult   *res;
10640         int                     i_conforencoding;
10641         int                     i_contoencoding;
10642         int                     i_conproc;
10643         int                     i_condefault;
10644         const char *conforencoding;
10645         const char *contoencoding;
10646         const char *conproc;
10647         bool            condefault;
10648
10649         /* Skip if not to be dumped */
10650         if (!convinfo->dobj.dump || dataOnly)
10651                 return;
10652
10653         query = createPQExpBuffer();
10654         q = createPQExpBuffer();
10655         delq = createPQExpBuffer();
10656         labelq = createPQExpBuffer();
10657
10658         /* Make sure we are in proper schema */
10659         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10660
10661         /* Get conversion-specific details */
10662         appendPQExpBuffer(query, "SELECT "
10663                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10664                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10665                                           "conproc, condefault "
10666                                           "FROM pg_catalog.pg_conversion c "
10667                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10668                                           convinfo->dobj.catId.oid);
10669
10670         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10671
10672         i_conforencoding = PQfnumber(res, "conforencoding");
10673         i_contoencoding = PQfnumber(res, "contoencoding");
10674         i_conproc = PQfnumber(res, "conproc");
10675         i_condefault = PQfnumber(res, "condefault");
10676
10677         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10678         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10679         conproc = PQgetvalue(res, 0, i_conproc);
10680         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10681
10682         /*
10683          * DROP must be fully qualified in case same name appears in pg_catalog
10684          */
10685         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10686                                           fmtId(convinfo->dobj.namespace->dobj.name));
10687         appendPQExpBuffer(delq, ".%s;\n",
10688                                           fmtId(convinfo->dobj.name));
10689
10690         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10691                                           (condefault) ? "DEFAULT " : "",
10692                                           fmtId(convinfo->dobj.name));
10693         appendStringLiteralAH(q, conforencoding, fout);
10694         appendPQExpBuffer(q, " TO ");
10695         appendStringLiteralAH(q, contoencoding, fout);
10696         /* regproc is automatically quoted in 7.3 and above */
10697         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10698
10699         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10700
10701         if (binary_upgrade)
10702                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10703
10704         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10705                                  convinfo->dobj.name,
10706                                  convinfo->dobj.namespace->dobj.name,
10707                                  NULL,
10708                                  convinfo->rolname,
10709                                  false, "CONVERSION", SECTION_PRE_DATA,
10710                                  q->data, delq->data, NULL,
10711                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10712                                  NULL, NULL);
10713
10714         /* Dump Conversion Comments */
10715         dumpComment(fout, labelq->data,
10716                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10717                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10718
10719         PQclear(res);
10720
10721         destroyPQExpBuffer(query);
10722         destroyPQExpBuffer(q);
10723         destroyPQExpBuffer(delq);
10724         destroyPQExpBuffer(labelq);
10725 }
10726
10727 /*
10728  * format_aggregate_signature: generate aggregate name and argument list
10729  *
10730  * The argument type names are qualified if needed.  The aggregate name
10731  * is never qualified.
10732  */
10733 static char *
10734 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10735 {
10736         PQExpBufferData buf;
10737         int                     j;
10738
10739         initPQExpBuffer(&buf);
10740         if (honor_quotes)
10741                 appendPQExpBuffer(&buf, "%s",
10742                                                   fmtId(agginfo->aggfn.dobj.name));
10743         else
10744                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10745
10746         if (agginfo->aggfn.nargs == 0)
10747                 appendPQExpBuffer(&buf, "(*)");
10748         else
10749         {
10750                 appendPQExpBuffer(&buf, "(");
10751                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10752                 {
10753                         char       *typname;
10754
10755                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10756                                                                                    zeroAsOpaque);
10757
10758                         appendPQExpBuffer(&buf, "%s%s",
10759                                                           (j > 0) ? ", " : "",
10760                                                           typname);
10761                         free(typname);
10762                 }
10763                 appendPQExpBuffer(&buf, ")");
10764         }
10765         return buf.data;
10766 }
10767
10768 /*
10769  * dumpAgg
10770  *        write out a single aggregate definition
10771  */
10772 static void
10773 dumpAgg(Archive *fout, AggInfo *agginfo)
10774 {
10775         PQExpBuffer query;
10776         PQExpBuffer q;
10777         PQExpBuffer delq;
10778         PQExpBuffer labelq;
10779         PQExpBuffer details;
10780         char       *aggsig;
10781         char       *aggsig_tag;
10782         PGresult   *res;
10783         int                     i_aggtransfn;
10784         int                     i_aggfinalfn;
10785         int                     i_aggsortop;
10786         int                     i_aggtranstype;
10787         int                     i_agginitval;
10788         int                     i_convertok;
10789         const char *aggtransfn;
10790         const char *aggfinalfn;
10791         const char *aggsortop;
10792         const char *aggtranstype;
10793         const char *agginitval;
10794         bool            convertok;
10795
10796         /* Skip if not to be dumped */
10797         if (!agginfo->aggfn.dobj.dump || dataOnly)
10798                 return;
10799
10800         query = createPQExpBuffer();
10801         q = createPQExpBuffer();
10802         delq = createPQExpBuffer();
10803         labelq = createPQExpBuffer();
10804         details = createPQExpBuffer();
10805
10806         /* Make sure we are in proper schema */
10807         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10808
10809         /* Get aggregate-specific details */
10810         if (fout->remoteVersion >= 80100)
10811         {
10812                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10813                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10814                                                   "aggsortop::pg_catalog.regoperator, "
10815                                                   "agginitval, "
10816                                                   "'t'::boolean AS convertok "
10817                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10818                                                   "WHERE a.aggfnoid = p.oid "
10819                                                   "AND p.oid = '%u'::pg_catalog.oid",
10820                                                   agginfo->aggfn.dobj.catId.oid);
10821         }
10822         else if (fout->remoteVersion >= 70300)
10823         {
10824                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10825                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10826                                                   "0 AS aggsortop, "
10827                                                   "agginitval, "
10828                                                   "'t'::boolean AS convertok "
10829                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10830                                                   "WHERE a.aggfnoid = p.oid "
10831                                                   "AND p.oid = '%u'::pg_catalog.oid",
10832                                                   agginfo->aggfn.dobj.catId.oid);
10833         }
10834         else if (fout->remoteVersion >= 70100)
10835         {
10836                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10837                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
10838                                                   "0 AS aggsortop, "
10839                                                   "agginitval, "
10840                                                   "'t'::boolean AS convertok "
10841                                                   "FROM pg_aggregate "
10842                                                   "WHERE oid = '%u'::oid",
10843                                                   agginfo->aggfn.dobj.catId.oid);
10844         }
10845         else
10846         {
10847                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10848                                                   "aggfinalfn, "
10849                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10850                                                   "0 AS aggsortop, "
10851                                                   "agginitval1 AS agginitval, "
10852                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10853                                                   "FROM pg_aggregate "
10854                                                   "WHERE oid = '%u'::oid",
10855                                                   agginfo->aggfn.dobj.catId.oid);
10856         }
10857
10858         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10859
10860         i_aggtransfn = PQfnumber(res, "aggtransfn");
10861         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10862         i_aggsortop = PQfnumber(res, "aggsortop");
10863         i_aggtranstype = PQfnumber(res, "aggtranstype");
10864         i_agginitval = PQfnumber(res, "agginitval");
10865         i_convertok = PQfnumber(res, "convertok");
10866
10867         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10868         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10869         aggsortop = PQgetvalue(res, 0, i_aggsortop);
10870         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10871         agginitval = PQgetvalue(res, 0, i_agginitval);
10872         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10873
10874         aggsig = format_aggregate_signature(agginfo, fout, true);
10875         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10876
10877         if (!convertok)
10878         {
10879                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10880                                   aggsig);
10881                 return;
10882         }
10883
10884         if (fout->remoteVersion >= 70300)
10885         {
10886                 /* If using 7.3's regproc or regtype, data is already quoted */
10887                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10888                                                   aggtransfn,
10889                                                   aggtranstype);
10890         }
10891         else if (fout->remoteVersion >= 70100)
10892         {
10893                 /* format_type quotes, regproc does not */
10894                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10895                                                   fmtId(aggtransfn),
10896                                                   aggtranstype);
10897         }
10898         else
10899         {
10900                 /* need quotes all around */
10901                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
10902                                                   fmtId(aggtransfn));
10903                 appendPQExpBuffer(details, "    STYPE = %s",
10904                                                   fmtId(aggtranstype));
10905         }
10906
10907         if (!PQgetisnull(res, 0, i_agginitval))
10908         {
10909                 appendPQExpBuffer(details, ",\n    INITCOND = ");
10910                 appendStringLiteralAH(details, agginitval, fout);
10911         }
10912
10913         if (strcmp(aggfinalfn, "-") != 0)
10914         {
10915                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
10916                                                   aggfinalfn);
10917         }
10918
10919         aggsortop = convertOperatorReference(fout, aggsortop);
10920         if (aggsortop)
10921         {
10922                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
10923                                                   aggsortop);
10924         }
10925
10926         /*
10927          * DROP must be fully qualified in case same name appears in pg_catalog
10928          */
10929         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10930                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10931                                           aggsig);
10932
10933         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10934                                           aggsig, details->data);
10935
10936         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10937
10938         if (binary_upgrade)
10939                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10940
10941         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10942                                  aggsig_tag,
10943                                  agginfo->aggfn.dobj.namespace->dobj.name,
10944                                  NULL,
10945                                  agginfo->aggfn.rolname,
10946                                  false, "AGGREGATE", SECTION_PRE_DATA,
10947                                  q->data, delq->data, NULL,
10948                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10949                                  NULL, NULL);
10950
10951         /* Dump Aggregate Comments */
10952         dumpComment(fout, labelq->data,
10953                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10954                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10955         dumpSecLabel(fout, labelq->data,
10956                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10957                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10958
10959         /*
10960          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10961          * command look like a function's GRANT; in particular this affects the
10962          * syntax for zero-argument aggregates.
10963          */
10964         free(aggsig);
10965         free(aggsig_tag);
10966
10967         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
10968         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
10969
10970         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10971                         "FUNCTION",
10972                         aggsig, NULL, aggsig_tag,
10973                         agginfo->aggfn.dobj.namespace->dobj.name,
10974                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
10975
10976         free(aggsig);
10977         free(aggsig_tag);
10978
10979         PQclear(res);
10980
10981         destroyPQExpBuffer(query);
10982         destroyPQExpBuffer(q);
10983         destroyPQExpBuffer(delq);
10984         destroyPQExpBuffer(labelq);
10985         destroyPQExpBuffer(details);
10986 }
10987
10988 /*
10989  * dumpTSParser
10990  *        write out a single text search parser
10991  */
10992 static void
10993 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
10994 {
10995         PQExpBuffer q;
10996         PQExpBuffer delq;
10997         PQExpBuffer labelq;
10998
10999         /* Skip if not to be dumped */
11000         if (!prsinfo->dobj.dump || dataOnly)
11001                 return;
11002
11003         q = createPQExpBuffer();
11004         delq = createPQExpBuffer();
11005         labelq = createPQExpBuffer();
11006
11007         /* Make sure we are in proper schema */
11008         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11009
11010         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11011                                           fmtId(prsinfo->dobj.name));
11012
11013         appendPQExpBuffer(q, "    START = %s,\n",
11014                                           convertTSFunction(fout, prsinfo->prsstart));
11015         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11016                                           convertTSFunction(fout, prsinfo->prstoken));
11017         appendPQExpBuffer(q, "    END = %s,\n",
11018                                           convertTSFunction(fout, prsinfo->prsend));
11019         if (prsinfo->prsheadline != InvalidOid)
11020                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11021                                                   convertTSFunction(fout, prsinfo->prsheadline));
11022         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11023                                           convertTSFunction(fout, prsinfo->prslextype));
11024
11025         /*
11026          * DROP must be fully qualified in case same name appears in pg_catalog
11027          */
11028         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11029                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11030         appendPQExpBuffer(delq, ".%s;\n",
11031                                           fmtId(prsinfo->dobj.name));
11032
11033         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11034                                           fmtId(prsinfo->dobj.name));
11035
11036         if (binary_upgrade)
11037                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11038
11039         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11040                                  prsinfo->dobj.name,
11041                                  prsinfo->dobj.namespace->dobj.name,
11042                                  NULL,
11043                                  "",
11044                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11045                                  q->data, delq->data, NULL,
11046                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11047                                  NULL, NULL);
11048
11049         /* Dump Parser Comments */
11050         dumpComment(fout, labelq->data,
11051                                 NULL, "",
11052                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11053
11054         destroyPQExpBuffer(q);
11055         destroyPQExpBuffer(delq);
11056         destroyPQExpBuffer(labelq);
11057 }
11058
11059 /*
11060  * dumpTSDictionary
11061  *        write out a single text search dictionary
11062  */
11063 static void
11064 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11065 {
11066         PQExpBuffer q;
11067         PQExpBuffer delq;
11068         PQExpBuffer labelq;
11069         PQExpBuffer query;
11070         PGresult   *res;
11071         char       *nspname;
11072         char       *tmplname;
11073
11074         /* Skip if not to be dumped */
11075         if (!dictinfo->dobj.dump || dataOnly)
11076                 return;
11077
11078         q = createPQExpBuffer();
11079         delq = createPQExpBuffer();
11080         labelq = createPQExpBuffer();
11081         query = createPQExpBuffer();
11082
11083         /* Fetch name and namespace of the dictionary's template */
11084         selectSourceSchema(fout, "pg_catalog");
11085         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11086                                           "FROM pg_ts_template p, pg_namespace n "
11087                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11088                                           dictinfo->dicttemplate);
11089         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11090         nspname = PQgetvalue(res, 0, 0);
11091         tmplname = PQgetvalue(res, 0, 1);
11092
11093         /* Make sure we are in proper schema */
11094         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11095
11096         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11097                                           fmtId(dictinfo->dobj.name));
11098
11099         appendPQExpBuffer(q, "    TEMPLATE = ");
11100         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11101                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11102         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11103
11104         PQclear(res);
11105
11106         /* the dictinitoption can be dumped straight into the command */
11107         if (dictinfo->dictinitoption)
11108                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11109
11110         appendPQExpBuffer(q, " );\n");
11111
11112         /*
11113          * DROP must be fully qualified in case same name appears in pg_catalog
11114          */
11115         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11116                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11117         appendPQExpBuffer(delq, ".%s;\n",
11118                                           fmtId(dictinfo->dobj.name));
11119
11120         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11121                                           fmtId(dictinfo->dobj.name));
11122
11123         if (binary_upgrade)
11124                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11125
11126         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11127                                  dictinfo->dobj.name,
11128                                  dictinfo->dobj.namespace->dobj.name,
11129                                  NULL,
11130                                  dictinfo->rolname,
11131                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11132                                  q->data, delq->data, NULL,
11133                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11134                                  NULL, NULL);
11135
11136         /* Dump Dictionary Comments */
11137         dumpComment(fout, labelq->data,
11138                                 NULL, dictinfo->rolname,
11139                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11140
11141         destroyPQExpBuffer(q);
11142         destroyPQExpBuffer(delq);
11143         destroyPQExpBuffer(labelq);
11144         destroyPQExpBuffer(query);
11145 }
11146
11147 /*
11148  * dumpTSTemplate
11149  *        write out a single text search template
11150  */
11151 static void
11152 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11153 {
11154         PQExpBuffer q;
11155         PQExpBuffer delq;
11156         PQExpBuffer labelq;
11157
11158         /* Skip if not to be dumped */
11159         if (!tmplinfo->dobj.dump || dataOnly)
11160                 return;
11161
11162         q = createPQExpBuffer();
11163         delq = createPQExpBuffer();
11164         labelq = createPQExpBuffer();
11165
11166         /* Make sure we are in proper schema */
11167         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11168
11169         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11170                                           fmtId(tmplinfo->dobj.name));
11171
11172         if (tmplinfo->tmplinit != InvalidOid)
11173                 appendPQExpBuffer(q, "    INIT = %s,\n",
11174                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11175         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11176                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11177
11178         /*
11179          * DROP must be fully qualified in case same name appears in pg_catalog
11180          */
11181         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11182                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11183         appendPQExpBuffer(delq, ".%s;\n",
11184                                           fmtId(tmplinfo->dobj.name));
11185
11186         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11187                                           fmtId(tmplinfo->dobj.name));
11188
11189         if (binary_upgrade)
11190                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11191
11192         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11193                                  tmplinfo->dobj.name,
11194                                  tmplinfo->dobj.namespace->dobj.name,
11195                                  NULL,
11196                                  "",
11197                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11198                                  q->data, delq->data, NULL,
11199                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11200                                  NULL, NULL);
11201
11202         /* Dump Template Comments */
11203         dumpComment(fout, labelq->data,
11204                                 NULL, "",
11205                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11206
11207         destroyPQExpBuffer(q);
11208         destroyPQExpBuffer(delq);
11209         destroyPQExpBuffer(labelq);
11210 }
11211
11212 /*
11213  * dumpTSConfig
11214  *        write out a single text search configuration
11215  */
11216 static void
11217 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11218 {
11219         PQExpBuffer q;
11220         PQExpBuffer delq;
11221         PQExpBuffer labelq;
11222         PQExpBuffer query;
11223         PGresult   *res;
11224         char       *nspname;
11225         char       *prsname;
11226         int                     ntups,
11227                                 i;
11228         int                     i_tokenname;
11229         int                     i_dictname;
11230
11231         /* Skip if not to be dumped */
11232         if (!cfginfo->dobj.dump || dataOnly)
11233                 return;
11234
11235         q = createPQExpBuffer();
11236         delq = createPQExpBuffer();
11237         labelq = createPQExpBuffer();
11238         query = createPQExpBuffer();
11239
11240         /* Fetch name and namespace of the config's parser */
11241         selectSourceSchema(fout, "pg_catalog");
11242         appendPQExpBuffer(query, "SELECT nspname, prsname "
11243                                           "FROM pg_ts_parser p, pg_namespace n "
11244                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11245                                           cfginfo->cfgparser);
11246         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11247         nspname = PQgetvalue(res, 0, 0);
11248         prsname = PQgetvalue(res, 0, 1);
11249
11250         /* Make sure we are in proper schema */
11251         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11252
11253         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11254                                           fmtId(cfginfo->dobj.name));
11255
11256         appendPQExpBuffer(q, "    PARSER = ");
11257         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11258                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11259         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11260
11261         PQclear(res);
11262
11263         resetPQExpBuffer(query);
11264         appendPQExpBuffer(query,
11265                                           "SELECT \n"
11266                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11267                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11268                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11269                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11270                                           "WHERE m.mapcfg = '%u' \n"
11271                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11272                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11273
11274         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11275         ntups = PQntuples(res);
11276
11277         i_tokenname = PQfnumber(res, "tokenname");
11278         i_dictname = PQfnumber(res, "dictname");
11279
11280         for (i = 0; i < ntups; i++)
11281         {
11282                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11283                 char       *dictname = PQgetvalue(res, i, i_dictname);
11284
11285                 if (i == 0 ||
11286                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11287                 {
11288                         /* starting a new token type, so start a new command */
11289                         if (i > 0)
11290                                 appendPQExpBuffer(q, ";\n");
11291                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11292                                                           fmtId(cfginfo->dobj.name));
11293                         /* tokenname needs quoting, dictname does NOT */
11294                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11295                                                           fmtId(tokenname), dictname);
11296                 }
11297                 else
11298                         appendPQExpBuffer(q, ", %s", dictname);
11299         }
11300
11301         if (ntups > 0)
11302                 appendPQExpBuffer(q, ";\n");
11303
11304         PQclear(res);
11305
11306         /*
11307          * DROP must be fully qualified in case same name appears in pg_catalog
11308          */
11309         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11310                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11311         appendPQExpBuffer(delq, ".%s;\n",
11312                                           fmtId(cfginfo->dobj.name));
11313
11314         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11315                                           fmtId(cfginfo->dobj.name));
11316
11317         if (binary_upgrade)
11318                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11319
11320         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11321                                  cfginfo->dobj.name,
11322                                  cfginfo->dobj.namespace->dobj.name,
11323                                  NULL,
11324                                  cfginfo->rolname,
11325                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11326                                  q->data, delq->data, NULL,
11327                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11328                                  NULL, NULL);
11329
11330         /* Dump Configuration Comments */
11331         dumpComment(fout, labelq->data,
11332                                 NULL, cfginfo->rolname,
11333                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11334
11335         destroyPQExpBuffer(q);
11336         destroyPQExpBuffer(delq);
11337         destroyPQExpBuffer(labelq);
11338         destroyPQExpBuffer(query);
11339 }
11340
11341 /*
11342  * dumpForeignDataWrapper
11343  *        write out a single foreign-data wrapper definition
11344  */
11345 static void
11346 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11347 {
11348         PQExpBuffer q;
11349         PQExpBuffer delq;
11350         PQExpBuffer labelq;
11351         char       *qfdwname;
11352
11353         /* Skip if not to be dumped */
11354         if (!fdwinfo->dobj.dump || dataOnly)
11355                 return;
11356
11357         /*
11358          * FDWs that belong to an extension are dumped based on their "dump"
11359          * field. Otherwise omit them if we are only dumping some specific object.
11360          */
11361         if (!fdwinfo->dobj.ext_member)
11362                 if (!include_everything)
11363                         return;
11364
11365         q = createPQExpBuffer();
11366         delq = createPQExpBuffer();
11367         labelq = createPQExpBuffer();
11368
11369         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11370
11371         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11372                                           qfdwname);
11373
11374         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11375                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11376
11377         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11378                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11379
11380         if (strlen(fdwinfo->fdwoptions) > 0)
11381                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11382
11383         appendPQExpBuffer(q, ";\n");
11384
11385         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11386                                           qfdwname);
11387
11388         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11389                                           qfdwname);
11390
11391         if (binary_upgrade)
11392                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11393
11394         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11395                                  fdwinfo->dobj.name,
11396                                  NULL,
11397                                  NULL,
11398                                  fdwinfo->rolname,
11399                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11400                                  q->data, delq->data, NULL,
11401                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11402                                  NULL, NULL);
11403
11404         /* Handle the ACL */
11405         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11406                         "FOREIGN DATA WRAPPER",
11407                         qfdwname, NULL, fdwinfo->dobj.name,
11408                         NULL, fdwinfo->rolname,
11409                         fdwinfo->fdwacl);
11410
11411         /* Dump Foreign Data Wrapper Comments */
11412         dumpComment(fout, labelq->data,
11413                                 NULL, fdwinfo->rolname,
11414                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11415
11416         free(qfdwname);
11417
11418         destroyPQExpBuffer(q);
11419         destroyPQExpBuffer(delq);
11420         destroyPQExpBuffer(labelq);
11421 }
11422
11423 /*
11424  * dumpForeignServer
11425  *        write out a foreign server definition
11426  */
11427 static void
11428 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11429 {
11430         PQExpBuffer q;
11431         PQExpBuffer delq;
11432         PQExpBuffer labelq;
11433         PQExpBuffer query;
11434         PGresult   *res;
11435         char       *qsrvname;
11436         char       *fdwname;
11437
11438         /* Skip if not to be dumped */
11439         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11440                 return;
11441
11442         q = createPQExpBuffer();
11443         delq = createPQExpBuffer();
11444         labelq = createPQExpBuffer();
11445         query = createPQExpBuffer();
11446
11447         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11448
11449         /* look up the foreign-data wrapper */
11450         selectSourceSchema(fout, "pg_catalog");
11451         appendPQExpBuffer(query, "SELECT fdwname "
11452                                           "FROM pg_foreign_data_wrapper w "
11453                                           "WHERE w.oid = '%u'",
11454                                           srvinfo->srvfdw);
11455         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11456         fdwname = PQgetvalue(res, 0, 0);
11457
11458         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11459         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11460         {
11461                 appendPQExpBuffer(q, " TYPE ");
11462                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11463         }
11464         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11465         {
11466                 appendPQExpBuffer(q, " VERSION ");
11467                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11468         }
11469
11470         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11471         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11472
11473         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11474                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11475
11476         appendPQExpBuffer(q, ";\n");
11477
11478         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11479                                           qsrvname);
11480
11481         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11482
11483         if (binary_upgrade)
11484                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11485
11486         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11487                                  srvinfo->dobj.name,
11488                                  NULL,
11489                                  NULL,
11490                                  srvinfo->rolname,
11491                                  false, "SERVER", SECTION_PRE_DATA,
11492                                  q->data, delq->data, NULL,
11493                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11494                                  NULL, NULL);
11495
11496         /* Handle the ACL */
11497         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11498                         "FOREIGN SERVER",
11499                         qsrvname, NULL, srvinfo->dobj.name,
11500                         NULL, srvinfo->rolname,
11501                         srvinfo->srvacl);
11502
11503         /* Dump user mappings */
11504         dumpUserMappings(fout,
11505                                          srvinfo->dobj.name, NULL,
11506                                          srvinfo->rolname,
11507                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11508
11509         /* Dump Foreign Server Comments */
11510         dumpComment(fout, labelq->data,
11511                                 NULL, srvinfo->rolname,
11512                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11513
11514         free(qsrvname);
11515
11516         destroyPQExpBuffer(q);
11517         destroyPQExpBuffer(delq);
11518         destroyPQExpBuffer(labelq);
11519 }
11520
11521 /*
11522  * dumpUserMappings
11523  *
11524  * This routine is used to dump any user mappings associated with the
11525  * server handed to this routine. Should be called after ArchiveEntry()
11526  * for the server.
11527  */
11528 static void
11529 dumpUserMappings(Archive *fout,
11530                                  const char *servername, const char *namespace,
11531                                  const char *owner,
11532                                  CatalogId catalogId, DumpId dumpId)
11533 {
11534         PQExpBuffer q;
11535         PQExpBuffer delq;
11536         PQExpBuffer query;
11537         PQExpBuffer tag;
11538         PGresult   *res;
11539         int                     ntups;
11540         int                     i_usename;
11541         int                     i_umoptions;
11542         int                     i;
11543
11544         q = createPQExpBuffer();
11545         tag = createPQExpBuffer();
11546         delq = createPQExpBuffer();
11547         query = createPQExpBuffer();
11548
11549         /*
11550          * We read from the publicly accessible view pg_user_mappings, so as not
11551          * to fail if run by a non-superuser.  Note that the view will show
11552          * umoptions as null if the user hasn't got privileges for the associated
11553          * server; this means that pg_dump will dump such a mapping, but with no
11554          * OPTIONS clause.      A possible alternative is to skip such mappings
11555          * altogether, but it's not clear that that's an improvement.
11556          */
11557         selectSourceSchema(fout, "pg_catalog");
11558
11559         appendPQExpBuffer(query,
11560                                           "SELECT usename, "
11561                                           "array_to_string(ARRAY("
11562                                           "SELECT quote_ident(option_name) || ' ' || "
11563                                           "quote_literal(option_value) "
11564                                           "FROM pg_options_to_table(umoptions) "
11565                                           "ORDER BY option_name"
11566                                           "), E',\n    ') AS umoptions "
11567                                           "FROM pg_user_mappings "
11568                                           "WHERE srvid = '%u' "
11569                                           "ORDER BY usename",
11570                                           catalogId.oid);
11571
11572         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11573
11574         ntups = PQntuples(res);
11575         i_usename = PQfnumber(res, "usename");
11576         i_umoptions = PQfnumber(res, "umoptions");
11577
11578         for (i = 0; i < ntups; i++)
11579         {
11580                 char       *usename;
11581                 char       *umoptions;
11582
11583                 usename = PQgetvalue(res, i, i_usename);
11584                 umoptions = PQgetvalue(res, i, i_umoptions);
11585
11586                 resetPQExpBuffer(q);
11587                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11588                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11589
11590                 if (umoptions && strlen(umoptions) > 0)
11591                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11592
11593                 appendPQExpBuffer(q, ";\n");
11594
11595                 resetPQExpBuffer(delq);
11596                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11597                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11598
11599                 resetPQExpBuffer(tag);
11600                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11601                                                   usename, servername);
11602
11603                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11604                                          tag->data,
11605                                          namespace,
11606                                          NULL,
11607                                          owner, false,
11608                                          "USER MAPPING", SECTION_PRE_DATA,
11609                                          q->data, delq->data, NULL,
11610                                          &dumpId, 1,
11611                                          NULL, NULL);
11612         }
11613
11614         PQclear(res);
11615
11616         destroyPQExpBuffer(query);
11617         destroyPQExpBuffer(delq);
11618         destroyPQExpBuffer(q);
11619 }
11620
11621 /*
11622  * Write out default privileges information
11623  */
11624 static void
11625 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11626 {
11627         PQExpBuffer q;
11628         PQExpBuffer tag;
11629         const char *type;
11630
11631         /* Skip if not to be dumped */
11632         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11633                 return;
11634
11635         q = createPQExpBuffer();
11636         tag = createPQExpBuffer();
11637
11638         switch (daclinfo->defaclobjtype)
11639         {
11640                 case DEFACLOBJ_RELATION:
11641                         type = "TABLES";
11642                         break;
11643                 case DEFACLOBJ_SEQUENCE:
11644                         type = "SEQUENCES";
11645                         break;
11646                 case DEFACLOBJ_FUNCTION:
11647                         type = "FUNCTIONS";
11648                         break;
11649                 default:
11650                         /* shouldn't get here */
11651                         exit_horribly(NULL,
11652                                                   "unknown object type (%d) in default privileges\n",
11653                                                   (int) daclinfo->defaclobjtype);
11654                         type = "";                      /* keep compiler quiet */
11655         }
11656
11657         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11658
11659         /* build the actual command(s) for this tuple */
11660         if (!buildDefaultACLCommands(type,
11661                                                                  daclinfo->dobj.namespace != NULL ?
11662                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11663                                                                  daclinfo->defaclacl,
11664                                                                  daclinfo->defaclrole,
11665                                                                  fout->remoteVersion,
11666                                                                  q))
11667                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11668                                           daclinfo->defaclacl);
11669
11670         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11671                                  tag->data,
11672            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11673                                  NULL,
11674                                  daclinfo->defaclrole,
11675                                  false, "DEFAULT ACL", SECTION_NONE,
11676                                  q->data, "", NULL,
11677                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11678                                  NULL, NULL);
11679
11680         destroyPQExpBuffer(tag);
11681         destroyPQExpBuffer(q);
11682 }
11683
11684 /*----------
11685  * Write out grant/revoke information
11686  *
11687  * 'objCatId' is the catalog ID of the underlying object.
11688  * 'objDumpId' is the dump ID of the underlying object.
11689  * 'type' must be one of
11690  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11691  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11692  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11693  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11694  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11695  * 'nspname' is the namespace the object is in (NULL if none).
11696  * 'owner' is the owner, NULL if there is no owner (for languages).
11697  * 'acls' is the string read out of the fooacl system catalog field;
11698  *              it will be parsed here.
11699  *----------
11700  */
11701 static void
11702 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11703                 const char *type, const char *name, const char *subname,
11704                 const char *tag, const char *nspname, const char *owner,
11705                 const char *acls)
11706 {
11707         PQExpBuffer sql;
11708
11709         /* Do nothing if ACL dump is not enabled */
11710         if (aclsSkip)
11711                 return;
11712
11713         /* --data-only skips ACLs *except* BLOB ACLs */
11714         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11715                 return;
11716
11717         sql = createPQExpBuffer();
11718
11719         if (!buildACLCommands(name, subname, type, acls, owner,
11720                                                   "", fout->remoteVersion, sql))
11721                 exit_horribly(NULL,
11722                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11723                                           acls, name, type);
11724
11725         if (sql->len > 0)
11726                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11727                                          tag, nspname,
11728                                          NULL,
11729                                          owner ? owner : "",
11730                                          false, "ACL", SECTION_NONE,
11731                                          sql->data, "", NULL,
11732                                          &(objDumpId), 1,
11733                                          NULL, NULL);
11734
11735         destroyPQExpBuffer(sql);
11736 }
11737
11738 /*
11739  * dumpSecLabel
11740  *
11741  * This routine is used to dump any security labels associated with the
11742  * object handed to this routine. The routine takes a constant character
11743  * string for the target part of the security-label command, plus
11744  * the namespace and owner of the object (for labeling the ArchiveEntry),
11745  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11746  * plus the dump ID for the object (for setting a dependency).
11747  * If a matching pg_seclabel entry is found, it is dumped.
11748  *
11749  * Note: although this routine takes a dumpId for dependency purposes,
11750  * that purpose is just to mark the dependency in the emitted dump file
11751  * for possible future use by pg_restore.  We do NOT use it for determining
11752  * ordering of the label in the dump file, because this routine is called
11753  * after dependency sorting occurs.  This routine should be called just after
11754  * calling ArchiveEntry() for the specified object.
11755  */
11756 static void
11757 dumpSecLabel(Archive *fout, const char *target,
11758                          const char *namespace, const char *owner,
11759                          CatalogId catalogId, int subid, DumpId dumpId)
11760 {
11761         SecLabelItem *labels;
11762         int                     nlabels;
11763         int                     i;
11764         PQExpBuffer query;
11765
11766         /* do nothing, if --no-security-labels is supplied */
11767         if (no_security_labels)
11768                 return;
11769
11770         /* Comments are schema not data ... except blob comments are data */
11771         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11772         {
11773                 if (dataOnly)
11774                         return;
11775         }
11776         else
11777         {
11778                 if (schemaOnly)
11779                         return;
11780         }
11781
11782         /* Search for security labels associated with catalogId, using table */
11783         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11784
11785         query = createPQExpBuffer();
11786
11787         for (i = 0; i < nlabels; i++)
11788         {
11789                 /*
11790                  * Ignore label entries for which the subid doesn't match.
11791                  */
11792                 if (labels[i].objsubid != subid)
11793                         continue;
11794
11795                 appendPQExpBuffer(query,
11796                                                   "SECURITY LABEL FOR %s ON %s IS ",
11797                                                   fmtId(labels[i].provider), target);
11798                 appendStringLiteralAH(query, labels[i].label, fout);
11799                 appendPQExpBuffer(query, ";\n");
11800         }
11801
11802         if (query->len > 0)
11803         {
11804                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11805                                          target, namespace, NULL, owner,
11806                                          false, "SECURITY LABEL", SECTION_NONE,
11807                                          query->data, "", NULL,
11808                                          &(dumpId), 1,
11809                                          NULL, NULL);
11810         }
11811         destroyPQExpBuffer(query);
11812 }
11813
11814 /*
11815  * dumpTableSecLabel
11816  *
11817  * As above, but dump security label for both the specified table (or view)
11818  * and its columns.
11819  */
11820 static void
11821 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11822 {
11823         SecLabelItem *labels;
11824         int                     nlabels;
11825         int                     i;
11826         PQExpBuffer query;
11827         PQExpBuffer target;
11828
11829         /* do nothing, if --no-security-labels is supplied */
11830         if (no_security_labels)
11831                 return;
11832
11833         /* SecLabel are SCHEMA not data */
11834         if (dataOnly)
11835                 return;
11836
11837         /* Search for comments associated with relation, using table */
11838         nlabels = findSecLabels(fout,
11839                                                         tbinfo->dobj.catId.tableoid,
11840                                                         tbinfo->dobj.catId.oid,
11841                                                         &labels);
11842
11843         /* If security labels exist, build SECURITY LABEL statements */
11844         if (nlabels <= 0)
11845                 return;
11846
11847         query = createPQExpBuffer();
11848         target = createPQExpBuffer();
11849
11850         for (i = 0; i < nlabels; i++)
11851         {
11852                 const char *colname;
11853                 const char *provider = labels[i].provider;
11854                 const char *label = labels[i].label;
11855                 int                     objsubid = labels[i].objsubid;
11856
11857                 resetPQExpBuffer(target);
11858                 if (objsubid == 0)
11859                 {
11860                         appendPQExpBuffer(target, "%s %s", reltypename,
11861                                                           fmtId(tbinfo->dobj.name));
11862                 }
11863                 else
11864                 {
11865                         colname = getAttrName(objsubid, tbinfo);
11866                         /* first fmtId result must be consumed before calling it again */
11867                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11868                         appendPQExpBuffer(target, ".%s", fmtId(colname));
11869                 }
11870                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11871                                                   fmtId(provider), target->data);
11872                 appendStringLiteralAH(query, label, fout);
11873                 appendPQExpBuffer(query, ";\n");
11874         }
11875         if (query->len > 0)
11876         {
11877                 resetPQExpBuffer(target);
11878                 appendPQExpBuffer(target, "%s %s", reltypename,
11879                                                   fmtId(tbinfo->dobj.name));
11880                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11881                                          target->data,
11882                                          tbinfo->dobj.namespace->dobj.name,
11883                                          NULL, tbinfo->rolname,
11884                                          false, "SECURITY LABEL", SECTION_NONE,
11885                                          query->data, "", NULL,
11886                                          &(tbinfo->dobj.dumpId), 1,
11887                                          NULL, NULL);
11888         }
11889         destroyPQExpBuffer(query);
11890         destroyPQExpBuffer(target);
11891 }
11892
11893 /*
11894  * findSecLabels
11895  *
11896  * Find the security label(s), if any, associated with the given object.
11897  * All the objsubid values associated with the given classoid/objoid are
11898  * found with one search.
11899  */
11900 static int
11901 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11902 {
11903         /* static storage for table of security labels */
11904         static SecLabelItem *labels = NULL;
11905         static int      nlabels = -1;
11906
11907         SecLabelItem *middle = NULL;
11908         SecLabelItem *low;
11909         SecLabelItem *high;
11910         int                     nmatch;
11911
11912         /* Get security labels if we didn't already */
11913         if (nlabels < 0)
11914                 nlabels = collectSecLabels(fout, &labels);
11915
11916         if (nlabels <= 0)                       /* no labels, so no match is possible */
11917         {
11918                 *items = NULL;
11919                 return 0;
11920         }
11921
11922         /*
11923          * Do binary search to find some item matching the object.
11924          */
11925         low = &labels[0];
11926         high = &labels[nlabels - 1];
11927         while (low <= high)
11928         {
11929                 middle = low + (high - low) / 2;
11930
11931                 if (classoid < middle->classoid)
11932                         high = middle - 1;
11933                 else if (classoid > middle->classoid)
11934                         low = middle + 1;
11935                 else if (objoid < middle->objoid)
11936                         high = middle - 1;
11937                 else if (objoid > middle->objoid)
11938                         low = middle + 1;
11939                 else
11940                         break;                          /* found a match */
11941         }
11942
11943         if (low > high)                         /* no matches */
11944         {
11945                 *items = NULL;
11946                 return 0;
11947         }
11948
11949         /*
11950          * Now determine how many items match the object.  The search loop
11951          * invariant still holds: only items between low and high inclusive could
11952          * match.
11953          */
11954         nmatch = 1;
11955         while (middle > low)
11956         {
11957                 if (classoid != middle[-1].classoid ||
11958                         objoid != middle[-1].objoid)
11959                         break;
11960                 middle--;
11961                 nmatch++;
11962         }
11963
11964         *items = middle;
11965
11966         middle += nmatch;
11967         while (middle <= high)
11968         {
11969                 if (classoid != middle->classoid ||
11970                         objoid != middle->objoid)
11971                         break;
11972                 middle++;
11973                 nmatch++;
11974         }
11975
11976         return nmatch;
11977 }
11978
11979 /*
11980  * collectSecLabels
11981  *
11982  * Construct a table of all security labels available for database objects.
11983  * It's much faster to pull them all at once.
11984  *
11985  * The table is sorted by classoid/objid/objsubid for speed in lookup.
11986  */
11987 static int
11988 collectSecLabels(Archive *fout, SecLabelItem **items)
11989 {
11990         PGresult   *res;
11991         PQExpBuffer query;
11992         int                     i_label;
11993         int                     i_provider;
11994         int                     i_classoid;
11995         int                     i_objoid;
11996         int                     i_objsubid;
11997         int                     ntups;
11998         int                     i;
11999         SecLabelItem *labels;
12000
12001         query = createPQExpBuffer();
12002
12003         appendPQExpBuffer(query,
12004                                           "SELECT label, provider, classoid, objoid, objsubid "
12005                                           "FROM pg_catalog.pg_seclabel "
12006                                           "ORDER BY classoid, objoid, objsubid");
12007
12008         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12009
12010         /* Construct lookup table containing OIDs in numeric form */
12011         i_label = PQfnumber(res, "label");
12012         i_provider = PQfnumber(res, "provider");
12013         i_classoid = PQfnumber(res, "classoid");
12014         i_objoid = PQfnumber(res, "objoid");
12015         i_objsubid = PQfnumber(res, "objsubid");
12016
12017         ntups = PQntuples(res);
12018
12019         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12020
12021         for (i = 0; i < ntups; i++)
12022         {
12023                 labels[i].label = PQgetvalue(res, i, i_label);
12024                 labels[i].provider = PQgetvalue(res, i, i_provider);
12025                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12026                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12027                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12028         }
12029
12030         /* Do NOT free the PGresult since we are keeping pointers into it */
12031         destroyPQExpBuffer(query);
12032
12033         *items = labels;
12034         return ntups;
12035 }
12036
12037 /*
12038  * dumpTable
12039  *        write out to fout the declarations (not data) of a user-defined table
12040  */
12041 static void
12042 dumpTable(Archive *fout, TableInfo *tbinfo)
12043 {
12044         if (tbinfo->dobj.dump)
12045         {
12046                 char       *namecopy;
12047
12048                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12049                         dumpSequence(fout, tbinfo);
12050                 else if (!dataOnly)
12051                         dumpTableSchema(fout, tbinfo);
12052
12053                 /* Handle the ACL here */
12054                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12055                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12056                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12057                                 "TABLE",
12058                                 namecopy, NULL, tbinfo->dobj.name,
12059                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12060                                 tbinfo->relacl);
12061
12062                 /*
12063                  * Handle column ACLs, if any.  Note: we pull these with a separate
12064                  * query rather than trying to fetch them during getTableAttrs, so
12065                  * that we won't miss ACLs on system columns.
12066                  */
12067                 if (fout->remoteVersion >= 80400)
12068                 {
12069                         PQExpBuffer query = createPQExpBuffer();
12070                         PGresult   *res;
12071                         int                     i;
12072
12073                         appendPQExpBuffer(query,
12074                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12075                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12076                                                           "ORDER BY attnum",
12077                                                           tbinfo->dobj.catId.oid);
12078                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12079
12080                         for (i = 0; i < PQntuples(res); i++)
12081                         {
12082                                 char       *attname = PQgetvalue(res, i, 0);
12083                                 char       *attacl = PQgetvalue(res, i, 1);
12084                                 char       *attnamecopy;
12085                                 char       *acltag;
12086
12087                                 attnamecopy = pg_strdup(fmtId(attname));
12088                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12089                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12090                                 /* Column's GRANT type is always TABLE */
12091                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12092                                                 namecopy, attnamecopy, acltag,
12093                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12094                                                 attacl);
12095                                 free(attnamecopy);
12096                                 free(acltag);
12097                         }
12098                         PQclear(res);
12099                         destroyPQExpBuffer(query);
12100                 }
12101
12102                 free(namecopy);
12103         }
12104 }
12105
12106 /*
12107  * dumpTableSchema
12108  *        write the declaration (not data) of one user-defined table or view
12109  */
12110 static void
12111 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12112 {
12113         PQExpBuffer query = createPQExpBuffer();
12114         PQExpBuffer q = createPQExpBuffer();
12115         PQExpBuffer delq = createPQExpBuffer();
12116         PQExpBuffer labelq = createPQExpBuffer();
12117         PGresult   *res;
12118         int                     numParents;
12119         TableInfo **parents;
12120         int                     actual_atts;    /* number of attrs in this CREATE statement */
12121         const char *reltypename;
12122         char       *storage;
12123         char       *srvname;
12124         char       *ftoptions;
12125         int                     j,
12126                                 k;
12127
12128         /* Make sure we are in proper schema */
12129         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12130
12131         if (binary_upgrade)
12132                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12133                                                                                                 tbinfo->dobj.catId.oid);
12134
12135         /* Is it a table or a view? */
12136         if (tbinfo->relkind == RELKIND_VIEW)
12137         {
12138                 char       *viewdef;
12139
12140                 reltypename = "VIEW";
12141
12142                 /* Fetch the view definition */
12143                 if (fout->remoteVersion >= 70300)
12144                 {
12145                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12146                         appendPQExpBuffer(query,
12147                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12148                                                           tbinfo->dobj.catId.oid);
12149                 }
12150                 else
12151                 {
12152                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12153                                                           "FROM pg_views WHERE viewname = ");
12154                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12155                         appendPQExpBuffer(query, ";");
12156                 }
12157
12158                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12159
12160                 if (PQntuples(res) != 1)
12161                 {
12162                         if (PQntuples(res) < 1)
12163                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12164                                                           tbinfo->dobj.name);
12165                         else
12166                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12167                                                           tbinfo->dobj.name);
12168                 }
12169
12170                 viewdef = PQgetvalue(res, 0, 0);
12171
12172                 if (strlen(viewdef) == 0)
12173                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12174                                                   tbinfo->dobj.name);
12175
12176                 /*
12177                  * DROP must be fully qualified in case same name appears in
12178                  * pg_catalog
12179                  */
12180                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12181                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12182                 appendPQExpBuffer(delq, "%s;\n",
12183                                                   fmtId(tbinfo->dobj.name));
12184
12185                 if (binary_upgrade)
12186                         binary_upgrade_set_pg_class_oids(fout, q,
12187                                                                                          tbinfo->dobj.catId.oid, false);
12188
12189                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12190                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12191                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12192                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12193
12194                 appendPQExpBuffer(labelq, "VIEW %s",
12195                                                   fmtId(tbinfo->dobj.name));
12196
12197                 PQclear(res);
12198         }
12199         else
12200         {
12201                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12202                 {
12203                         int                     i_srvname;
12204                         int                     i_ftoptions;
12205
12206                         reltypename = "FOREIGN TABLE";
12207
12208                         /* retrieve name of foreign server and generic options */
12209                         appendPQExpBuffer(query,
12210                                                           "SELECT fs.srvname, "
12211                                                           "pg_catalog.array_to_string(ARRAY("
12212                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12213                                                           "' ' || pg_catalog.quote_literal(option_value) "
12214                                                         "FROM pg_catalog.pg_options_to_table(ftoptions) "
12215                                                           "ORDER BY option_name"
12216                                                           "), E',\n    ') AS ftoptions "
12217                                                           "FROM pg_catalog.pg_foreign_table ft "
12218                                                           "JOIN pg_catalog.pg_foreign_server fs "
12219                                                           "ON (fs.oid = ft.ftserver) "
12220                                                           "WHERE ft.ftrelid = '%u'",
12221                                                           tbinfo->dobj.catId.oid);
12222                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12223                         i_srvname = PQfnumber(res, "srvname");
12224                         i_ftoptions = PQfnumber(res, "ftoptions");
12225                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12226                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12227                         PQclear(res);
12228                 }
12229                 else
12230                 {
12231                         reltypename = "TABLE";
12232                         srvname = NULL;
12233                         ftoptions = NULL;
12234                 }
12235                 numParents = tbinfo->numParents;
12236                 parents = tbinfo->parents;
12237
12238                 /*
12239                  * DROP must be fully qualified in case same name appears in
12240                  * pg_catalog
12241                  */
12242                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12243                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12244                 appendPQExpBuffer(delq, "%s;\n",
12245                                                   fmtId(tbinfo->dobj.name));
12246
12247                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12248                                                   fmtId(tbinfo->dobj.name));
12249
12250                 if (binary_upgrade)
12251                         binary_upgrade_set_pg_class_oids(fout, q,
12252                                                                                          tbinfo->dobj.catId.oid, false);
12253
12254                 appendPQExpBuffer(q, "CREATE %s%s %s",
12255                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12256                                                   "UNLOGGED " : "",
12257                                                   reltypename,
12258                                                   fmtId(tbinfo->dobj.name));
12259
12260                 /*
12261                  * Attach to type, if reloftype; except in case of a binary upgrade,
12262                  * we dump the table normally and attach it to the type afterward.
12263                  */
12264                 if (tbinfo->reloftype && !binary_upgrade)
12265                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12266
12267                 /* Dump the attributes */
12268                 actual_atts = 0;
12269                 for (j = 0; j < tbinfo->numatts; j++)
12270                 {
12271                         /*
12272                          * Normally, dump if it's locally defined in this table, and not
12273                          * dropped.  But for binary upgrade, we'll dump all the columns,
12274                          * and then fix up the dropped and nonlocal cases below.
12275                          */
12276                         if (shouldPrintColumn(tbinfo, j))
12277                         {
12278                                 /*
12279                                  * Default value --- suppress if to be printed separately.
12280                                  */
12281                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12282                                                                                    !tbinfo->attrdefs[j]->separate);
12283
12284                                 /*
12285                                  * Not Null constraint --- suppress if inherited, except in
12286                                  * binary-upgrade case where that won't work.
12287                                  */
12288                                 bool            has_notnull = (tbinfo->notnull[j] &&
12289                                                                                    (!tbinfo->inhNotNull[j] ||
12290                                                                                         binary_upgrade));
12291
12292                                 /* Skip column if fully defined by reloftype */
12293                                 if (tbinfo->reloftype &&
12294                                         !has_default && !has_notnull && !binary_upgrade)
12295                                         continue;
12296
12297                                 /* Format properly if not first attr */
12298                                 if (actual_atts == 0)
12299                                         appendPQExpBuffer(q, " (");
12300                                 else
12301                                         appendPQExpBuffer(q, ",");
12302                                 appendPQExpBuffer(q, "\n    ");
12303                                 actual_atts++;
12304
12305                                 /* Attribute name */
12306                                 appendPQExpBuffer(q, "%s ",
12307                                                                   fmtId(tbinfo->attnames[j]));
12308
12309                                 if (tbinfo->attisdropped[j])
12310                                 {
12311                                         /*
12312                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12313                                          * so we will not have gotten a valid type name; insert
12314                                          * INTEGER as a stopgap.  We'll clean things up later.
12315                                          */
12316                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12317                                         /* Skip all the rest, too */
12318                                         continue;
12319                                 }
12320
12321                                 /* Attribute type */
12322                                 if (tbinfo->reloftype && !binary_upgrade)
12323                                 {
12324                                         appendPQExpBuffer(q, "WITH OPTIONS");
12325                                 }
12326                                 else if (fout->remoteVersion >= 70100)
12327                                 {
12328                                         appendPQExpBuffer(q, "%s",
12329                                                                           tbinfo->atttypnames[j]);
12330                                 }
12331                                 else
12332                                 {
12333                                         /* If no format_type, fake it */
12334                                         appendPQExpBuffer(q, "%s",
12335                                                                           myFormatType(tbinfo->atttypnames[j],
12336                                                                                                    tbinfo->atttypmod[j]));
12337                                 }
12338
12339                                 /* Add collation if not default for the type */
12340                                 if (OidIsValid(tbinfo->attcollation[j]))
12341                                 {
12342                                         CollInfo   *coll;
12343
12344                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12345                                         if (coll)
12346                                         {
12347                                                 /* always schema-qualify, don't try to be smart */
12348                                                 appendPQExpBuffer(q, " COLLATE %s.",
12349                                                                          fmtId(coll->dobj.namespace->dobj.name));
12350                                                 appendPQExpBuffer(q, "%s",
12351                                                                                   fmtId(coll->dobj.name));
12352                                         }
12353                                 }
12354
12355                                 if (has_default)
12356                                         appendPQExpBuffer(q, " DEFAULT %s",
12357                                                                           tbinfo->attrdefs[j]->adef_expr);
12358
12359                                 if (has_notnull)
12360                                         appendPQExpBuffer(q, " NOT NULL");
12361                         }
12362                 }
12363
12364                 /*
12365                  * Add non-inherited CHECK constraints, if any.
12366                  */
12367                 for (j = 0; j < tbinfo->ncheck; j++)
12368                 {
12369                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12370
12371                         if (constr->separate || !constr->conislocal)
12372                                 continue;
12373
12374                         if (actual_atts == 0)
12375                                 appendPQExpBuffer(q, " (\n    ");
12376                         else
12377                                 appendPQExpBuffer(q, ",\n    ");
12378
12379                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12380                                                           fmtId(constr->dobj.name));
12381                         appendPQExpBuffer(q, "%s", constr->condef);
12382
12383                         actual_atts++;
12384                 }
12385
12386                 if (actual_atts)
12387                         appendPQExpBuffer(q, "\n)");
12388                 else if (!(tbinfo->reloftype && !binary_upgrade))
12389                 {
12390                         /*
12391                          * We must have a parenthesized attribute list, even though empty,
12392                          * when not using the OF TYPE syntax.
12393                          */
12394                         appendPQExpBuffer(q, " (\n)");
12395                 }
12396
12397                 if (numParents > 0 && !binary_upgrade)
12398                 {
12399                         appendPQExpBuffer(q, "\nINHERITS (");
12400                         for (k = 0; k < numParents; k++)
12401                         {
12402                                 TableInfo  *parentRel = parents[k];
12403
12404                                 if (k > 0)
12405                                         appendPQExpBuffer(q, ", ");
12406                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12407                                         appendPQExpBuffer(q, "%s.",
12408                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12409                                 appendPQExpBuffer(q, "%s",
12410                                                                   fmtId(parentRel->dobj.name));
12411                         }
12412                         appendPQExpBuffer(q, ")");
12413                 }
12414
12415                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12416                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12417
12418                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12419                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12420                 {
12421                         bool            addcomma = false;
12422
12423                         appendPQExpBuffer(q, "\nWITH (");
12424                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12425                         {
12426                                 addcomma = true;
12427                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12428                         }
12429                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12430                         {
12431                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12432                                                                   tbinfo->toast_reloptions);
12433                         }
12434                         appendPQExpBuffer(q, ")");
12435                 }
12436
12437                 /* Dump generic options if any */
12438                 if (ftoptions && ftoptions[0])
12439                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12440
12441                 appendPQExpBuffer(q, ";\n");
12442
12443                 /*
12444                  * To create binary-compatible heap files, we have to ensure the same
12445                  * physical column order, including dropped columns, as in the
12446                  * original.  Therefore, we create dropped columns above and drop them
12447                  * here, also updating their attlen/attalign values so that the
12448                  * dropped column can be skipped properly.      (We do not bother with
12449                  * restoring the original attbyval setting.)  Also, inheritance
12450                  * relationships are set up by doing ALTER INHERIT rather than using
12451                  * an INHERITS clause --- the latter would possibly mess up the column
12452                  * order.  That also means we have to take care about setting
12453                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12454                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12455                  */
12456                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12457                 {
12458                         for (j = 0; j < tbinfo->numatts; j++)
12459                         {
12460                                 if (tbinfo->attisdropped[j])
12461                                 {
12462                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12463                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12464                                                                           "SET attlen = %d, "
12465                                                                           "attalign = '%c', attbyval = false\n"
12466                                                                           "WHERE attname = ",
12467                                                                           tbinfo->attlen[j],
12468                                                                           tbinfo->attalign[j]);
12469                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12470                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12471                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12472                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12473
12474                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12475                                                                           fmtId(tbinfo->dobj.name));
12476                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12477                                                                           fmtId(tbinfo->attnames[j]));
12478                                 }
12479                                 else if (!tbinfo->attislocal[j])
12480                                 {
12481                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12482                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12483                                                                           "SET attislocal = false\n"
12484                                                                           "WHERE attname = ");
12485                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12486                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12487                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12488                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12489                                 }
12490                         }
12491
12492                         for (k = 0; k < tbinfo->ncheck; k++)
12493                         {
12494                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12495
12496                                 if (constr->separate || constr->conislocal)
12497                                         continue;
12498
12499                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12500                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12501                                                                   fmtId(tbinfo->dobj.name));
12502                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12503                                                                   fmtId(constr->dobj.name));
12504                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12505                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12506                                                                   "SET conislocal = false\n"
12507                                                                   "WHERE contype = 'c' AND conname = ");
12508                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12509                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12510                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12511                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12512                         }
12513
12514                         if (numParents > 0)
12515                         {
12516                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12517                                 for (k = 0; k < numParents; k++)
12518                                 {
12519                                         TableInfo  *parentRel = parents[k];
12520
12521                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12522                                                                           fmtId(tbinfo->dobj.name));
12523                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12524                                                 appendPQExpBuffer(q, "%s.",
12525                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12526                                         appendPQExpBuffer(q, "%s;\n",
12527                                                                           fmtId(parentRel->dobj.name));
12528                                 }
12529                         }
12530
12531                         if (tbinfo->reloftype)
12532                         {
12533                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12534                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12535                                                                   fmtId(tbinfo->dobj.name),
12536                                                                   tbinfo->reloftype);
12537                         }
12538
12539                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12540                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12541                                                           "SET relfrozenxid = '%u'\n"
12542                                                           "WHERE oid = ",
12543                                                           tbinfo->frozenxid);
12544                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12545                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12546
12547                         if (tbinfo->toast_oid)
12548                         {
12549                                 /* We preserve the toast oids, so we can use it during restore */
12550                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12551                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12552                                                                   "SET relfrozenxid = '%u'\n"
12553                                                                   "WHERE oid = '%u';\n",
12554                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12555                         }
12556                 }
12557
12558                 /*
12559                  * Dump additional per-column properties that we can't handle in the
12560                  * main CREATE TABLE command.
12561                  */
12562                 for (j = 0; j < tbinfo->numatts; j++)
12563                 {
12564                         /* None of this applies to dropped columns */
12565                         if (tbinfo->attisdropped[j])
12566                                 continue;
12567
12568                         /*
12569                          * If we didn't dump the column definition explicitly above, and
12570                          * it is NOT NULL and did not inherit that property from a parent,
12571                          * we have to mark it separately.
12572                          */
12573                         if (!shouldPrintColumn(tbinfo, j) &&
12574                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12575                         {
12576                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12577                                                                   fmtId(tbinfo->dobj.name));
12578                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12579                                                                   fmtId(tbinfo->attnames[j]));
12580                         }
12581
12582                         /*
12583                          * Dump per-column statistics information. We only issue an ALTER
12584                          * TABLE statement if the attstattarget entry for this column is
12585                          * non-negative (i.e. it's not the default value)
12586                          */
12587                         if (tbinfo->attstattarget[j] >= 0)
12588                         {
12589                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12590                                                                   fmtId(tbinfo->dobj.name));
12591                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12592                                                                   fmtId(tbinfo->attnames[j]));
12593                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12594                                                                   tbinfo->attstattarget[j]);
12595                         }
12596
12597                         /*
12598                          * Dump per-column storage information.  The statement is only
12599                          * dumped if the storage has been changed from the type's default.
12600                          */
12601                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12602                         {
12603                                 switch (tbinfo->attstorage[j])
12604                                 {
12605                                         case 'p':
12606                                                 storage = "PLAIN";
12607                                                 break;
12608                                         case 'e':
12609                                                 storage = "EXTERNAL";
12610                                                 break;
12611                                         case 'm':
12612                                                 storage = "MAIN";
12613                                                 break;
12614                                         case 'x':
12615                                                 storage = "EXTENDED";
12616                                                 break;
12617                                         default:
12618                                                 storage = NULL;
12619                                 }
12620
12621                                 /*
12622                                  * Only dump the statement if it's a storage type we recognize
12623                                  */
12624                                 if (storage != NULL)
12625                                 {
12626                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12627                                                                           fmtId(tbinfo->dobj.name));
12628                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12629                                                                           fmtId(tbinfo->attnames[j]));
12630                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12631                                                                           storage);
12632                                 }
12633                         }
12634
12635                         /*
12636                          * Dump per-column attributes.
12637                          */
12638                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12639                         {
12640                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12641                                                                   fmtId(tbinfo->dobj.name));
12642                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12643                                                                   fmtId(tbinfo->attnames[j]));
12644                                 appendPQExpBuffer(q, "SET (%s);\n",
12645                                                                   tbinfo->attoptions[j]);
12646                         }
12647
12648                         /*
12649                          * Dump per-column fdw options.
12650                          */
12651                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12652                                 tbinfo->attfdwoptions[j] &&
12653                                 tbinfo->attfdwoptions[j][0] != '\0')
12654                         {
12655                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12656                                                                   fmtId(tbinfo->dobj.name));
12657                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12658                                                                   fmtId(tbinfo->attnames[j]));
12659                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12660                                                                   tbinfo->attfdwoptions[j]);
12661                         }
12662                 }
12663         }
12664
12665         if (binary_upgrade)
12666                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12667
12668         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12669                                  tbinfo->dobj.name,
12670                                  tbinfo->dobj.namespace->dobj.name,
12671                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12672                                  tbinfo->rolname,
12673                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12674                                  reltypename, SECTION_PRE_DATA,
12675                                  q->data, delq->data, NULL,
12676                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12677                                  NULL, NULL);
12678
12679
12680         /* Dump Table Comments */
12681         dumpTableComment(fout, tbinfo, reltypename);
12682
12683         /* Dump Table Security Labels */
12684         dumpTableSecLabel(fout, tbinfo, reltypename);
12685
12686         /* Dump comments on inlined table constraints */
12687         for (j = 0; j < tbinfo->ncheck; j++)
12688         {
12689                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12690
12691                 if (constr->separate || !constr->conislocal)
12692                         continue;
12693
12694                 dumpTableConstraintComment(fout, constr);
12695         }
12696
12697         destroyPQExpBuffer(query);
12698         destroyPQExpBuffer(q);
12699         destroyPQExpBuffer(delq);
12700         destroyPQExpBuffer(labelq);
12701 }
12702
12703 /*
12704  * dumpAttrDef --- dump an attribute's default-value declaration
12705  */
12706 static void
12707 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12708 {
12709         TableInfo  *tbinfo = adinfo->adtable;
12710         int                     adnum = adinfo->adnum;
12711         PQExpBuffer q;
12712         PQExpBuffer delq;
12713
12714         /* Skip if table definition not to be dumped */
12715         if (!tbinfo->dobj.dump || dataOnly)
12716                 return;
12717
12718         /* Skip if not "separate"; it was dumped in the table's definition */
12719         if (!adinfo->separate)
12720                 return;
12721
12722         q = createPQExpBuffer();
12723         delq = createPQExpBuffer();
12724
12725         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12726                                           fmtId(tbinfo->dobj.name));
12727         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12728                                           fmtId(tbinfo->attnames[adnum - 1]),
12729                                           adinfo->adef_expr);
12730
12731         /*
12732          * DROP must be fully qualified in case same name appears in pg_catalog
12733          */
12734         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12735                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12736         appendPQExpBuffer(delq, "%s ",
12737                                           fmtId(tbinfo->dobj.name));
12738         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12739                                           fmtId(tbinfo->attnames[adnum - 1]));
12740
12741         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12742                                  tbinfo->attnames[adnum - 1],
12743                                  tbinfo->dobj.namespace->dobj.name,
12744                                  NULL,
12745                                  tbinfo->rolname,
12746                                  false, "DEFAULT", SECTION_PRE_DATA,
12747                                  q->data, delq->data, NULL,
12748                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12749                                  NULL, NULL);
12750
12751         destroyPQExpBuffer(q);
12752         destroyPQExpBuffer(delq);
12753 }
12754
12755 /*
12756  * getAttrName: extract the correct name for an attribute
12757  *
12758  * The array tblInfo->attnames[] only provides names of user attributes;
12759  * if a system attribute number is supplied, we have to fake it.
12760  * We also do a little bit of bounds checking for safety's sake.
12761  */
12762 static const char *
12763 getAttrName(int attrnum, TableInfo *tblInfo)
12764 {
12765         if (attrnum > 0 && attrnum <= tblInfo->numatts)
12766                 return tblInfo->attnames[attrnum - 1];
12767         switch (attrnum)
12768         {
12769                 case SelfItemPointerAttributeNumber:
12770                         return "ctid";
12771                 case ObjectIdAttributeNumber:
12772                         return "oid";
12773                 case MinTransactionIdAttributeNumber:
12774                         return "xmin";
12775                 case MinCommandIdAttributeNumber:
12776                         return "cmin";
12777                 case MaxTransactionIdAttributeNumber:
12778                         return "xmax";
12779                 case MaxCommandIdAttributeNumber:
12780                         return "cmax";
12781                 case TableOidAttributeNumber:
12782                         return "tableoid";
12783         }
12784         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12785                                   attrnum, tblInfo->dobj.name);
12786         return NULL;                            /* keep compiler quiet */
12787 }
12788
12789 /*
12790  * dumpIndex
12791  *        write out to fout a user-defined index
12792  */
12793 static void
12794 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12795 {
12796         TableInfo  *tbinfo = indxinfo->indextable;
12797         PQExpBuffer q;
12798         PQExpBuffer delq;
12799         PQExpBuffer labelq;
12800
12801         if (dataOnly)
12802                 return;
12803
12804         q = createPQExpBuffer();
12805         delq = createPQExpBuffer();
12806         labelq = createPQExpBuffer();
12807
12808         appendPQExpBuffer(labelq, "INDEX %s",
12809                                           fmtId(indxinfo->dobj.name));
12810
12811         /*
12812          * If there's an associated constraint, don't dump the index per se, but
12813          * do dump any comment for it.  (This is safe because dependency ordering
12814          * will have ensured the constraint is emitted first.)
12815          */
12816         if (indxinfo->indexconstraint == 0)
12817         {
12818                 if (binary_upgrade)
12819                         binary_upgrade_set_pg_class_oids(fout, q,
12820                                                                                          indxinfo->dobj.catId.oid, true);
12821
12822                 /* Plain secondary index */
12823                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12824
12825                 /* If the index is clustered, we need to record that. */
12826                 if (indxinfo->indisclustered)
12827                 {
12828                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12829                                                           fmtId(tbinfo->dobj.name));
12830                         appendPQExpBuffer(q, " ON %s;\n",
12831                                                           fmtId(indxinfo->dobj.name));
12832                 }
12833
12834                 /*
12835                  * DROP must be fully qualified in case same name appears in
12836                  * pg_catalog
12837                  */
12838                 appendPQExpBuffer(delq, "DROP INDEX %s.",
12839                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12840                 appendPQExpBuffer(delq, "%s;\n",
12841                                                   fmtId(indxinfo->dobj.name));
12842
12843                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12844                                          indxinfo->dobj.name,
12845                                          tbinfo->dobj.namespace->dobj.name,
12846                                          indxinfo->tablespace,
12847                                          tbinfo->rolname, false,
12848                                          "INDEX", SECTION_POST_DATA,
12849                                          q->data, delq->data, NULL,
12850                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12851                                          NULL, NULL);
12852         }
12853
12854         /* Dump Index Comments */
12855         dumpComment(fout, labelq->data,
12856                                 tbinfo->dobj.namespace->dobj.name,
12857                                 tbinfo->rolname,
12858                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12859
12860         destroyPQExpBuffer(q);
12861         destroyPQExpBuffer(delq);
12862         destroyPQExpBuffer(labelq);
12863 }
12864
12865 /*
12866  * dumpConstraint
12867  *        write out to fout a user-defined constraint
12868  */
12869 static void
12870 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12871 {
12872         TableInfo  *tbinfo = coninfo->contable;
12873         PQExpBuffer q;
12874         PQExpBuffer delq;
12875
12876         /* Skip if not to be dumped */
12877         if (!coninfo->dobj.dump || dataOnly)
12878                 return;
12879
12880         q = createPQExpBuffer();
12881         delq = createPQExpBuffer();
12882
12883         if (coninfo->contype == 'p' ||
12884                 coninfo->contype == 'u' ||
12885                 coninfo->contype == 'x')
12886         {
12887                 /* Index-related constraint */
12888                 IndxInfo   *indxinfo;
12889                 int                     k;
12890
12891                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12892
12893                 if (indxinfo == NULL)
12894                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12895                                                   coninfo->dobj.name);
12896
12897                 if (binary_upgrade)
12898                         binary_upgrade_set_pg_class_oids(fout, q,
12899                                                                                          indxinfo->dobj.catId.oid, true);
12900
12901                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12902                                                   fmtId(tbinfo->dobj.name));
12903                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
12904                                                   fmtId(coninfo->dobj.name));
12905
12906                 if (coninfo->condef)
12907                 {
12908                         /* pg_get_constraintdef should have provided everything */
12909                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12910                 }
12911                 else
12912                 {
12913                         appendPQExpBuffer(q, "%s (",
12914                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12915                         for (k = 0; k < indxinfo->indnkeys; k++)
12916                         {
12917                                 int                     indkey = (int) indxinfo->indkeys[k];
12918                                 const char *attname;
12919
12920                                 if (indkey == InvalidAttrNumber)
12921                                         break;
12922                                 attname = getAttrName(indkey, tbinfo);
12923
12924                                 appendPQExpBuffer(q, "%s%s",
12925                                                                   (k == 0) ? "" : ", ",
12926                                                                   fmtId(attname));
12927                         }
12928
12929                         appendPQExpBuffer(q, ")");
12930
12931                         if (indxinfo->options && strlen(indxinfo->options) > 0)
12932                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12933
12934                         if (coninfo->condeferrable)
12935                         {
12936                                 appendPQExpBuffer(q, " DEFERRABLE");
12937                                 if (coninfo->condeferred)
12938                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
12939                         }
12940
12941                         appendPQExpBuffer(q, ";\n");
12942                 }
12943
12944                 /* If the index is clustered, we need to record that. */
12945                 if (indxinfo->indisclustered)
12946                 {
12947                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12948                                                           fmtId(tbinfo->dobj.name));
12949                         appendPQExpBuffer(q, " ON %s;\n",
12950                                                           fmtId(indxinfo->dobj.name));
12951                 }
12952
12953                 /*
12954                  * DROP must be fully qualified in case same name appears in
12955                  * pg_catalog
12956                  */
12957                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12958                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12959                 appendPQExpBuffer(delq, "%s ",
12960                                                   fmtId(tbinfo->dobj.name));
12961                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12962                                                   fmtId(coninfo->dobj.name));
12963
12964                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
12965                                          coninfo->dobj.name,
12966                                          tbinfo->dobj.namespace->dobj.name,
12967                                          indxinfo->tablespace,
12968                                          tbinfo->rolname, false,
12969                                          "CONSTRAINT", SECTION_POST_DATA,
12970                                          q->data, delq->data, NULL,
12971                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
12972                                          NULL, NULL);
12973         }
12974         else if (coninfo->contype == 'f')
12975         {
12976                 /*
12977                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
12978                  * current table data is not processed
12979                  */
12980                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12981                                                   fmtId(tbinfo->dobj.name));
12982                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
12983                                                   fmtId(coninfo->dobj.name),
12984                                                   coninfo->condef);
12985
12986                 /*
12987                  * DROP must be fully qualified in case same name appears in
12988                  * pg_catalog
12989                  */
12990                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12991                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12992                 appendPQExpBuffer(delq, "%s ",
12993                                                   fmtId(tbinfo->dobj.name));
12994                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12995                                                   fmtId(coninfo->dobj.name));
12996
12997                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
12998                                          coninfo->dobj.name,
12999                                          tbinfo->dobj.namespace->dobj.name,
13000                                          NULL,
13001                                          tbinfo->rolname, false,
13002                                          "FK CONSTRAINT", SECTION_POST_DATA,
13003                                          q->data, delq->data, NULL,
13004                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13005                                          NULL, NULL);
13006         }
13007         else if (coninfo->contype == 'c' && tbinfo)
13008         {
13009                 /* CHECK constraint on a table */
13010
13011                 /* Ignore if not to be dumped separately */
13012                 if (coninfo->separate)
13013                 {
13014                         /* not ONLY since we want it to propagate to children */
13015                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13016                                                           fmtId(tbinfo->dobj.name));
13017                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13018                                                           fmtId(coninfo->dobj.name),
13019                                                           coninfo->condef);
13020
13021                         /*
13022                          * DROP must be fully qualified in case same name appears in
13023                          * pg_catalog
13024                          */
13025                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13026                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13027                         appendPQExpBuffer(delq, "%s ",
13028                                                           fmtId(tbinfo->dobj.name));
13029                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13030                                                           fmtId(coninfo->dobj.name));
13031
13032                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13033                                                  coninfo->dobj.name,
13034                                                  tbinfo->dobj.namespace->dobj.name,
13035                                                  NULL,
13036                                                  tbinfo->rolname, false,
13037                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13038                                                  q->data, delq->data, NULL,
13039                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13040                                                  NULL, NULL);
13041                 }
13042         }
13043         else if (coninfo->contype == 'c' && tbinfo == NULL)
13044         {
13045                 /* CHECK constraint on a domain */
13046                 TypeInfo   *tyinfo = coninfo->condomain;
13047
13048                 /* Ignore if not to be dumped separately */
13049                 if (coninfo->separate)
13050                 {
13051                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13052                                                           fmtId(tyinfo->dobj.name));
13053                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13054                                                           fmtId(coninfo->dobj.name),
13055                                                           coninfo->condef);
13056
13057                         /*
13058                          * DROP must be fully qualified in case same name appears in
13059                          * pg_catalog
13060                          */
13061                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13062                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13063                         appendPQExpBuffer(delq, "%s ",
13064                                                           fmtId(tyinfo->dobj.name));
13065                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13066                                                           fmtId(coninfo->dobj.name));
13067
13068                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13069                                                  coninfo->dobj.name,
13070                                                  tyinfo->dobj.namespace->dobj.name,
13071                                                  NULL,
13072                                                  tyinfo->rolname, false,
13073                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13074                                                  q->data, delq->data, NULL,
13075                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13076                                                  NULL, NULL);
13077                 }
13078         }
13079         else
13080         {
13081                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13082                                           coninfo->contype);
13083         }
13084
13085         /* Dump Constraint Comments --- only works for table constraints */
13086         if (tbinfo && coninfo->separate)
13087                 dumpTableConstraintComment(fout, coninfo);
13088
13089         destroyPQExpBuffer(q);
13090         destroyPQExpBuffer(delq);
13091 }
13092
13093 /*
13094  * dumpTableConstraintComment --- dump a constraint's comment if any
13095  *
13096  * This is split out because we need the function in two different places
13097  * depending on whether the constraint is dumped as part of CREATE TABLE
13098  * or as a separate ALTER command.
13099  */
13100 static void
13101 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13102 {
13103         TableInfo  *tbinfo = coninfo->contable;
13104         PQExpBuffer labelq = createPQExpBuffer();
13105
13106         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13107                                           fmtId(coninfo->dobj.name));
13108         appendPQExpBuffer(labelq, "ON %s",
13109                                           fmtId(tbinfo->dobj.name));
13110         dumpComment(fout, labelq->data,
13111                                 tbinfo->dobj.namespace->dobj.name,
13112                                 tbinfo->rolname,
13113                                 coninfo->dobj.catId, 0,
13114                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13115
13116         destroyPQExpBuffer(labelq);
13117 }
13118
13119 /*
13120  * findLastBuiltInOid -
13121  * find the last built in oid
13122  *
13123  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13124  * pg_database entry for the current database
13125  */
13126 static Oid
13127 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13128 {
13129         PGresult   *res;
13130         Oid                     last_oid;
13131         PQExpBuffer query = createPQExpBuffer();
13132
13133         resetPQExpBuffer(query);
13134         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13135         appendStringLiteralAH(query, dbname, fout);
13136
13137         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13138         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13139         PQclear(res);
13140         destroyPQExpBuffer(query);
13141         return last_oid;
13142 }
13143
13144 /*
13145  * findLastBuiltInOid -
13146  * find the last built in oid
13147  *
13148  * For 7.0, we do this by assuming that the last thing that initdb does is to
13149  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13150  * initdb won't be changing anymore, it'll do.
13151  */
13152 static Oid
13153 findLastBuiltinOid_V70(Archive *fout)
13154 {
13155         PGresult   *res;
13156         int                     last_oid;
13157
13158         res = ExecuteSqlQueryForSingleRow(fout,
13159                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13160         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13161         PQclear(res);
13162         return last_oid;
13163 }
13164
13165 static void
13166 dumpSequence(Archive *fout, TableInfo *tbinfo)
13167 {
13168         PGresult   *res;
13169         char       *startv,
13170                            *last,
13171                            *incby,
13172                            *maxv = NULL,
13173                            *minv = NULL,
13174                            *cache;
13175         char            bufm[100],
13176                                 bufx[100];
13177         bool            cycled,
13178                                 called;
13179         PQExpBuffer query = createPQExpBuffer();
13180         PQExpBuffer delqry = createPQExpBuffer();
13181         PQExpBuffer labelq = createPQExpBuffer();
13182
13183         /* Make sure we are in proper schema */
13184         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13185
13186         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13187         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13188
13189         if (fout->remoteVersion >= 80400)
13190         {
13191                 appendPQExpBuffer(query,
13192                                                   "SELECT sequence_name, "
13193                                                   "start_value, last_value, increment_by, "
13194                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13195                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13196                                                   "     ELSE max_value "
13197                                                   "END AS max_value, "
13198                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13199                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13200                                                   "     ELSE min_value "
13201                                                   "END AS min_value, "
13202                                                   "cache_value, is_cycled, is_called from %s",
13203                                                   bufx, bufm,
13204                                                   fmtId(tbinfo->dobj.name));
13205         }
13206         else
13207         {
13208                 appendPQExpBuffer(query,
13209                                                   "SELECT sequence_name, "
13210                                                   "0 AS start_value, last_value, increment_by, "
13211                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13212                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13213                                                   "     ELSE max_value "
13214                                                   "END AS max_value, "
13215                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13216                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13217                                                   "     ELSE min_value "
13218                                                   "END AS min_value, "
13219                                                   "cache_value, is_cycled, is_called from %s",
13220                                                   bufx, bufm,
13221                                                   fmtId(tbinfo->dobj.name));
13222         }
13223
13224         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13225
13226         if (PQntuples(res) != 1)
13227         {
13228                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13229                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13230                                                                  PQntuples(res)),
13231                                   tbinfo->dobj.name, PQntuples(res));
13232                 exit_nicely(1);
13233         }
13234
13235         /* Disable this check: it fails if sequence has been renamed */
13236 #ifdef NOT_USED
13237         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13238         {
13239                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13240                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13241                 exit_nicely(1);
13242         }
13243 #endif
13244
13245         startv = PQgetvalue(res, 0, 1);
13246         last = PQgetvalue(res, 0, 2);
13247         incby = PQgetvalue(res, 0, 3);
13248         if (!PQgetisnull(res, 0, 4))
13249                 maxv = PQgetvalue(res, 0, 4);
13250         if (!PQgetisnull(res, 0, 5))
13251                 minv = PQgetvalue(res, 0, 5);
13252         cache = PQgetvalue(res, 0, 6);
13253         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13254         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13255
13256         /*
13257          * The logic we use for restoring sequences is as follows:
13258          *
13259          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13260          * last_val for start if called is false, else use min_val for start_val).
13261          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13262          * BY command for it.
13263          *
13264          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13265          */
13266         if (!dataOnly)
13267         {
13268                 /*
13269                  * DROP must be fully qualified in case same name appears in
13270                  * pg_catalog
13271                  */
13272                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13273                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13274                 appendPQExpBuffer(delqry, "%s;\n",
13275                                                   fmtId(tbinfo->dobj.name));
13276
13277                 resetPQExpBuffer(query);
13278
13279                 if (binary_upgrade)
13280                 {
13281                         binary_upgrade_set_pg_class_oids(fout, query,
13282                                                                                          tbinfo->dobj.catId.oid, false);
13283                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13284                                                                                                         tbinfo->dobj.catId.oid);
13285                 }
13286
13287                 appendPQExpBuffer(query,
13288                                                   "CREATE SEQUENCE %s\n",
13289                                                   fmtId(tbinfo->dobj.name));
13290
13291                 if (fout->remoteVersion >= 80400)
13292                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13293                 else
13294                 {
13295                         /*
13296                          * Versions before 8.4 did not remember the true start value.  If
13297                          * is_called is false then the sequence has never been incremented
13298                          * so we can use last_val.      Otherwise punt and let it default.
13299                          */
13300                         if (!called)
13301                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13302                 }
13303
13304                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13305
13306                 if (minv)
13307                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13308                 else
13309                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13310
13311                 if (maxv)
13312                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13313                 else
13314                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13315
13316                 appendPQExpBuffer(query,
13317                                                   "    CACHE %s%s",
13318                                                   cache, (cycled ? "\n    CYCLE" : ""));
13319
13320                 appendPQExpBuffer(query, ";\n");
13321
13322                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13323
13324                 /* binary_upgrade:      no need to clear TOAST table oid */
13325
13326                 if (binary_upgrade)
13327                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13328                                                                                         labelq->data);
13329
13330                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13331                                          tbinfo->dobj.name,
13332                                          tbinfo->dobj.namespace->dobj.name,
13333                                          NULL,
13334                                          tbinfo->rolname,
13335                                          false, "SEQUENCE", SECTION_PRE_DATA,
13336                                          query->data, delqry->data, NULL,
13337                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13338                                          NULL, NULL);
13339
13340                 /*
13341                  * If the sequence is owned by a table column, emit the ALTER for it
13342                  * as a separate TOC entry immediately following the sequence's own
13343                  * entry.  It's OK to do this rather than using full sorting logic,
13344                  * because the dependency that tells us it's owned will have forced
13345                  * the table to be created first.  We can't just include the ALTER in
13346                  * the TOC entry because it will fail if we haven't reassigned the
13347                  * sequence owner to match the table's owner.
13348                  *
13349                  * We need not schema-qualify the table reference because both
13350                  * sequence and table must be in the same schema.
13351                  */
13352                 if (OidIsValid(tbinfo->owning_tab))
13353                 {
13354                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13355
13356                         if (owning_tab && owning_tab->dobj.dump)
13357                         {
13358                                 resetPQExpBuffer(query);
13359                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13360                                                                   fmtId(tbinfo->dobj.name));
13361                                 appendPQExpBuffer(query, " OWNED BY %s",
13362                                                                   fmtId(owning_tab->dobj.name));
13363                                 appendPQExpBuffer(query, ".%s;\n",
13364                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13365
13366                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13367                                                          tbinfo->dobj.name,
13368                                                          tbinfo->dobj.namespace->dobj.name,
13369                                                          NULL,
13370                                                          tbinfo->rolname,
13371                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13372                                                          query->data, "", NULL,
13373                                                          &(tbinfo->dobj.dumpId), 1,
13374                                                          NULL, NULL);
13375                         }
13376                 }
13377
13378                 /* Dump Sequence Comments and Security Labels */
13379                 dumpComment(fout, labelq->data,
13380                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13381                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13382                 dumpSecLabel(fout, labelq->data,
13383                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13384                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13385         }
13386
13387         if (!schemaOnly)
13388         {
13389                 resetPQExpBuffer(query);
13390                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13391                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13392                 appendPQExpBuffer(query, ", %s, %s);\n",
13393                                                   last, (called ? "true" : "false"));
13394
13395                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13396                                          tbinfo->dobj.name,
13397                                          tbinfo->dobj.namespace->dobj.name,
13398                                          NULL,
13399                                          tbinfo->rolname,
13400                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13401                                          query->data, "", NULL,
13402                                          &(tbinfo->dobj.dumpId), 1,
13403                                          NULL, NULL);
13404         }
13405
13406         PQclear(res);
13407
13408         destroyPQExpBuffer(query);
13409         destroyPQExpBuffer(delqry);
13410         destroyPQExpBuffer(labelq);
13411 }
13412
13413 static void
13414 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13415 {
13416         TableInfo  *tbinfo = tginfo->tgtable;
13417         PQExpBuffer query;
13418         PQExpBuffer delqry;
13419         PQExpBuffer labelq;
13420         char       *tgargs;
13421         size_t          lentgargs;
13422         const char *p;
13423         int                     findx;
13424
13425         if (dataOnly)
13426                 return;
13427
13428         query = createPQExpBuffer();
13429         delqry = createPQExpBuffer();
13430         labelq = createPQExpBuffer();
13431
13432         /*
13433          * DROP must be fully qualified in case same name appears in pg_catalog
13434          */
13435         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13436                                           fmtId(tginfo->dobj.name));
13437         appendPQExpBuffer(delqry, "ON %s.",
13438                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13439         appendPQExpBuffer(delqry, "%s;\n",
13440                                           fmtId(tbinfo->dobj.name));
13441
13442         if (tginfo->tgdef)
13443         {
13444                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13445         }
13446         else
13447         {
13448                 if (tginfo->tgisconstraint)
13449                 {
13450                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13451                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13452                 }
13453                 else
13454                 {
13455                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13456                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13457                 }
13458                 appendPQExpBuffer(query, "\n    ");
13459
13460                 /* Trigger type */
13461                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13462                         appendPQExpBuffer(query, "BEFORE");
13463                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13464                         appendPQExpBuffer(query, "AFTER");
13465                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13466                         appendPQExpBuffer(query, "INSTEAD OF");
13467                 else
13468                 {
13469                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13470                         exit_nicely(1);
13471                 }
13472
13473                 findx = 0;
13474                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13475                 {
13476                         appendPQExpBuffer(query, " INSERT");
13477                         findx++;
13478                 }
13479                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13480                 {
13481                         if (findx > 0)
13482                                 appendPQExpBuffer(query, " OR DELETE");
13483                         else
13484                                 appendPQExpBuffer(query, " DELETE");
13485                         findx++;
13486                 }
13487                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13488                 {
13489                         if (findx > 0)
13490                                 appendPQExpBuffer(query, " OR UPDATE");
13491                         else
13492                                 appendPQExpBuffer(query, " UPDATE");
13493                         findx++;
13494                 }
13495                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13496                 {
13497                         if (findx > 0)
13498                                 appendPQExpBuffer(query, " OR TRUNCATE");
13499                         else
13500                                 appendPQExpBuffer(query, " TRUNCATE");
13501                         findx++;
13502                 }
13503                 appendPQExpBuffer(query, " ON %s\n",
13504                                                   fmtId(tbinfo->dobj.name));
13505
13506                 if (tginfo->tgisconstraint)
13507                 {
13508                         if (OidIsValid(tginfo->tgconstrrelid))
13509                         {
13510                                 /* If we are using regclass, name is already quoted */
13511                                 if (fout->remoteVersion >= 70300)
13512                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13513                                                                           tginfo->tgconstrrelname);
13514                                 else
13515                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13516                                                                           fmtId(tginfo->tgconstrrelname));
13517                         }
13518                         if (!tginfo->tgdeferrable)
13519                                 appendPQExpBuffer(query, "NOT ");
13520                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13521                         if (tginfo->tginitdeferred)
13522                                 appendPQExpBuffer(query, "DEFERRED\n");
13523                         else
13524                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13525                 }
13526
13527                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13528                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13529                 else
13530                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13531
13532                 /* In 7.3, result of regproc is already quoted */
13533                 if (fout->remoteVersion >= 70300)
13534                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13535                                                           tginfo->tgfname);
13536                 else
13537                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13538                                                           fmtId(tginfo->tgfname));
13539
13540                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13541                                                                                   &lentgargs);
13542                 p = tgargs;
13543                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13544                 {
13545                         /* find the embedded null that terminates this trigger argument */
13546                         size_t          tlen = strlen(p);
13547
13548                         if (p + tlen >= tgargs + lentgargs)
13549                         {
13550                                 /* hm, not found before end of bytea value... */
13551                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13552                                                   tginfo->tgargs,
13553                                                   tginfo->dobj.name,
13554                                                   tbinfo->dobj.name);
13555                                 exit_nicely(1);
13556                         }
13557
13558                         if (findx > 0)
13559                                 appendPQExpBuffer(query, ", ");
13560                         appendStringLiteralAH(query, p, fout);
13561                         p += tlen + 1;
13562                 }
13563                 free(tgargs);
13564                 appendPQExpBuffer(query, ");\n");
13565         }
13566
13567         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13568         {
13569                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13570                                                   fmtId(tbinfo->dobj.name));
13571                 switch (tginfo->tgenabled)
13572                 {
13573                         case 'D':
13574                         case 'f':
13575                                 appendPQExpBuffer(query, "DISABLE");
13576                                 break;
13577                         case 'A':
13578                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13579                                 break;
13580                         case 'R':
13581                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13582                                 break;
13583                         default:
13584                                 appendPQExpBuffer(query, "ENABLE");
13585                                 break;
13586                 }
13587                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13588                                                   fmtId(tginfo->dobj.name));
13589         }
13590
13591         appendPQExpBuffer(labelq, "TRIGGER %s ",
13592                                           fmtId(tginfo->dobj.name));
13593         appendPQExpBuffer(labelq, "ON %s",
13594                                           fmtId(tbinfo->dobj.name));
13595
13596         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13597                                  tginfo->dobj.name,
13598                                  tbinfo->dobj.namespace->dobj.name,
13599                                  NULL,
13600                                  tbinfo->rolname, false,
13601                                  "TRIGGER", SECTION_POST_DATA,
13602                                  query->data, delqry->data, NULL,
13603                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13604                                  NULL, NULL);
13605
13606         dumpComment(fout, labelq->data,
13607                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13608                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13609
13610         destroyPQExpBuffer(query);
13611         destroyPQExpBuffer(delqry);
13612         destroyPQExpBuffer(labelq);
13613 }
13614
13615 /*
13616  * dumpRule
13617  *              Dump a rule
13618  */
13619 static void
13620 dumpRule(Archive *fout, RuleInfo *rinfo)
13621 {
13622         TableInfo  *tbinfo = rinfo->ruletable;
13623         PQExpBuffer query;
13624         PQExpBuffer cmd;
13625         PQExpBuffer delcmd;
13626         PQExpBuffer labelq;
13627         PGresult   *res;
13628
13629         /* Skip if not to be dumped */
13630         if (!rinfo->dobj.dump || dataOnly)
13631                 return;
13632
13633         /*
13634          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13635          * we do not want to dump it as a separate object.
13636          */
13637         if (!rinfo->separate)
13638                 return;
13639
13640         /*
13641          * Make sure we are in proper schema.
13642          */
13643         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13644
13645         query = createPQExpBuffer();
13646         cmd = createPQExpBuffer();
13647         delcmd = createPQExpBuffer();
13648         labelq = createPQExpBuffer();
13649
13650         if (fout->remoteVersion >= 70300)
13651         {
13652                 appendPQExpBuffer(query,
13653                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13654                                                   rinfo->dobj.catId.oid);
13655         }
13656         else
13657         {
13658                 /* Rule name was unique before 7.3 ... */
13659                 appendPQExpBuffer(query,
13660                                                   "SELECT pg_get_ruledef('%s') AS definition",
13661                                                   rinfo->dobj.name);
13662         }
13663
13664         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13665
13666         if (PQntuples(res) != 1)
13667         {
13668                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13669                                   rinfo->dobj.name, tbinfo->dobj.name);
13670                 exit_nicely(1);
13671         }
13672
13673         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13674
13675         /*
13676          * Add the command to alter the rules replication firing semantics if it
13677          * differs from the default.
13678          */
13679         if (rinfo->ev_enabled != 'O')
13680         {
13681                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13682                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13683                 appendPQExpBuffer(cmd, "%s ",
13684                                                   fmtId(tbinfo->dobj.name));
13685                 switch (rinfo->ev_enabled)
13686                 {
13687                         case 'A':
13688                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13689                                                                   fmtId(rinfo->dobj.name));
13690                                 break;
13691                         case 'R':
13692                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13693                                                                   fmtId(rinfo->dobj.name));
13694                                 break;
13695                         case 'D':
13696                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13697                                                                   fmtId(rinfo->dobj.name));
13698                                 break;
13699                 }
13700         }
13701
13702         /*
13703          * DROP must be fully qualified in case same name appears in pg_catalog
13704          */
13705         appendPQExpBuffer(delcmd, "DROP RULE %s ",
13706                                           fmtId(rinfo->dobj.name));
13707         appendPQExpBuffer(delcmd, "ON %s.",
13708                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13709         appendPQExpBuffer(delcmd, "%s;\n",
13710                                           fmtId(tbinfo->dobj.name));
13711
13712         appendPQExpBuffer(labelq, "RULE %s",
13713                                           fmtId(rinfo->dobj.name));
13714         appendPQExpBuffer(labelq, " ON %s",
13715                                           fmtId(tbinfo->dobj.name));
13716
13717         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13718                                  rinfo->dobj.name,
13719                                  tbinfo->dobj.namespace->dobj.name,
13720                                  NULL,
13721                                  tbinfo->rolname, false,
13722                                  "RULE", SECTION_POST_DATA,
13723                                  cmd->data, delcmd->data, NULL,
13724                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13725                                  NULL, NULL);
13726
13727         /* Dump rule comments */
13728         dumpComment(fout, labelq->data,
13729                                 tbinfo->dobj.namespace->dobj.name,
13730                                 tbinfo->rolname,
13731                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13732
13733         PQclear(res);
13734
13735         destroyPQExpBuffer(query);
13736         destroyPQExpBuffer(cmd);
13737         destroyPQExpBuffer(delcmd);
13738         destroyPQExpBuffer(labelq);
13739 }
13740
13741 /*
13742  * getExtensionMembership --- obtain extension membership data
13743  */
13744 void
13745 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13746                                            int numExtensions)
13747 {
13748         PQExpBuffer query;
13749         PGresult   *res;
13750         int                     ntups,
13751                                 i;
13752         int                     i_classid,
13753                                 i_objid,
13754                                 i_refclassid,
13755                                 i_refobjid;
13756         DumpableObject *dobj,
13757                            *refdobj;
13758
13759         /* Nothing to do if no extensions */
13760         if (numExtensions == 0)
13761                 return;
13762
13763         /* Make sure we are in proper schema */
13764         selectSourceSchema(fout, "pg_catalog");
13765
13766         query = createPQExpBuffer();
13767
13768         /* refclassid constraint is redundant but may speed the search */
13769         appendPQExpBuffer(query, "SELECT "
13770                                           "classid, objid, refclassid, refobjid "
13771                                           "FROM pg_depend "
13772                                           "WHERE refclassid = 'pg_extension'::regclass "
13773                                           "AND deptype = 'e' "
13774                                           "ORDER BY 3,4");
13775
13776         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13777
13778         ntups = PQntuples(res);
13779
13780         i_classid = PQfnumber(res, "classid");
13781         i_objid = PQfnumber(res, "objid");
13782         i_refclassid = PQfnumber(res, "refclassid");
13783         i_refobjid = PQfnumber(res, "refobjid");
13784
13785         /*
13786          * Since we ordered the SELECT by referenced ID, we can expect that
13787          * multiple entries for the same extension will appear together; this
13788          * saves on searches.
13789          */
13790         refdobj = NULL;
13791
13792         for (i = 0; i < ntups; i++)
13793         {
13794                 CatalogId       objId;
13795                 CatalogId       refobjId;
13796
13797                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13798                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13799                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13800                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13801
13802                 if (refdobj == NULL ||
13803                         refdobj->catId.tableoid != refobjId.tableoid ||
13804                         refdobj->catId.oid != refobjId.oid)
13805                         refdobj = findObjectByCatalogId(refobjId);
13806
13807                 /*
13808                  * Failure to find objects mentioned in pg_depend is not unexpected,
13809                  * since for example we don't collect info about TOAST tables.
13810                  */
13811                 if (refdobj == NULL)
13812                 {
13813 #ifdef NOT_USED
13814                         fprintf(stderr, "no referenced object %u %u\n",
13815                                         refobjId.tableoid, refobjId.oid);
13816 #endif
13817                         continue;
13818                 }
13819
13820                 dobj = findObjectByCatalogId(objId);
13821
13822                 if (dobj == NULL)
13823                 {
13824 #ifdef NOT_USED
13825                         fprintf(stderr, "no referencing object %u %u\n",
13826                                         objId.tableoid, objId.oid);
13827 #endif
13828                         continue;
13829                 }
13830
13831                 /* Record dependency so that getDependencies needn't repeat this */
13832                 addObjectDependency(dobj, refdobj->dumpId);
13833
13834                 dobj->ext_member = true;
13835
13836                 /*
13837                  * Normally, mark the member object as not to be dumped.  But in
13838                  * binary upgrades, we still dump the members individually, since the
13839                  * idea is to exactly reproduce the database contents rather than
13840                  * replace the extension contents with something different.
13841                  */
13842                 if (!binary_upgrade)
13843                         dobj->dump = false;
13844                 else
13845                         dobj->dump = refdobj->dump;
13846         }
13847
13848         PQclear(res);
13849
13850         /*
13851          * Now identify extension configuration tables and create TableDataInfo
13852          * objects for them, ensuring their data will be dumped even though the
13853          * tables themselves won't be.
13854          *
13855          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13856          * user data in a configuration table is treated like schema data. This
13857          * seems appropriate since system data in a config table would get
13858          * reloaded by CREATE EXTENSION.
13859          */
13860         for (i = 0; i < numExtensions; i++)
13861         {
13862                 ExtensionInfo *curext = &(extinfo[i]);
13863                 char       *extconfig = curext->extconfig;
13864                 char       *extcondition = curext->extcondition;
13865                 char      **extconfigarray = NULL;
13866                 char      **extconditionarray = NULL;
13867                 int                     nconfigitems;
13868                 int                     nconditionitems;
13869
13870                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13871                 if (!curext->dobj.dump)
13872                         continue;
13873
13874                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13875                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13876                         nconfigitems == nconditionitems)
13877                 {
13878                         int                     j;
13879
13880                         for (j = 0; j < nconfigitems; j++)
13881                         {
13882                                 TableInfo  *configtbl;
13883
13884                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
13885                                 if (configtbl == NULL)
13886                                         continue;
13887
13888                                 /*
13889                                  * Note: config tables are dumped without OIDs regardless of
13890                                  * the --oids setting.  This is because row filtering
13891                                  * conditions aren't compatible with dumping OIDs.
13892                                  */
13893                                 makeTableDataInfo(configtbl, false);
13894                                 if (configtbl->dataObj != NULL)
13895                                 {
13896                                         if (strlen(extconditionarray[j]) > 0)
13897                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13898                                 }
13899                         }
13900                 }
13901                 if (extconfigarray)
13902                         free(extconfigarray);
13903                 if (extconditionarray)
13904                         free(extconditionarray);
13905         }
13906
13907         destroyPQExpBuffer(query);
13908 }
13909
13910 /*
13911  * getDependencies --- obtain available dependency data
13912  */
13913 static void
13914 getDependencies(Archive *fout)
13915 {
13916         PQExpBuffer query;
13917         PGresult   *res;
13918         int                     ntups,
13919                                 i;
13920         int                     i_classid,
13921                                 i_objid,
13922                                 i_refclassid,
13923                                 i_refobjid,
13924                                 i_deptype;
13925         DumpableObject *dobj,
13926                            *refdobj;
13927
13928         /* No dependency info available before 7.3 */
13929         if (fout->remoteVersion < 70300)
13930                 return;
13931
13932         if (g_verbose)
13933                 write_msg(NULL, "reading dependency data\n");
13934
13935         /* Make sure we are in proper schema */
13936         selectSourceSchema(fout, "pg_catalog");
13937
13938         query = createPQExpBuffer();
13939
13940         /*
13941          * PIN dependencies aren't interesting, and EXTENSION dependencies were
13942          * already processed by getExtensionMembership.
13943          */
13944         appendPQExpBuffer(query, "SELECT "
13945                                           "classid, objid, refclassid, refobjid, deptype "
13946                                           "FROM pg_depend "
13947                                           "WHERE deptype != 'p' AND deptype != 'e' "
13948                                           "ORDER BY 1,2");
13949
13950         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13951
13952         ntups = PQntuples(res);
13953
13954         i_classid = PQfnumber(res, "classid");
13955         i_objid = PQfnumber(res, "objid");
13956         i_refclassid = PQfnumber(res, "refclassid");
13957         i_refobjid = PQfnumber(res, "refobjid");
13958         i_deptype = PQfnumber(res, "deptype");
13959
13960         /*
13961          * Since we ordered the SELECT by referencing ID, we can expect that
13962          * multiple entries for the same object will appear together; this saves
13963          * on searches.
13964          */
13965         dobj = NULL;
13966
13967         for (i = 0; i < ntups; i++)
13968         {
13969                 CatalogId       objId;
13970                 CatalogId       refobjId;
13971                 char            deptype;
13972
13973                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13974                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13975                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13976                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13977                 deptype = *(PQgetvalue(res, i, i_deptype));
13978
13979                 if (dobj == NULL ||
13980                         dobj->catId.tableoid != objId.tableoid ||
13981                         dobj->catId.oid != objId.oid)
13982                         dobj = findObjectByCatalogId(objId);
13983
13984                 /*
13985                  * Failure to find objects mentioned in pg_depend is not unexpected,
13986                  * since for example we don't collect info about TOAST tables.
13987                  */
13988                 if (dobj == NULL)
13989                 {
13990 #ifdef NOT_USED
13991                         fprintf(stderr, "no referencing object %u %u\n",
13992                                         objId.tableoid, objId.oid);
13993 #endif
13994                         continue;
13995                 }
13996
13997                 refdobj = findObjectByCatalogId(refobjId);
13998
13999                 if (refdobj == NULL)
14000                 {
14001 #ifdef NOT_USED
14002                         fprintf(stderr, "no referenced object %u %u\n",
14003                                         refobjId.tableoid, refobjId.oid);
14004 #endif
14005                         continue;
14006                 }
14007
14008                 /*
14009                  * Ordinarily, table rowtypes have implicit dependencies on their
14010                  * tables.      However, for a composite type the implicit dependency goes
14011                  * the other way in pg_depend; which is the right thing for DROP but
14012                  * it doesn't produce the dependency ordering we need. So in that one
14013                  * case, we reverse the direction of the dependency.
14014                  */
14015                 if (deptype == 'i' &&
14016                         dobj->objType == DO_TABLE &&
14017                         refdobj->objType == DO_TYPE)
14018                         addObjectDependency(refdobj, dobj->dumpId);
14019                 else
14020                         /* normal case */
14021                         addObjectDependency(dobj, refdobj->dumpId);
14022         }
14023
14024         PQclear(res);
14025
14026         destroyPQExpBuffer(query);
14027 }
14028
14029
14030 /*
14031  * selectSourceSchema - make the specified schema the active search path
14032  * in the source database.
14033  *
14034  * NB: pg_catalog is explicitly searched after the specified schema;
14035  * so user names are only qualified if they are cross-schema references,
14036  * and system names are only qualified if they conflict with a user name
14037  * in the current schema.
14038  *
14039  * Whenever the selected schema is not pg_catalog, be careful to qualify
14040  * references to system catalogs and types in our emitted commands!
14041  */
14042 static void
14043 selectSourceSchema(Archive *fout, const char *schemaName)
14044 {
14045         static char *curSchemaName = NULL;
14046         PQExpBuffer query;
14047
14048         /* Not relevant if fetching from pre-7.3 DB */
14049         if (fout->remoteVersion < 70300)
14050                 return;
14051         /* Ignore null schema names */
14052         if (schemaName == NULL || *schemaName == '\0')
14053                 return;
14054         /* Optimize away repeated selection of same schema */
14055         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14056                 return;
14057
14058         query = createPQExpBuffer();
14059         appendPQExpBuffer(query, "SET search_path = %s",
14060                                           fmtId(schemaName));
14061         if (strcmp(schemaName, "pg_catalog") != 0)
14062                 appendPQExpBuffer(query, ", pg_catalog");
14063
14064         ExecuteSqlStatement(fout, query->data);
14065
14066         destroyPQExpBuffer(query);
14067         if (curSchemaName)
14068                 free(curSchemaName);
14069         curSchemaName = pg_strdup(schemaName);
14070 }
14071
14072 /*
14073  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14074  * given type name.
14075  *
14076  * NB: in 7.3 and up the result may depend on the currently-selected
14077  * schema; this is why we don't try to cache the names.
14078  */
14079 static char *
14080 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14081 {
14082         char       *result;
14083         PQExpBuffer query;
14084         PGresult   *res;
14085
14086         if (oid == 0)
14087         {
14088                 if ((opts & zeroAsOpaque) != 0)
14089                         return pg_strdup(g_opaque_type);
14090                 else if ((opts & zeroAsAny) != 0)
14091                         return pg_strdup("'any'");
14092                 else if ((opts & zeroAsStar) != 0)
14093                         return pg_strdup("*");
14094                 else if ((opts & zeroAsNone) != 0)
14095                         return pg_strdup("NONE");
14096         }
14097
14098         query = createPQExpBuffer();
14099         if (fout->remoteVersion >= 70300)
14100         {
14101                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14102                                                   oid);
14103         }
14104         else if (fout->remoteVersion >= 70100)
14105         {
14106                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14107                                                   oid);
14108         }
14109         else
14110         {
14111                 appendPQExpBuffer(query, "SELECT typname "
14112                                                   "FROM pg_type "
14113                                                   "WHERE oid = '%u'::oid",
14114                                                   oid);
14115         }
14116
14117         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14118
14119         if (fout->remoteVersion >= 70100)
14120         {
14121                 /* already quoted */
14122                 result = pg_strdup(PQgetvalue(res, 0, 0));
14123         }
14124         else
14125         {
14126                 /* may need to quote it */
14127                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14128         }
14129
14130         PQclear(res);
14131         destroyPQExpBuffer(query);
14132
14133         return result;
14134 }
14135
14136 /*
14137  * myFormatType --- local implementation of format_type for use with 7.0.
14138  */
14139 static char *
14140 myFormatType(const char *typname, int32 typmod)
14141 {
14142         char       *result;
14143         bool            isarray = false;
14144         PQExpBuffer buf = createPQExpBuffer();
14145
14146         /* Handle array types */
14147         if (typname[0] == '_')
14148         {
14149                 isarray = true;
14150                 typname++;
14151         }
14152
14153         /* Show lengths on bpchar and varchar */
14154         if (strcmp(typname, "bpchar") == 0)
14155         {
14156                 int                     len = (typmod - VARHDRSZ);
14157
14158                 appendPQExpBuffer(buf, "character");
14159                 if (len > 1)
14160                         appendPQExpBuffer(buf, "(%d)",
14161                                                           typmod - VARHDRSZ);
14162         }
14163         else if (strcmp(typname, "varchar") == 0)
14164         {
14165                 appendPQExpBuffer(buf, "character varying");
14166                 if (typmod != -1)
14167                         appendPQExpBuffer(buf, "(%d)",
14168                                                           typmod - VARHDRSZ);
14169         }
14170         else if (strcmp(typname, "numeric") == 0)
14171         {
14172                 appendPQExpBuffer(buf, "numeric");
14173                 if (typmod != -1)
14174                 {
14175                         int32           tmp_typmod;
14176                         int                     precision;
14177                         int                     scale;
14178
14179                         tmp_typmod = typmod - VARHDRSZ;
14180                         precision = (tmp_typmod >> 16) & 0xffff;
14181                         scale = tmp_typmod & 0xffff;
14182                         appendPQExpBuffer(buf, "(%d,%d)",
14183                                                           precision, scale);
14184                 }
14185         }
14186
14187         /*
14188          * char is an internal single-byte data type; Let's make sure we force it
14189          * through with quotes. - thomas 1998-12-13
14190          */
14191         else if (strcmp(typname, "char") == 0)
14192                 appendPQExpBuffer(buf, "\"char\"");
14193         else
14194                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14195
14196         /* Append array qualifier for array types */
14197         if (isarray)
14198                 appendPQExpBuffer(buf, "[]");
14199
14200         result = pg_strdup(buf->data);
14201         destroyPQExpBuffer(buf);
14202
14203         return result;
14204 }
14205
14206 /*
14207  * fmtQualifiedId - convert a qualified name to the proper format for
14208  * the source database.
14209  *
14210  * Like fmtId, use the result before calling again.
14211  */
14212 static const char *
14213 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14214 {
14215         static PQExpBuffer id_return = NULL;
14216
14217         if (id_return)                          /* first time through? */
14218                 resetPQExpBuffer(id_return);
14219         else
14220                 id_return = createPQExpBuffer();
14221
14222         /* Suppress schema name if fetching from pre-7.3 DB */
14223         if (fout->remoteVersion >= 70300 && schema && *schema)
14224         {
14225                 appendPQExpBuffer(id_return, "%s.",
14226                                                   fmtId(schema));
14227         }
14228         appendPQExpBuffer(id_return, "%s",
14229                                           fmtId(id));
14230
14231         return id_return->data;
14232 }
14233
14234 /*
14235  * Return a column list clause for the given relation.
14236  *
14237  * Special case: if there are no undropped columns in the relation, return
14238  * "", not an invalid "()" column list.
14239  */
14240 static const char *
14241 fmtCopyColumnList(const TableInfo *ti)
14242 {
14243         static PQExpBuffer q = NULL;
14244         int                     numatts = ti->numatts;
14245         char      **attnames = ti->attnames;
14246         bool       *attisdropped = ti->attisdropped;
14247         bool            needComma;
14248         int                     i;
14249
14250         if (q)                                          /* first time through? */
14251                 resetPQExpBuffer(q);
14252         else
14253                 q = createPQExpBuffer();
14254
14255         appendPQExpBuffer(q, "(");
14256         needComma = false;
14257         for (i = 0; i < numatts; i++)
14258         {
14259                 if (attisdropped[i])
14260                         continue;
14261                 if (needComma)
14262                         appendPQExpBuffer(q, ", ");
14263                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14264                 needComma = true;
14265         }
14266
14267         if (!needComma)
14268                 return "";                              /* no undropped columns */
14269
14270         appendPQExpBuffer(q, ")");
14271         return q->data;
14272 }
14273
14274 /*
14275  * Execute an SQL query and verify that we got exactly one row back.
14276  */
14277 static PGresult *
14278 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14279 {
14280         PGresult   *res;
14281         int                     ntups;
14282
14283         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14284
14285         /* Expecting a single result only */
14286         ntups = PQntuples(res);
14287         if (ntups != 1)
14288                 exit_horribly(NULL,
14289                                           ngettext("query returned %d row instead of one: %s\n",
14290                                                            "query returned %d rows instead of one: %s\n",
14291                                                            ntups),
14292                                           ntups, query);
14293
14294         return res;
14295 }