]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Make pg_dump emit more accurate dependency information.
[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 BuildArchiveDependencies(Archive *fout);
214 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
215                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
216
217 static DumpableObject *createBoundaryObjects(void);
218 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
219                                                 DumpableObject *boundaryObjs);
220
221 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
222 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
223 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
224 static void getTableDataFKConstraints(void);
225 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
226 static char *format_function_arguments_old(Archive *fout,
227                                                           FuncInfo *finfo, int nallargs,
228                                                           char **allargtypes,
229                                                           char **argmodes,
230                                                           char **argnames);
231 static char *format_function_signature(Archive *fout,
232                                                   FuncInfo *finfo, bool honor_quotes);
233 static const char *convertRegProcReference(Archive *fout,
234                                                 const char *proc);
235 static const char *convertOperatorReference(Archive *fout, const char *opr);
236 static const char *convertTSFunction(Archive *fout, Oid funcOid);
237 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
238 static Oid      findLastBuiltinOid_V70(Archive *fout);
239 static void selectSourceSchema(Archive *fout, const char *schemaName);
240 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
241 static char *myFormatType(const char *typname, int32 typmod);
242 static const char *fmtQualifiedId(Archive *fout,
243                            const char *schema, const char *id);
244 static void getBlobs(Archive *fout);
245 static void dumpBlob(Archive *fout, BlobInfo *binfo);
246 static int      dumpBlobs(Archive *fout, void *arg);
247 static void dumpDatabase(Archive *AH);
248 static void dumpEncoding(Archive *AH);
249 static void dumpStdStrings(Archive *AH);
250 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
251                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
252 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
253                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
254 static void binary_upgrade_set_pg_class_oids(Archive *fout,
255                                                                  PQExpBuffer upgrade_buffer,
256                                                                  Oid pg_class_oid, bool is_index);
257 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
258                                                                 DumpableObject *dobj,
259                                                                 const char *objlabel);
260 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
261 static const char *fmtCopyColumnList(const TableInfo *ti);
262 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
263
264
265 int
266 main(int argc, char **argv)
267 {
268         int                     c;
269         const char *filename = NULL;
270         const char *format = "p";
271         const char *dbname = NULL;
272         const char *pghost = NULL;
273         const char *pgport = NULL;
274         const char *username = NULL;
275         const char *dumpencoding = NULL;
276         bool            oids = false;
277         TableInfo  *tblinfo;
278         int                     numTables;
279         DumpableObject **dobjs;
280         int                     numObjs;
281         DumpableObject *boundaryObjs;
282         int                     i;
283         enum trivalue prompt_password = TRI_DEFAULT;
284         int                     compressLevel = -1;
285         int                     plainText = 0;
286         int                     outputClean = 0;
287         int                     outputCreateDB = 0;
288         bool            outputBlobs = false;
289         int                     outputNoOwner = 0;
290         char       *outputSuperuser = NULL;
291         char       *use_role = NULL;
292         int                     my_version;
293         int                     optindex;
294         RestoreOptions *ropt;
295         ArchiveFormat archiveFormat = archUnknown;
296         ArchiveMode archiveMode;
297         Archive    *fout;                       /* the script file */
298
299         static int      disable_triggers = 0;
300         static int      outputNoTablespaces = 0;
301         static int      use_setsessauth = 0;
302
303         static struct option long_options[] = {
304                 {"data-only", no_argument, NULL, 'a'},
305                 {"blobs", no_argument, NULL, 'b'},
306                 {"clean", no_argument, NULL, 'c'},
307                 {"create", no_argument, NULL, 'C'},
308                 {"file", required_argument, NULL, 'f'},
309                 {"format", required_argument, NULL, 'F'},
310                 {"host", required_argument, NULL, 'h'},
311                 {"ignore-version", no_argument, NULL, 'i'},
312                 {"no-reconnect", no_argument, NULL, 'R'},
313                 {"oids", no_argument, NULL, 'o'},
314                 {"no-owner", no_argument, NULL, 'O'},
315                 {"port", required_argument, NULL, 'p'},
316                 {"schema", required_argument, NULL, 'n'},
317                 {"exclude-schema", required_argument, NULL, 'N'},
318                 {"schema-only", no_argument, NULL, 's'},
319                 {"superuser", required_argument, NULL, 'S'},
320                 {"table", required_argument, NULL, 't'},
321                 {"exclude-table", required_argument, NULL, 'T'},
322                 {"no-password", no_argument, NULL, 'w'},
323                 {"password", no_argument, NULL, 'W'},
324                 {"username", required_argument, NULL, 'U'},
325                 {"verbose", no_argument, NULL, 'v'},
326                 {"no-privileges", no_argument, NULL, 'x'},
327                 {"no-acl", no_argument, NULL, 'x'},
328                 {"compress", required_argument, NULL, 'Z'},
329                 {"encoding", required_argument, NULL, 'E'},
330                 {"help", no_argument, NULL, '?'},
331                 {"version", no_argument, NULL, 'V'},
332
333                 /*
334                  * the following options don't have an equivalent short option letter
335                  */
336                 {"attribute-inserts", no_argument, &column_inserts, 1},
337                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
338                 {"column-inserts", no_argument, &column_inserts, 1},
339                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
340                 {"disable-triggers", no_argument, &disable_triggers, 1},
341                 {"exclude-table-data", required_argument, NULL, 4},
342                 {"inserts", no_argument, &dump_inserts, 1},
343                 {"lock-wait-timeout", required_argument, NULL, 2},
344                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
345                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
346                 {"role", required_argument, NULL, 3},
347                 {"section", required_argument, NULL, 5},
348                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
349                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
350                 {"no-security-labels", no_argument, &no_security_labels, 1},
351                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
352
353                 {NULL, 0, NULL, 0}
354         };
355
356         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
357
358         g_verbose = false;
359
360         strcpy(g_comment_start, "-- ");
361         g_comment_end[0] = '\0';
362         strcpy(g_opaque_type, "opaque");
363
364         dataOnly = schemaOnly = false;
365         dumpSections = DUMP_UNSECTIONED;
366         lockWaitTimeout = NULL;
367
368         progname = get_progname(argv[0]);
369
370         /* Set default options based on progname */
371         if (strcmp(progname, "pg_backup") == 0)
372                 format = "c";
373
374         if (argc > 1)
375         {
376                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
377                 {
378                         help(progname);
379                         exit_nicely(0);
380                 }
381                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
382                 {
383                         puts("pg_dump (PostgreSQL) " PG_VERSION);
384                         exit_nicely(0);
385                 }
386         }
387
388         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
389                                                         long_options, &optindex)) != -1)
390         {
391                 switch (c)
392                 {
393                         case 'a':                       /* Dump data only */
394                                 dataOnly = true;
395                                 break;
396
397                         case 'b':                       /* Dump blobs */
398                                 outputBlobs = true;
399                                 break;
400
401                         case 'c':                       /* clean (i.e., drop) schema prior to create */
402                                 outputClean = 1;
403                                 break;
404
405                         case 'C':                       /* Create DB */
406                                 outputCreateDB = 1;
407                                 break;
408
409                         case 'E':                       /* Dump encoding */
410                                 dumpencoding = optarg;
411                                 break;
412
413                         case 'f':
414                                 filename = optarg;
415                                 break;
416
417                         case 'F':
418                                 format = optarg;
419                                 break;
420
421                         case 'h':                       /* server host */
422                                 pghost = optarg;
423                                 break;
424
425                         case 'i':
426                                 /* ignored, deprecated option */
427                                 break;
428
429                         case 'n':                       /* include schema(s) */
430                                 simple_string_list_append(&schema_include_patterns, optarg);
431                                 include_everything = false;
432                                 break;
433
434                         case 'N':                       /* exclude schema(s) */
435                                 simple_string_list_append(&schema_exclude_patterns, optarg);
436                                 break;
437
438                         case 'o':                       /* Dump oids */
439                                 oids = true;
440                                 break;
441
442                         case 'O':                       /* Don't reconnect to match owner */
443                                 outputNoOwner = 1;
444                                 break;
445
446                         case 'p':                       /* server port */
447                                 pgport = optarg;
448                                 break;
449
450                         case 'R':
451                                 /* no-op, still accepted for backwards compatibility */
452                                 break;
453
454                         case 's':                       /* dump schema only */
455                                 schemaOnly = true;
456                                 break;
457
458                         case 'S':                       /* Username for superuser in plain text output */
459                                 outputSuperuser = pg_strdup(optarg);
460                                 break;
461
462                         case 't':                       /* include table(s) */
463                                 simple_string_list_append(&table_include_patterns, optarg);
464                                 include_everything = false;
465                                 break;
466
467                         case 'T':                       /* exclude table(s) */
468                                 simple_string_list_append(&table_exclude_patterns, optarg);
469                                 break;
470
471                         case 'U':
472                                 username = optarg;
473                                 break;
474
475                         case 'v':                       /* verbose */
476                                 g_verbose = true;
477                                 break;
478
479                         case 'w':
480                                 prompt_password = TRI_NO;
481                                 break;
482
483                         case 'W':
484                                 prompt_password = TRI_YES;
485                                 break;
486
487                         case 'x':                       /* skip ACL dump */
488                                 aclsSkip = true;
489                                 break;
490
491                         case 'Z':                       /* Compression Level */
492                                 compressLevel = atoi(optarg);
493                                 break;
494
495                         case 0:
496                                 /* This covers the long options. */
497                                 break;
498
499                         case 2:                         /* lock-wait-timeout */
500                                 lockWaitTimeout = optarg;
501                                 break;
502
503                         case 3:                         /* SET ROLE */
504                                 use_role = optarg;
505                                 break;
506
507                         case 4:                         /* exclude table(s) data */
508                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
509                                 break;
510
511                         case 5:                         /* section */
512                                 set_dump_section(optarg, &dumpSections);
513                                 break;
514
515                         default:
516                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
517                                 exit_nicely(1);
518                 }
519         }
520
521         /* Get database name from command line */
522         if (optind < argc)
523                 dbname = argv[optind++];
524
525         /* Complain if any arguments remain */
526         if (optind < argc)
527         {
528                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
529                                 progname, argv[optind]);
530                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
531                                 progname);
532                 exit_nicely(1);
533         }
534
535         /* --column-inserts implies --inserts */
536         if (column_inserts)
537                 dump_inserts = 1;
538
539         if (dataOnly && schemaOnly)
540                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
541
542         if (dataOnly && outputClean)
543                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
544
545         if (dump_inserts && oids)
546         {
547                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
548                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
549                 exit_nicely(1);
550         }
551
552         /* Identify archive format to emit */
553         archiveFormat = parseArchiveFormat(format, &archiveMode);
554
555         /* archiveFormat specific setup */
556         if (archiveFormat == archNull)
557                 plainText = 1;
558
559         /* Custom and directory formats are compressed by default, others not */
560         if (compressLevel == -1)
561         {
562                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
563                         compressLevel = Z_DEFAULT_COMPRESSION;
564                 else
565                         compressLevel = 0;
566         }
567
568         /* Open the output file */
569         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
570
571         /* Register the cleanup hook */
572         on_exit_close_archive(fout);
573
574         if (fout == NULL)
575                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
576
577         /* Let the archiver know how noisy to be */
578         fout->verbose = g_verbose;
579
580         my_version = parse_version(PG_VERSION);
581         if (my_version < 0)
582                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
583
584         /*
585          * We allow the server to be back to 7.0, and up to any minor release of
586          * our own major version.  (See also version check in pg_dumpall.c.)
587          */
588         fout->minRemoteVersion = 70000;
589         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
590
591         /*
592          * Open the database using the Archiver, so it knows about it. Errors mean
593          * death.
594          */
595         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
596         setup_connection(fout, dumpencoding, use_role);
597
598         /*
599          * Disable security label support if server version < v9.1.x (prevents
600          * access to nonexistent pg_seclabel catalog)
601          */
602         if (fout->remoteVersion < 90100)
603                 no_security_labels = 1;
604
605         /*
606          * Start transaction-snapshot mode transaction to dump consistent data.
607          */
608         ExecuteSqlStatement(fout, "BEGIN");
609         if (fout->remoteVersion >= 90100)
610         {
611                 if (serializable_deferrable)
612                         ExecuteSqlStatement(fout,
613                                                                 "SET TRANSACTION ISOLATION LEVEL "
614                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
615                 else
616                         ExecuteSqlStatement(fout,
617                                                                 "SET TRANSACTION ISOLATION LEVEL "
618                                                                 "REPEATABLE READ");
619         }
620         else
621                 ExecuteSqlStatement(fout,
622                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
623
624         /* Select the appropriate subquery to convert user IDs to names */
625         if (fout->remoteVersion >= 80100)
626                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
627         else if (fout->remoteVersion >= 70300)
628                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
629         else
630                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
631
632         /* Find the last built-in OID, if needed */
633         if (fout->remoteVersion < 70300)
634         {
635                 if (fout->remoteVersion >= 70100)
636                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
637                                                                                                   PQdb(GetConnection(fout)));
638                 else
639                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
640                 if (g_verbose)
641                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
642         }
643
644         /* Expand schema selection patterns into OID lists */
645         if (schema_include_patterns.head != NULL)
646         {
647                 expand_schema_name_patterns(fout, &schema_include_patterns,
648                                                                         &schema_include_oids);
649                 if (schema_include_oids.head == NULL)
650                         exit_horribly(NULL, "No matching schemas were found\n");
651         }
652         expand_schema_name_patterns(fout, &schema_exclude_patterns,
653                                                                 &schema_exclude_oids);
654         /* non-matching exclusion patterns aren't an error */
655
656         /* Expand table selection patterns into OID lists */
657         if (table_include_patterns.head != NULL)
658         {
659                 expand_table_name_patterns(fout, &table_include_patterns,
660                                                                    &table_include_oids);
661                 if (table_include_oids.head == NULL)
662                         exit_horribly(NULL, "No matching tables were found\n");
663         }
664         expand_table_name_patterns(fout, &table_exclude_patterns,
665                                                            &table_exclude_oids);
666
667         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
668                                                            &tabledata_exclude_oids);
669
670         /* non-matching exclusion patterns aren't an error */
671
672         /*
673          * Dumping blobs is now default unless we saw an inclusion switch or -s
674          * ... but even if we did see one of these, -b turns it back on.
675          */
676         if (include_everything && !schemaOnly)
677                 outputBlobs = true;
678
679         /*
680          * Now scan the database and create DumpableObject structs for all the
681          * objects we intend to dump.
682          */
683         tblinfo = getSchemaData(fout, &numTables);
684
685         if (fout->remoteVersion < 80400)
686                 guessConstraintInheritance(tblinfo, numTables);
687
688         if (!schemaOnly)
689         {
690                 getTableData(tblinfo, numTables, oids);
691                 if (dataOnly)
692                         getTableDataFKConstraints();
693         }
694
695         if (outputBlobs)
696                 getBlobs(fout);
697
698         /*
699          * Collect dependency data to assist in ordering the objects.
700          */
701         getDependencies(fout);
702
703         /* Lastly, create dummy objects to represent the section boundaries */
704         boundaryObjs = createBoundaryObjects();
705
706         /* Get pointers to all the known DumpableObjects */
707         getDumpableObjects(&dobjs, &numObjs);
708
709         /*
710          * Add dummy dependencies to enforce the dump section ordering.
711          */
712         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
713
714         /*
715          * Sort the objects into a safe dump order (no forward references).
716          *
717          * In 7.3 or later, we can rely on dependency information to help us
718          * determine a safe order, so the initial sort is mostly for cosmetic
719          * purposes: we sort by name to ensure that logically identical schemas
720          * will dump identically.  Before 7.3 we don't have dependencies and we
721          * use OID ordering as an (unreliable) guide to creation order.
722          */
723         if (fout->remoteVersion >= 70300)
724                 sortDumpableObjectsByTypeName(dobjs, numObjs);
725         else
726                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
727
728         sortDumpableObjects(dobjs, numObjs,
729                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
730
731         /*
732          * Create archive TOC entries for all the objects to be dumped, in a safe
733          * order.
734          */
735
736         /* First the special ENCODING and STDSTRINGS entries. */
737         dumpEncoding(fout);
738         dumpStdStrings(fout);
739
740         /* The database item is always next, unless we don't want it at all */
741         if (include_everything && !dataOnly)
742                 dumpDatabase(fout);
743
744         /* Now the rearrangeable objects. */
745         for (i = 0; i < numObjs; i++)
746                 dumpDumpableObject(fout, dobjs[i]);
747
748         /*
749          * Set up options info to ensure we dump what we want.
750          */
751         ropt = NewRestoreOptions();
752         ropt->filename = filename;
753         ropt->dropSchema = outputClean;
754         ropt->dataOnly = dataOnly;
755         ropt->schemaOnly = schemaOnly;
756         ropt->dumpSections = dumpSections;
757         ropt->aclsSkip = aclsSkip;
758         ropt->superuser = outputSuperuser;
759         ropt->createDB = outputCreateDB;
760         ropt->noOwner = outputNoOwner;
761         ropt->noTablespace = outputNoTablespaces;
762         ropt->disable_triggers = disable_triggers;
763         ropt->use_setsessauth = use_setsessauth;
764
765         if (compressLevel == -1)
766                 ropt->compression = 0;
767         else
768                 ropt->compression = compressLevel;
769
770         ropt->suppressDumpWarnings = true;      /* We've already shown them */
771
772         SetArchiveRestoreOptions(fout, ropt);
773
774         /*
775          * The archive's TOC entries are now marked as to which ones will
776          * actually be output, so we can set up their dependency lists properly.
777          * This isn't necessary for plain-text output, though.
778          */
779         if (!plainText)
780                 BuildArchiveDependencies(fout);
781
782         /*
783          * And finally we can do the actual output.
784          *
785          * Note: for non-plain-text output formats, the output file is written
786          * inside CloseArchive().  This is, um, bizarre; but not worth changing
787          * right now.
788          */
789         if (plainText)
790                 RestoreArchive(fout);
791
792         CloseArchive(fout);
793
794         exit_nicely(0);
795 }
796
797
798 static void
799 help(const char *progname)
800 {
801         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
802         printf(_("Usage:\n"));
803         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
804
805         printf(_("\nGeneral options:\n"));
806         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
807         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
808                          "                               plain text (default))\n"));
809         printf(_("  -v, --verbose                verbose mode\n"));
810         printf(_("  -V, --version                output version information, then exit\n"));
811         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
812         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
813         printf(_("  -?, --help                   show this help, then exit\n"));
814
815         printf(_("\nOptions controlling the output content:\n"));
816         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
817         printf(_("  -b, --blobs                  include large objects in dump\n"));
818         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
819         printf(_("  -C, --create                 include commands to create database in dump\n"));
820         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
821         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
822         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
823         printf(_("  -o, --oids                   include OIDs in dump\n"));
824         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
825                          "                               plain-text format\n"));
826         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
827         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
828         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
829         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
830         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
831         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
832         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
833         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
834         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
835         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
836         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
837         printf(_("  --no-security-labels         do not dump security label assignments\n"));
838         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
839         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
840         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
841         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
842         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
843         printf(_("  --use-set-session-authorization\n"
844                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
845                          "                               ALTER OWNER commands to set ownership\n"));
846
847         printf(_("\nConnection options:\n"));
848         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
849         printf(_("  -p, --port=PORT          database server port number\n"));
850         printf(_("  -U, --username=NAME      connect as specified database user\n"));
851         printf(_("  -w, --no-password        never prompt for password\n"));
852         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
853         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
854
855         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
856                          "variable value is used.\n\n"));
857         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
858 }
859
860 static void
861 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
862 {
863         PGconn     *conn = GetConnection(AH);
864         const char *std_strings;
865
866         /* Set the client encoding if requested */
867         if (dumpencoding)
868         {
869                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
870                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
871                                                   dumpencoding);
872         }
873
874         /*
875          * Get the active encoding and the standard_conforming_strings setting, so
876          * we know how to escape strings.
877          */
878         AH->encoding = PQclientEncoding(conn);
879
880         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
881         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
882
883         /* Set the role if requested */
884         if (use_role && AH->remoteVersion >= 80100)
885         {
886                 PQExpBuffer query = createPQExpBuffer();
887
888                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
889                 ExecuteSqlStatement(AH, query->data);
890                 destroyPQExpBuffer(query);
891         }
892
893         /* Set the datestyle to ISO to ensure the dump's portability */
894         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
895
896         /* Likewise, avoid using sql_standard intervalstyle */
897         if (AH->remoteVersion >= 80400)
898                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
899
900         /*
901          * If supported, set extra_float_digits so that we can dump float data
902          * exactly (given correctly implemented float I/O code, anyway)
903          */
904         if (AH->remoteVersion >= 90000)
905                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
906         else if (AH->remoteVersion >= 70400)
907                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
908
909         /*
910          * If synchronized scanning is supported, disable it, to prevent
911          * unpredictable changes in row ordering across a dump and reload.
912          */
913         if (AH->remoteVersion >= 80300)
914                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
915
916         /*
917          * Disable timeouts if supported.
918          */
919         if (AH->remoteVersion >= 70300)
920                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
921
922         /*
923          * Quote all identifiers, if requested.
924          */
925         if (quote_all_identifiers && AH->remoteVersion >= 90100)
926                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
927 }
928
929 static ArchiveFormat
930 parseArchiveFormat(const char *format, ArchiveMode *mode)
931 {
932         ArchiveFormat archiveFormat;
933
934         *mode = archModeWrite;
935
936         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
937         {
938                 /* This is used by pg_dumpall, and is not documented */
939                 archiveFormat = archNull;
940                 *mode = archModeAppend;
941         }
942         else if (pg_strcasecmp(format, "c") == 0)
943                 archiveFormat = archCustom;
944         else if (pg_strcasecmp(format, "custom") == 0)
945                 archiveFormat = archCustom;
946         else if (pg_strcasecmp(format, "d") == 0)
947                 archiveFormat = archDirectory;
948         else if (pg_strcasecmp(format, "directory") == 0)
949                 archiveFormat = archDirectory;
950         else if (pg_strcasecmp(format, "p") == 0)
951                 archiveFormat = archNull;
952         else if (pg_strcasecmp(format, "plain") == 0)
953                 archiveFormat = archNull;
954         else if (pg_strcasecmp(format, "t") == 0)
955                 archiveFormat = archTar;
956         else if (pg_strcasecmp(format, "tar") == 0)
957                 archiveFormat = archTar;
958         else
959                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
960         return archiveFormat;
961 }
962
963 /*
964  * Find the OIDs of all schemas matching the given list of patterns,
965  * and append them to the given OID list.
966  */
967 static void
968 expand_schema_name_patterns(Archive *fout,
969                                                         SimpleStringList *patterns,
970                                                         SimpleOidList *oids)
971 {
972         PQExpBuffer query;
973         PGresult   *res;
974         SimpleStringListCell *cell;
975         int                     i;
976
977         if (patterns->head == NULL)
978                 return;                                 /* nothing to do */
979
980         if (fout->remoteVersion < 70300)
981                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
982
983         query = createPQExpBuffer();
984
985         /*
986          * We use UNION ALL rather than UNION; this might sometimes result in
987          * duplicate entries in the OID list, but we don't care.
988          */
989
990         for (cell = patterns->head; cell; cell = cell->next)
991         {
992                 if (cell != patterns->head)
993                         appendPQExpBuffer(query, "UNION ALL\n");
994                 appendPQExpBuffer(query,
995                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
996                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
997                                                           false, NULL, "n.nspname", NULL, NULL);
998         }
999
1000         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1001
1002         for (i = 0; i < PQntuples(res); i++)
1003         {
1004                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1005         }
1006
1007         PQclear(res);
1008         destroyPQExpBuffer(query);
1009 }
1010
1011 /*
1012  * Find the OIDs of all tables matching the given list of patterns,
1013  * and append them to the given OID list.
1014  */
1015 static void
1016 expand_table_name_patterns(Archive *fout,
1017                                                    SimpleStringList *patterns, SimpleOidList *oids)
1018 {
1019         PQExpBuffer query;
1020         PGresult   *res;
1021         SimpleStringListCell *cell;
1022         int                     i;
1023
1024         if (patterns->head == NULL)
1025                 return;                                 /* nothing to do */
1026
1027         query = createPQExpBuffer();
1028
1029         /*
1030          * We use UNION ALL rather than UNION; this might sometimes result in
1031          * duplicate entries in the OID list, but we don't care.
1032          */
1033
1034         for (cell = patterns->head; cell; cell = cell->next)
1035         {
1036                 if (cell != patterns->head)
1037                         appendPQExpBuffer(query, "UNION ALL\n");
1038                 appendPQExpBuffer(query,
1039                                                   "SELECT c.oid"
1040                                                   "\nFROM pg_catalog.pg_class c"
1041                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1042                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1043                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1044                                                   RELKIND_FOREIGN_TABLE);
1045                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1046                                                           false, "n.nspname", "c.relname", NULL,
1047                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1048         }
1049
1050         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1051
1052         for (i = 0; i < PQntuples(res); i++)
1053         {
1054                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1055         }
1056
1057         PQclear(res);
1058         destroyPQExpBuffer(query);
1059 }
1060
1061 /*
1062  * selectDumpableNamespace: policy-setting subroutine
1063  *              Mark a namespace as to be dumped or not
1064  */
1065 static void
1066 selectDumpableNamespace(NamespaceInfo *nsinfo)
1067 {
1068         /*
1069          * If specific tables are being dumped, do not dump any complete
1070          * namespaces. If specific namespaces are being dumped, dump just those
1071          * namespaces. Otherwise, dump all non-system namespaces.
1072          */
1073         if (table_include_oids.head != NULL)
1074                 nsinfo->dobj.dump = false;
1075         else if (schema_include_oids.head != NULL)
1076                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1077                                                                                                    nsinfo->dobj.catId.oid);
1078         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1079                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1080                 nsinfo->dobj.dump = false;
1081         else
1082                 nsinfo->dobj.dump = true;
1083
1084         /*
1085          * In any case, a namespace can be excluded by an exclusion switch
1086          */
1087         if (nsinfo->dobj.dump &&
1088                 simple_oid_list_member(&schema_exclude_oids,
1089                                                            nsinfo->dobj.catId.oid))
1090                 nsinfo->dobj.dump = false;
1091 }
1092
1093 /*
1094  * selectDumpableTable: policy-setting subroutine
1095  *              Mark a table as to be dumped or not
1096  */
1097 static void
1098 selectDumpableTable(TableInfo *tbinfo)
1099 {
1100         /*
1101          * If specific tables are being dumped, dump just those tables; else, dump
1102          * according to the parent namespace's dump flag.
1103          */
1104         if (table_include_oids.head != NULL)
1105                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1106                                                                                                    tbinfo->dobj.catId.oid);
1107         else
1108                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1109
1110         /*
1111          * In any case, a table can be excluded by an exclusion switch
1112          */
1113         if (tbinfo->dobj.dump &&
1114                 simple_oid_list_member(&table_exclude_oids,
1115                                                            tbinfo->dobj.catId.oid))
1116                 tbinfo->dobj.dump = false;
1117 }
1118
1119 /*
1120  * selectDumpableType: policy-setting subroutine
1121  *              Mark a type as to be dumped or not
1122  *
1123  * If it's a table's rowtype or an autogenerated array type, we also apply a
1124  * special type code to facilitate sorting into the desired order.      (We don't
1125  * want to consider those to be ordinary types because that would bring tables
1126  * up into the datatype part of the dump order.)  We still set the object's
1127  * dump flag; that's not going to cause the dummy type to be dumped, but we
1128  * need it so that casts involving such types will be dumped correctly -- see
1129  * dumpCast.  This means the flag should be set the same as for the underlying
1130  * object (the table or base type).
1131  */
1132 static void
1133 selectDumpableType(TypeInfo *tyinfo)
1134 {
1135         /* skip complex types, except for standalone composite types */
1136         if (OidIsValid(tyinfo->typrelid) &&
1137                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1138         {
1139                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1140
1141                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1142                 if (tytable != NULL)
1143                         tyinfo->dobj.dump = tytable->dobj.dump;
1144                 else
1145                         tyinfo->dobj.dump = false;
1146                 return;
1147         }
1148
1149         /* skip auto-generated array types */
1150         if (tyinfo->isArray)
1151         {
1152                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1153
1154                 /*
1155                  * Fall through to set the dump flag; we assume that the subsequent
1156                  * rules will do the same thing as they would for the array's base
1157                  * type.  (We cannot reliably look up the base type here, since
1158                  * getTypes may not have processed it yet.)
1159                  */
1160         }
1161
1162         /* dump only types in dumpable namespaces */
1163         if (!tyinfo->dobj.namespace->dobj.dump)
1164                 tyinfo->dobj.dump = false;
1165
1166         /* skip undefined placeholder types */
1167         else if (!tyinfo->isDefined)
1168                 tyinfo->dobj.dump = false;
1169
1170         else
1171                 tyinfo->dobj.dump = true;
1172 }
1173
1174 /*
1175  * selectDumpableDefaultACL: policy-setting subroutine
1176  *              Mark a default ACL as to be dumped or not
1177  *
1178  * For per-schema default ACLs, dump if the schema is to be dumped.
1179  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1180  * and aclsSkip are checked separately.
1181  */
1182 static void
1183 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1184 {
1185         if (dinfo->dobj.namespace)
1186                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1187         else
1188                 dinfo->dobj.dump = include_everything;
1189 }
1190
1191 /*
1192  * selectDumpableExtension: policy-setting subroutine
1193  *              Mark an extension as to be dumped or not
1194  *
1195  * Normally, we dump all extensions, or none of them if include_everything
1196  * is false (i.e., a --schema or --table switch was given).  However, in
1197  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1198  * assume those will already be installed in the target database.  We identify
1199  * such extensions by their having OIDs in the range reserved for initdb.
1200  */
1201 static void
1202 selectDumpableExtension(ExtensionInfo *extinfo)
1203 {
1204         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1205                 extinfo->dobj.dump = false;
1206         else
1207                 extinfo->dobj.dump = include_everything;
1208 }
1209
1210 /*
1211  * selectDumpableObject: policy-setting subroutine
1212  *              Mark a generic dumpable object as to be dumped or not
1213  *
1214  * Use this only for object types without a special-case routine above.
1215  */
1216 static void
1217 selectDumpableObject(DumpableObject *dobj)
1218 {
1219         /*
1220          * Default policy is to dump if parent namespace is dumpable, or always
1221          * for non-namespace-associated items.
1222          */
1223         if (dobj->namespace)
1224                 dobj->dump = dobj->namespace->dobj.dump;
1225         else
1226                 dobj->dump = true;
1227 }
1228
1229 /*
1230  *      Dump a table's contents for loading using the COPY command
1231  *      - this routine is called by the Archiver when it wants the table
1232  *        to be dumped.
1233  */
1234
1235 static int
1236 dumpTableData_copy(Archive *fout, void *dcontext)
1237 {
1238         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1239         TableInfo  *tbinfo = tdinfo->tdtable;
1240         const char *classname = tbinfo->dobj.name;
1241         const bool      hasoids = tbinfo->hasoids;
1242         const bool      oids = tdinfo->oids;
1243         PQExpBuffer q = createPQExpBuffer();
1244         PGconn     *conn = GetConnection(fout);
1245         PGresult   *res;
1246         int                     ret;
1247         char       *copybuf;
1248         const char *column_list;
1249
1250         if (g_verbose)
1251                 write_msg(NULL, "dumping contents of table %s\n", classname);
1252
1253         /*
1254          * Make sure we are in proper schema.  We will qualify the table name
1255          * below anyway (in case its name conflicts with a pg_catalog table); but
1256          * this ensures reproducible results in case the table contains regproc,
1257          * regclass, etc columns.
1258          */
1259         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1260
1261         /*
1262          * If possible, specify the column list explicitly so that we have no
1263          * possibility of retrieving data in the wrong column order.  (The default
1264          * column ordering of COPY will not be what we want in certain corner
1265          * cases involving ADD COLUMN and inheritance.)
1266          */
1267         if (fout->remoteVersion >= 70300)
1268                 column_list = fmtCopyColumnList(tbinfo);
1269         else
1270                 column_list = "";               /* can't select columns in COPY */
1271
1272         if (oids && hasoids)
1273         {
1274                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1275                                                   fmtQualifiedId(fout,
1276                                                                                  tbinfo->dobj.namespace->dobj.name,
1277                                                                                  classname),
1278                                                   column_list);
1279         }
1280         else if (tdinfo->filtercond)
1281         {
1282                 /* Note: this syntax is only supported in 8.2 and up */
1283                 appendPQExpBufferStr(q, "COPY (SELECT ");
1284                 /* klugery to get rid of parens in column list */
1285                 if (strlen(column_list) > 2)
1286                 {
1287                         appendPQExpBufferStr(q, column_list + 1);
1288                         q->data[q->len - 1] = ' ';
1289                 }
1290                 else
1291                         appendPQExpBufferStr(q, "* ");
1292                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1293                                                   fmtQualifiedId(fout,
1294                                                                                  tbinfo->dobj.namespace->dobj.name,
1295                                                                                  classname),
1296                                                   tdinfo->filtercond);
1297         }
1298         else
1299         {
1300                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1301                                                   fmtQualifiedId(fout,
1302                                                                                  tbinfo->dobj.namespace->dobj.name,
1303                                                                                  classname),
1304                                                   column_list);
1305         }
1306         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1307         PQclear(res);
1308
1309         for (;;)
1310         {
1311                 ret = PQgetCopyData(conn, &copybuf, 0);
1312
1313                 if (ret < 0)
1314                         break;                          /* done or error */
1315
1316                 if (copybuf)
1317                 {
1318                         WriteData(fout, copybuf, ret);
1319                         PQfreemem(copybuf);
1320                 }
1321
1322                 /* ----------
1323                  * THROTTLE:
1324                  *
1325                  * There was considerable discussion in late July, 2000 regarding
1326                  * slowing down pg_dump when backing up large tables. Users with both
1327                  * slow & fast (multi-processor) machines experienced performance
1328                  * degradation when doing a backup.
1329                  *
1330                  * Initial attempts based on sleeping for a number of ms for each ms
1331                  * of work were deemed too complex, then a simple 'sleep in each loop'
1332                  * implementation was suggested. The latter failed because the loop
1333                  * was too tight. Finally, the following was implemented:
1334                  *
1335                  * If throttle is non-zero, then
1336                  *              See how long since the last sleep.
1337                  *              Work out how long to sleep (based on ratio).
1338                  *              If sleep is more than 100ms, then
1339                  *                      sleep
1340                  *                      reset timer
1341                  *              EndIf
1342                  * EndIf
1343                  *
1344                  * where the throttle value was the number of ms to sleep per ms of
1345                  * work. The calculation was done in each loop.
1346                  *
1347                  * Most of the hard work is done in the backend, and this solution
1348                  * still did not work particularly well: on slow machines, the ratio
1349                  * was 50:1, and on medium paced machines, 1:1, and on fast
1350                  * multi-processor machines, it had little or no effect, for reasons
1351                  * that were unclear.
1352                  *
1353                  * Further discussion ensued, and the proposal was dropped.
1354                  *
1355                  * For those people who want this feature, it can be implemented using
1356                  * gettimeofday in each loop, calculating the time since last sleep,
1357                  * multiplying that by the sleep ratio, then if the result is more
1358                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1359                  * function to sleep for a subsecond period ie.
1360                  *
1361                  * select(0, NULL, NULL, NULL, &tvi);
1362                  *
1363                  * This will return after the interval specified in the structure tvi.
1364                  * Finally, call gettimeofday again to save the 'last sleep time'.
1365                  * ----------
1366                  */
1367         }
1368         archprintf(fout, "\\.\n\n\n");
1369
1370         if (ret == -2)
1371         {
1372                 /* copy data transfer failed */
1373                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1374                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1375                 write_msg(NULL, "The command was: %s\n", q->data);
1376                 exit_nicely(1);
1377         }
1378
1379         /* Check command status and return to normal libpq state */
1380         res = PQgetResult(conn);
1381         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1382         {
1383                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1384                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1385                 write_msg(NULL, "The command was: %s\n", q->data);
1386                 exit_nicely(1);
1387         }
1388         PQclear(res);
1389
1390         destroyPQExpBuffer(q);
1391         return 1;
1392 }
1393
1394 /*
1395  * Dump table data using INSERT commands.
1396  *
1397  * Caution: when we restore from an archive file direct to database, the
1398  * INSERT commands emitted by this function have to be parsed by
1399  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1400  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1401  */
1402 static int
1403 dumpTableData_insert(Archive *fout, void *dcontext)
1404 {
1405         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1406         TableInfo  *tbinfo = tdinfo->tdtable;
1407         const char *classname = tbinfo->dobj.name;
1408         PQExpBuffer q = createPQExpBuffer();
1409         PGresult   *res;
1410         int                     tuple;
1411         int                     nfields;
1412         int                     field;
1413
1414         /*
1415          * Make sure we are in proper schema.  We will qualify the table name
1416          * below anyway (in case its name conflicts with a pg_catalog table); but
1417          * this ensures reproducible results in case the table contains regproc,
1418          * regclass, etc columns.
1419          */
1420         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1421
1422         if (fout->remoteVersion >= 70100)
1423         {
1424                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1425                                                   "SELECT * FROM ONLY %s",
1426                                                   fmtQualifiedId(fout,
1427                                                                                  tbinfo->dobj.namespace->dobj.name,
1428                                                                                  classname));
1429         }
1430         else
1431         {
1432                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1433                                                   "SELECT * FROM %s",
1434                                                   fmtQualifiedId(fout,
1435                                                                                  tbinfo->dobj.namespace->dobj.name,
1436                                                                                  classname));
1437         }
1438         if (tdinfo->filtercond)
1439                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1440
1441         ExecuteSqlStatement(fout, q->data);
1442
1443         while (1)
1444         {
1445                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1446                                                           PGRES_TUPLES_OK);
1447                 nfields = PQnfields(res);
1448                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1449                 {
1450                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1451                         if (nfields == 0)
1452                         {
1453                                 /* corner case for zero-column table */
1454                                 archprintf(fout, "DEFAULT VALUES;\n");
1455                                 continue;
1456                         }
1457                         if (column_inserts)
1458                         {
1459                                 resetPQExpBuffer(q);
1460                                 appendPQExpBuffer(q, "(");
1461                                 for (field = 0; field < nfields; field++)
1462                                 {
1463                                         if (field > 0)
1464                                                 appendPQExpBuffer(q, ", ");
1465                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1466                                 }
1467                                 appendPQExpBuffer(q, ") ");
1468                                 archputs(q->data, fout);
1469                         }
1470                         archprintf(fout, "VALUES (");
1471                         for (field = 0; field < nfields; field++)
1472                         {
1473                                 if (field > 0)
1474                                         archprintf(fout, ", ");
1475                                 if (PQgetisnull(res, tuple, field))
1476                                 {
1477                                         archprintf(fout, "NULL");
1478                                         continue;
1479                                 }
1480
1481                                 /* XXX This code is partially duplicated in ruleutils.c */
1482                                 switch (PQftype(res, field))
1483                                 {
1484                                         case INT2OID:
1485                                         case INT4OID:
1486                                         case INT8OID:
1487                                         case OIDOID:
1488                                         case FLOAT4OID:
1489                                         case FLOAT8OID:
1490                                         case NUMERICOID:
1491                                                 {
1492                                                         /*
1493                                                          * These types are printed without quotes unless
1494                                                          * they contain values that aren't accepted by the
1495                                                          * scanner unquoted (e.g., 'NaN').      Note that
1496                                                          * strtod() and friends might accept NaN, so we
1497                                                          * can't use that to test.
1498                                                          *
1499                                                          * In reality we only need to defend against
1500                                                          * infinity and NaN, so we need not get too crazy
1501                                                          * about pattern matching here.
1502                                                          */
1503                                                         const char *s = PQgetvalue(res, tuple, field);
1504
1505                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1506                                                                 archprintf(fout, "%s", s);
1507                                                         else
1508                                                                 archprintf(fout, "'%s'", s);
1509                                                 }
1510                                                 break;
1511
1512                                         case BITOID:
1513                                         case VARBITOID:
1514                                                 archprintf(fout, "B'%s'",
1515                                                                    PQgetvalue(res, tuple, field));
1516                                                 break;
1517
1518                                         case BOOLOID:
1519                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1520                                                         archprintf(fout, "true");
1521                                                 else
1522                                                         archprintf(fout, "false");
1523                                                 break;
1524
1525                                         default:
1526                                                 /* All other types are printed as string literals. */
1527                                                 resetPQExpBuffer(q);
1528                                                 appendStringLiteralAH(q,
1529                                                                                           PQgetvalue(res, tuple, field),
1530                                                                                           fout);
1531                                                 archputs(q->data, fout);
1532                                                 break;
1533                                 }
1534                         }
1535                         archprintf(fout, ");\n");
1536                 }
1537
1538                 if (PQntuples(res) <= 0)
1539                 {
1540                         PQclear(res);
1541                         break;
1542                 }
1543                 PQclear(res);
1544         }
1545
1546         archprintf(fout, "\n\n");
1547
1548         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1549
1550         destroyPQExpBuffer(q);
1551         return 1;
1552 }
1553
1554
1555 /*
1556  * dumpTableData -
1557  *        dump the contents of a single table
1558  *
1559  * Actually, this just makes an ArchiveEntry for the table contents.
1560  */
1561 static void
1562 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1563 {
1564         TableInfo  *tbinfo = tdinfo->tdtable;
1565         PQExpBuffer copyBuf = createPQExpBuffer();
1566         DataDumperPtr dumpFn;
1567         char       *copyStmt;
1568
1569         if (!dump_inserts)
1570         {
1571                 /* Dump/restore using COPY */
1572                 dumpFn = dumpTableData_copy;
1573                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1574                 appendPQExpBuffer(copyBuf, "COPY %s ",
1575                                                   fmtId(tbinfo->dobj.name));
1576                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1577                                                   fmtCopyColumnList(tbinfo),
1578                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1579                 copyStmt = copyBuf->data;
1580         }
1581         else
1582         {
1583                 /* Restore using INSERT */
1584                 dumpFn = dumpTableData_insert;
1585                 copyStmt = NULL;
1586         }
1587
1588         /*
1589          * Note: although the TableDataInfo is a full DumpableObject, we treat its
1590          * dependency on its table as "special" and pass it to ArchiveEntry now.
1591          * See comments for BuildArchiveDependencies.
1592          */
1593         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1594                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1595                                  NULL, tbinfo->rolname,
1596                                  false, "TABLE DATA", SECTION_DATA,
1597                                  "", "", copyStmt,
1598                                  &(tbinfo->dobj.dumpId), 1,
1599                                  dumpFn, tdinfo);
1600
1601         destroyPQExpBuffer(copyBuf);
1602 }
1603
1604 /*
1605  * getTableData -
1606  *        set up dumpable objects representing the contents of tables
1607  */
1608 static void
1609 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1610 {
1611         int                     i;
1612
1613         for (i = 0; i < numTables; i++)
1614         {
1615                 if (tblinfo[i].dobj.dump)
1616                         makeTableDataInfo(&(tblinfo[i]), oids);
1617         }
1618 }
1619
1620 /*
1621  * Make a dumpable object for the data of this specific table
1622  *
1623  * Note: we make a TableDataInfo if and only if we are going to dump the
1624  * table data; the "dump" flag in such objects isn't used.
1625  */
1626 static void
1627 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1628 {
1629         TableDataInfo *tdinfo;
1630
1631         /*
1632          * Nothing to do if we already decided to dump the table.  This will
1633          * happen for "config" tables.
1634          */
1635         if (tbinfo->dataObj != NULL)
1636                 return;
1637
1638         /* Skip VIEWs (no data to dump) */
1639         if (tbinfo->relkind == RELKIND_VIEW)
1640                 return;
1641         /* Skip SEQUENCEs (handled elsewhere) */
1642         if (tbinfo->relkind == RELKIND_SEQUENCE)
1643                 return;
1644         /* Skip FOREIGN TABLEs (no data to dump) */
1645         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1646                 return;
1647
1648         /* Don't dump data in unlogged tables, if so requested */
1649         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1650                 no_unlogged_table_data)
1651                 return;
1652
1653         /* Check that the data is not explicitly excluded */
1654         if (simple_oid_list_member(&tabledata_exclude_oids,
1655                                                            tbinfo->dobj.catId.oid))
1656                 return;
1657
1658         /* OK, let's dump it */
1659         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1660
1661         tdinfo->dobj.objType = DO_TABLE_DATA;
1662
1663         /*
1664          * Note: use tableoid 0 so that this object won't be mistaken for
1665          * something that pg_depend entries apply to.
1666          */
1667         tdinfo->dobj.catId.tableoid = 0;
1668         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1669         AssignDumpId(&tdinfo->dobj);
1670         tdinfo->dobj.name = tbinfo->dobj.name;
1671         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1672         tdinfo->tdtable = tbinfo;
1673         tdinfo->oids = oids;
1674         tdinfo->filtercond = NULL;      /* might get set later */
1675         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1676
1677         tbinfo->dataObj = tdinfo;
1678 }
1679
1680 /*
1681  * getTableDataFKConstraints -
1682  *        add dump-order dependencies reflecting foreign key constraints
1683  *
1684  * This code is executed only in a data-only dump --- in schema+data dumps
1685  * we handle foreign key issues by not creating the FK constraints until
1686  * after the data is loaded.  In a data-only dump, however, we want to
1687  * order the table data objects in such a way that a table's referenced
1688  * tables are restored first.  (In the presence of circular references or
1689  * self-references this may be impossible; we'll detect and complain about
1690  * that during the dependency sorting step.)
1691  */
1692 static void
1693 getTableDataFKConstraints(void)
1694 {
1695         DumpableObject **dobjs;
1696         int                     numObjs;
1697         int                     i;
1698
1699         /* Search through all the dumpable objects for FK constraints */
1700         getDumpableObjects(&dobjs, &numObjs);
1701         for (i = 0; i < numObjs; i++)
1702         {
1703                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1704                 {
1705                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1706                         TableInfo  *ftable;
1707
1708                         /* Not interesting unless both tables are to be dumped */
1709                         if (cinfo->contable == NULL ||
1710                                 cinfo->contable->dataObj == NULL)
1711                                 continue;
1712                         ftable = findTableByOid(cinfo->confrelid);
1713                         if (ftable == NULL ||
1714                                 ftable->dataObj == NULL)
1715                                 continue;
1716
1717                         /*
1718                          * Okay, make referencing table's TABLE_DATA object depend on the
1719                          * referenced table's TABLE_DATA object.
1720                          */
1721                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1722                                                                 ftable->dataObj->dobj.dumpId);
1723                 }
1724         }
1725         free(dobjs);
1726 }
1727
1728
1729 /*
1730  * guessConstraintInheritance:
1731  *      In pre-8.4 databases, we can't tell for certain which constraints
1732  *      are inherited.  We assume a CHECK constraint is inherited if its name
1733  *      matches the name of any constraint in the parent.  Originally this code
1734  *      tried to compare the expression texts, but that can fail for various
1735  *      reasons --- for example, if the parent and child tables are in different
1736  *      schemas, reverse-listing of function calls may produce different text
1737  *      (schema-qualified or not) depending on search path.
1738  *
1739  *      In 8.4 and up we can rely on the conislocal field to decide which
1740  *      constraints must be dumped; much safer.
1741  *
1742  *      This function assumes all conislocal flags were initialized to TRUE.
1743  *      It clears the flag on anything that seems to be inherited.
1744  */
1745 static void
1746 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1747 {
1748         int                     i,
1749                                 j,
1750                                 k;
1751
1752         for (i = 0; i < numTables; i++)
1753         {
1754                 TableInfo  *tbinfo = &(tblinfo[i]);
1755                 int                     numParents;
1756                 TableInfo **parents;
1757                 TableInfo  *parent;
1758
1759                 /* Sequences and views never have parents */
1760                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1761                         tbinfo->relkind == RELKIND_VIEW)
1762                         continue;
1763
1764                 /* Don't bother computing anything for non-target tables, either */
1765                 if (!tbinfo->dobj.dump)
1766                         continue;
1767
1768                 numParents = tbinfo->numParents;
1769                 parents = tbinfo->parents;
1770
1771                 if (numParents == 0)
1772                         continue;                       /* nothing to see here, move along */
1773
1774                 /* scan for inherited CHECK constraints */
1775                 for (j = 0; j < tbinfo->ncheck; j++)
1776                 {
1777                         ConstraintInfo *constr;
1778
1779                         constr = &(tbinfo->checkexprs[j]);
1780
1781                         for (k = 0; k < numParents; k++)
1782                         {
1783                                 int                     l;
1784
1785                                 parent = parents[k];
1786                                 for (l = 0; l < parent->ncheck; l++)
1787                                 {
1788                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1789
1790                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1791                                         {
1792                                                 constr->conislocal = false;
1793                                                 break;
1794                                         }
1795                                 }
1796                                 if (!constr->conislocal)
1797                                         break;
1798                         }
1799                 }
1800         }
1801 }
1802
1803
1804 /*
1805  * dumpDatabase:
1806  *      dump the database definition
1807  */
1808 static void
1809 dumpDatabase(Archive *fout)
1810 {
1811         PQExpBuffer dbQry = createPQExpBuffer();
1812         PQExpBuffer delQry = createPQExpBuffer();
1813         PQExpBuffer creaQry = createPQExpBuffer();
1814         PGconn     *conn = GetConnection(fout);
1815         PGresult   *res;
1816         int                     i_tableoid,
1817                                 i_oid,
1818                                 i_dba,
1819                                 i_encoding,
1820                                 i_collate,
1821                                 i_ctype,
1822                                 i_frozenxid,
1823                                 i_tablespace;
1824         CatalogId       dbCatId;
1825         DumpId          dbDumpId;
1826         const char *datname,
1827                            *dba,
1828                            *encoding,
1829                            *collate,
1830                            *ctype,
1831                            *tablespace;
1832         uint32          frozenxid;
1833
1834         datname = PQdb(conn);
1835
1836         if (g_verbose)
1837                 write_msg(NULL, "saving database definition\n");
1838
1839         /* Make sure we are in proper schema */
1840         selectSourceSchema(fout, "pg_catalog");
1841
1842         /* Get the database owner and parameters from pg_database */
1843         if (fout->remoteVersion >= 80400)
1844         {
1845                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1846                                                   "(%s datdba) AS dba, "
1847                                                   "pg_encoding_to_char(encoding) AS encoding, "
1848                                                   "datcollate, datctype, datfrozenxid, "
1849                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1850                                           "shobj_description(oid, 'pg_database') AS description "
1851
1852                                                   "FROM pg_database "
1853                                                   "WHERE datname = ",
1854                                                   username_subquery);
1855                 appendStringLiteralAH(dbQry, datname, fout);
1856         }
1857         else if (fout->remoteVersion >= 80200)
1858         {
1859                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1860                                                   "(%s datdba) AS dba, "
1861                                                   "pg_encoding_to_char(encoding) AS encoding, "
1862                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1863                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1864                                           "shobj_description(oid, 'pg_database') AS description "
1865
1866                                                   "FROM pg_database "
1867                                                   "WHERE datname = ",
1868                                                   username_subquery);
1869                 appendStringLiteralAH(dbQry, datname, fout);
1870         }
1871         else if (fout->remoteVersion >= 80000)
1872         {
1873                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1874                                                   "(%s datdba) AS dba, "
1875                                                   "pg_encoding_to_char(encoding) AS encoding, "
1876                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1877                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1878                                                   "FROM pg_database "
1879                                                   "WHERE datname = ",
1880                                                   username_subquery);
1881                 appendStringLiteralAH(dbQry, datname, fout);
1882         }
1883         else if (fout->remoteVersion >= 70100)
1884         {
1885                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1886                                                   "(%s datdba) AS dba, "
1887                                                   "pg_encoding_to_char(encoding) AS encoding, "
1888                                                   "NULL AS datcollate, NULL AS datctype, "
1889                                                   "0 AS datfrozenxid, "
1890                                                   "NULL AS tablespace "
1891                                                   "FROM pg_database "
1892                                                   "WHERE datname = ",
1893                                                   username_subquery);
1894                 appendStringLiteralAH(dbQry, datname, fout);
1895         }
1896         else
1897         {
1898                 appendPQExpBuffer(dbQry, "SELECT "
1899                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1900                                                   "oid, "
1901                                                   "(%s datdba) AS dba, "
1902                                                   "pg_encoding_to_char(encoding) AS encoding, "
1903                                                   "NULL AS datcollate, NULL AS datctype, "
1904                                                   "0 AS datfrozenxid, "
1905                                                   "NULL AS tablespace "
1906                                                   "FROM pg_database "
1907                                                   "WHERE datname = ",
1908                                                   username_subquery);
1909                 appendStringLiteralAH(dbQry, datname, fout);
1910         }
1911
1912         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1913
1914         i_tableoid = PQfnumber(res, "tableoid");
1915         i_oid = PQfnumber(res, "oid");
1916         i_dba = PQfnumber(res, "dba");
1917         i_encoding = PQfnumber(res, "encoding");
1918         i_collate = PQfnumber(res, "datcollate");
1919         i_ctype = PQfnumber(res, "datctype");
1920         i_frozenxid = PQfnumber(res, "datfrozenxid");
1921         i_tablespace = PQfnumber(res, "tablespace");
1922
1923         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1924         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1925         dba = PQgetvalue(res, 0, i_dba);
1926         encoding = PQgetvalue(res, 0, i_encoding);
1927         collate = PQgetvalue(res, 0, i_collate);
1928         ctype = PQgetvalue(res, 0, i_ctype);
1929         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1930         tablespace = PQgetvalue(res, 0, i_tablespace);
1931
1932         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1933                                           fmtId(datname));
1934         if (strlen(encoding) > 0)
1935         {
1936                 appendPQExpBuffer(creaQry, " ENCODING = ");
1937                 appendStringLiteralAH(creaQry, encoding, fout);
1938         }
1939         if (strlen(collate) > 0)
1940         {
1941                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1942                 appendStringLiteralAH(creaQry, collate, fout);
1943         }
1944         if (strlen(ctype) > 0)
1945         {
1946                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1947                 appendStringLiteralAH(creaQry, ctype, fout);
1948         }
1949         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1950                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1951                                                   fmtId(tablespace));
1952         appendPQExpBuffer(creaQry, ";\n");
1953
1954         if (binary_upgrade)
1955         {
1956                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1957                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1958                                                   "SET datfrozenxid = '%u'\n"
1959                                                   "WHERE        datname = ",
1960                                                   frozenxid);
1961                 appendStringLiteralAH(creaQry, datname, fout);
1962                 appendPQExpBuffer(creaQry, ";\n");
1963
1964         }
1965
1966         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1967                                           fmtId(datname));
1968
1969         dbDumpId = createDumpId();
1970
1971         ArchiveEntry(fout,
1972                                  dbCatId,               /* catalog ID */
1973                                  dbDumpId,              /* dump ID */
1974                                  datname,               /* Name */
1975                                  NULL,                  /* Namespace */
1976                                  NULL,                  /* Tablespace */
1977                                  dba,                   /* Owner */
1978                                  false,                 /* with oids */
1979                                  "DATABASE",    /* Desc */
1980                                  SECTION_PRE_DATA,              /* Section */
1981                                  creaQry->data, /* Create */
1982                                  delQry->data,  /* Del */
1983                                  NULL,                  /* Copy */
1984                                  NULL,                  /* Deps */
1985                                  0,                             /* # Deps */
1986                                  NULL,                  /* Dumper */
1987                                  NULL);                 /* Dumper Arg */
1988
1989         /*
1990          * pg_largeobject and pg_largeobject_metadata come from the old system
1991          * intact, so set their relfrozenxids.
1992          */
1993         if (binary_upgrade)
1994         {
1995                 PGresult   *lo_res;
1996                 PQExpBuffer loFrozenQry = createPQExpBuffer();
1997                 PQExpBuffer loOutQry = createPQExpBuffer();
1998                 int                     i_relfrozenxid;
1999
2000                 /*
2001                  * pg_largeobject
2002                  */
2003                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2004                                                   "FROM pg_catalog.pg_class\n"
2005                                                   "WHERE oid = %u;\n",
2006                                                   LargeObjectRelationId);
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.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                                                   LargeObjectRelationId);
2018                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2019                                          "pg_largeobject", NULL, NULL, "",
2020                                          false, "pg_largeobject", SECTION_PRE_DATA,
2021                                          loOutQry->data, "", NULL,
2022                                          NULL, 0,
2023                                          NULL, NULL);
2024
2025                 PQclear(lo_res);
2026
2027                 /*
2028                  * pg_largeobject_metadata
2029                  */
2030                 if (fout->remoteVersion >= 90000)
2031                 {
2032                         resetPQExpBuffer(loFrozenQry);
2033                         resetPQExpBuffer(loOutQry);
2034
2035                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2036                                                           "FROM pg_catalog.pg_class\n"
2037                                                           "WHERE oid = %u;\n",
2038                                                           LargeObjectMetadataRelationId);
2039
2040                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2041
2042                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2043
2044                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2045                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2046                                                           "SET relfrozenxid = '%u'\n"
2047                                                           "WHERE oid = %u;\n",
2048                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2049                                                           LargeObjectMetadataRelationId);
2050                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2051                                                  "pg_largeobject_metadata", NULL, NULL, "",
2052                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2053                                                  loOutQry->data, "", NULL,
2054                                                  NULL, 0,
2055                                                  NULL, NULL);
2056
2057                         PQclear(lo_res);
2058                 }
2059
2060                 destroyPQExpBuffer(loFrozenQry);
2061                 destroyPQExpBuffer(loOutQry);
2062         }
2063
2064         /* Dump DB comment if any */
2065         if (fout->remoteVersion >= 80200)
2066         {
2067                 /*
2068                  * 8.2 keeps comments on shared objects in a shared table, so we
2069                  * cannot use the dumpComment used for other database objects.
2070                  */
2071                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2072
2073                 if (comment && strlen(comment))
2074                 {
2075                         resetPQExpBuffer(dbQry);
2076
2077                         /*
2078                          * Generates warning when loaded into a differently-named
2079                          * database.
2080                          */
2081                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2082                         appendStringLiteralAH(dbQry, comment, fout);
2083                         appendPQExpBuffer(dbQry, ";\n");
2084
2085                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2086                                                  dba, false, "COMMENT", SECTION_NONE,
2087                                                  dbQry->data, "", NULL,
2088                                                  &dbDumpId, 1, NULL, NULL);
2089                 }
2090         }
2091         else
2092         {
2093                 resetPQExpBuffer(dbQry);
2094                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2095                 dumpComment(fout, dbQry->data, NULL, "",
2096                                         dbCatId, 0, dbDumpId);
2097         }
2098
2099         PQclear(res);
2100
2101         /* Dump shared security label. */
2102         if (!no_security_labels && fout->remoteVersion >= 90200)
2103         {
2104                 PQExpBuffer seclabelQry = createPQExpBuffer();
2105
2106                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2107                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2108                 resetPQExpBuffer(seclabelQry);
2109                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2110                 if (strlen(seclabelQry->data))
2111                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2112                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2113                                                  seclabelQry->data, "", NULL,
2114                                                  &dbDumpId, 1, NULL, NULL);
2115                 destroyPQExpBuffer(seclabelQry);
2116         }
2117
2118         destroyPQExpBuffer(dbQry);
2119         destroyPQExpBuffer(delQry);
2120         destroyPQExpBuffer(creaQry);
2121 }
2122
2123
2124 /*
2125  * dumpEncoding: put the correct encoding into the archive
2126  */
2127 static void
2128 dumpEncoding(Archive *AH)
2129 {
2130         const char *encname = pg_encoding_to_char(AH->encoding);
2131         PQExpBuffer qry = createPQExpBuffer();
2132
2133         if (g_verbose)
2134                 write_msg(NULL, "saving encoding = %s\n", encname);
2135
2136         appendPQExpBuffer(qry, "SET client_encoding = ");
2137         appendStringLiteralAH(qry, encname, AH);
2138         appendPQExpBuffer(qry, ";\n");
2139
2140         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2141                                  "ENCODING", NULL, NULL, "",
2142                                  false, "ENCODING", SECTION_PRE_DATA,
2143                                  qry->data, "", NULL,
2144                                  NULL, 0,
2145                                  NULL, NULL);
2146
2147         destroyPQExpBuffer(qry);
2148 }
2149
2150
2151 /*
2152  * dumpStdStrings: put the correct escape string behavior into the archive
2153  */
2154 static void
2155 dumpStdStrings(Archive *AH)
2156 {
2157         const char *stdstrings = AH->std_strings ? "on" : "off";
2158         PQExpBuffer qry = createPQExpBuffer();
2159
2160         if (g_verbose)
2161                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2162                                   stdstrings);
2163
2164         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2165                                           stdstrings);
2166
2167         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2168                                  "STDSTRINGS", NULL, NULL, "",
2169                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2170                                  qry->data, "", NULL,
2171                                  NULL, 0,
2172                                  NULL, NULL);
2173
2174         destroyPQExpBuffer(qry);
2175 }
2176
2177
2178 /*
2179  * getBlobs:
2180  *      Collect schema-level data about large objects
2181  */
2182 static void
2183 getBlobs(Archive *fout)
2184 {
2185         PQExpBuffer blobQry = createPQExpBuffer();
2186         BlobInfo   *binfo;
2187         DumpableObject *bdata;
2188         PGresult   *res;
2189         int                     ntups;
2190         int                     i;
2191
2192         /* Verbose message */
2193         if (g_verbose)
2194                 write_msg(NULL, "reading large objects\n");
2195
2196         /* Make sure we are in proper schema */
2197         selectSourceSchema(fout, "pg_catalog");
2198
2199         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2200         if (fout->remoteVersion >= 90000)
2201                 appendPQExpBuffer(blobQry,
2202                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2203                                                   " FROM pg_largeobject_metadata",
2204                                                   username_subquery);
2205         else if (fout->remoteVersion >= 70100)
2206                 appendPQExpBuffer(blobQry,
2207                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2208                                                   " FROM pg_largeobject");
2209         else
2210                 appendPQExpBuffer(blobQry,
2211                                                   "SELECT oid, NULL::oid, NULL::oid"
2212                                                   " FROM pg_class WHERE relkind = 'l'");
2213
2214         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2215
2216         ntups = PQntuples(res);
2217         if (ntups > 0)
2218         {
2219                 /*
2220                  * Each large object has its own BLOB archive entry.
2221                  */
2222                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2223
2224                 for (i = 0; i < ntups; i++)
2225                 {
2226                         binfo[i].dobj.objType = DO_BLOB;
2227                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2228                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2229                         AssignDumpId(&binfo[i].dobj);
2230
2231                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2232                         if (!PQgetisnull(res, i, 1))
2233                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2234                         else
2235                                 binfo[i].rolname = "";
2236                         if (!PQgetisnull(res, i, 2))
2237                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2238                         else
2239                                 binfo[i].blobacl = NULL;
2240                 }
2241
2242                 /*
2243                  * If we have any large objects, a "BLOBS" archive entry is needed.
2244                  * This is just a placeholder for sorting; it carries no data now.
2245                  */
2246                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2247                 bdata->objType = DO_BLOB_DATA;
2248                 bdata->catId = nilCatalogId;
2249                 AssignDumpId(bdata);
2250                 bdata->name = pg_strdup("BLOBS");
2251         }
2252
2253         PQclear(res);
2254         destroyPQExpBuffer(blobQry);
2255 }
2256
2257 /*
2258  * dumpBlob
2259  *
2260  * dump the definition (metadata) of the given large object
2261  */
2262 static void
2263 dumpBlob(Archive *fout, BlobInfo *binfo)
2264 {
2265         PQExpBuffer cquery = createPQExpBuffer();
2266         PQExpBuffer dquery = createPQExpBuffer();
2267
2268         appendPQExpBuffer(cquery,
2269                                           "SELECT pg_catalog.lo_create('%s');\n",
2270                                           binfo->dobj.name);
2271
2272         appendPQExpBuffer(dquery,
2273                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2274                                           binfo->dobj.name);
2275
2276         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2277                                  binfo->dobj.name,
2278                                  NULL, NULL,
2279                                  binfo->rolname, false,
2280                                  "BLOB", SECTION_PRE_DATA,
2281                                  cquery->data, dquery->data, NULL,
2282                                  NULL, 0,
2283                                  NULL, NULL);
2284
2285         /* set up tag for comment and/or ACL */
2286         resetPQExpBuffer(cquery);
2287         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2288
2289         /* Dump comment if any */
2290         dumpComment(fout, cquery->data,
2291                                 NULL, binfo->rolname,
2292                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2293
2294         /* Dump security label if any */
2295         dumpSecLabel(fout, cquery->data,
2296                                  NULL, binfo->rolname,
2297                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2298
2299         /* Dump ACL if any */
2300         if (binfo->blobacl)
2301                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2302                                 binfo->dobj.name, NULL, cquery->data,
2303                                 NULL, binfo->rolname, binfo->blobacl);
2304
2305         destroyPQExpBuffer(cquery);
2306         destroyPQExpBuffer(dquery);
2307 }
2308
2309 /*
2310  * dumpBlobs:
2311  *      dump the data contents of all large objects
2312  */
2313 static int
2314 dumpBlobs(Archive *fout, void *arg)
2315 {
2316         const char *blobQry;
2317         const char *blobFetchQry;
2318         PGconn     *conn = GetConnection(fout);
2319         PGresult   *res;
2320         char            buf[LOBBUFSIZE];
2321         int                     ntups;
2322         int                     i;
2323         int                     cnt;
2324
2325         if (g_verbose)
2326                 write_msg(NULL, "saving large objects\n");
2327
2328         /* Make sure we are in proper schema */
2329         selectSourceSchema(fout, "pg_catalog");
2330
2331         /*
2332          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2333          * the already-in-memory dumpable objects instead...
2334          */
2335         if (fout->remoteVersion >= 90000)
2336                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2337         else if (fout->remoteVersion >= 70100)
2338                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2339         else
2340                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2341
2342         ExecuteSqlStatement(fout, blobQry);
2343
2344         /* Command to fetch from cursor */
2345         blobFetchQry = "FETCH 1000 IN bloboid";
2346
2347         do
2348         {
2349                 /* Do a fetch */
2350                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2351
2352                 /* Process the tuples, if any */
2353                 ntups = PQntuples(res);
2354                 for (i = 0; i < ntups; i++)
2355                 {
2356                         Oid                     blobOid;
2357                         int                     loFd;
2358
2359                         blobOid = atooid(PQgetvalue(res, i, 0));
2360                         /* Open the BLOB */
2361                         loFd = lo_open(conn, blobOid, INV_READ);
2362                         if (loFd == -1)
2363                                 exit_horribly(NULL, "could not open large object %u: %s",
2364                                                           blobOid, PQerrorMessage(conn));
2365
2366                         StartBlob(fout, blobOid);
2367
2368                         /* Now read it in chunks, sending data to archive */
2369                         do
2370                         {
2371                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2372                                 if (cnt < 0)
2373                                         exit_horribly(NULL, "error reading large object %u: %s",
2374                                                                   blobOid, PQerrorMessage(conn));
2375
2376                                 WriteData(fout, buf, cnt);
2377                         } while (cnt > 0);
2378
2379                         lo_close(conn, loFd);
2380
2381                         EndBlob(fout, blobOid);
2382                 }
2383
2384                 PQclear(res);
2385         } while (ntups > 0);
2386
2387         return 1;
2388 }
2389
2390 static void
2391 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2392                                                                                  PQExpBuffer upgrade_buffer,
2393                                                                                  Oid pg_type_oid)
2394 {
2395         PQExpBuffer upgrade_query = createPQExpBuffer();
2396         PGresult   *upgrade_res;
2397         Oid                     pg_type_array_oid;
2398
2399         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2400         appendPQExpBuffer(upgrade_buffer,
2401          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2402                                           pg_type_oid);
2403
2404         /* we only support old >= 8.3 for binary upgrades */
2405         appendPQExpBuffer(upgrade_query,
2406                                           "SELECT typarray "
2407                                           "FROM pg_catalog.pg_type "
2408                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2409                                           pg_type_oid);
2410
2411         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2412
2413         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2414
2415         if (OidIsValid(pg_type_array_oid))
2416         {
2417                 appendPQExpBuffer(upgrade_buffer,
2418                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2419                 appendPQExpBuffer(upgrade_buffer,
2420                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2421                                                   pg_type_array_oid);
2422         }
2423
2424         PQclear(upgrade_res);
2425         destroyPQExpBuffer(upgrade_query);
2426 }
2427
2428 static bool
2429 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2430                                                                                 PQExpBuffer upgrade_buffer,
2431                                                                                 Oid pg_rel_oid)
2432 {
2433         PQExpBuffer upgrade_query = createPQExpBuffer();
2434         PGresult   *upgrade_res;
2435         Oid                     pg_type_oid;
2436         bool            toast_set = false;
2437
2438         /* we only support old >= 8.3 for binary upgrades */
2439         appendPQExpBuffer(upgrade_query,
2440                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2441                                           "FROM pg_catalog.pg_class c "
2442                                           "LEFT JOIN pg_catalog.pg_class t ON "
2443                                           "  (c.reltoastrelid = t.oid) "
2444                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2445                                           pg_rel_oid);
2446
2447         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2448
2449         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2450
2451         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2452                                                                                          pg_type_oid);
2453
2454         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2455         {
2456                 /* Toast tables do not have pg_type array rows */
2457                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2458                                                                                         PQfnumber(upgrade_res, "trel")));
2459
2460                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2461                 appendPQExpBuffer(upgrade_buffer,
2462                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2463                                                   pg_type_toast_oid);
2464
2465                 toast_set = true;
2466         }
2467
2468         PQclear(upgrade_res);
2469         destroyPQExpBuffer(upgrade_query);
2470
2471         return toast_set;
2472 }
2473
2474 static void
2475 binary_upgrade_set_pg_class_oids(Archive *fout,
2476                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2477                                                                  bool is_index)
2478 {
2479         PQExpBuffer upgrade_query = createPQExpBuffer();
2480         PGresult   *upgrade_res;
2481         Oid                     pg_class_reltoastrelid;
2482         Oid                     pg_class_reltoastidxid;
2483
2484         appendPQExpBuffer(upgrade_query,
2485                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2486                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2487                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2488                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2489                                           pg_class_oid);
2490
2491         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2492
2493         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2494         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2495
2496         appendPQExpBuffer(upgrade_buffer,
2497                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2498
2499         if (!is_index)
2500         {
2501                 appendPQExpBuffer(upgrade_buffer,
2502                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2503                                                   pg_class_oid);
2504                 /* only tables have toast tables, not indexes */
2505                 if (OidIsValid(pg_class_reltoastrelid))
2506                 {
2507                         /*
2508                          * One complexity is that the table definition might not require
2509                          * the creation of a TOAST table, and the TOAST table might have
2510                          * been created long after table creation, when the table was
2511                          * loaded with wide data.  By setting the TOAST oid we force
2512                          * creation of the TOAST heap and TOAST index by the backend so we
2513                          * can cleanly copy the files during binary upgrade.
2514                          */
2515
2516                         appendPQExpBuffer(upgrade_buffer,
2517                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2518                                                           pg_class_reltoastrelid);
2519
2520                         /* every toast table has an index */
2521                         appendPQExpBuffer(upgrade_buffer,
2522                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2523                                                           pg_class_reltoastidxid);
2524                 }
2525         }
2526         else
2527                 appendPQExpBuffer(upgrade_buffer,
2528                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2529                                                   pg_class_oid);
2530
2531         appendPQExpBuffer(upgrade_buffer, "\n");
2532
2533         PQclear(upgrade_res);
2534         destroyPQExpBuffer(upgrade_query);
2535 }
2536
2537 /*
2538  * If the DumpableObject is a member of an extension, add a suitable
2539  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2540  */
2541 static void
2542 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2543                                                                 DumpableObject *dobj,
2544                                                                 const char *objlabel)
2545 {
2546         DumpableObject *extobj = NULL;
2547         int                     i;
2548
2549         if (!dobj->ext_member)
2550                 return;
2551
2552         /*
2553          * Find the parent extension.  We could avoid this search if we wanted to
2554          * add a link field to DumpableObject, but the space costs of that would
2555          * be considerable.  We assume that member objects could only have a
2556          * direct dependency on their own extension, not any others.
2557          */
2558         for (i = 0; i < dobj->nDeps; i++)
2559         {
2560                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2561                 if (extobj && extobj->objType == DO_EXTENSION)
2562                         break;
2563                 extobj = NULL;
2564         }
2565         if (extobj == NULL)
2566                 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2567
2568         appendPQExpBuffer(upgrade_buffer,
2569           "\n-- For binary upgrade, handle extension membership the hard way\n");
2570         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2571                                           fmtId(extobj->name),
2572                                           objlabel);
2573 }
2574
2575 /*
2576  * getNamespaces:
2577  *        read all namespaces in the system catalogs and return them in the
2578  * NamespaceInfo* structure
2579  *
2580  *      numNamespaces is set to the number of namespaces read in
2581  */
2582 NamespaceInfo *
2583 getNamespaces(Archive *fout, int *numNamespaces)
2584 {
2585         PGresult   *res;
2586         int                     ntups;
2587         int                     i;
2588         PQExpBuffer query;
2589         NamespaceInfo *nsinfo;
2590         int                     i_tableoid;
2591         int                     i_oid;
2592         int                     i_nspname;
2593         int                     i_rolname;
2594         int                     i_nspacl;
2595
2596         /*
2597          * Before 7.3, there are no real namespaces; create two dummy entries, one
2598          * for user stuff and one for system stuff.
2599          */
2600         if (fout->remoteVersion < 70300)
2601         {
2602                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2603
2604                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2605                 nsinfo[0].dobj.catId.tableoid = 0;
2606                 nsinfo[0].dobj.catId.oid = 0;
2607                 AssignDumpId(&nsinfo[0].dobj);
2608                 nsinfo[0].dobj.name = pg_strdup("public");
2609                 nsinfo[0].rolname = pg_strdup("");
2610                 nsinfo[0].nspacl = pg_strdup("");
2611
2612                 selectDumpableNamespace(&nsinfo[0]);
2613
2614                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2615                 nsinfo[1].dobj.catId.tableoid = 0;
2616                 nsinfo[1].dobj.catId.oid = 1;
2617                 AssignDumpId(&nsinfo[1].dobj);
2618                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2619                 nsinfo[1].rolname = pg_strdup("");
2620                 nsinfo[1].nspacl = pg_strdup("");
2621
2622                 selectDumpableNamespace(&nsinfo[1]);
2623
2624                 *numNamespaces = 2;
2625
2626                 return nsinfo;
2627         }
2628
2629         query = createPQExpBuffer();
2630
2631         /* Make sure we are in proper schema */
2632         selectSourceSchema(fout, "pg_catalog");
2633
2634         /*
2635          * we fetch all namespaces including system ones, so that every object we
2636          * read in can be linked to a containing namespace.
2637          */
2638         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2639                                           "(%s nspowner) AS rolname, "
2640                                           "nspacl FROM pg_namespace",
2641                                           username_subquery);
2642
2643         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2644
2645         ntups = PQntuples(res);
2646
2647         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2648
2649         i_tableoid = PQfnumber(res, "tableoid");
2650         i_oid = PQfnumber(res, "oid");
2651         i_nspname = PQfnumber(res, "nspname");
2652         i_rolname = PQfnumber(res, "rolname");
2653         i_nspacl = PQfnumber(res, "nspacl");
2654
2655         for (i = 0; i < ntups; i++)
2656         {
2657                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2658                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2659                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2660                 AssignDumpId(&nsinfo[i].dobj);
2661                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2662                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2663                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2664
2665                 /* Decide whether to dump this namespace */
2666                 selectDumpableNamespace(&nsinfo[i]);
2667
2668                 if (strlen(nsinfo[i].rolname) == 0)
2669                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2670                                           nsinfo[i].dobj.name);
2671         }
2672
2673         PQclear(res);
2674         destroyPQExpBuffer(query);
2675
2676         *numNamespaces = ntups;
2677
2678         return nsinfo;
2679 }
2680
2681 /*
2682  * findNamespace:
2683  *              given a namespace OID and an object OID, look up the info read by
2684  *              getNamespaces
2685  *
2686  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2687  * a system object or not.      In 7.3 and later there is no guessing, and we
2688  * don't use objoid at all.
2689  */
2690 static NamespaceInfo *
2691 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2692 {
2693         NamespaceInfo *nsinfo;
2694
2695         if (fout->remoteVersion >= 70300)
2696         {
2697                 nsinfo = findNamespaceByOid(nsoid);
2698         }
2699         else
2700         {
2701                 /* This code depends on the dummy objects set up by getNamespaces. */
2702                 Oid                     i;
2703
2704                 if (objoid > g_last_builtin_oid)
2705                         i = 0;                          /* user object */
2706                 else
2707                         i = 1;                          /* system object */
2708                 nsinfo = findNamespaceByOid(i);
2709         }
2710
2711         if (nsinfo == NULL)
2712                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2713
2714         return nsinfo;
2715 }
2716
2717 /*
2718  * getExtensions:
2719  *        read all extensions in the system catalogs and return them in the
2720  * ExtensionInfo* structure
2721  *
2722  *      numExtensions is set to the number of extensions read in
2723  */
2724 ExtensionInfo *
2725 getExtensions(Archive *fout, int *numExtensions)
2726 {
2727         PGresult   *res;
2728         int                     ntups;
2729         int                     i;
2730         PQExpBuffer query;
2731         ExtensionInfo *extinfo;
2732         int                     i_tableoid;
2733         int                     i_oid;
2734         int                     i_extname;
2735         int                     i_nspname;
2736         int                     i_extrelocatable;
2737         int                     i_extversion;
2738         int                     i_extconfig;
2739         int                     i_extcondition;
2740
2741         /*
2742          * Before 9.1, there are no extensions.
2743          */
2744         if (fout->remoteVersion < 90100)
2745         {
2746                 *numExtensions = 0;
2747                 return NULL;
2748         }
2749
2750         query = createPQExpBuffer();
2751
2752         /* Make sure we are in proper schema */
2753         selectSourceSchema(fout, "pg_catalog");
2754
2755         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2756                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2757                                           "FROM pg_extension x "
2758                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2759
2760         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2761
2762         ntups = PQntuples(res);
2763
2764         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2765
2766         i_tableoid = PQfnumber(res, "tableoid");
2767         i_oid = PQfnumber(res, "oid");
2768         i_extname = PQfnumber(res, "extname");
2769         i_nspname = PQfnumber(res, "nspname");
2770         i_extrelocatable = PQfnumber(res, "extrelocatable");
2771         i_extversion = PQfnumber(res, "extversion");
2772         i_extconfig = PQfnumber(res, "extconfig");
2773         i_extcondition = PQfnumber(res, "extcondition");
2774
2775         for (i = 0; i < ntups; i++)
2776         {
2777                 extinfo[i].dobj.objType = DO_EXTENSION;
2778                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2779                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2780                 AssignDumpId(&extinfo[i].dobj);
2781                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2782                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2783                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2784                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2785                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2786                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2787
2788                 /* Decide whether we want to dump it */
2789                 selectDumpableExtension(&(extinfo[i]));
2790         }
2791
2792         PQclear(res);
2793         destroyPQExpBuffer(query);
2794
2795         *numExtensions = ntups;
2796
2797         return extinfo;
2798 }
2799
2800 /*
2801  * getTypes:
2802  *        read all types in the system catalogs and return them in the
2803  * TypeInfo* structure
2804  *
2805  *      numTypes is set to the number of types read in
2806  *
2807  * NB: this must run after getFuncs() because we assume we can do
2808  * findFuncByOid().
2809  */
2810 TypeInfo *
2811 getTypes(Archive *fout, int *numTypes)
2812 {
2813         PGresult   *res;
2814         int                     ntups;
2815         int                     i;
2816         PQExpBuffer query = createPQExpBuffer();
2817         TypeInfo   *tyinfo;
2818         ShellTypeInfo *stinfo;
2819         int                     i_tableoid;
2820         int                     i_oid;
2821         int                     i_typname;
2822         int                     i_typnamespace;
2823         int                     i_rolname;
2824         int                     i_typinput;
2825         int                     i_typoutput;
2826         int                     i_typelem;
2827         int                     i_typrelid;
2828         int                     i_typrelkind;
2829         int                     i_typtype;
2830         int                     i_typisdefined;
2831         int                     i_isarray;
2832
2833         /*
2834          * we include even the built-in types because those may be used as array
2835          * elements by user-defined types
2836          *
2837          * we filter out the built-in types when we dump out the types
2838          *
2839          * same approach for undefined (shell) types and array types
2840          *
2841          * Note: as of 8.3 we can reliably detect whether a type is an
2842          * auto-generated array type by checking the element type's typarray.
2843          * (Before that the test is capable of generating false positives.) We
2844          * still check for name beginning with '_', though, so as to avoid the
2845          * cost of the subselect probe for all standard types.  This would have to
2846          * be revisited if the backend ever allows renaming of array types.
2847          */
2848
2849         /* Make sure we are in proper schema */
2850         selectSourceSchema(fout, "pg_catalog");
2851
2852         if (fout->remoteVersion >= 80300)
2853         {
2854                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2855                                                   "typnamespace, "
2856                                                   "(%s typowner) AS rolname, "
2857                                                   "typinput::oid AS typinput, "
2858                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2859                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2860                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2861                                                   "typtype, typisdefined, "
2862                                                   "typname[0] = '_' AND typelem != 0 AND "
2863                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2864                                                   "FROM pg_type",
2865                                                   username_subquery);
2866         }
2867         else if (fout->remoteVersion >= 70300)
2868         {
2869                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2870                                                   "typnamespace, "
2871                                                   "(%s typowner) AS rolname, "
2872                                                   "typinput::oid AS typinput, "
2873                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2874                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2875                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2876                                                   "typtype, typisdefined, "
2877                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2878                                                   "FROM pg_type",
2879                                                   username_subquery);
2880         }
2881         else if (fout->remoteVersion >= 70100)
2882         {
2883                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2884                                                   "0::oid AS typnamespace, "
2885                                                   "(%s typowner) AS rolname, "
2886                                                   "typinput::oid AS typinput, "
2887                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2888                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2889                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2890                                                   "typtype, typisdefined, "
2891                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2892                                                   "FROM pg_type",
2893                                                   username_subquery);
2894         }
2895         else
2896         {
2897                 appendPQExpBuffer(query, "SELECT "
2898                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2899                                                   "oid, typname, "
2900                                                   "0::oid AS typnamespace, "
2901                                                   "(%s typowner) AS rolname, "
2902                                                   "typinput::oid AS typinput, "
2903                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2904                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2905                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2906                                                   "typtype, typisdefined, "
2907                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2908                                                   "FROM pg_type",
2909                                                   username_subquery);
2910         }
2911
2912         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2913
2914         ntups = PQntuples(res);
2915
2916         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2917
2918         i_tableoid = PQfnumber(res, "tableoid");
2919         i_oid = PQfnumber(res, "oid");
2920         i_typname = PQfnumber(res, "typname");
2921         i_typnamespace = PQfnumber(res, "typnamespace");
2922         i_rolname = PQfnumber(res, "rolname");
2923         i_typinput = PQfnumber(res, "typinput");
2924         i_typoutput = PQfnumber(res, "typoutput");
2925         i_typelem = PQfnumber(res, "typelem");
2926         i_typrelid = PQfnumber(res, "typrelid");
2927         i_typrelkind = PQfnumber(res, "typrelkind");
2928         i_typtype = PQfnumber(res, "typtype");
2929         i_typisdefined = PQfnumber(res, "typisdefined");
2930         i_isarray = PQfnumber(res, "isarray");
2931
2932         for (i = 0; i < ntups; i++)
2933         {
2934                 tyinfo[i].dobj.objType = DO_TYPE;
2935                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2936                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2937                 AssignDumpId(&tyinfo[i].dobj);
2938                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2939                 tyinfo[i].dobj.namespace =
2940                         findNamespace(fout,
2941                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2942                                                   tyinfo[i].dobj.catId.oid);
2943                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2944                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2945                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2946                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2947                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2948                 tyinfo[i].shellType = NULL;
2949
2950                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2951                         tyinfo[i].isDefined = true;
2952                 else
2953                         tyinfo[i].isDefined = false;
2954
2955                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2956                         tyinfo[i].isArray = true;
2957                 else
2958                         tyinfo[i].isArray = false;
2959
2960                 /* Decide whether we want to dump it */
2961                 selectDumpableType(&tyinfo[i]);
2962
2963                 /*
2964                  * If it's a domain, fetch info about its constraints, if any
2965                  */
2966                 tyinfo[i].nDomChecks = 0;
2967                 tyinfo[i].domChecks = NULL;
2968                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2969                         getDomainConstraints(fout, &(tyinfo[i]));
2970
2971                 /*
2972                  * If it's a base type, make a DumpableObject representing a shell
2973                  * definition of the type.      We will need to dump that ahead of the I/O
2974                  * functions for the type.      Similarly, range types need a shell
2975                  * definition in case they have a canonicalize function.
2976                  *
2977                  * Note: the shell type doesn't have a catId.  You might think it
2978                  * should copy the base type's catId, but then it might capture the
2979                  * pg_depend entries for the type, which we don't want.
2980                  */
2981                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2982                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
2983                 {
2984                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2985                         stinfo->dobj.objType = DO_SHELL_TYPE;
2986                         stinfo->dobj.catId = nilCatalogId;
2987                         AssignDumpId(&stinfo->dobj);
2988                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2989                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2990                         stinfo->baseType = &(tyinfo[i]);
2991                         tyinfo[i].shellType = stinfo;
2992
2993                         /*
2994                          * Initially mark the shell type as not to be dumped.  We'll only
2995                          * dump it if the I/O or canonicalize functions need to be dumped;
2996                          * this is taken care of while sorting dependencies.
2997                          */
2998                         stinfo->dobj.dump = false;
2999
3000                         /*
3001                          * However, if dumping from pre-7.3, there will be no dependency
3002                          * info so we have to fake it here.  We only need to worry about
3003                          * typinput and typoutput since the other functions only exist
3004                          * post-7.3.
3005                          */
3006                         if (fout->remoteVersion < 70300)
3007                         {
3008                                 Oid                     typinput;
3009                                 Oid                     typoutput;
3010                                 FuncInfo   *funcInfo;
3011
3012                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3013                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3014
3015                                 funcInfo = findFuncByOid(typinput);
3016                                 if (funcInfo && funcInfo->dobj.dump)
3017                                 {
3018                                         /* base type depends on function */
3019                                         addObjectDependency(&tyinfo[i].dobj,
3020                                                                                 funcInfo->dobj.dumpId);
3021                                         /* function depends on shell type */
3022                                         addObjectDependency(&funcInfo->dobj,
3023                                                                                 stinfo->dobj.dumpId);
3024                                         /* mark shell type as to be dumped */
3025                                         stinfo->dobj.dump = true;
3026                                 }
3027
3028                                 funcInfo = findFuncByOid(typoutput);
3029                                 if (funcInfo && funcInfo->dobj.dump)
3030                                 {
3031                                         /* base type depends on function */
3032                                         addObjectDependency(&tyinfo[i].dobj,
3033                                                                                 funcInfo->dobj.dumpId);
3034                                         /* function depends on shell type */
3035                                         addObjectDependency(&funcInfo->dobj,
3036                                                                                 stinfo->dobj.dumpId);
3037                                         /* mark shell type as to be dumped */
3038                                         stinfo->dobj.dump = true;
3039                                 }
3040                         }
3041                 }
3042
3043                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3044                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3045                                           tyinfo[i].dobj.name);
3046         }
3047
3048         *numTypes = ntups;
3049
3050         PQclear(res);
3051
3052         destroyPQExpBuffer(query);
3053
3054         return tyinfo;
3055 }
3056
3057 /*
3058  * getOperators:
3059  *        read all operators in the system catalogs and return them in the
3060  * OprInfo* structure
3061  *
3062  *      numOprs is set to the number of operators read in
3063  */
3064 OprInfo *
3065 getOperators(Archive *fout, int *numOprs)
3066 {
3067         PGresult   *res;
3068         int                     ntups;
3069         int                     i;
3070         PQExpBuffer query = createPQExpBuffer();
3071         OprInfo    *oprinfo;
3072         int                     i_tableoid;
3073         int                     i_oid;
3074         int                     i_oprname;
3075         int                     i_oprnamespace;
3076         int                     i_rolname;
3077         int                     i_oprkind;
3078         int                     i_oprcode;
3079
3080         /*
3081          * find all operators, including builtin operators; we filter out
3082          * system-defined operators at dump-out time.
3083          */
3084
3085         /* Make sure we are in proper schema */
3086         selectSourceSchema(fout, "pg_catalog");
3087
3088         if (fout->remoteVersion >= 70300)
3089         {
3090                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3091                                                   "oprnamespace, "
3092                                                   "(%s oprowner) AS rolname, "
3093                                                   "oprkind, "
3094                                                   "oprcode::oid AS oprcode "
3095                                                   "FROM pg_operator",
3096                                                   username_subquery);
3097         }
3098         else if (fout->remoteVersion >= 70100)
3099         {
3100                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3101                                                   "0::oid AS oprnamespace, "
3102                                                   "(%s oprowner) AS rolname, "
3103                                                   "oprkind, "
3104                                                   "oprcode::oid AS oprcode "
3105                                                   "FROM pg_operator",
3106                                                   username_subquery);
3107         }
3108         else
3109         {
3110                 appendPQExpBuffer(query, "SELECT "
3111                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3112                                                   "oid, oprname, "
3113                                                   "0::oid AS oprnamespace, "
3114                                                   "(%s oprowner) AS rolname, "
3115                                                   "oprkind, "
3116                                                   "oprcode::oid AS oprcode "
3117                                                   "FROM pg_operator",
3118                                                   username_subquery);
3119         }
3120
3121         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3122
3123         ntups = PQntuples(res);
3124         *numOprs = ntups;
3125
3126         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3127
3128         i_tableoid = PQfnumber(res, "tableoid");
3129         i_oid = PQfnumber(res, "oid");
3130         i_oprname = PQfnumber(res, "oprname");
3131         i_oprnamespace = PQfnumber(res, "oprnamespace");
3132         i_rolname = PQfnumber(res, "rolname");
3133         i_oprkind = PQfnumber(res, "oprkind");
3134         i_oprcode = PQfnumber(res, "oprcode");
3135
3136         for (i = 0; i < ntups; i++)
3137         {
3138                 oprinfo[i].dobj.objType = DO_OPERATOR;
3139                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3140                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3141                 AssignDumpId(&oprinfo[i].dobj);
3142                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3143                 oprinfo[i].dobj.namespace =
3144                         findNamespace(fout,
3145                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3146                                                   oprinfo[i].dobj.catId.oid);
3147                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3148                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3149                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3150
3151                 /* Decide whether we want to dump it */
3152                 selectDumpableObject(&(oprinfo[i].dobj));
3153
3154                 if (strlen(oprinfo[i].rolname) == 0)
3155                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3156                                           oprinfo[i].dobj.name);
3157         }
3158
3159         PQclear(res);
3160
3161         destroyPQExpBuffer(query);
3162
3163         return oprinfo;
3164 }
3165
3166 /*
3167  * getCollations:
3168  *        read all collations in the system catalogs and return them in the
3169  * CollInfo* structure
3170  *
3171  *      numCollations is set to the number of collations read in
3172  */
3173 CollInfo *
3174 getCollations(Archive *fout, int *numCollations)
3175 {
3176         PGresult   *res;
3177         int                     ntups;
3178         int                     i;
3179         PQExpBuffer query;
3180         CollInfo   *collinfo;
3181         int                     i_tableoid;
3182         int                     i_oid;
3183         int                     i_collname;
3184         int                     i_collnamespace;
3185         int                     i_rolname;
3186
3187         /* Collations didn't exist pre-9.1 */
3188         if (fout->remoteVersion < 90100)
3189         {
3190                 *numCollations = 0;
3191                 return NULL;
3192         }
3193
3194         query = createPQExpBuffer();
3195
3196         /*
3197          * find all collations, including builtin collations; we filter out
3198          * system-defined collations at dump-out time.
3199          */
3200
3201         /* Make sure we are in proper schema */
3202         selectSourceSchema(fout, "pg_catalog");
3203
3204         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3205                                           "collnamespace, "
3206                                           "(%s collowner) AS rolname "
3207                                           "FROM pg_collation",
3208                                           username_subquery);
3209
3210         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3211
3212         ntups = PQntuples(res);
3213         *numCollations = ntups;
3214
3215         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3216
3217         i_tableoid = PQfnumber(res, "tableoid");
3218         i_oid = PQfnumber(res, "oid");
3219         i_collname = PQfnumber(res, "collname");
3220         i_collnamespace = PQfnumber(res, "collnamespace");
3221         i_rolname = PQfnumber(res, "rolname");
3222
3223         for (i = 0; i < ntups; i++)
3224         {
3225                 collinfo[i].dobj.objType = DO_COLLATION;
3226                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3227                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3228                 AssignDumpId(&collinfo[i].dobj);
3229                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3230                 collinfo[i].dobj.namespace =
3231                         findNamespace(fout,
3232                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3233                                                   collinfo[i].dobj.catId.oid);
3234                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3235
3236                 /* Decide whether we want to dump it */
3237                 selectDumpableObject(&(collinfo[i].dobj));
3238         }
3239
3240         PQclear(res);
3241
3242         destroyPQExpBuffer(query);
3243
3244         return collinfo;
3245 }
3246
3247 /*
3248  * getConversions:
3249  *        read all conversions in the system catalogs and return them in the
3250  * ConvInfo* structure
3251  *
3252  *      numConversions is set to the number of conversions read in
3253  */
3254 ConvInfo *
3255 getConversions(Archive *fout, int *numConversions)
3256 {
3257         PGresult   *res;
3258         int                     ntups;
3259         int                     i;
3260         PQExpBuffer query = createPQExpBuffer();
3261         ConvInfo   *convinfo;
3262         int                     i_tableoid;
3263         int                     i_oid;
3264         int                     i_conname;
3265         int                     i_connamespace;
3266         int                     i_rolname;
3267
3268         /* Conversions didn't exist pre-7.3 */
3269         if (fout->remoteVersion < 70300)
3270         {
3271                 *numConversions = 0;
3272                 return NULL;
3273         }
3274
3275         /*
3276          * find all conversions, including builtin conversions; we filter out
3277          * system-defined conversions at dump-out time.
3278          */
3279
3280         /* Make sure we are in proper schema */
3281         selectSourceSchema(fout, "pg_catalog");
3282
3283         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3284                                           "connamespace, "
3285                                           "(%s conowner) AS rolname "
3286                                           "FROM pg_conversion",
3287                                           username_subquery);
3288
3289         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3290
3291         ntups = PQntuples(res);
3292         *numConversions = ntups;
3293
3294         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3295
3296         i_tableoid = PQfnumber(res, "tableoid");
3297         i_oid = PQfnumber(res, "oid");
3298         i_conname = PQfnumber(res, "conname");
3299         i_connamespace = PQfnumber(res, "connamespace");
3300         i_rolname = PQfnumber(res, "rolname");
3301
3302         for (i = 0; i < ntups; i++)
3303         {
3304                 convinfo[i].dobj.objType = DO_CONVERSION;
3305                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3306                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3307                 AssignDumpId(&convinfo[i].dobj);
3308                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3309                 convinfo[i].dobj.namespace =
3310                         findNamespace(fout,
3311                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3312                                                   convinfo[i].dobj.catId.oid);
3313                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3314
3315                 /* Decide whether we want to dump it */
3316                 selectDumpableObject(&(convinfo[i].dobj));
3317         }
3318
3319         PQclear(res);
3320
3321         destroyPQExpBuffer(query);
3322
3323         return convinfo;
3324 }
3325
3326 /*
3327  * getOpclasses:
3328  *        read all opclasses in the system catalogs and return them in the
3329  * OpclassInfo* structure
3330  *
3331  *      numOpclasses is set to the number of opclasses read in
3332  */
3333 OpclassInfo *
3334 getOpclasses(Archive *fout, int *numOpclasses)
3335 {
3336         PGresult   *res;
3337         int                     ntups;
3338         int                     i;
3339         PQExpBuffer query = createPQExpBuffer();
3340         OpclassInfo *opcinfo;
3341         int                     i_tableoid;
3342         int                     i_oid;
3343         int                     i_opcname;
3344         int                     i_opcnamespace;
3345         int                     i_rolname;
3346
3347         /*
3348          * find all opclasses, including builtin opclasses; we filter out
3349          * system-defined opclasses at dump-out time.
3350          */
3351
3352         /* Make sure we are in proper schema */
3353         selectSourceSchema(fout, "pg_catalog");
3354
3355         if (fout->remoteVersion >= 70300)
3356         {
3357                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3358                                                   "opcnamespace, "
3359                                                   "(%s opcowner) AS rolname "
3360                                                   "FROM pg_opclass",
3361                                                   username_subquery);
3362         }
3363         else if (fout->remoteVersion >= 70100)
3364         {
3365                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3366                                                   "0::oid AS opcnamespace, "
3367                                                   "''::name AS rolname "
3368                                                   "FROM pg_opclass");
3369         }
3370         else
3371         {
3372                 appendPQExpBuffer(query, "SELECT "
3373                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3374                                                   "oid, opcname, "
3375                                                   "0::oid AS opcnamespace, "
3376                                                   "''::name AS rolname "
3377                                                   "FROM pg_opclass");
3378         }
3379
3380         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3381
3382         ntups = PQntuples(res);
3383         *numOpclasses = ntups;
3384
3385         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3386
3387         i_tableoid = PQfnumber(res, "tableoid");
3388         i_oid = PQfnumber(res, "oid");
3389         i_opcname = PQfnumber(res, "opcname");
3390         i_opcnamespace = PQfnumber(res, "opcnamespace");
3391         i_rolname = PQfnumber(res, "rolname");
3392
3393         for (i = 0; i < ntups; i++)
3394         {
3395                 opcinfo[i].dobj.objType = DO_OPCLASS;
3396                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3397                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3398                 AssignDumpId(&opcinfo[i].dobj);
3399                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3400                 opcinfo[i].dobj.namespace =
3401                         findNamespace(fout,
3402                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3403                                                   opcinfo[i].dobj.catId.oid);
3404                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3405
3406                 /* Decide whether we want to dump it */
3407                 selectDumpableObject(&(opcinfo[i].dobj));
3408
3409                 if (fout->remoteVersion >= 70300)
3410                 {
3411                         if (strlen(opcinfo[i].rolname) == 0)
3412                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3413                                                   opcinfo[i].dobj.name);
3414                 }
3415         }
3416
3417         PQclear(res);
3418
3419         destroyPQExpBuffer(query);
3420
3421         return opcinfo;
3422 }
3423
3424 /*
3425  * getOpfamilies:
3426  *        read all opfamilies in the system catalogs and return them in the
3427  * OpfamilyInfo* structure
3428  *
3429  *      numOpfamilies is set to the number of opfamilies read in
3430  */
3431 OpfamilyInfo *
3432 getOpfamilies(Archive *fout, int *numOpfamilies)
3433 {
3434         PGresult   *res;
3435         int                     ntups;
3436         int                     i;
3437         PQExpBuffer query;
3438         OpfamilyInfo *opfinfo;
3439         int                     i_tableoid;
3440         int                     i_oid;
3441         int                     i_opfname;
3442         int                     i_opfnamespace;
3443         int                     i_rolname;
3444
3445         /* Before 8.3, there is no separate concept of opfamilies */
3446         if (fout->remoteVersion < 80300)
3447         {
3448                 *numOpfamilies = 0;
3449                 return NULL;
3450         }
3451
3452         query = createPQExpBuffer();
3453
3454         /*
3455          * find all opfamilies, including builtin opfamilies; we filter out
3456          * system-defined opfamilies at dump-out time.
3457          */
3458
3459         /* Make sure we are in proper schema */
3460         selectSourceSchema(fout, "pg_catalog");
3461
3462         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3463                                           "opfnamespace, "
3464                                           "(%s opfowner) AS rolname "
3465                                           "FROM pg_opfamily",
3466                                           username_subquery);
3467
3468         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3469
3470         ntups = PQntuples(res);
3471         *numOpfamilies = ntups;
3472
3473         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3474
3475         i_tableoid = PQfnumber(res, "tableoid");
3476         i_oid = PQfnumber(res, "oid");
3477         i_opfname = PQfnumber(res, "opfname");
3478         i_opfnamespace = PQfnumber(res, "opfnamespace");
3479         i_rolname = PQfnumber(res, "rolname");
3480
3481         for (i = 0; i < ntups; i++)
3482         {
3483                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3484                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3485                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3486                 AssignDumpId(&opfinfo[i].dobj);
3487                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3488                 opfinfo[i].dobj.namespace =
3489                         findNamespace(fout,
3490                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3491                                                   opfinfo[i].dobj.catId.oid);
3492                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3493
3494                 /* Decide whether we want to dump it */
3495                 selectDumpableObject(&(opfinfo[i].dobj));
3496
3497                 if (fout->remoteVersion >= 70300)
3498                 {
3499                         if (strlen(opfinfo[i].rolname) == 0)
3500                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3501                                                   opfinfo[i].dobj.name);
3502                 }
3503         }
3504
3505         PQclear(res);
3506
3507         destroyPQExpBuffer(query);
3508
3509         return opfinfo;
3510 }
3511
3512 /*
3513  * getAggregates:
3514  *        read all the user-defined aggregates in the system catalogs and
3515  * return them in the AggInfo* structure
3516  *
3517  * numAggs is set to the number of aggregates read in
3518  */
3519 AggInfo *
3520 getAggregates(Archive *fout, int *numAggs)
3521 {
3522         PGresult   *res;
3523         int                     ntups;
3524         int                     i;
3525         PQExpBuffer query = createPQExpBuffer();
3526         AggInfo    *agginfo;
3527         int                     i_tableoid;
3528         int                     i_oid;
3529         int                     i_aggname;
3530         int                     i_aggnamespace;
3531         int                     i_pronargs;
3532         int                     i_proargtypes;
3533         int                     i_rolname;
3534         int                     i_aggacl;
3535
3536         /* Make sure we are in proper schema */
3537         selectSourceSchema(fout, "pg_catalog");
3538
3539         /*
3540          * Find all user-defined aggregates.  See comment in getFuncs() for the
3541          * rationale behind the filtering logic.
3542          */
3543
3544         if (fout->remoteVersion >= 80200)
3545         {
3546                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3547                                                   "pronamespace AS aggnamespace, "
3548                                                   "pronargs, proargtypes, "
3549                                                   "(%s proowner) AS rolname, "
3550                                                   "proacl AS aggacl "
3551                                                   "FROM pg_proc p "
3552                                                   "WHERE proisagg AND ("
3553                                                   "pronamespace != "
3554                                                   "(SELECT oid FROM pg_namespace "
3555                                                   "WHERE nspname = 'pg_catalog')",
3556                                                   username_subquery);
3557                 if (binary_upgrade && fout->remoteVersion >= 90100)
3558                         appendPQExpBuffer(query,
3559                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3560                                                           "classid = 'pg_proc'::regclass AND "
3561                                                           "objid = p.oid AND "
3562                                                           "refclassid = 'pg_extension'::regclass AND "
3563                                                           "deptype = 'e')");
3564                 appendPQExpBuffer(query, ")");
3565         }
3566         else if (fout->remoteVersion >= 70300)
3567         {
3568                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3569                                                   "pronamespace AS aggnamespace, "
3570                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3571                                                   "proargtypes, "
3572                                                   "(%s proowner) AS rolname, "
3573                                                   "proacl AS aggacl "
3574                                                   "FROM pg_proc "
3575                                                   "WHERE proisagg "
3576                                                   "AND pronamespace != "
3577                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3578                                                   username_subquery);
3579         }
3580         else if (fout->remoteVersion >= 70100)
3581         {
3582                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3583                                                   "0::oid AS aggnamespace, "
3584                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3585                                                   "aggbasetype AS proargtypes, "
3586                                                   "(%s aggowner) AS rolname, "
3587                                                   "'{=X}' AS aggacl "
3588                                                   "FROM pg_aggregate "
3589                                                   "where oid > '%u'::oid",
3590                                                   username_subquery,
3591                                                   g_last_builtin_oid);
3592         }
3593         else
3594         {
3595                 appendPQExpBuffer(query, "SELECT "
3596                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3597                                                   "oid, aggname, "
3598                                                   "0::oid AS aggnamespace, "
3599                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3600                                                   "aggbasetype AS proargtypes, "
3601                                                   "(%s aggowner) AS rolname, "
3602                                                   "'{=X}' AS aggacl "
3603                                                   "FROM pg_aggregate "
3604                                                   "where oid > '%u'::oid",
3605                                                   username_subquery,
3606                                                   g_last_builtin_oid);
3607         }
3608
3609         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3610
3611         ntups = PQntuples(res);
3612         *numAggs = ntups;
3613
3614         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3615
3616         i_tableoid = PQfnumber(res, "tableoid");
3617         i_oid = PQfnumber(res, "oid");
3618         i_aggname = PQfnumber(res, "aggname");
3619         i_aggnamespace = PQfnumber(res, "aggnamespace");
3620         i_pronargs = PQfnumber(res, "pronargs");
3621         i_proargtypes = PQfnumber(res, "proargtypes");
3622         i_rolname = PQfnumber(res, "rolname");
3623         i_aggacl = PQfnumber(res, "aggacl");
3624
3625         for (i = 0; i < ntups; i++)
3626         {
3627                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3628                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3629                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3630                 AssignDumpId(&agginfo[i].aggfn.dobj);
3631                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3632                 agginfo[i].aggfn.dobj.namespace =
3633                         findNamespace(fout,
3634                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3635                                                   agginfo[i].aggfn.dobj.catId.oid);
3636                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3637                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3638                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3639                                           agginfo[i].aggfn.dobj.name);
3640                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3641                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3642                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3643                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3644                 if (agginfo[i].aggfn.nargs == 0)
3645                         agginfo[i].aggfn.argtypes = NULL;
3646                 else
3647                 {
3648                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3649                         if (fout->remoteVersion >= 70300)
3650                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3651                                                           agginfo[i].aggfn.argtypes,
3652                                                           agginfo[i].aggfn.nargs);
3653                         else
3654                                 /* it's just aggbasetype */
3655                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3656                 }
3657
3658                 /* Decide whether we want to dump it */
3659                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3660         }
3661
3662         PQclear(res);
3663
3664         destroyPQExpBuffer(query);
3665
3666         return agginfo;
3667 }
3668
3669 /*
3670  * getFuncs:
3671  *        read all the user-defined functions in the system catalogs and
3672  * return them in the FuncInfo* structure
3673  *
3674  * numFuncs is set to the number of functions read in
3675  */
3676 FuncInfo *
3677 getFuncs(Archive *fout, int *numFuncs)
3678 {
3679         PGresult   *res;
3680         int                     ntups;
3681         int                     i;
3682         PQExpBuffer query = createPQExpBuffer();
3683         FuncInfo   *finfo;
3684         int                     i_tableoid;
3685         int                     i_oid;
3686         int                     i_proname;
3687         int                     i_pronamespace;
3688         int                     i_rolname;
3689         int                     i_prolang;
3690         int                     i_pronargs;
3691         int                     i_proargtypes;
3692         int                     i_prorettype;
3693         int                     i_proacl;
3694
3695         /* Make sure we are in proper schema */
3696         selectSourceSchema(fout, "pg_catalog");
3697
3698         /*
3699          * Find all user-defined functions.  Normally we can exclude functions in
3700          * pg_catalog, which is worth doing since there are several thousand of
3701          * 'em.  However, there are some extensions that create functions in
3702          * pg_catalog.  In normal dumps we can still ignore those --- but in
3703          * binary-upgrade mode, we must dump the member objects of the extension,
3704          * so be sure to fetch any such functions.
3705          *
3706          * Also, in 9.2 and up, exclude functions that are internally dependent on
3707          * something else, since presumably those will be created as a result of
3708          * creating the something else.  This currently only acts to suppress
3709          * constructor functions for range types.  Note that this is OK only
3710          * because the constructors don't have any dependencies the range type
3711          * doesn't have; otherwise we might not get creation ordering correct.
3712          */
3713
3714         if (fout->remoteVersion >= 70300)
3715         {
3716                 appendPQExpBuffer(query,
3717                                                   "SELECT tableoid, oid, proname, prolang, "
3718                                                   "pronargs, proargtypes, prorettype, proacl, "
3719                                                   "pronamespace, "
3720                                                   "(%s proowner) AS rolname "
3721                                                   "FROM pg_proc p "
3722                                                   "WHERE NOT proisagg AND ("
3723                                                   "pronamespace != "
3724                                                   "(SELECT oid FROM pg_namespace "
3725                                                   "WHERE nspname = 'pg_catalog')",
3726                                                   username_subquery);
3727                 if (fout->remoteVersion >= 90200)
3728                         appendPQExpBuffer(query,
3729                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3730                                                           "WHERE classid = 'pg_proc'::regclass AND "
3731                                                           "objid = p.oid AND deptype = 'i')");
3732                 if (binary_upgrade && fout->remoteVersion >= 90100)
3733                         appendPQExpBuffer(query,
3734                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3735                                                           "classid = 'pg_proc'::regclass AND "
3736                                                           "objid = p.oid AND "
3737                                                           "refclassid = 'pg_extension'::regclass AND "
3738                                                           "deptype = 'e')");
3739                 appendPQExpBuffer(query, ")");
3740         }
3741         else if (fout->remoteVersion >= 70100)
3742         {
3743                 appendPQExpBuffer(query,
3744                                                   "SELECT tableoid, oid, proname, prolang, "
3745                                                   "pronargs, proargtypes, prorettype, "
3746                                                   "'{=X}' AS proacl, "
3747                                                   "0::oid AS pronamespace, "
3748                                                   "(%s proowner) AS rolname "
3749                                                   "FROM pg_proc "
3750                                                   "WHERE pg_proc.oid > '%u'::oid",
3751                                                   username_subquery,
3752                                                   g_last_builtin_oid);
3753         }
3754         else
3755         {
3756                 appendPQExpBuffer(query,
3757                                                   "SELECT "
3758                                                   "(SELECT oid FROM pg_class "
3759                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3760                                                   "oid, proname, prolang, "
3761                                                   "pronargs, proargtypes, prorettype, "
3762                                                   "'{=X}' AS proacl, "
3763                                                   "0::oid AS pronamespace, "
3764                                                   "(%s proowner) AS rolname "
3765                                                   "FROM pg_proc "
3766                                                   "where pg_proc.oid > '%u'::oid",
3767                                                   username_subquery,
3768                                                   g_last_builtin_oid);
3769         }
3770
3771         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3772
3773         ntups = PQntuples(res);
3774
3775         *numFuncs = ntups;
3776
3777         finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3778
3779         i_tableoid = PQfnumber(res, "tableoid");
3780         i_oid = PQfnumber(res, "oid");
3781         i_proname = PQfnumber(res, "proname");
3782         i_pronamespace = PQfnumber(res, "pronamespace");
3783         i_rolname = PQfnumber(res, "rolname");
3784         i_prolang = PQfnumber(res, "prolang");
3785         i_pronargs = PQfnumber(res, "pronargs");
3786         i_proargtypes = PQfnumber(res, "proargtypes");
3787         i_prorettype = PQfnumber(res, "prorettype");
3788         i_proacl = PQfnumber(res, "proacl");
3789
3790         for (i = 0; i < ntups; i++)
3791         {
3792                 finfo[i].dobj.objType = DO_FUNC;
3793                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3794                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3795                 AssignDumpId(&finfo[i].dobj);
3796                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3797                 finfo[i].dobj.namespace =
3798                         findNamespace(fout,
3799                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3800                                                   finfo[i].dobj.catId.oid);
3801                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3802                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3803                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3804                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3805                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3806                 if (finfo[i].nargs == 0)
3807                         finfo[i].argtypes = NULL;
3808                 else
3809                 {
3810                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3811                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3812                                                   finfo[i].argtypes, finfo[i].nargs);
3813                 }
3814
3815                 /* Decide whether we want to dump it */
3816                 selectDumpableObject(&(finfo[i].dobj));
3817
3818                 if (strlen(finfo[i].rolname) == 0)
3819                         write_msg(NULL,
3820                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3821                                           finfo[i].dobj.name);
3822         }
3823
3824         PQclear(res);
3825
3826         destroyPQExpBuffer(query);
3827
3828         return finfo;
3829 }
3830
3831 /*
3832  * getTables
3833  *        read all the user-defined tables (no indexes, no catalogs)
3834  * in the system catalogs return them in the TableInfo* structure
3835  *
3836  * numTables is set to the number of tables read in
3837  */
3838 TableInfo *
3839 getTables(Archive *fout, int *numTables)
3840 {
3841         PGresult   *res;
3842         int                     ntups;
3843         int                     i;
3844         PQExpBuffer query = createPQExpBuffer();
3845         TableInfo  *tblinfo;
3846         int                     i_reltableoid;
3847         int                     i_reloid;
3848         int                     i_relname;
3849         int                     i_relnamespace;
3850         int                     i_relkind;
3851         int                     i_relacl;
3852         int                     i_rolname;
3853         int                     i_relchecks;
3854         int                     i_relhastriggers;
3855         int                     i_relhasindex;
3856         int                     i_relhasrules;
3857         int                     i_relhasoids;
3858         int                     i_relfrozenxid;
3859         int                     i_toastoid;
3860         int                     i_toastfrozenxid;
3861         int                     i_relpersistence;
3862         int                     i_owning_tab;
3863         int                     i_owning_col;
3864         int                     i_reltablespace;
3865         int                     i_reloptions;
3866         int                     i_toastreloptions;
3867         int                     i_reloftype;
3868
3869         /* Make sure we are in proper schema */
3870         selectSourceSchema(fout, "pg_catalog");
3871
3872         /*
3873          * Find all the tables and table-like objects.
3874          *
3875          * We include system catalogs, so that we can work if a user table is
3876          * defined to inherit from a system catalog (pretty weird, but...)
3877          *
3878          * We ignore relations that are not ordinary tables, sequences, views,
3879          * composite types, or foreign tables.
3880          *
3881          * Composite-type table entries won't be dumped as such, but we have to
3882          * make a DumpableObject for them so that we can track dependencies of the
3883          * composite type (pg_depend entries for columns of the composite type
3884          * link to the pg_class entry not the pg_type entry).
3885          *
3886          * Note: in this phase we should collect only a minimal amount of
3887          * information about each table, basically just enough to decide if it is
3888          * interesting. We must fetch all tables in this phase because otherwise
3889          * we cannot correctly identify inherited columns, owned sequences, etc.
3890          */
3891
3892         if (fout->remoteVersion >= 90100)
3893         {
3894                 /*
3895                  * Left join to pick up dependency info linking sequences to their
3896                  * owning column, if any (note this dependency is AUTO as of 8.2)
3897                  */
3898                 appendPQExpBuffer(query,
3899                                                   "SELECT c.tableoid, c.oid, c.relname, "
3900                                                   "c.relacl, c.relkind, c.relnamespace, "
3901                                                   "(%s c.relowner) AS rolname, "
3902                                                   "c.relchecks, c.relhastriggers, "
3903                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3904                                                   "c.relfrozenxid, tc.oid AS toid, "
3905                                                   "tc.relfrozenxid AS tfrozenxid, "
3906                                                   "c.relpersistence, "
3907                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3908                                                   "d.refobjid AS owning_tab, "
3909                                                   "d.refobjsubid AS owning_col, "
3910                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3911                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3912                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3913                                                   "FROM pg_class c "
3914                                                   "LEFT JOIN pg_depend d ON "
3915                                                   "(c.relkind = '%c' AND "
3916                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3917                                                   "d.objsubid = 0 AND "
3918                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3919                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3920                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3921                                                   "ORDER BY c.oid",
3922                                                   username_subquery,
3923                                                   RELKIND_SEQUENCE,
3924                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3925                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3926                                                   RELKIND_FOREIGN_TABLE);
3927         }
3928         else if (fout->remoteVersion >= 90000)
3929         {
3930                 /*
3931                  * Left join to pick up dependency info linking sequences to their
3932                  * owning column, if any (note this dependency is AUTO as of 8.2)
3933                  */
3934                 appendPQExpBuffer(query,
3935                                                   "SELECT c.tableoid, c.oid, c.relname, "
3936                                                   "c.relacl, c.relkind, c.relnamespace, "
3937                                                   "(%s c.relowner) AS rolname, "
3938                                                   "c.relchecks, c.relhastriggers, "
3939                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3940                                                   "c.relfrozenxid, tc.oid AS toid, "
3941                                                   "tc.relfrozenxid AS tfrozenxid, "
3942                                                   "'p' AS relpersistence, "
3943                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3944                                                   "d.refobjid AS owning_tab, "
3945                                                   "d.refobjsubid AS owning_col, "
3946                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3947                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3948                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3949                                                   "FROM pg_class c "
3950                                                   "LEFT JOIN pg_depend d ON "
3951                                                   "(c.relkind = '%c' AND "
3952                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3953                                                   "d.objsubid = 0 AND "
3954                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3955                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3956                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3957                                                   "ORDER BY c.oid",
3958                                                   username_subquery,
3959                                                   RELKIND_SEQUENCE,
3960                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3961                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3962         }
3963         else if (fout->remoteVersion >= 80400)
3964         {
3965                 /*
3966                  * Left join to pick up dependency info linking sequences to their
3967                  * owning column, if any (note this dependency is AUTO as of 8.2)
3968                  */
3969                 appendPQExpBuffer(query,
3970                                                   "SELECT c.tableoid, c.oid, c.relname, "
3971                                                   "c.relacl, c.relkind, c.relnamespace, "
3972                                                   "(%s c.relowner) AS rolname, "
3973                                                   "c.relchecks, c.relhastriggers, "
3974                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3975                                                   "c.relfrozenxid, tc.oid AS toid, "
3976                                                   "tc.relfrozenxid AS tfrozenxid, "
3977                                                   "'p' AS relpersistence, "
3978                                                   "NULL AS reloftype, "
3979                                                   "d.refobjid AS owning_tab, "
3980                                                   "d.refobjsubid AS owning_col, "
3981                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3982                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3983                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3984                                                   "FROM pg_class c "
3985                                                   "LEFT JOIN pg_depend d ON "
3986                                                   "(c.relkind = '%c' AND "
3987                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3988                                                   "d.objsubid = 0 AND "
3989                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3990                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3991                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3992                                                   "ORDER BY c.oid",
3993                                                   username_subquery,
3994                                                   RELKIND_SEQUENCE,
3995                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3996                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3997         }
3998         else if (fout->remoteVersion >= 80200)
3999         {
4000                 /*
4001                  * Left join to pick up dependency info linking sequences to their
4002                  * owning column, if any (note this dependency is AUTO as of 8.2)
4003                  */
4004                 appendPQExpBuffer(query,
4005                                                   "SELECT c.tableoid, c.oid, c.relname, "
4006                                                   "c.relacl, c.relkind, c.relnamespace, "
4007                                                   "(%s c.relowner) AS rolname, "
4008                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4009                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4010                                                   "c.relfrozenxid, tc.oid AS toid, "
4011                                                   "tc.relfrozenxid AS tfrozenxid, "
4012                                                   "'p' AS relpersistence, "
4013                                                   "NULL AS reloftype, "
4014                                                   "d.refobjid AS owning_tab, "
4015                                                   "d.refobjsubid AS owning_col, "
4016                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4017                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4018                                                   "NULL AS toast_reloptions "
4019                                                   "FROM pg_class c "
4020                                                   "LEFT JOIN pg_depend d ON "
4021                                                   "(c.relkind = '%c' AND "
4022                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4023                                                   "d.objsubid = 0 AND "
4024                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4025                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4026                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4027                                                   "ORDER BY c.oid",
4028                                                   username_subquery,
4029                                                   RELKIND_SEQUENCE,
4030                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4031                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4032         }
4033         else if (fout->remoteVersion >= 80000)
4034         {
4035                 /*
4036                  * Left join to pick up dependency info linking sequences to their
4037                  * owning column, if any
4038                  */
4039                 appendPQExpBuffer(query,
4040                                                   "SELECT c.tableoid, c.oid, relname, "
4041                                                   "relacl, relkind, relnamespace, "
4042                                                   "(%s relowner) AS rolname, "
4043                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4044                                                   "relhasindex, relhasrules, relhasoids, "
4045                                                   "0 AS relfrozenxid, "
4046                                                   "0 AS toid, "
4047                                                   "0 AS tfrozenxid, "
4048                                                   "'p' AS relpersistence, "
4049                                                   "NULL AS reloftype, "
4050                                                   "d.refobjid AS owning_tab, "
4051                                                   "d.refobjsubid AS owning_col, "
4052                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4053                                                   "NULL AS reloptions, "
4054                                                   "NULL AS toast_reloptions "
4055                                                   "FROM pg_class c "
4056                                                   "LEFT JOIN pg_depend d ON "
4057                                                   "(c.relkind = '%c' AND "
4058                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4059                                                   "d.objsubid = 0 AND "
4060                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4061                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4062                                                   "ORDER BY c.oid",
4063                                                   username_subquery,
4064                                                   RELKIND_SEQUENCE,
4065                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4066                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4067         }
4068         else if (fout->remoteVersion >= 70300)
4069         {
4070                 /*
4071                  * Left join to pick up dependency info linking sequences to their
4072                  * owning column, if any
4073                  */
4074                 appendPQExpBuffer(query,
4075                                                   "SELECT c.tableoid, c.oid, relname, "
4076                                                   "relacl, relkind, relnamespace, "
4077                                                   "(%s relowner) AS rolname, "
4078                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4079                                                   "relhasindex, relhasrules, relhasoids, "
4080                                                   "0 AS relfrozenxid, "
4081                                                   "0 AS toid, "
4082                                                   "0 AS tfrozenxid, "
4083                                                   "'p' AS relpersistence, "
4084                                                   "NULL AS reloftype, "
4085                                                   "d.refobjid AS owning_tab, "
4086                                                   "d.refobjsubid AS owning_col, "
4087                                                   "NULL AS reltablespace, "
4088                                                   "NULL AS reloptions, "
4089                                                   "NULL AS toast_reloptions "
4090                                                   "FROM pg_class c "
4091                                                   "LEFT JOIN pg_depend d ON "
4092                                                   "(c.relkind = '%c' AND "
4093                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4094                                                   "d.objsubid = 0 AND "
4095                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4096                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4097                                                   "ORDER BY c.oid",
4098                                                   username_subquery,
4099                                                   RELKIND_SEQUENCE,
4100                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4101                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4102         }
4103         else if (fout->remoteVersion >= 70200)
4104         {
4105                 appendPQExpBuffer(query,
4106                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4107                                                   "0::oid AS relnamespace, "
4108                                                   "(%s relowner) AS rolname, "
4109                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4110                                                   "relhasindex, relhasrules, relhasoids, "
4111                                                   "0 AS relfrozenxid, "
4112                                                   "0 AS toid, "
4113                                                   "0 AS tfrozenxid, "
4114                                                   "'p' AS relpersistence, "
4115                                                   "NULL AS reloftype, "
4116                                                   "NULL::oid AS owning_tab, "
4117                                                   "NULL::int4 AS owning_col, "
4118                                                   "NULL AS reltablespace, "
4119                                                   "NULL AS reloptions, "
4120                                                   "NULL AS toast_reloptions "
4121                                                   "FROM pg_class "
4122                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4123                                                   "ORDER BY oid",
4124                                                   username_subquery,
4125                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4126         }
4127         else if (fout->remoteVersion >= 70100)
4128         {
4129                 /* all tables have oids in 7.1 */
4130                 appendPQExpBuffer(query,
4131                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4132                                                   "0::oid AS relnamespace, "
4133                                                   "(%s relowner) AS rolname, "
4134                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4135                                                   "relhasindex, relhasrules, "
4136                                                   "'t'::bool AS relhasoids, "
4137                                                   "0 AS relfrozenxid, "
4138                                                   "0 AS toid, "
4139                                                   "0 AS tfrozenxid, "
4140                                                   "'p' AS relpersistence, "
4141                                                   "NULL AS reloftype, "
4142                                                   "NULL::oid AS owning_tab, "
4143                                                   "NULL::int4 AS owning_col, "
4144                                                   "NULL AS reltablespace, "
4145                                                   "NULL AS reloptions, "
4146                                                   "NULL AS toast_reloptions "
4147                                                   "FROM pg_class "
4148                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4149                                                   "ORDER BY oid",
4150                                                   username_subquery,
4151                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4152         }
4153         else
4154         {
4155                 /*
4156                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4157                  * have a view by looking for a rule in pg_rewrite.
4158                  */
4159                 appendPQExpBuffer(query,
4160                                                   "SELECT "
4161                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4162                                                   "oid, relname, relacl, "
4163                                                   "CASE WHEN relhasrules and relkind = 'r' "
4164                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4165                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4166                                                   "THEN '%c'::\"char\" "
4167                                                   "ELSE relkind END AS relkind,"
4168                                                   "0::oid AS relnamespace, "
4169                                                   "(%s relowner) AS rolname, "
4170                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4171                                                   "relhasindex, relhasrules, "
4172                                                   "'t'::bool AS relhasoids, "
4173                                                   "0 as relfrozenxid, "
4174                                                   "0 AS toid, "
4175                                                   "0 AS tfrozenxid, "
4176                                                   "'p' AS relpersistence, "
4177                                                   "NULL AS reloftype, "
4178                                                   "NULL::oid AS owning_tab, "
4179                                                   "NULL::int4 AS owning_col, "
4180                                                   "NULL AS reltablespace, "
4181                                                   "NULL AS reloptions, "
4182                                                   "NULL AS toast_reloptions "
4183                                                   "FROM pg_class c "
4184                                                   "WHERE relkind IN ('%c', '%c') "
4185                                                   "ORDER BY oid",
4186                                                   RELKIND_VIEW,
4187                                                   username_subquery,
4188                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4189         }
4190
4191         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4192
4193         ntups = PQntuples(res);
4194
4195         *numTables = ntups;
4196
4197         /*
4198          * Extract data from result and lock dumpable tables.  We do the locking
4199          * before anything else, to minimize the window wherein a table could
4200          * disappear under us.
4201          *
4202          * Note that we have to save info about all tables here, even when dumping
4203          * only one, because we don't yet know which tables might be inheritance
4204          * ancestors of the target table.
4205          */
4206         tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4207
4208         i_reltableoid = PQfnumber(res, "tableoid");
4209         i_reloid = PQfnumber(res, "oid");
4210         i_relname = PQfnumber(res, "relname");
4211         i_relnamespace = PQfnumber(res, "relnamespace");
4212         i_relacl = PQfnumber(res, "relacl");
4213         i_relkind = PQfnumber(res, "relkind");
4214         i_rolname = PQfnumber(res, "rolname");
4215         i_relchecks = PQfnumber(res, "relchecks");
4216         i_relhastriggers = PQfnumber(res, "relhastriggers");
4217         i_relhasindex = PQfnumber(res, "relhasindex");
4218         i_relhasrules = PQfnumber(res, "relhasrules");
4219         i_relhasoids = PQfnumber(res, "relhasoids");
4220         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4221         i_toastoid = PQfnumber(res, "toid");
4222         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4223         i_relpersistence = PQfnumber(res, "relpersistence");
4224         i_owning_tab = PQfnumber(res, "owning_tab");
4225         i_owning_col = PQfnumber(res, "owning_col");
4226         i_reltablespace = PQfnumber(res, "reltablespace");
4227         i_reloptions = PQfnumber(res, "reloptions");
4228         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4229         i_reloftype = PQfnumber(res, "reloftype");
4230
4231         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4232         {
4233                 /*
4234                  * Arrange to fail instead of waiting forever for a table lock.
4235                  *
4236                  * NB: this coding assumes that the only queries issued within the
4237                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4238                  * applied to other things too.
4239                  */
4240                 resetPQExpBuffer(query);
4241                 appendPQExpBuffer(query, "SET statement_timeout = ");
4242                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4243                 ExecuteSqlStatement(fout, query->data);
4244         }
4245
4246         for (i = 0; i < ntups; i++)
4247         {
4248                 tblinfo[i].dobj.objType = DO_TABLE;
4249                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4250                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4251                 AssignDumpId(&tblinfo[i].dobj);
4252                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4253                 tblinfo[i].dobj.namespace =
4254                         findNamespace(fout,
4255                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4256                                                   tblinfo[i].dobj.catId.oid);
4257                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4258                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4259                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4260                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4261                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4262                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4263                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4264                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4265                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4266                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4267                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4268                 if (PQgetisnull(res, i, i_reloftype))
4269                         tblinfo[i].reloftype = NULL;
4270                 else
4271                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4272                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4273                 if (PQgetisnull(res, i, i_owning_tab))
4274                 {
4275                         tblinfo[i].owning_tab = InvalidOid;
4276                         tblinfo[i].owning_col = 0;
4277                 }
4278                 else
4279                 {
4280                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4281                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4282                 }
4283                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4284                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4285                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4286
4287                 /* other fields were zeroed above */
4288
4289                 /*
4290                  * Decide whether we want to dump this table.
4291                  */
4292                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4293                         tblinfo[i].dobj.dump = false;
4294                 else
4295                         selectDumpableTable(&tblinfo[i]);
4296                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4297
4298                 /*
4299                  * Read-lock target tables to make sure they aren't DROPPED or altered
4300                  * in schema before we get around to dumping them.
4301                  *
4302                  * Note that we don't explicitly lock parents of the target tables; we
4303                  * assume our lock on the child is enough to prevent schema
4304                  * alterations to parent tables.
4305                  *
4306                  * NOTE: it'd be kinda nice to lock other relations too, not only
4307                  * plain tables, but the backend doesn't presently allow that.
4308                  */
4309                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4310                 {
4311                         resetPQExpBuffer(query);
4312                         appendPQExpBuffer(query,
4313                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4314                                                           fmtQualifiedId(fout,
4315                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4316                                                                                          tblinfo[i].dobj.name));
4317                         ExecuteSqlStatement(fout, query->data);
4318                 }
4319
4320                 /* Emit notice if join for owner failed */
4321                 if (strlen(tblinfo[i].rolname) == 0)
4322                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4323                                           tblinfo[i].dobj.name);
4324         }
4325
4326         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4327         {
4328                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4329         }
4330
4331         PQclear(res);
4332
4333         destroyPQExpBuffer(query);
4334
4335         return tblinfo;
4336 }
4337
4338 /*
4339  * getOwnedSeqs
4340  *        identify owned sequences and mark them as dumpable if owning table is
4341  *
4342  * We used to do this in getTables(), but it's better to do it after the
4343  * index used by findTableByOid() has been set up.
4344  */
4345 void
4346 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4347 {
4348         int                     i;
4349
4350         /*
4351          * Force sequences that are "owned" by table columns to be dumped whenever
4352          * their owning table is being dumped.
4353          */
4354         for (i = 0; i < numTables; i++)
4355         {
4356                 TableInfo  *seqinfo = &tblinfo[i];
4357                 TableInfo  *owning_tab;
4358
4359                 if (!OidIsValid(seqinfo->owning_tab))
4360                         continue;                       /* not an owned sequence */
4361                 if (seqinfo->dobj.dump)
4362                         continue;                       /* no need to search */
4363                 owning_tab = findTableByOid(seqinfo->owning_tab);
4364                 if (owning_tab && owning_tab->dobj.dump)
4365                 {
4366                         seqinfo->interesting = true;
4367                         seqinfo->dobj.dump = true;
4368                 }
4369         }
4370 }
4371
4372 /*
4373  * getInherits
4374  *        read all the inheritance information
4375  * from the system catalogs return them in the InhInfo* structure
4376  *
4377  * numInherits is set to the number of pairs read in
4378  */
4379 InhInfo *
4380 getInherits(Archive *fout, int *numInherits)
4381 {
4382         PGresult   *res;
4383         int                     ntups;
4384         int                     i;
4385         PQExpBuffer query = createPQExpBuffer();
4386         InhInfo    *inhinfo;
4387
4388         int                     i_inhrelid;
4389         int                     i_inhparent;
4390
4391         /* Make sure we are in proper schema */
4392         selectSourceSchema(fout, "pg_catalog");
4393
4394         /* find all the inheritance information */
4395
4396         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4397
4398         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4399
4400         ntups = PQntuples(res);
4401
4402         *numInherits = ntups;
4403
4404         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4405
4406         i_inhrelid = PQfnumber(res, "inhrelid");
4407         i_inhparent = PQfnumber(res, "inhparent");
4408
4409         for (i = 0; i < ntups; i++)
4410         {
4411                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4412                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4413         }
4414
4415         PQclear(res);
4416
4417         destroyPQExpBuffer(query);
4418
4419         return inhinfo;
4420 }
4421
4422 /*
4423  * getIndexes
4424  *        get information about every index on a dumpable table
4425  *
4426  * Note: index data is not returned directly to the caller, but it
4427  * does get entered into the DumpableObject tables.
4428  */
4429 void
4430 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4431 {
4432         int                     i,
4433                                 j;
4434         PQExpBuffer query = createPQExpBuffer();
4435         PGresult   *res;
4436         IndxInfo   *indxinfo;
4437         ConstraintInfo *constrinfo;
4438         int                     i_tableoid,
4439                                 i_oid,
4440                                 i_indexname,
4441                                 i_indexdef,
4442                                 i_indnkeys,
4443                                 i_indkey,
4444                                 i_indisclustered,
4445                                 i_contype,
4446                                 i_conname,
4447                                 i_condeferrable,
4448                                 i_condeferred,
4449                                 i_contableoid,
4450                                 i_conoid,
4451                                 i_condef,
4452                                 i_tablespace,
4453                                 i_options;
4454         int                     ntups;
4455
4456         for (i = 0; i < numTables; i++)
4457         {
4458                 TableInfo  *tbinfo = &tblinfo[i];
4459
4460                 /* Only plain tables have indexes */
4461                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4462                         continue;
4463
4464                 /* Ignore indexes of tables not to be dumped */
4465                 if (!tbinfo->dobj.dump)
4466                         continue;
4467
4468                 if (g_verbose)
4469                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4470                                           tbinfo->dobj.name);
4471
4472                 /* Make sure we are in proper schema so indexdef is right */
4473                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4474
4475                 /*
4476                  * The point of the messy-looking outer join is to find a constraint
4477                  * that is related by an internal dependency link to the index. If we
4478                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4479                  * assume an index won't have more than one internal dependency.
4480                  *
4481                  * As of 9.0 we don't need to look at pg_depend but can check for a
4482                  * match to pg_constraint.conindid.  The check on conrelid is
4483                  * redundant but useful because that column is indexed while conindid
4484                  * is not.
4485                  */
4486                 resetPQExpBuffer(query);
4487                 if (fout->remoteVersion >= 90000)
4488                 {
4489                         appendPQExpBuffer(query,
4490                                                           "SELECT t.tableoid, t.oid, "
4491                                                           "t.relname AS indexname, "
4492                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4493                                                           "t.relnatts AS indnkeys, "
4494                                                           "i.indkey, i.indisclustered, "
4495                                                           "c.contype, c.conname, "
4496                                                           "c.condeferrable, c.condeferred, "
4497                                                           "c.tableoid AS contableoid, "
4498                                                           "c.oid AS conoid, "
4499                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4500                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4501                                                         "array_to_string(t.reloptions, ', ') AS options "
4502                                                           "FROM pg_catalog.pg_index i "
4503                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4504                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4505                                                           "ON (i.indrelid = c.conrelid AND "
4506                                                           "i.indexrelid = c.conindid AND "
4507                                                           "c.contype IN ('p','u','x')) "
4508                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4509                                                           "ORDER BY indexname",
4510                                                           tbinfo->dobj.catId.oid);
4511                 }
4512                 else if (fout->remoteVersion >= 80200)
4513                 {
4514                         appendPQExpBuffer(query,
4515                                                           "SELECT t.tableoid, t.oid, "
4516                                                           "t.relname AS indexname, "
4517                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4518                                                           "t.relnatts AS indnkeys, "
4519                                                           "i.indkey, i.indisclustered, "
4520                                                           "c.contype, c.conname, "
4521                                                           "c.condeferrable, c.condeferred, "
4522                                                           "c.tableoid AS contableoid, "
4523                                                           "c.oid AS conoid, "
4524                                                           "null AS condef, "
4525                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4526                                                         "array_to_string(t.reloptions, ', ') AS options "
4527                                                           "FROM pg_catalog.pg_index i "
4528                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4529                                                           "LEFT JOIN pg_catalog.pg_depend d "
4530                                                           "ON (d.classid = t.tableoid "
4531                                                           "AND d.objid = t.oid "
4532                                                           "AND d.deptype = 'i') "
4533                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4534                                                           "ON (d.refclassid = c.tableoid "
4535                                                           "AND d.refobjid = c.oid) "
4536                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4537                                                           "ORDER BY indexname",
4538                                                           tbinfo->dobj.catId.oid);
4539                 }
4540                 else if (fout->remoteVersion >= 80000)
4541                 {
4542                         appendPQExpBuffer(query,
4543                                                           "SELECT t.tableoid, t.oid, "
4544                                                           "t.relname AS indexname, "
4545                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4546                                                           "t.relnatts AS indnkeys, "
4547                                                           "i.indkey, i.indisclustered, "
4548                                                           "c.contype, c.conname, "
4549                                                           "c.condeferrable, c.condeferred, "
4550                                                           "c.tableoid AS contableoid, "
4551                                                           "c.oid AS conoid, "
4552                                                           "null AS condef, "
4553                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4554                                                           "null AS options "
4555                                                           "FROM pg_catalog.pg_index i "
4556                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4557                                                           "LEFT JOIN pg_catalog.pg_depend d "
4558                                                           "ON (d.classid = t.tableoid "
4559                                                           "AND d.objid = t.oid "
4560                                                           "AND d.deptype = 'i') "
4561                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4562                                                           "ON (d.refclassid = c.tableoid "
4563                                                           "AND d.refobjid = c.oid) "
4564                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4565                                                           "ORDER BY indexname",
4566                                                           tbinfo->dobj.catId.oid);
4567                 }
4568                 else if (fout->remoteVersion >= 70300)
4569                 {
4570                         appendPQExpBuffer(query,
4571                                                           "SELECT t.tableoid, t.oid, "
4572                                                           "t.relname AS indexname, "
4573                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4574                                                           "t.relnatts AS indnkeys, "
4575                                                           "i.indkey, i.indisclustered, "
4576                                                           "c.contype, c.conname, "
4577                                                           "c.condeferrable, c.condeferred, "
4578                                                           "c.tableoid AS contableoid, "
4579                                                           "c.oid AS conoid, "
4580                                                           "null AS condef, "
4581                                                           "NULL AS tablespace, "
4582                                                           "null AS options "
4583                                                           "FROM pg_catalog.pg_index i "
4584                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4585                                                           "LEFT JOIN pg_catalog.pg_depend d "
4586                                                           "ON (d.classid = t.tableoid "
4587                                                           "AND d.objid = t.oid "
4588                                                           "AND d.deptype = 'i') "
4589                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4590                                                           "ON (d.refclassid = c.tableoid "
4591                                                           "AND d.refobjid = c.oid) "
4592                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4593                                                           "ORDER BY indexname",
4594                                                           tbinfo->dobj.catId.oid);
4595                 }
4596                 else if (fout->remoteVersion >= 70100)
4597                 {
4598                         appendPQExpBuffer(query,
4599                                                           "SELECT t.tableoid, t.oid, "
4600                                                           "t.relname AS indexname, "
4601                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4602                                                           "t.relnatts AS indnkeys, "
4603                                                           "i.indkey, false AS indisclustered, "
4604                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4605                                                           "ELSE '0'::char END AS contype, "
4606                                                           "t.relname AS conname, "
4607                                                           "false AS condeferrable, "
4608                                                           "false AS condeferred, "
4609                                                           "0::oid AS contableoid, "
4610                                                           "t.oid AS conoid, "
4611                                                           "null AS condef, "
4612                                                           "NULL AS tablespace, "
4613                                                           "null AS options "
4614                                                           "FROM pg_index i, pg_class t "
4615                                                           "WHERE t.oid = i.indexrelid "
4616                                                           "AND i.indrelid = '%u'::oid "
4617                                                           "ORDER BY indexname",
4618                                                           tbinfo->dobj.catId.oid);
4619                 }
4620                 else
4621                 {
4622                         appendPQExpBuffer(query,
4623                                                           "SELECT "
4624                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4625                                                           "t.oid, "
4626                                                           "t.relname AS indexname, "
4627                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4628                                                           "t.relnatts AS indnkeys, "
4629                                                           "i.indkey, false AS indisclustered, "
4630                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4631                                                           "ELSE '0'::char END AS contype, "
4632                                                           "t.relname AS conname, "
4633                                                           "false AS condeferrable, "
4634                                                           "false AS condeferred, "
4635                                                           "0::oid AS contableoid, "
4636                                                           "t.oid AS conoid, "
4637                                                           "null AS condef, "
4638                                                           "NULL AS tablespace, "
4639                                                           "null AS options "
4640                                                           "FROM pg_index i, pg_class t "
4641                                                           "WHERE t.oid = i.indexrelid "
4642                                                           "AND i.indrelid = '%u'::oid "
4643                                                           "ORDER BY indexname",
4644                                                           tbinfo->dobj.catId.oid);
4645                 }
4646
4647                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4648
4649                 ntups = PQntuples(res);
4650
4651                 i_tableoid = PQfnumber(res, "tableoid");
4652                 i_oid = PQfnumber(res, "oid");
4653                 i_indexname = PQfnumber(res, "indexname");
4654                 i_indexdef = PQfnumber(res, "indexdef");
4655                 i_indnkeys = PQfnumber(res, "indnkeys");
4656                 i_indkey = PQfnumber(res, "indkey");
4657                 i_indisclustered = PQfnumber(res, "indisclustered");
4658                 i_contype = PQfnumber(res, "contype");
4659                 i_conname = PQfnumber(res, "conname");
4660                 i_condeferrable = PQfnumber(res, "condeferrable");
4661                 i_condeferred = PQfnumber(res, "condeferred");
4662                 i_contableoid = PQfnumber(res, "contableoid");
4663                 i_conoid = PQfnumber(res, "conoid");
4664                 i_condef = PQfnumber(res, "condef");
4665                 i_tablespace = PQfnumber(res, "tablespace");
4666                 i_options = PQfnumber(res, "options");
4667
4668                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4669                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4670
4671                 for (j = 0; j < ntups; j++)
4672                 {
4673                         char            contype;
4674
4675                         indxinfo[j].dobj.objType = DO_INDEX;
4676                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4677                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4678                         AssignDumpId(&indxinfo[j].dobj);
4679                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4680                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4681                         indxinfo[j].indextable = tbinfo;
4682                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4683                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4684                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4685                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4686
4687                         /*
4688                          * In pre-7.4 releases, indkeys may contain more entries than
4689                          * indnkeys says (since indnkeys will be 1 for a functional
4690                          * index).      We don't actually care about this case since we don't
4691                          * examine indkeys except for indexes associated with PRIMARY and
4692                          * UNIQUE constraints, which are never functional indexes. But we
4693                          * have to allocate enough space to keep parseOidArray from
4694                          * complaining.
4695                          */
4696                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4697                         parseOidArray(PQgetvalue(res, j, i_indkey),
4698                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4699                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4700                         contype = *(PQgetvalue(res, j, i_contype));
4701
4702                         if (contype == 'p' || contype == 'u' || contype == 'x')
4703                         {
4704                                 /*
4705                                  * If we found a constraint matching the index, create an
4706                                  * entry for it.
4707                                  *
4708                                  * In a pre-7.3 database, we take this path iff the index was
4709                                  * marked indisprimary.
4710                                  */
4711                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4712                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4713                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4714                                 AssignDumpId(&constrinfo[j].dobj);
4715                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4716                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4717                                 constrinfo[j].contable = tbinfo;
4718                                 constrinfo[j].condomain = NULL;
4719                                 constrinfo[j].contype = contype;
4720                                 if (contype == 'x')
4721                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4722                                 else
4723                                         constrinfo[j].condef = NULL;
4724                                 constrinfo[j].confrelid = InvalidOid;
4725                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4726                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4727                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4728                                 constrinfo[j].conislocal = true;
4729                                 constrinfo[j].separate = true;
4730
4731                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4732
4733                                 /* If pre-7.3 DB, better make sure table comes first */
4734                                 addObjectDependency(&constrinfo[j].dobj,
4735                                                                         tbinfo->dobj.dumpId);
4736                         }
4737                         else
4738                         {
4739                                 /* Plain secondary index */
4740                                 indxinfo[j].indexconstraint = 0;
4741                         }
4742                 }
4743
4744                 PQclear(res);
4745         }
4746
4747         destroyPQExpBuffer(query);
4748 }
4749
4750 /*
4751  * getConstraints
4752  *
4753  * Get info about constraints on dumpable tables.
4754  *
4755  * Currently handles foreign keys only.
4756  * Unique and primary key constraints are handled with indexes,
4757  * while check constraints are processed in getTableAttrs().
4758  */
4759 void
4760 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4761 {
4762         int                     i,
4763                                 j;
4764         ConstraintInfo *constrinfo;
4765         PQExpBuffer query;
4766         PGresult   *res;
4767         int                     i_contableoid,
4768                                 i_conoid,
4769                                 i_conname,
4770                                 i_confrelid,
4771                                 i_condef;
4772         int                     ntups;
4773
4774         /* pg_constraint was created in 7.3, so nothing to do if older */
4775         if (fout->remoteVersion < 70300)
4776                 return;
4777
4778         query = createPQExpBuffer();
4779
4780         for (i = 0; i < numTables; i++)
4781         {
4782                 TableInfo  *tbinfo = &tblinfo[i];
4783
4784                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4785                         continue;
4786
4787                 if (g_verbose)
4788                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4789                                           tbinfo->dobj.name);
4790
4791                 /*
4792                  * select table schema to ensure constraint expr is qualified if
4793                  * needed
4794                  */
4795                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4796
4797                 resetPQExpBuffer(query);
4798                 appendPQExpBuffer(query,
4799                                                   "SELECT tableoid, oid, conname, confrelid, "
4800                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4801                                                   "FROM pg_catalog.pg_constraint "
4802                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4803                                                   "AND contype = 'f'",
4804                                                   tbinfo->dobj.catId.oid);
4805                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4806
4807                 ntups = PQntuples(res);
4808
4809                 i_contableoid = PQfnumber(res, "tableoid");
4810                 i_conoid = PQfnumber(res, "oid");
4811                 i_conname = PQfnumber(res, "conname");
4812                 i_confrelid = PQfnumber(res, "confrelid");
4813                 i_condef = PQfnumber(res, "condef");
4814
4815                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4816
4817                 for (j = 0; j < ntups; j++)
4818                 {
4819                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4820                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4821                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4822                         AssignDumpId(&constrinfo[j].dobj);
4823                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4824                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4825                         constrinfo[j].contable = tbinfo;
4826                         constrinfo[j].condomain = NULL;
4827                         constrinfo[j].contype = 'f';
4828                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4829                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4830                         constrinfo[j].conindex = 0;
4831                         constrinfo[j].condeferrable = false;
4832                         constrinfo[j].condeferred = false;
4833                         constrinfo[j].conislocal = true;
4834                         constrinfo[j].separate = true;
4835                 }
4836
4837                 PQclear(res);
4838         }
4839
4840         destroyPQExpBuffer(query);
4841 }
4842
4843 /*
4844  * getDomainConstraints
4845  *
4846  * Get info about constraints on a domain.
4847  */
4848 static void
4849 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4850 {
4851         int                     i;
4852         ConstraintInfo *constrinfo;
4853         PQExpBuffer query;
4854         PGresult   *res;
4855         int                     i_tableoid,
4856                                 i_oid,
4857                                 i_conname,
4858                                 i_consrc;
4859         int                     ntups;
4860
4861         /* pg_constraint was created in 7.3, so nothing to do if older */
4862         if (fout->remoteVersion < 70300)
4863                 return;
4864
4865         /*
4866          * select appropriate schema to ensure names in constraint are properly
4867          * qualified
4868          */
4869         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4870
4871         query = createPQExpBuffer();
4872
4873         if (fout->remoteVersion >= 90100)
4874                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4875                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4876                                                   "convalidated "
4877                                                   "FROM pg_catalog.pg_constraint "
4878                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4879                                                   "ORDER BY conname",
4880                                                   tyinfo->dobj.catId.oid);
4881
4882         else if (fout->remoteVersion >= 70400)
4883                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4884                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4885                                                   "true as convalidated "
4886                                                   "FROM pg_catalog.pg_constraint "
4887                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4888                                                   "ORDER BY conname",
4889                                                   tyinfo->dobj.catId.oid);
4890         else
4891                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4892                                                   "'CHECK (' || consrc || ')' AS consrc, "
4893                                                   "true as convalidated "
4894                                                   "FROM pg_catalog.pg_constraint "
4895                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4896                                                   "ORDER BY conname",
4897                                                   tyinfo->dobj.catId.oid);
4898
4899         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4900
4901         ntups = PQntuples(res);
4902
4903         i_tableoid = PQfnumber(res, "tableoid");
4904         i_oid = PQfnumber(res, "oid");
4905         i_conname = PQfnumber(res, "conname");
4906         i_consrc = PQfnumber(res, "consrc");
4907
4908         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4909
4910         tyinfo->nDomChecks = ntups;
4911         tyinfo->domChecks = constrinfo;
4912
4913         for (i = 0; i < ntups; i++)
4914         {
4915                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
4916
4917                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4918                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4919                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4920                 AssignDumpId(&constrinfo[i].dobj);
4921                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4922                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4923                 constrinfo[i].contable = NULL;
4924                 constrinfo[i].condomain = tyinfo;
4925                 constrinfo[i].contype = 'c';
4926                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4927                 constrinfo[i].confrelid = InvalidOid;
4928                 constrinfo[i].conindex = 0;
4929                 constrinfo[i].condeferrable = false;
4930                 constrinfo[i].condeferred = false;
4931                 constrinfo[i].conislocal = true;
4932
4933                 constrinfo[i].separate = !validated;
4934
4935                 /*
4936                  * Make the domain depend on the constraint, ensuring it won't be
4937                  * output till any constraint dependencies are OK.      If the constraint
4938                  * has not been validated, it's going to be dumped after the domain
4939                  * anyway, so this doesn't matter.
4940                  */
4941                 if (validated)
4942                         addObjectDependency(&tyinfo->dobj,
4943                                                                 constrinfo[i].dobj.dumpId);
4944         }
4945
4946         PQclear(res);
4947
4948         destroyPQExpBuffer(query);
4949 }
4950
4951 /*
4952  * getRules
4953  *        get basic information about every rule in the system
4954  *
4955  * numRules is set to the number of rules read in
4956  */
4957 RuleInfo *
4958 getRules(Archive *fout, int *numRules)
4959 {
4960         PGresult   *res;
4961         int                     ntups;
4962         int                     i;
4963         PQExpBuffer query = createPQExpBuffer();
4964         RuleInfo   *ruleinfo;
4965         int                     i_tableoid;
4966         int                     i_oid;
4967         int                     i_rulename;
4968         int                     i_ruletable;
4969         int                     i_ev_type;
4970         int                     i_is_instead;
4971         int                     i_ev_enabled;
4972
4973         /* Make sure we are in proper schema */
4974         selectSourceSchema(fout, "pg_catalog");
4975
4976         if (fout->remoteVersion >= 80300)
4977         {
4978                 appendPQExpBuffer(query, "SELECT "
4979                                                   "tableoid, oid, rulename, "
4980                                                   "ev_class AS ruletable, ev_type, is_instead, "
4981                                                   "ev_enabled "
4982                                                   "FROM pg_rewrite "
4983                                                   "ORDER BY oid");
4984         }
4985         else if (fout->remoteVersion >= 70100)
4986         {
4987                 appendPQExpBuffer(query, "SELECT "
4988                                                   "tableoid, oid, rulename, "
4989                                                   "ev_class AS ruletable, ev_type, is_instead, "
4990                                                   "'O'::char AS ev_enabled "
4991                                                   "FROM pg_rewrite "
4992                                                   "ORDER BY oid");
4993         }
4994         else
4995         {
4996                 appendPQExpBuffer(query, "SELECT "
4997                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4998                                                   "oid, rulename, "
4999                                                   "ev_class AS ruletable, ev_type, is_instead, "
5000                                                   "'O'::char AS ev_enabled "
5001                                                   "FROM pg_rewrite "
5002                                                   "ORDER BY oid");
5003         }
5004
5005         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5006
5007         ntups = PQntuples(res);
5008
5009         *numRules = ntups;
5010
5011         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5012
5013         i_tableoid = PQfnumber(res, "tableoid");
5014         i_oid = PQfnumber(res, "oid");
5015         i_rulename = PQfnumber(res, "rulename");
5016         i_ruletable = PQfnumber(res, "ruletable");
5017         i_ev_type = PQfnumber(res, "ev_type");
5018         i_is_instead = PQfnumber(res, "is_instead");
5019         i_ev_enabled = PQfnumber(res, "ev_enabled");
5020
5021         for (i = 0; i < ntups; i++)
5022         {
5023                 Oid                     ruletableoid;
5024
5025                 ruleinfo[i].dobj.objType = DO_RULE;
5026                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5027                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5028                 AssignDumpId(&ruleinfo[i].dobj);
5029                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5030                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5031                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5032                 if (ruleinfo[i].ruletable == NULL)
5033                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5034                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5035                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5036                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5037                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5038                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5039                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5040                 if (ruleinfo[i].ruletable)
5041                 {
5042                         /*
5043                          * If the table is a view, force its ON SELECT rule to be sorted
5044                          * before the view itself --- this ensures that any dependencies
5045                          * for the rule affect the table's positioning. Other rules are
5046                          * forced to appear after their table.
5047                          */
5048                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5049                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5050                         {
5051                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5052                                                                         ruleinfo[i].dobj.dumpId);
5053                                 /* We'll merge the rule into CREATE VIEW, if possible */
5054                                 ruleinfo[i].separate = false;
5055                         }
5056                         else
5057                         {
5058                                 addObjectDependency(&ruleinfo[i].dobj,
5059                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5060                                 ruleinfo[i].separate = true;
5061                         }
5062                 }
5063                 else
5064                         ruleinfo[i].separate = true;
5065         }
5066
5067         PQclear(res);
5068
5069         destroyPQExpBuffer(query);
5070
5071         return ruleinfo;
5072 }
5073
5074 /*
5075  * getTriggers
5076  *        get information about every trigger on a dumpable table
5077  *
5078  * Note: trigger data is not returned directly to the caller, but it
5079  * does get entered into the DumpableObject tables.
5080  */
5081 void
5082 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5083 {
5084         int                     i,
5085                                 j;
5086         PQExpBuffer query = createPQExpBuffer();
5087         PGresult   *res;
5088         TriggerInfo *tginfo;
5089         int                     i_tableoid,
5090                                 i_oid,
5091                                 i_tgname,
5092                                 i_tgfname,
5093                                 i_tgtype,
5094                                 i_tgnargs,
5095                                 i_tgargs,
5096                                 i_tgisconstraint,
5097                                 i_tgconstrname,
5098                                 i_tgconstrrelid,
5099                                 i_tgconstrrelname,
5100                                 i_tgenabled,
5101                                 i_tgdeferrable,
5102                                 i_tginitdeferred,
5103                                 i_tgdef;
5104         int                     ntups;
5105
5106         for (i = 0; i < numTables; i++)
5107         {
5108                 TableInfo  *tbinfo = &tblinfo[i];
5109
5110                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5111                         continue;
5112
5113                 if (g_verbose)
5114                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5115                                           tbinfo->dobj.name);
5116
5117                 /*
5118                  * select table schema to ensure regproc name is qualified if needed
5119                  */
5120                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5121
5122                 resetPQExpBuffer(query);
5123                 if (fout->remoteVersion >= 90000)
5124                 {
5125                         /*
5126                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5127                          * could result in non-forward-compatible dumps of WHEN clauses
5128                          * due to under-parenthesization.
5129                          */
5130                         appendPQExpBuffer(query,
5131                                                           "SELECT tgname, "
5132                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5133                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5134                                                           "tgenabled, tableoid, oid "
5135                                                           "FROM pg_catalog.pg_trigger t "
5136                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5137                                                           "AND NOT tgisinternal",
5138                                                           tbinfo->dobj.catId.oid);
5139                 }
5140                 else if (fout->remoteVersion >= 80300)
5141                 {
5142                         /*
5143                          * We ignore triggers that are tied to a foreign-key constraint
5144                          */
5145                         appendPQExpBuffer(query,
5146                                                           "SELECT tgname, "
5147                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5148                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5149                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5150                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5151                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5152                                                           "FROM pg_catalog.pg_trigger t "
5153                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5154                                                           "AND tgconstraint = 0",
5155                                                           tbinfo->dobj.catId.oid);
5156                 }
5157                 else if (fout->remoteVersion >= 70300)
5158                 {
5159                         /*
5160                          * We ignore triggers that are tied to a foreign-key constraint,
5161                          * but in these versions we have to grovel through pg_constraint
5162                          * to find out
5163                          */
5164                         appendPQExpBuffer(query,
5165                                                           "SELECT tgname, "
5166                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5167                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5168                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5169                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5170                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5171                                                           "FROM pg_catalog.pg_trigger t "
5172                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5173                                                           "AND (NOT tgisconstraint "
5174                                                           " OR NOT EXISTS"
5175                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5176                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5177                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5178                                                           tbinfo->dobj.catId.oid);
5179                 }
5180                 else if (fout->remoteVersion >= 70100)
5181                 {
5182                         appendPQExpBuffer(query,
5183                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5184                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5185                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5186                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5187                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5188                                                           "             AS tgconstrrelname "
5189                                                           "FROM pg_trigger "
5190                                                           "WHERE tgrelid = '%u'::oid",
5191                                                           tbinfo->dobj.catId.oid);
5192                 }
5193                 else
5194                 {
5195                         appendPQExpBuffer(query,
5196                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5197                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5198                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5199                                                           "tgconstrrelid, tginitdeferred, "
5200                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5201                                                           "oid, "
5202                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5203                                                           "             AS tgconstrrelname "
5204                                                           "FROM pg_trigger "
5205                                                           "WHERE tgrelid = '%u'::oid",
5206                                                           tbinfo->dobj.catId.oid);
5207                 }
5208                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5209
5210                 ntups = PQntuples(res);
5211
5212                 i_tableoid = PQfnumber(res, "tableoid");
5213                 i_oid = PQfnumber(res, "oid");
5214                 i_tgname = PQfnumber(res, "tgname");
5215                 i_tgfname = PQfnumber(res, "tgfname");
5216                 i_tgtype = PQfnumber(res, "tgtype");
5217                 i_tgnargs = PQfnumber(res, "tgnargs");
5218                 i_tgargs = PQfnumber(res, "tgargs");
5219                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5220                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5221                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5222                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5223                 i_tgenabled = PQfnumber(res, "tgenabled");
5224                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5225                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5226                 i_tgdef = PQfnumber(res, "tgdef");
5227
5228                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5229
5230                 for (j = 0; j < ntups; j++)
5231                 {
5232                         tginfo[j].dobj.objType = DO_TRIGGER;
5233                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5234                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5235                         AssignDumpId(&tginfo[j].dobj);
5236                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5237                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5238                         tginfo[j].tgtable = tbinfo;
5239                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5240                         if (i_tgdef >= 0)
5241                         {
5242                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5243
5244                                 /* remaining fields are not valid if we have tgdef */
5245                                 tginfo[j].tgfname = NULL;
5246                                 tginfo[j].tgtype = 0;
5247                                 tginfo[j].tgnargs = 0;
5248                                 tginfo[j].tgargs = NULL;
5249                                 tginfo[j].tgisconstraint = false;
5250                                 tginfo[j].tgdeferrable = false;
5251                                 tginfo[j].tginitdeferred = false;
5252                                 tginfo[j].tgconstrname = NULL;
5253                                 tginfo[j].tgconstrrelid = InvalidOid;
5254                                 tginfo[j].tgconstrrelname = NULL;
5255                         }
5256                         else
5257                         {
5258                                 tginfo[j].tgdef = NULL;
5259
5260                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5261                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5262                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5263                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5264                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5265                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5266                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5267
5268                                 if (tginfo[j].tgisconstraint)
5269                                 {
5270                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5271                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5272                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5273                                         {
5274                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5275                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5276                                                                                   tginfo[j].dobj.name,
5277                                                                                   tbinfo->dobj.name,
5278                                                                                   tginfo[j].tgconstrrelid);
5279                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5280                                         }
5281                                         else
5282                                                 tginfo[j].tgconstrrelname = NULL;
5283                                 }
5284                                 else
5285                                 {
5286                                         tginfo[j].tgconstrname = NULL;
5287                                         tginfo[j].tgconstrrelid = InvalidOid;
5288                                         tginfo[j].tgconstrrelname = NULL;
5289                                 }
5290                         }
5291                 }
5292
5293                 PQclear(res);
5294         }
5295
5296         destroyPQExpBuffer(query);
5297 }
5298
5299 /*
5300  * getProcLangs
5301  *        get basic information about every procedural language in the system
5302  *
5303  * numProcLangs is set to the number of langs read in
5304  *
5305  * NB: this must run after getFuncs() because we assume we can do
5306  * findFuncByOid().
5307  */
5308 ProcLangInfo *
5309 getProcLangs(Archive *fout, int *numProcLangs)
5310 {
5311         PGresult   *res;
5312         int                     ntups;
5313         int                     i;
5314         PQExpBuffer query = createPQExpBuffer();
5315         ProcLangInfo *planginfo;
5316         int                     i_tableoid;
5317         int                     i_oid;
5318         int                     i_lanname;
5319         int                     i_lanpltrusted;
5320         int                     i_lanplcallfoid;
5321         int                     i_laninline;
5322         int                     i_lanvalidator;
5323         int                     i_lanacl;
5324         int                     i_lanowner;
5325
5326         /* Make sure we are in proper schema */
5327         selectSourceSchema(fout, "pg_catalog");
5328
5329         if (fout->remoteVersion >= 90000)
5330         {
5331                 /* pg_language has a laninline column */
5332                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5333                                                   "lanname, lanpltrusted, lanplcallfoid, "
5334                                                   "laninline, lanvalidator,  lanacl, "
5335                                                   "(%s lanowner) AS lanowner "
5336                                                   "FROM pg_language "
5337                                                   "WHERE lanispl "
5338                                                   "ORDER BY oid",
5339                                                   username_subquery);
5340         }
5341         else if (fout->remoteVersion >= 80300)
5342         {
5343                 /* pg_language has a lanowner column */
5344                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5345                                                   "lanname, lanpltrusted, lanplcallfoid, "
5346                                                   "lanvalidator,  lanacl, "
5347                                                   "(%s lanowner) AS lanowner "
5348                                                   "FROM pg_language "
5349                                                   "WHERE lanispl "
5350                                                   "ORDER BY oid",
5351                                                   username_subquery);
5352         }
5353         else if (fout->remoteVersion >= 80100)
5354         {
5355                 /* Languages are owned by the bootstrap superuser, OID 10 */
5356                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5357                                                   "(%s '10') AS lanowner "
5358                                                   "FROM pg_language "
5359                                                   "WHERE lanispl "
5360                                                   "ORDER BY oid",
5361                                                   username_subquery);
5362         }
5363         else if (fout->remoteVersion >= 70400)
5364         {
5365                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5366                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5367                                                   "(%s '1') AS lanowner "
5368                                                   "FROM pg_language "
5369                                                   "WHERE lanispl "
5370                                                   "ORDER BY oid",
5371                                                   username_subquery);
5372         }
5373         else if (fout->remoteVersion >= 70100)
5374         {
5375                 /* No clear notion of an owner at all before 7.4 ... */
5376                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5377                                                   "WHERE lanispl "
5378                                                   "ORDER BY oid");
5379         }
5380         else
5381         {
5382                 appendPQExpBuffer(query, "SELECT "
5383                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5384                                                   "oid, * FROM pg_language "
5385                                                   "WHERE lanispl "
5386                                                   "ORDER BY oid");
5387         }
5388
5389         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5390
5391         ntups = PQntuples(res);
5392
5393         *numProcLangs = ntups;
5394
5395         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5396
5397         i_tableoid = PQfnumber(res, "tableoid");
5398         i_oid = PQfnumber(res, "oid");
5399         i_lanname = PQfnumber(res, "lanname");
5400         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5401         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5402         /* these may fail and return -1: */
5403         i_laninline = PQfnumber(res, "laninline");
5404         i_lanvalidator = PQfnumber(res, "lanvalidator");
5405         i_lanacl = PQfnumber(res, "lanacl");
5406         i_lanowner = PQfnumber(res, "lanowner");
5407
5408         for (i = 0; i < ntups; i++)
5409         {
5410                 planginfo[i].dobj.objType = DO_PROCLANG;
5411                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5412                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5413                 AssignDumpId(&planginfo[i].dobj);
5414
5415                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5416                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5417                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5418                 if (i_laninline >= 0)
5419                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5420                 else
5421                         planginfo[i].laninline = InvalidOid;
5422                 if (i_lanvalidator >= 0)
5423                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5424                 else
5425                         planginfo[i].lanvalidator = InvalidOid;
5426                 if (i_lanacl >= 0)
5427                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5428                 else
5429                         planginfo[i].lanacl = pg_strdup("{=U}");
5430                 if (i_lanowner >= 0)
5431                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5432                 else
5433                         planginfo[i].lanowner = pg_strdup("");
5434
5435                 if (fout->remoteVersion < 70300)
5436                 {
5437                         /*
5438                          * We need to make a dependency to ensure the function will be
5439                          * dumped first.  (In 7.3 and later the regular dependency
5440                          * mechanism will handle this for us.)
5441                          */
5442                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5443
5444                         if (funcInfo)
5445                                 addObjectDependency(&planginfo[i].dobj,
5446                                                                         funcInfo->dobj.dumpId);
5447                 }
5448         }
5449
5450         PQclear(res);
5451
5452         destroyPQExpBuffer(query);
5453
5454         return planginfo;
5455 }
5456
5457 /*
5458  * getCasts
5459  *        get basic information about every cast in the system
5460  *
5461  * numCasts is set to the number of casts read in
5462  */
5463 CastInfo *
5464 getCasts(Archive *fout, int *numCasts)
5465 {
5466         PGresult   *res;
5467         int                     ntups;
5468         int                     i;
5469         PQExpBuffer query = createPQExpBuffer();
5470         CastInfo   *castinfo;
5471         int                     i_tableoid;
5472         int                     i_oid;
5473         int                     i_castsource;
5474         int                     i_casttarget;
5475         int                     i_castfunc;
5476         int                     i_castcontext;
5477         int                     i_castmethod;
5478
5479         /* Make sure we are in proper schema */
5480         selectSourceSchema(fout, "pg_catalog");
5481
5482         if (fout->remoteVersion >= 80400)
5483         {
5484                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5485                                                   "castsource, casttarget, castfunc, castcontext, "
5486                                                   "castmethod "
5487                                                   "FROM pg_cast ORDER BY 3,4");
5488         }
5489         else if (fout->remoteVersion >= 70300)
5490         {
5491                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5492                                                   "castsource, casttarget, castfunc, castcontext, "
5493                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5494                                                   "FROM pg_cast ORDER BY 3,4");
5495         }
5496         else
5497         {
5498                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5499                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5500                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5501                                                   "'f' AS castmethod "
5502                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5503                                                   "WHERE p.pronargs = 1 AND "
5504                                                   "p.proargtypes[0] = t1.oid AND "
5505                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5506                                                   "ORDER BY 3,4");
5507         }
5508
5509         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5510
5511         ntups = PQntuples(res);
5512
5513         *numCasts = ntups;
5514
5515         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5516
5517         i_tableoid = PQfnumber(res, "tableoid");
5518         i_oid = PQfnumber(res, "oid");
5519         i_castsource = PQfnumber(res, "castsource");
5520         i_casttarget = PQfnumber(res, "casttarget");
5521         i_castfunc = PQfnumber(res, "castfunc");
5522         i_castcontext = PQfnumber(res, "castcontext");
5523         i_castmethod = PQfnumber(res, "castmethod");
5524
5525         for (i = 0; i < ntups; i++)
5526         {
5527                 PQExpBufferData namebuf;
5528                 TypeInfo   *sTypeInfo;
5529                 TypeInfo   *tTypeInfo;
5530
5531                 castinfo[i].dobj.objType = DO_CAST;
5532                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5533                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5534                 AssignDumpId(&castinfo[i].dobj);
5535                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5536                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5537                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5538                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5539                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5540
5541                 /*
5542                  * Try to name cast as concatenation of typnames.  This is only used
5543                  * for purposes of sorting.  If we fail to find either type, the name
5544                  * will be an empty string.
5545                  */
5546                 initPQExpBuffer(&namebuf);
5547                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5548                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5549                 if (sTypeInfo && tTypeInfo)
5550                         appendPQExpBuffer(&namebuf, "%s %s",
5551                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5552                 castinfo[i].dobj.name = namebuf.data;
5553
5554                 if (OidIsValid(castinfo[i].castfunc))
5555                 {
5556                         /*
5557                          * We need to make a dependency to ensure the function will be
5558                          * dumped first.  (In 7.3 and later the regular dependency
5559                          * mechanism will handle this for us.)
5560                          */
5561                         FuncInfo   *funcInfo;
5562
5563                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5564                         if (funcInfo)
5565                                 addObjectDependency(&castinfo[i].dobj,
5566                                                                         funcInfo->dobj.dumpId);
5567                 }
5568         }
5569
5570         PQclear(res);
5571
5572         destroyPQExpBuffer(query);
5573
5574         return castinfo;
5575 }
5576
5577 /*
5578  * getTableAttrs -
5579  *        for each interesting table, read info about its attributes
5580  *        (names, types, default values, CHECK constraints, etc)
5581  *
5582  * This is implemented in a very inefficient way right now, looping
5583  * through the tblinfo and doing a join per table to find the attrs and their
5584  * types.  However, because we want type names and so forth to be named
5585  * relative to the schema of each table, we couldn't do it in just one
5586  * query.  (Maybe one query per schema?)
5587  *
5588  *      modifies tblinfo
5589  */
5590 void
5591 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5592 {
5593         int                     i,
5594                                 j;
5595         PQExpBuffer q = createPQExpBuffer();
5596         int                     i_attnum;
5597         int                     i_attname;
5598         int                     i_atttypname;
5599         int                     i_atttypmod;
5600         int                     i_attstattarget;
5601         int                     i_attstorage;
5602         int                     i_typstorage;
5603         int                     i_attnotnull;
5604         int                     i_atthasdef;
5605         int                     i_attisdropped;
5606         int                     i_attlen;
5607         int                     i_attalign;
5608         int                     i_attislocal;
5609         int                     i_attoptions;
5610         int                     i_attcollation;
5611         int                     i_attfdwoptions;
5612         PGresult   *res;
5613         int                     ntups;
5614         bool            hasdefaults;
5615
5616         for (i = 0; i < numTables; i++)
5617         {
5618                 TableInfo  *tbinfo = &tblinfo[i];
5619
5620                 /* Don't bother to collect info for sequences */
5621                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5622                         continue;
5623
5624                 /* Don't bother with uninteresting tables, either */
5625                 if (!tbinfo->interesting)
5626                         continue;
5627
5628                 /*
5629                  * Make sure we are in proper schema for this table; this allows
5630                  * correct retrieval of formatted type names and default exprs
5631                  */
5632                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5633
5634                 /* find all the user attributes and their types */
5635
5636                 /*
5637                  * we must read the attribute names in attribute number order! because
5638                  * we will use the attnum to index into the attnames array later.  We
5639                  * actually ask to order by "attrelid, attnum" because (at least up to
5640                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5641                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5642                  */
5643                 if (g_verbose)
5644                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5645                                           tbinfo->dobj.name);
5646
5647                 resetPQExpBuffer(q);
5648
5649                 if (fout->remoteVersion >= 90200)
5650                 {
5651                         /*
5652                          * attfdwoptions is new in 9.2.
5653                          */
5654                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5655                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5656                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5657                                                           "a.attlen, a.attalign, a.attislocal, "
5658                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5659                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5660                                                           "CASE WHEN a.attcollation <> t.typcollation "
5661                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5662                                                           "pg_catalog.array_to_string(ARRAY("
5663                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5664                                                           "' ' || pg_catalog.quote_literal(option_value) "
5665                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5666                                                           "ORDER BY option_name"
5667                                                           "), E',\n    ') AS attfdwoptions "
5668                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5669                                                           "ON a.atttypid = t.oid "
5670                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5671                                                           "AND a.attnum > 0::pg_catalog.int2 "
5672                                                           "ORDER BY a.attrelid, a.attnum",
5673                                                           tbinfo->dobj.catId.oid);
5674                 }
5675                 else if (fout->remoteVersion >= 90100)
5676                 {
5677                         /*
5678                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5679                          * clauses for attributes whose collation is different from their
5680                          * type's default, we use a CASE here to suppress uninteresting
5681                          * attcollations cheaply.
5682                          */
5683                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5684                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5685                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5686                                                           "a.attlen, a.attalign, a.attislocal, "
5687                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5688                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5689                                                           "CASE WHEN a.attcollation <> t.typcollation "
5690                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5691                                                           "NULL AS attfdwoptions "
5692                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5693                                                           "ON a.atttypid = t.oid "
5694                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5695                                                           "AND a.attnum > 0::pg_catalog.int2 "
5696                                                           "ORDER BY a.attrelid, a.attnum",
5697                                                           tbinfo->dobj.catId.oid);
5698                 }
5699                 else if (fout->remoteVersion >= 90000)
5700                 {
5701                         /* attoptions is new in 9.0 */
5702                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5703                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5704                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5705                                                           "a.attlen, a.attalign, a.attislocal, "
5706                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5707                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5708                                                           "0 AS attcollation, "
5709                                                           "NULL AS attfdwoptions "
5710                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5711                                                           "ON a.atttypid = t.oid "
5712                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5713                                                           "AND a.attnum > 0::pg_catalog.int2 "
5714                                                           "ORDER BY a.attrelid, a.attnum",
5715                                                           tbinfo->dobj.catId.oid);
5716                 }
5717                 else if (fout->remoteVersion >= 70300)
5718                 {
5719                         /* need left join here to not fail on dropped columns ... */
5720                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5721                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5722                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5723                                                           "a.attlen, a.attalign, a.attislocal, "
5724                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5725                                                           "'' AS attoptions, 0 AS attcollation, "
5726                                                           "NULL AS attfdwoptions "
5727                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5728                                                           "ON a.atttypid = t.oid "
5729                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5730                                                           "AND a.attnum > 0::pg_catalog.int2 "
5731                                                           "ORDER BY a.attrelid, a.attnum",
5732                                                           tbinfo->dobj.catId.oid);
5733                 }
5734                 else if (fout->remoteVersion >= 70100)
5735                 {
5736                         /*
5737                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5738                          * we don't dump it because we can't tell whether it's been
5739                          * explicitly set or was just a default.
5740                          *
5741                          * attislocal doesn't exist before 7.3, either; in older databases
5742                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5743                          */
5744                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5745                                                           "-1 AS attstattarget, a.attstorage, "
5746                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5747                                                           "false AS attisdropped, a.attlen, "
5748                                                           "a.attalign, true AS attislocal, "
5749                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5750                                                           "'' AS attoptions, 0 AS attcollation, "
5751                                                           "NULL AS attfdwoptions "
5752                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5753                                                           "ON a.atttypid = t.oid "
5754                                                           "WHERE a.attrelid = '%u'::oid "
5755                                                           "AND a.attnum > 0::int2 "
5756                                                           "ORDER BY a.attrelid, a.attnum",
5757                                                           tbinfo->dobj.catId.oid);
5758                 }
5759                 else
5760                 {
5761                         /* format_type not available before 7.1 */
5762                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5763                                                           "-1 AS attstattarget, "
5764                                                           "attstorage, attstorage AS typstorage, "
5765                                                           "attnotnull, atthasdef, false AS attisdropped, "
5766                                                           "attlen, attalign, "
5767                                                           "true AS attislocal, "
5768                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5769                                                           "'' AS attoptions, 0 AS attcollation, "
5770                                                           "NULL AS attfdwoptions "
5771                                                           "FROM pg_attribute a "
5772                                                           "WHERE attrelid = '%u'::oid "
5773                                                           "AND attnum > 0::int2 "
5774                                                           "ORDER BY attrelid, attnum",
5775                                                           tbinfo->dobj.catId.oid);
5776                 }
5777
5778                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5779
5780                 ntups = PQntuples(res);
5781
5782                 i_attnum = PQfnumber(res, "attnum");
5783                 i_attname = PQfnumber(res, "attname");
5784                 i_atttypname = PQfnumber(res, "atttypname");
5785                 i_atttypmod = PQfnumber(res, "atttypmod");
5786                 i_attstattarget = PQfnumber(res, "attstattarget");
5787                 i_attstorage = PQfnumber(res, "attstorage");
5788                 i_typstorage = PQfnumber(res, "typstorage");
5789                 i_attnotnull = PQfnumber(res, "attnotnull");
5790                 i_atthasdef = PQfnumber(res, "atthasdef");
5791                 i_attisdropped = PQfnumber(res, "attisdropped");
5792                 i_attlen = PQfnumber(res, "attlen");
5793                 i_attalign = PQfnumber(res, "attalign");
5794                 i_attislocal = PQfnumber(res, "attislocal");
5795                 i_attoptions = PQfnumber(res, "attoptions");
5796                 i_attcollation = PQfnumber(res, "attcollation");
5797                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5798
5799                 tbinfo->numatts = ntups;
5800                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5801                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5802                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5803                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5804                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5805                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5806                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5807                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5808                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5809                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5810                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5811                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5812                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5813                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5814                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5815                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5816                 hasdefaults = false;
5817
5818                 for (j = 0; j < ntups; j++)
5819                 {
5820                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5821                                 exit_horribly(NULL,
5822                                                           "invalid column numbering in table \"%s\"\n",
5823                                                           tbinfo->dobj.name);
5824                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5825                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5826                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5827                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5828                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5829                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5830                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5831                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5832                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5833                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5834                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5835                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5836                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5837                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5838                         tbinfo->attrdefs[j] = NULL; /* fix below */
5839                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5840                                 hasdefaults = true;
5841                         /* these flags will be set in flagInhAttrs() */
5842                         tbinfo->inhNotNull[j] = false;
5843                 }
5844
5845                 PQclear(res);
5846
5847                 /*
5848                  * Get info about column defaults
5849                  */
5850                 if (hasdefaults)
5851                 {
5852                         AttrDefInfo *attrdefs;
5853                         int                     numDefaults;
5854
5855                         if (g_verbose)
5856                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5857                                                   tbinfo->dobj.name);
5858
5859                         resetPQExpBuffer(q);
5860                         if (fout->remoteVersion >= 70300)
5861                         {
5862                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5863                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5864                                                                   "FROM pg_catalog.pg_attrdef "
5865                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5866                                                                   tbinfo->dobj.catId.oid);
5867                         }
5868                         else if (fout->remoteVersion >= 70200)
5869                         {
5870                                 /* 7.2 did not have OIDs in pg_attrdef */
5871                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5872                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5873                                                                   "FROM pg_attrdef "
5874                                                                   "WHERE adrelid = '%u'::oid",
5875                                                                   tbinfo->dobj.catId.oid);
5876                         }
5877                         else if (fout->remoteVersion >= 70100)
5878                         {
5879                                 /* no pg_get_expr, so must rely on adsrc */
5880                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5881                                                                   "FROM pg_attrdef "
5882                                                                   "WHERE adrelid = '%u'::oid",
5883                                                                   tbinfo->dobj.catId.oid);
5884                         }
5885                         else
5886                         {
5887                                 /* no pg_get_expr, no tableoid either */
5888                                 appendPQExpBuffer(q, "SELECT "
5889                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5890                                                                   "oid, adnum, adsrc "
5891                                                                   "FROM pg_attrdef "
5892                                                                   "WHERE adrelid = '%u'::oid",
5893                                                                   tbinfo->dobj.catId.oid);
5894                         }
5895                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5896
5897                         numDefaults = PQntuples(res);
5898                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5899
5900                         for (j = 0; j < numDefaults; j++)
5901                         {
5902                                 int                     adnum;
5903
5904                                 adnum = atoi(PQgetvalue(res, j, 2));
5905
5906                                 if (adnum <= 0 || adnum > ntups)
5907                                         exit_horribly(NULL,
5908                                                                   "invalid adnum value %d for table \"%s\"\n",
5909                                                                   adnum, tbinfo->dobj.name);
5910
5911                                 /*
5912                                  * dropped columns shouldn't have defaults, but just in case,
5913                                  * ignore 'em
5914                                  */
5915                                 if (tbinfo->attisdropped[adnum - 1])
5916                                         continue;
5917
5918                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
5919                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5920                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5921                                 AssignDumpId(&attrdefs[j].dobj);
5922                                 attrdefs[j].adtable = tbinfo;
5923                                 attrdefs[j].adnum = adnum;
5924                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5925
5926                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5927                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5928
5929                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5930
5931                                 /*
5932                                  * Defaults on a VIEW must always be dumped as separate ALTER
5933                                  * TABLE commands.      Defaults on regular tables are dumped as
5934                                  * part of the CREATE TABLE if possible, which it won't be if
5935                                  * the column is not going to be emitted explicitly.
5936                                  */
5937                                 if (tbinfo->relkind == RELKIND_VIEW)
5938                                 {
5939                                         attrdefs[j].separate = true;
5940                                         /* needed in case pre-7.3 DB: */
5941                                         addObjectDependency(&attrdefs[j].dobj,
5942                                                                                 tbinfo->dobj.dumpId);
5943                                 }
5944                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5945                                 {
5946                                         /* column will be suppressed, print default separately */
5947                                         attrdefs[j].separate = true;
5948                                         /* needed in case pre-7.3 DB: */
5949                                         addObjectDependency(&attrdefs[j].dobj,
5950                                                                                 tbinfo->dobj.dumpId);
5951                                 }
5952                                 else
5953                                 {
5954                                         attrdefs[j].separate = false;
5955
5956                                         /*
5957                                          * Mark the default as needing to appear before the table,
5958                                          * so that any dependencies it has must be emitted before
5959                                          * the CREATE TABLE.  If this is not possible, we'll
5960                                          * change to "separate" mode while sorting dependencies.
5961                                          */
5962                                         addObjectDependency(&tbinfo->dobj,
5963                                                                                 attrdefs[j].dobj.dumpId);
5964                                 }
5965
5966                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5967                         }
5968                         PQclear(res);
5969                 }
5970
5971                 /*
5972                  * Get info about table CHECK constraints
5973                  */
5974                 if (tbinfo->ncheck > 0)
5975                 {
5976                         ConstraintInfo *constrs;
5977                         int                     numConstrs;
5978
5979                         if (g_verbose)
5980                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5981                                                   tbinfo->dobj.name);
5982
5983                         resetPQExpBuffer(q);
5984                         if (fout->remoteVersion >= 90200)
5985                         {
5986                                 /*
5987                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
5988                                  * but it wasn't ever false for check constraints until 9.2).
5989                                  */
5990                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5991                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5992                                                                   "conislocal, convalidated "
5993                                                                   "FROM pg_catalog.pg_constraint "
5994                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5995                                                                   "   AND contype = 'c' "
5996                                                                   "ORDER BY conname",
5997                                                                   tbinfo->dobj.catId.oid);
5998                         }
5999                         else if (fout->remoteVersion >= 80400)
6000                         {
6001                                 /* conislocal is new in 8.4 */
6002                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6003                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6004                                                                   "conislocal, true AS convalidated "
6005                                                                   "FROM pg_catalog.pg_constraint "
6006                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6007                                                                   "   AND contype = 'c' "
6008                                                                   "ORDER BY conname",
6009                                                                   tbinfo->dobj.catId.oid);
6010                         }
6011                         else if (fout->remoteVersion >= 70400)
6012                         {
6013                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6014                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6015                                                                   "true AS conislocal, true AS convalidated "
6016                                                                   "FROM pg_catalog.pg_constraint "
6017                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6018                                                                   "   AND contype = 'c' "
6019                                                                   "ORDER BY conname",
6020                                                                   tbinfo->dobj.catId.oid);
6021                         }
6022                         else if (fout->remoteVersion >= 70300)
6023                         {
6024                                 /* no pg_get_constraintdef, must use consrc */
6025                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6026                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6027                                                                   "true AS conislocal, true AS convalidated "
6028                                                                   "FROM pg_catalog.pg_constraint "
6029                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6030                                                                   "   AND contype = 'c' "
6031                                                                   "ORDER BY conname",
6032                                                                   tbinfo->dobj.catId.oid);
6033                         }
6034                         else if (fout->remoteVersion >= 70200)
6035                         {
6036                                 /* 7.2 did not have OIDs in pg_relcheck */
6037                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6038                                                                   "rcname AS conname, "
6039                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6040                                                                   "true AS conislocal, true AS convalidated "
6041                                                                   "FROM pg_relcheck "
6042                                                                   "WHERE rcrelid = '%u'::oid "
6043                                                                   "ORDER BY rcname",
6044                                                                   tbinfo->dobj.catId.oid);
6045                         }
6046                         else if (fout->remoteVersion >= 70100)
6047                         {
6048                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6049                                                                   "rcname AS conname, "
6050                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6051                                                                   "true AS conislocal, true AS convalidated "
6052                                                                   "FROM pg_relcheck "
6053                                                                   "WHERE rcrelid = '%u'::oid "
6054                                                                   "ORDER BY rcname",
6055                                                                   tbinfo->dobj.catId.oid);
6056                         }
6057                         else
6058                         {
6059                                 /* no tableoid in 7.0 */
6060                                 appendPQExpBuffer(q, "SELECT "
6061                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6062                                                                   "oid, rcname AS conname, "
6063                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6064                                                                   "true AS conislocal, true AS convalidated "
6065                                                                   "FROM pg_relcheck "
6066                                                                   "WHERE rcrelid = '%u'::oid "
6067                                                                   "ORDER BY rcname",
6068                                                                   tbinfo->dobj.catId.oid);
6069                         }
6070                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6071
6072                         numConstrs = PQntuples(res);
6073                         if (numConstrs != tbinfo->ncheck)
6074                         {
6075                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6076                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6077                                                                                  tbinfo->ncheck),
6078                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6079                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6080                                 exit_nicely(1);
6081                         }
6082
6083                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6084                         tbinfo->checkexprs = constrs;
6085
6086                         for (j = 0; j < numConstrs; j++)
6087                         {
6088                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6089
6090                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6091                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6092                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6093                                 AssignDumpId(&constrs[j].dobj);
6094                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6095                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6096                                 constrs[j].contable = tbinfo;
6097                                 constrs[j].condomain = NULL;
6098                                 constrs[j].contype = 'c';
6099                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6100                                 constrs[j].confrelid = InvalidOid;
6101                                 constrs[j].conindex = 0;
6102                                 constrs[j].condeferrable = false;
6103                                 constrs[j].condeferred = false;
6104                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6105
6106                                 /*
6107                                  * An unvalidated constraint needs to be dumped separately, so
6108                                  * that potentially-violating existing data is loaded before
6109                                  * the constraint.
6110                                  */
6111                                 constrs[j].separate = !validated;
6112
6113                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6114
6115                                 /*
6116                                  * Mark the constraint as needing to appear before the table
6117                                  * --- this is so that any other dependencies of the
6118                                  * constraint will be emitted before we try to create the
6119                                  * table.  If the constraint is to be dumped separately, it
6120                                  * will be dumped after data is loaded anyway, so don't do it.
6121                                  * (There's an automatic dependency in the opposite direction
6122                                  * anyway, so don't need to add one manually here.)
6123                                  */
6124                                 if (!constrs[j].separate)
6125                                         addObjectDependency(&tbinfo->dobj,
6126                                                                                 constrs[j].dobj.dumpId);
6127
6128                                 /*
6129                                  * If the constraint is inherited, this will be detected later
6130                                  * (in pre-8.4 databases).      We also detect later if the
6131                                  * constraint must be split out from the table definition.
6132                                  */
6133                         }
6134                         PQclear(res);
6135                 }
6136         }
6137
6138         destroyPQExpBuffer(q);
6139 }
6140
6141 /*
6142  * Test whether a column should be printed as part of table's CREATE TABLE.
6143  * Column number is zero-based.
6144  *
6145  * Normally this is always true, but it's false for dropped columns, as well
6146  * as those that were inherited without any local definition.  (If we print
6147  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6148  * However, in binary_upgrade mode, we must print all such columns anyway and
6149  * fix the attislocal/attisdropped state later, so as to keep control of the
6150  * physical column order.
6151  *
6152  * This function exists because there are scattered nonobvious places that
6153  * must be kept in sync with this decision.
6154  */
6155 bool
6156 shouldPrintColumn(TableInfo *tbinfo, int colno)
6157 {
6158         if (binary_upgrade)
6159                 return true;
6160         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6161 }
6162
6163
6164 /*
6165  * getTSParsers:
6166  *        read all text search parsers in the system catalogs and return them
6167  *        in the TSParserInfo* structure
6168  *
6169  *      numTSParsers is set to the number of parsers read in
6170  */
6171 TSParserInfo *
6172 getTSParsers(Archive *fout, int *numTSParsers)
6173 {
6174         PGresult   *res;
6175         int                     ntups;
6176         int                     i;
6177         PQExpBuffer query;
6178         TSParserInfo *prsinfo;
6179         int                     i_tableoid;
6180         int                     i_oid;
6181         int                     i_prsname;
6182         int                     i_prsnamespace;
6183         int                     i_prsstart;
6184         int                     i_prstoken;
6185         int                     i_prsend;
6186         int                     i_prsheadline;
6187         int                     i_prslextype;
6188
6189         /* Before 8.3, there is no built-in text search support */
6190         if (fout->remoteVersion < 80300)
6191         {
6192                 *numTSParsers = 0;
6193                 return NULL;
6194         }
6195
6196         query = createPQExpBuffer();
6197
6198         /*
6199          * find all text search objects, including builtin ones; we filter out
6200          * system-defined objects at dump-out time.
6201          */
6202
6203         /* Make sure we are in proper schema */
6204         selectSourceSchema(fout, "pg_catalog");
6205
6206         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6207                                           "prsstart::oid, prstoken::oid, "
6208                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6209                                           "FROM pg_ts_parser");
6210
6211         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6212
6213         ntups = PQntuples(res);
6214         *numTSParsers = ntups;
6215
6216         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6217
6218         i_tableoid = PQfnumber(res, "tableoid");
6219         i_oid = PQfnumber(res, "oid");
6220         i_prsname = PQfnumber(res, "prsname");
6221         i_prsnamespace = PQfnumber(res, "prsnamespace");
6222         i_prsstart = PQfnumber(res, "prsstart");
6223         i_prstoken = PQfnumber(res, "prstoken");
6224         i_prsend = PQfnumber(res, "prsend");
6225         i_prsheadline = PQfnumber(res, "prsheadline");
6226         i_prslextype = PQfnumber(res, "prslextype");
6227
6228         for (i = 0; i < ntups; i++)
6229         {
6230                 prsinfo[i].dobj.objType = DO_TSPARSER;
6231                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6232                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6233                 AssignDumpId(&prsinfo[i].dobj);
6234                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6235                 prsinfo[i].dobj.namespace =
6236                         findNamespace(fout,
6237                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6238                                                   prsinfo[i].dobj.catId.oid);
6239                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6240                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6241                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6242                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6243                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6244
6245                 /* Decide whether we want to dump it */
6246                 selectDumpableObject(&(prsinfo[i].dobj));
6247         }
6248
6249         PQclear(res);
6250
6251         destroyPQExpBuffer(query);
6252
6253         return prsinfo;
6254 }
6255
6256 /*
6257  * getTSDictionaries:
6258  *        read all text search dictionaries in the system catalogs and return them
6259  *        in the TSDictInfo* structure
6260  *
6261  *      numTSDicts is set to the number of dictionaries read in
6262  */
6263 TSDictInfo *
6264 getTSDictionaries(Archive *fout, int *numTSDicts)
6265 {
6266         PGresult   *res;
6267         int                     ntups;
6268         int                     i;
6269         PQExpBuffer query;
6270         TSDictInfo *dictinfo;
6271         int                     i_tableoid;
6272         int                     i_oid;
6273         int                     i_dictname;
6274         int                     i_dictnamespace;
6275         int                     i_rolname;
6276         int                     i_dicttemplate;
6277         int                     i_dictinitoption;
6278
6279         /* Before 8.3, there is no built-in text search support */
6280         if (fout->remoteVersion < 80300)
6281         {
6282                 *numTSDicts = 0;
6283                 return NULL;
6284         }
6285
6286         query = createPQExpBuffer();
6287
6288         /* Make sure we are in proper schema */
6289         selectSourceSchema(fout, "pg_catalog");
6290
6291         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6292                                           "dictnamespace, (%s dictowner) AS rolname, "
6293                                           "dicttemplate, dictinitoption "
6294                                           "FROM pg_ts_dict",
6295                                           username_subquery);
6296
6297         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6298
6299         ntups = PQntuples(res);
6300         *numTSDicts = ntups;
6301
6302         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6303
6304         i_tableoid = PQfnumber(res, "tableoid");
6305         i_oid = PQfnumber(res, "oid");
6306         i_dictname = PQfnumber(res, "dictname");
6307         i_dictnamespace = PQfnumber(res, "dictnamespace");
6308         i_rolname = PQfnumber(res, "rolname");
6309         i_dictinitoption = PQfnumber(res, "dictinitoption");
6310         i_dicttemplate = PQfnumber(res, "dicttemplate");
6311
6312         for (i = 0; i < ntups; i++)
6313         {
6314                 dictinfo[i].dobj.objType = DO_TSDICT;
6315                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6316                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6317                 AssignDumpId(&dictinfo[i].dobj);
6318                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6319                 dictinfo[i].dobj.namespace =
6320                         findNamespace(fout,
6321                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6322                                                   dictinfo[i].dobj.catId.oid);
6323                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6324                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6325                 if (PQgetisnull(res, i, i_dictinitoption))
6326                         dictinfo[i].dictinitoption = NULL;
6327                 else
6328                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6329
6330                 /* Decide whether we want to dump it */
6331                 selectDumpableObject(&(dictinfo[i].dobj));
6332         }
6333
6334         PQclear(res);
6335
6336         destroyPQExpBuffer(query);
6337
6338         return dictinfo;
6339 }
6340
6341 /*
6342  * getTSTemplates:
6343  *        read all text search templates in the system catalogs and return them
6344  *        in the TSTemplateInfo* structure
6345  *
6346  *      numTSTemplates is set to the number of templates read in
6347  */
6348 TSTemplateInfo *
6349 getTSTemplates(Archive *fout, int *numTSTemplates)
6350 {
6351         PGresult   *res;
6352         int                     ntups;
6353         int                     i;
6354         PQExpBuffer query;
6355         TSTemplateInfo *tmplinfo;
6356         int                     i_tableoid;
6357         int                     i_oid;
6358         int                     i_tmplname;
6359         int                     i_tmplnamespace;
6360         int                     i_tmplinit;
6361         int                     i_tmpllexize;
6362
6363         /* Before 8.3, there is no built-in text search support */
6364         if (fout->remoteVersion < 80300)
6365         {
6366                 *numTSTemplates = 0;
6367                 return NULL;
6368         }
6369
6370         query = createPQExpBuffer();
6371
6372         /* Make sure we are in proper schema */
6373         selectSourceSchema(fout, "pg_catalog");
6374
6375         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6376                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6377                                           "FROM pg_ts_template");
6378
6379         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6380
6381         ntups = PQntuples(res);
6382         *numTSTemplates = ntups;
6383
6384         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6385
6386         i_tableoid = PQfnumber(res, "tableoid");
6387         i_oid = PQfnumber(res, "oid");
6388         i_tmplname = PQfnumber(res, "tmplname");
6389         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6390         i_tmplinit = PQfnumber(res, "tmplinit");
6391         i_tmpllexize = PQfnumber(res, "tmpllexize");
6392
6393         for (i = 0; i < ntups; i++)
6394         {
6395                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6396                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6397                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6398                 AssignDumpId(&tmplinfo[i].dobj);
6399                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6400                 tmplinfo[i].dobj.namespace =
6401                         findNamespace(fout,
6402                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6403                                                   tmplinfo[i].dobj.catId.oid);
6404                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6405                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6406
6407                 /* Decide whether we want to dump it */
6408                 selectDumpableObject(&(tmplinfo[i].dobj));
6409         }
6410
6411         PQclear(res);
6412
6413         destroyPQExpBuffer(query);
6414
6415         return tmplinfo;
6416 }
6417
6418 /*
6419  * getTSConfigurations:
6420  *        read all text search configurations in the system catalogs and return
6421  *        them in the TSConfigInfo* structure
6422  *
6423  *      numTSConfigs is set to the number of configurations read in
6424  */
6425 TSConfigInfo *
6426 getTSConfigurations(Archive *fout, int *numTSConfigs)
6427 {
6428         PGresult   *res;
6429         int                     ntups;
6430         int                     i;
6431         PQExpBuffer query;
6432         TSConfigInfo *cfginfo;
6433         int                     i_tableoid;
6434         int                     i_oid;
6435         int                     i_cfgname;
6436         int                     i_cfgnamespace;
6437         int                     i_rolname;
6438         int                     i_cfgparser;
6439
6440         /* Before 8.3, there is no built-in text search support */
6441         if (fout->remoteVersion < 80300)
6442         {
6443                 *numTSConfigs = 0;
6444                 return NULL;
6445         }
6446
6447         query = createPQExpBuffer();
6448
6449         /* Make sure we are in proper schema */
6450         selectSourceSchema(fout, "pg_catalog");
6451
6452         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6453                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6454                                           "FROM pg_ts_config",
6455                                           username_subquery);
6456
6457         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6458
6459         ntups = PQntuples(res);
6460         *numTSConfigs = ntups;
6461
6462         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6463
6464         i_tableoid = PQfnumber(res, "tableoid");
6465         i_oid = PQfnumber(res, "oid");
6466         i_cfgname = PQfnumber(res, "cfgname");
6467         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6468         i_rolname = PQfnumber(res, "rolname");
6469         i_cfgparser = PQfnumber(res, "cfgparser");
6470
6471         for (i = 0; i < ntups; i++)
6472         {
6473                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6474                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6475                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6476                 AssignDumpId(&cfginfo[i].dobj);
6477                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6478                 cfginfo[i].dobj.namespace =
6479                         findNamespace(fout,
6480                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6481                                                   cfginfo[i].dobj.catId.oid);
6482                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6483                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6484
6485                 /* Decide whether we want to dump it */
6486                 selectDumpableObject(&(cfginfo[i].dobj));
6487         }
6488
6489         PQclear(res);
6490
6491         destroyPQExpBuffer(query);
6492
6493         return cfginfo;
6494 }
6495
6496 /*
6497  * getForeignDataWrappers:
6498  *        read all foreign-data wrappers in the system catalogs and return
6499  *        them in the FdwInfo* structure
6500  *
6501  *      numForeignDataWrappers is set to the number of fdws read in
6502  */
6503 FdwInfo *
6504 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6505 {
6506         PGresult   *res;
6507         int                     ntups;
6508         int                     i;
6509         PQExpBuffer query = createPQExpBuffer();
6510         FdwInfo    *fdwinfo;
6511         int                     i_tableoid;
6512         int                     i_oid;
6513         int                     i_fdwname;
6514         int                     i_rolname;
6515         int                     i_fdwhandler;
6516         int                     i_fdwvalidator;
6517         int                     i_fdwacl;
6518         int                     i_fdwoptions;
6519
6520         /* Before 8.4, there are no foreign-data wrappers */
6521         if (fout->remoteVersion < 80400)
6522         {
6523                 *numForeignDataWrappers = 0;
6524                 return NULL;
6525         }
6526
6527         /* Make sure we are in proper schema */
6528         selectSourceSchema(fout, "pg_catalog");
6529
6530         if (fout->remoteVersion >= 90100)
6531         {
6532                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6533                                                   "(%s fdwowner) AS rolname, "
6534                                                   "fdwhandler::pg_catalog.regproc, "
6535                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6536                                                   "array_to_string(ARRAY("
6537                                                   "SELECT quote_ident(option_name) || ' ' || "
6538                                                   "quote_literal(option_value) "
6539                                                   "FROM pg_options_to_table(fdwoptions) "
6540                                                   "ORDER BY option_name"
6541                                                   "), E',\n    ') AS fdwoptions "
6542                                                   "FROM pg_foreign_data_wrapper",
6543                                                   username_subquery);
6544         }
6545         else
6546         {
6547                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6548                                                   "(%s fdwowner) AS rolname, "
6549                                                   "'-' AS fdwhandler, "
6550                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6551                                                   "array_to_string(ARRAY("
6552                                                   "SELECT quote_ident(option_name) || ' ' || "
6553                                                   "quote_literal(option_value) "
6554                                                   "FROM pg_options_to_table(fdwoptions) "
6555                                                   "ORDER BY option_name"
6556                                                   "), E',\n    ') AS fdwoptions "
6557                                                   "FROM pg_foreign_data_wrapper",
6558                                                   username_subquery);
6559         }
6560
6561         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6562
6563         ntups = PQntuples(res);
6564         *numForeignDataWrappers = ntups;
6565
6566         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6567
6568         i_tableoid = PQfnumber(res, "tableoid");
6569         i_oid = PQfnumber(res, "oid");
6570         i_fdwname = PQfnumber(res, "fdwname");
6571         i_rolname = PQfnumber(res, "rolname");
6572         i_fdwhandler = PQfnumber(res, "fdwhandler");
6573         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6574         i_fdwacl = PQfnumber(res, "fdwacl");
6575         i_fdwoptions = PQfnumber(res, "fdwoptions");
6576
6577         for (i = 0; i < ntups; i++)
6578         {
6579                 fdwinfo[i].dobj.objType = DO_FDW;
6580                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6581                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6582                 AssignDumpId(&fdwinfo[i].dobj);
6583                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6584                 fdwinfo[i].dobj.namespace = NULL;
6585                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6586                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6587                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6588                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6589                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6590
6591                 /* Decide whether we want to dump it */
6592                 selectDumpableObject(&(fdwinfo[i].dobj));
6593         }
6594
6595         PQclear(res);
6596
6597         destroyPQExpBuffer(query);
6598
6599         return fdwinfo;
6600 }
6601
6602 /*
6603  * getForeignServers:
6604  *        read all foreign servers in the system catalogs and return
6605  *        them in the ForeignServerInfo * structure
6606  *
6607  *      numForeignServers is set to the number of servers read in
6608  */
6609 ForeignServerInfo *
6610 getForeignServers(Archive *fout, int *numForeignServers)
6611 {
6612         PGresult   *res;
6613         int                     ntups;
6614         int                     i;
6615         PQExpBuffer query = createPQExpBuffer();
6616         ForeignServerInfo *srvinfo;
6617         int                     i_tableoid;
6618         int                     i_oid;
6619         int                     i_srvname;
6620         int                     i_rolname;
6621         int                     i_srvfdw;
6622         int                     i_srvtype;
6623         int                     i_srvversion;
6624         int                     i_srvacl;
6625         int                     i_srvoptions;
6626
6627         /* Before 8.4, there are no foreign servers */
6628         if (fout->remoteVersion < 80400)
6629         {
6630                 *numForeignServers = 0;
6631                 return NULL;
6632         }
6633
6634         /* Make sure we are in proper schema */
6635         selectSourceSchema(fout, "pg_catalog");
6636
6637         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6638                                           "(%s srvowner) AS rolname, "
6639                                           "srvfdw, srvtype, srvversion, srvacl,"
6640                                           "array_to_string(ARRAY("
6641                                           "SELECT quote_ident(option_name) || ' ' || "
6642                                           "quote_literal(option_value) "
6643                                           "FROM pg_options_to_table(srvoptions) "
6644                                           "ORDER BY option_name"
6645                                           "), E',\n    ') AS srvoptions "
6646                                           "FROM pg_foreign_server",
6647                                           username_subquery);
6648
6649         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6650
6651         ntups = PQntuples(res);
6652         *numForeignServers = ntups;
6653
6654         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6655
6656         i_tableoid = PQfnumber(res, "tableoid");
6657         i_oid = PQfnumber(res, "oid");
6658         i_srvname = PQfnumber(res, "srvname");
6659         i_rolname = PQfnumber(res, "rolname");
6660         i_srvfdw = PQfnumber(res, "srvfdw");
6661         i_srvtype = PQfnumber(res, "srvtype");
6662         i_srvversion = PQfnumber(res, "srvversion");
6663         i_srvacl = PQfnumber(res, "srvacl");
6664         i_srvoptions = PQfnumber(res, "srvoptions");
6665
6666         for (i = 0; i < ntups; i++)
6667         {
6668                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6669                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6670                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6671                 AssignDumpId(&srvinfo[i].dobj);
6672                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6673                 srvinfo[i].dobj.namespace = NULL;
6674                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6675                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6676                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6677                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6678                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6679                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6680
6681                 /* Decide whether we want to dump it */
6682                 selectDumpableObject(&(srvinfo[i].dobj));
6683         }
6684
6685         PQclear(res);
6686
6687         destroyPQExpBuffer(query);
6688
6689         return srvinfo;
6690 }
6691
6692 /*
6693  * getDefaultACLs:
6694  *        read all default ACL information in the system catalogs and return
6695  *        them in the DefaultACLInfo structure
6696  *
6697  *      numDefaultACLs is set to the number of ACLs read in
6698  */
6699 DefaultACLInfo *
6700 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6701 {
6702         DefaultACLInfo *daclinfo;
6703         PQExpBuffer query;
6704         PGresult   *res;
6705         int                     i_oid;
6706         int                     i_tableoid;
6707         int                     i_defaclrole;
6708         int                     i_defaclnamespace;
6709         int                     i_defaclobjtype;
6710         int                     i_defaclacl;
6711         int                     i,
6712                                 ntups;
6713
6714         if (fout->remoteVersion < 90000)
6715         {
6716                 *numDefaultACLs = 0;
6717                 return NULL;
6718         }
6719
6720         query = createPQExpBuffer();
6721
6722         /* Make sure we are in proper schema */
6723         selectSourceSchema(fout, "pg_catalog");
6724
6725         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6726                                           "(%s defaclrole) AS defaclrole, "
6727                                           "defaclnamespace, "
6728                                           "defaclobjtype, "
6729                                           "defaclacl "
6730                                           "FROM pg_default_acl",
6731                                           username_subquery);
6732
6733         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6734
6735         ntups = PQntuples(res);
6736         *numDefaultACLs = ntups;
6737
6738         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6739
6740         i_oid = PQfnumber(res, "oid");
6741         i_tableoid = PQfnumber(res, "tableoid");
6742         i_defaclrole = PQfnumber(res, "defaclrole");
6743         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6744         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6745         i_defaclacl = PQfnumber(res, "defaclacl");
6746
6747         for (i = 0; i < ntups; i++)
6748         {
6749                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6750
6751                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6752                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6753                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6754                 AssignDumpId(&daclinfo[i].dobj);
6755                 /* cheesy ... is it worth coming up with a better object name? */
6756                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6757
6758                 if (nspid != InvalidOid)
6759                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6760                                                                                                  daclinfo[i].dobj.catId.oid);
6761                 else
6762                         daclinfo[i].dobj.namespace = NULL;
6763
6764                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6765                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6766                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6767
6768                 /* Decide whether we want to dump it */
6769                 selectDumpableDefaultACL(&(daclinfo[i]));
6770         }
6771
6772         PQclear(res);
6773
6774         destroyPQExpBuffer(query);
6775
6776         return daclinfo;
6777 }
6778
6779 /*
6780  * dumpComment --
6781  *
6782  * This routine is used to dump any comments associated with the
6783  * object handed to this routine. The routine takes a constant character
6784  * string for the target part of the comment-creation command, plus
6785  * the namespace and owner of the object (for labeling the ArchiveEntry),
6786  * plus catalog ID and subid which are the lookup key for pg_description,
6787  * plus the dump ID for the object (for setting a dependency).
6788  * If a matching pg_description entry is found, it is dumped.
6789  *
6790  * Note: although this routine takes a dumpId for dependency purposes,
6791  * that purpose is just to mark the dependency in the emitted dump file
6792  * for possible future use by pg_restore.  We do NOT use it for determining
6793  * ordering of the comment in the dump file, because this routine is called
6794  * after dependency sorting occurs.  This routine should be called just after
6795  * calling ArchiveEntry() for the specified object.
6796  */
6797 static void
6798 dumpComment(Archive *fout, const char *target,
6799                         const char *namespace, const char *owner,
6800                         CatalogId catalogId, int subid, DumpId dumpId)
6801 {
6802         CommentItem *comments;
6803         int                     ncomments;
6804
6805         /* Comments are schema not data ... except blob comments are data */
6806         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6807         {
6808                 if (dataOnly)
6809                         return;
6810         }
6811         else
6812         {
6813                 if (schemaOnly)
6814                         return;
6815         }
6816
6817         /* Search for comments associated with catalogId, using table */
6818         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6819                                                          &comments);
6820
6821         /* Is there one matching the subid? */
6822         while (ncomments > 0)
6823         {
6824                 if (comments->objsubid == subid)
6825                         break;
6826                 comments++;
6827                 ncomments--;
6828         }
6829
6830         /* If a comment exists, build COMMENT ON statement */
6831         if (ncomments > 0)
6832         {
6833                 PQExpBuffer query = createPQExpBuffer();
6834
6835                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6836                 appendStringLiteralAH(query, comments->descr, fout);
6837                 appendPQExpBuffer(query, ";\n");
6838
6839                 /*
6840                  * We mark comments as SECTION_NONE because they really belong in the
6841                  * same section as their parent, whether that is pre-data or
6842                  * post-data.
6843                  */
6844                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6845                                          target, namespace, NULL, owner,
6846                                          false, "COMMENT", SECTION_NONE,
6847                                          query->data, "", NULL,
6848                                          &(dumpId), 1,
6849                                          NULL, NULL);
6850
6851                 destroyPQExpBuffer(query);
6852         }
6853 }
6854
6855 /*
6856  * dumpTableComment --
6857  *
6858  * As above, but dump comments for both the specified table (or view)
6859  * and its columns.
6860  */
6861 static void
6862 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6863                                  const char *reltypename)
6864 {
6865         CommentItem *comments;
6866         int                     ncomments;
6867         PQExpBuffer query;
6868         PQExpBuffer target;
6869
6870         /* Comments are SCHEMA not data */
6871         if (dataOnly)
6872                 return;
6873
6874         /* Search for comments associated with relation, using table */
6875         ncomments = findComments(fout,
6876                                                          tbinfo->dobj.catId.tableoid,
6877                                                          tbinfo->dobj.catId.oid,
6878                                                          &comments);
6879
6880         /* If comments exist, build COMMENT ON statements */
6881         if (ncomments <= 0)
6882                 return;
6883
6884         query = createPQExpBuffer();
6885         target = createPQExpBuffer();
6886
6887         while (ncomments > 0)
6888         {
6889                 const char *descr = comments->descr;
6890                 int                     objsubid = comments->objsubid;
6891
6892                 if (objsubid == 0)
6893                 {
6894                         resetPQExpBuffer(target);
6895                         appendPQExpBuffer(target, "%s %s", reltypename,
6896                                                           fmtId(tbinfo->dobj.name));
6897
6898                         resetPQExpBuffer(query);
6899                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6900                         appendStringLiteralAH(query, descr, fout);
6901                         appendPQExpBuffer(query, ";\n");
6902
6903                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6904                                                  target->data,
6905                                                  tbinfo->dobj.namespace->dobj.name,
6906                                                  NULL, tbinfo->rolname,
6907                                                  false, "COMMENT", SECTION_NONE,
6908                                                  query->data, "", NULL,
6909                                                  &(tbinfo->dobj.dumpId), 1,
6910                                                  NULL, NULL);
6911                 }
6912                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6913                 {
6914                         resetPQExpBuffer(target);
6915                         appendPQExpBuffer(target, "COLUMN %s.",
6916                                                           fmtId(tbinfo->dobj.name));
6917                         appendPQExpBuffer(target, "%s",
6918                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6919
6920                         resetPQExpBuffer(query);
6921                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6922                         appendStringLiteralAH(query, descr, fout);
6923                         appendPQExpBuffer(query, ";\n");
6924
6925                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6926                                                  target->data,
6927                                                  tbinfo->dobj.namespace->dobj.name,
6928                                                  NULL, tbinfo->rolname,
6929                                                  false, "COMMENT", SECTION_NONE,
6930                                                  query->data, "", NULL,
6931                                                  &(tbinfo->dobj.dumpId), 1,
6932                                                  NULL, NULL);
6933                 }
6934
6935                 comments++;
6936                 ncomments--;
6937         }
6938
6939         destroyPQExpBuffer(query);
6940         destroyPQExpBuffer(target);
6941 }
6942
6943 /*
6944  * findComments --
6945  *
6946  * Find the comment(s), if any, associated with the given object.  All the
6947  * objsubid values associated with the given classoid/objoid are found with
6948  * one search.
6949  */
6950 static int
6951 findComments(Archive *fout, Oid classoid, Oid objoid,
6952                          CommentItem **items)
6953 {
6954         /* static storage for table of comments */
6955         static CommentItem *comments = NULL;
6956         static int      ncomments = -1;
6957
6958         CommentItem *middle = NULL;
6959         CommentItem *low;
6960         CommentItem *high;
6961         int                     nmatch;
6962
6963         /* Get comments if we didn't already */
6964         if (ncomments < 0)
6965                 ncomments = collectComments(fout, &comments);
6966
6967         /*
6968          * Pre-7.2, pg_description does not contain classoid, so collectComments
6969          * just stores a zero.  If there's a collision on object OID, well, you
6970          * get duplicate comments.
6971          */
6972         if (fout->remoteVersion < 70200)
6973                 classoid = 0;
6974
6975         /*
6976          * Do binary search to find some item matching the object.
6977          */
6978         low = &comments[0];
6979         high = &comments[ncomments - 1];
6980         while (low <= high)
6981         {
6982                 middle = low + (high - low) / 2;
6983
6984                 if (classoid < middle->classoid)
6985                         high = middle - 1;
6986                 else if (classoid > middle->classoid)
6987                         low = middle + 1;
6988                 else if (objoid < middle->objoid)
6989                         high = middle - 1;
6990                 else if (objoid > middle->objoid)
6991                         low = middle + 1;
6992                 else
6993                         break;                          /* found a match */
6994         }
6995
6996         if (low > high)                         /* no matches */
6997         {
6998                 *items = NULL;
6999                 return 0;
7000         }
7001
7002         /*
7003          * Now determine how many items match the object.  The search loop
7004          * invariant still holds: only items between low and high inclusive could
7005          * match.
7006          */
7007         nmatch = 1;
7008         while (middle > low)
7009         {
7010                 if (classoid != middle[-1].classoid ||
7011                         objoid != middle[-1].objoid)
7012                         break;
7013                 middle--;
7014                 nmatch++;
7015         }
7016
7017         *items = middle;
7018
7019         middle += nmatch;
7020         while (middle <= high)
7021         {
7022                 if (classoid != middle->classoid ||
7023                         objoid != middle->objoid)
7024                         break;
7025                 middle++;
7026                 nmatch++;
7027         }
7028
7029         return nmatch;
7030 }
7031
7032 /*
7033  * collectComments --
7034  *
7035  * Construct a table of all comments available for database objects.
7036  * We used to do per-object queries for the comments, but it's much faster
7037  * to pull them all over at once, and on most databases the memory cost
7038  * isn't high.
7039  *
7040  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7041  */
7042 static int
7043 collectComments(Archive *fout, CommentItem **items)
7044 {
7045         PGresult   *res;
7046         PQExpBuffer query;
7047         int                     i_description;
7048         int                     i_classoid;
7049         int                     i_objoid;
7050         int                     i_objsubid;
7051         int                     ntups;
7052         int                     i;
7053         CommentItem *comments;
7054
7055         /*
7056          * Note we do NOT change source schema here; preserve the caller's
7057          * setting, instead.
7058          */
7059
7060         query = createPQExpBuffer();
7061
7062         if (fout->remoteVersion >= 70300)
7063         {
7064                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7065                                                   "FROM pg_catalog.pg_description "
7066                                                   "ORDER BY classoid, objoid, objsubid");
7067         }
7068         else if (fout->remoteVersion >= 70200)
7069         {
7070                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7071                                                   "FROM pg_description "
7072                                                   "ORDER BY classoid, objoid, objsubid");
7073         }
7074         else
7075         {
7076                 /* Note: this will fail to find attribute comments in pre-7.2... */
7077                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7078                                                   "FROM pg_description "
7079                                                   "ORDER BY objoid");
7080         }
7081
7082         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7083
7084         /* Construct lookup table containing OIDs in numeric form */
7085
7086         i_description = PQfnumber(res, "description");
7087         i_classoid = PQfnumber(res, "classoid");
7088         i_objoid = PQfnumber(res, "objoid");
7089         i_objsubid = PQfnumber(res, "objsubid");
7090
7091         ntups = PQntuples(res);
7092
7093         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7094
7095         for (i = 0; i < ntups; i++)
7096         {
7097                 comments[i].descr = PQgetvalue(res, i, i_description);
7098                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7099                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7100                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7101         }
7102
7103         /* Do NOT free the PGresult since we are keeping pointers into it */
7104         destroyPQExpBuffer(query);
7105
7106         *items = comments;
7107         return ntups;
7108 }
7109
7110 /*
7111  * dumpDumpableObject
7112  *
7113  * This routine and its subsidiaries are responsible for creating
7114  * ArchiveEntries (TOC objects) for each object to be dumped.
7115  */
7116 static void
7117 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7118 {
7119         switch (dobj->objType)
7120         {
7121                 case DO_NAMESPACE:
7122                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7123                         break;
7124                 case DO_EXTENSION:
7125                         dumpExtension(fout, (ExtensionInfo *) dobj);
7126                         break;
7127                 case DO_TYPE:
7128                         dumpType(fout, (TypeInfo *) dobj);
7129                         break;
7130                 case DO_SHELL_TYPE:
7131                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7132                         break;
7133                 case DO_FUNC:
7134                         dumpFunc(fout, (FuncInfo *) dobj);
7135                         break;
7136                 case DO_AGG:
7137                         dumpAgg(fout, (AggInfo *) dobj);
7138                         break;
7139                 case DO_OPERATOR:
7140                         dumpOpr(fout, (OprInfo *) dobj);
7141                         break;
7142                 case DO_OPCLASS:
7143                         dumpOpclass(fout, (OpclassInfo *) dobj);
7144                         break;
7145                 case DO_OPFAMILY:
7146                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7147                         break;
7148                 case DO_COLLATION:
7149                         dumpCollation(fout, (CollInfo *) dobj);
7150                         break;
7151                 case DO_CONVERSION:
7152                         dumpConversion(fout, (ConvInfo *) dobj);
7153                         break;
7154                 case DO_TABLE:
7155                         dumpTable(fout, (TableInfo *) dobj);
7156                         break;
7157                 case DO_ATTRDEF:
7158                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7159                         break;
7160                 case DO_INDEX:
7161                         dumpIndex(fout, (IndxInfo *) dobj);
7162                         break;
7163                 case DO_RULE:
7164                         dumpRule(fout, (RuleInfo *) dobj);
7165                         break;
7166                 case DO_TRIGGER:
7167                         dumpTrigger(fout, (TriggerInfo *) dobj);
7168                         break;
7169                 case DO_CONSTRAINT:
7170                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7171                         break;
7172                 case DO_FK_CONSTRAINT:
7173                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7174                         break;
7175                 case DO_PROCLANG:
7176                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7177                         break;
7178                 case DO_CAST:
7179                         dumpCast(fout, (CastInfo *) dobj);
7180                         break;
7181                 case DO_TABLE_DATA:
7182                         dumpTableData(fout, (TableDataInfo *) dobj);
7183                         break;
7184                 case DO_DUMMY_TYPE:
7185                         /* table rowtypes and array types are never dumped separately */
7186                         break;
7187                 case DO_TSPARSER:
7188                         dumpTSParser(fout, (TSParserInfo *) dobj);
7189                         break;
7190                 case DO_TSDICT:
7191                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7192                         break;
7193                 case DO_TSTEMPLATE:
7194                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7195                         break;
7196                 case DO_TSCONFIG:
7197                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7198                         break;
7199                 case DO_FDW:
7200                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7201                         break;
7202                 case DO_FOREIGN_SERVER:
7203                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7204                         break;
7205                 case DO_DEFAULT_ACL:
7206                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7207                         break;
7208                 case DO_BLOB:
7209                         dumpBlob(fout, (BlobInfo *) dobj);
7210                         break;
7211                 case DO_BLOB_DATA:
7212                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7213                                                  dobj->name, NULL, NULL, "",
7214                                                  false, "BLOBS", SECTION_DATA,
7215                                                  "", "", NULL,
7216                                                  NULL, 0,
7217                                                  dumpBlobs, NULL);
7218                         break;
7219                 case DO_PRE_DATA_BOUNDARY:
7220                 case DO_POST_DATA_BOUNDARY:
7221                         /* never dumped, nothing to do */
7222                         break;
7223         }
7224 }
7225
7226 /*
7227  * dumpNamespace
7228  *        writes out to fout the queries to recreate a user-defined namespace
7229  */
7230 static void
7231 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7232 {
7233         PQExpBuffer q;
7234         PQExpBuffer delq;
7235         PQExpBuffer labelq;
7236         char       *qnspname;
7237
7238         /* Skip if not to be dumped */
7239         if (!nspinfo->dobj.dump || dataOnly)
7240                 return;
7241
7242         /* don't dump dummy namespace from pre-7.3 source */
7243         if (strlen(nspinfo->dobj.name) == 0)
7244                 return;
7245
7246         q = createPQExpBuffer();
7247         delq = createPQExpBuffer();
7248         labelq = createPQExpBuffer();
7249
7250         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7251
7252         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7253
7254         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7255
7256         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7257
7258         if (binary_upgrade)
7259                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7260
7261         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7262                                  nspinfo->dobj.name,
7263                                  NULL, NULL,
7264                                  nspinfo->rolname,
7265                                  false, "SCHEMA", SECTION_PRE_DATA,
7266                                  q->data, delq->data, NULL,
7267                                  NULL, 0,
7268                                  NULL, NULL);
7269
7270         /* Dump Schema Comments and Security Labels */
7271         dumpComment(fout, labelq->data,
7272                                 NULL, nspinfo->rolname,
7273                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7274         dumpSecLabel(fout, labelq->data,
7275                                  NULL, nspinfo->rolname,
7276                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7277
7278         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7279                         qnspname, NULL, nspinfo->dobj.name, NULL,
7280                         nspinfo->rolname, nspinfo->nspacl);
7281
7282         free(qnspname);
7283
7284         destroyPQExpBuffer(q);
7285         destroyPQExpBuffer(delq);
7286         destroyPQExpBuffer(labelq);
7287 }
7288
7289 /*
7290  * dumpExtension
7291  *        writes out to fout the queries to recreate an extension
7292  */
7293 static void
7294 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7295 {
7296         PQExpBuffer q;
7297         PQExpBuffer delq;
7298         PQExpBuffer labelq;
7299         char       *qextname;
7300
7301         /* Skip if not to be dumped */
7302         if (!extinfo->dobj.dump || dataOnly)
7303                 return;
7304
7305         q = createPQExpBuffer();
7306         delq = createPQExpBuffer();
7307         labelq = createPQExpBuffer();
7308
7309         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7310
7311         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7312
7313         if (!binary_upgrade)
7314         {
7315                 /*
7316                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7317                  * problem if the extension already exists in the target database;
7318                  * this is essential for installed-by-default extensions such as
7319                  * plpgsql.
7320                  *
7321                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7322                  * built-in extensions based on their OIDs; see
7323                  * selectDumpableExtension.
7324                  */
7325                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7326                                                   qextname, fmtId(extinfo->namespace));
7327         }
7328         else
7329         {
7330                 int                     i;
7331                 int                     n;
7332
7333                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7334                 appendPQExpBuffer(q,
7335                                                   "SELECT binary_upgrade.create_empty_extension(");
7336                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7337                 appendPQExpBuffer(q, ", ");
7338                 appendStringLiteralAH(q, extinfo->namespace, fout);
7339                 appendPQExpBuffer(q, ", ");
7340                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7341                 appendStringLiteralAH(q, extinfo->extversion, fout);
7342                 appendPQExpBuffer(q, ", ");
7343
7344                 /*
7345                  * Note that we're pushing extconfig (an OID array) back into
7346                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7347                  * preserved in binary upgrade.
7348                  */
7349                 if (strlen(extinfo->extconfig) > 2)
7350                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7351                 else
7352                         appendPQExpBuffer(q, "NULL");
7353                 appendPQExpBuffer(q, ", ");
7354                 if (strlen(extinfo->extcondition) > 2)
7355                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7356                 else
7357                         appendPQExpBuffer(q, "NULL");
7358                 appendPQExpBuffer(q, ", ");
7359                 appendPQExpBuffer(q, "ARRAY[");
7360                 n = 0;
7361                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7362                 {
7363                         DumpableObject *extobj;
7364
7365                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7366                         if (extobj && extobj->objType == DO_EXTENSION)
7367                         {
7368                                 if (n++ > 0)
7369                                         appendPQExpBuffer(q, ",");
7370                                 appendStringLiteralAH(q, extobj->name, fout);
7371                         }
7372                 }
7373                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7374                 appendPQExpBuffer(q, ");\n");
7375         }
7376
7377         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7378
7379         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7380                                  extinfo->dobj.name,
7381                                  NULL, NULL,
7382                                  "",
7383                                  false, "EXTENSION", SECTION_PRE_DATA,
7384                                  q->data, delq->data, NULL,
7385                                  NULL, 0,
7386                                  NULL, NULL);
7387
7388         /* Dump Extension Comments and Security Labels */
7389         dumpComment(fout, labelq->data,
7390                                 NULL, "",
7391                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7392         dumpSecLabel(fout, labelq->data,
7393                                  NULL, "",
7394                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7395
7396         free(qextname);
7397
7398         destroyPQExpBuffer(q);
7399         destroyPQExpBuffer(delq);
7400         destroyPQExpBuffer(labelq);
7401 }
7402
7403 /*
7404  * dumpType
7405  *        writes out to fout the queries to recreate a user-defined type
7406  */
7407 static void
7408 dumpType(Archive *fout, TypeInfo *tyinfo)
7409 {
7410         /* Skip if not to be dumped */
7411         if (!tyinfo->dobj.dump || dataOnly)
7412                 return;
7413
7414         /* Dump out in proper style */
7415         if (tyinfo->typtype == TYPTYPE_BASE)
7416                 dumpBaseType(fout, tyinfo);
7417         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7418                 dumpDomain(fout, tyinfo);
7419         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7420                 dumpCompositeType(fout, tyinfo);
7421         else if (tyinfo->typtype == TYPTYPE_ENUM)
7422                 dumpEnumType(fout, tyinfo);
7423         else if (tyinfo->typtype == TYPTYPE_RANGE)
7424                 dumpRangeType(fout, tyinfo);
7425         else
7426                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7427                                   tyinfo->dobj.name);
7428 }
7429
7430 /*
7431  * dumpEnumType
7432  *        writes out to fout the queries to recreate a user-defined enum type
7433  */
7434 static void
7435 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7436 {
7437         PQExpBuffer q = createPQExpBuffer();
7438         PQExpBuffer delq = createPQExpBuffer();
7439         PQExpBuffer labelq = createPQExpBuffer();
7440         PQExpBuffer query = createPQExpBuffer();
7441         PGresult   *res;
7442         int                     num,
7443                                 i;
7444         Oid                     enum_oid;
7445         char       *label;
7446
7447         /* Set proper schema search path */
7448         selectSourceSchema(fout, "pg_catalog");
7449
7450         if (fout->remoteVersion >= 90100)
7451                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7452                                                   "FROM pg_catalog.pg_enum "
7453                                                   "WHERE enumtypid = '%u'"
7454                                                   "ORDER BY enumsortorder",
7455                                                   tyinfo->dobj.catId.oid);
7456         else
7457                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7458                                                   "FROM pg_catalog.pg_enum "
7459                                                   "WHERE enumtypid = '%u'"
7460                                                   "ORDER BY oid",
7461                                                   tyinfo->dobj.catId.oid);
7462
7463         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7464
7465         num = PQntuples(res);
7466
7467         /*
7468          * DROP must be fully qualified in case same name appears in pg_catalog.
7469          * CASCADE shouldn't be required here as for normal types since the I/O
7470          * functions are generic and do not get dropped.
7471          */
7472         appendPQExpBuffer(delq, "DROP TYPE %s.",
7473                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7474         appendPQExpBuffer(delq, "%s;\n",
7475                                           fmtId(tyinfo->dobj.name));
7476
7477         if (binary_upgrade)
7478                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7479                                                                                                  tyinfo->dobj.catId.oid);
7480
7481         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7482                                           fmtId(tyinfo->dobj.name));
7483
7484         if (!binary_upgrade)
7485         {
7486                 /* Labels with server-assigned oids */
7487                 for (i = 0; i < num; i++)
7488                 {
7489                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7490                         if (i > 0)
7491                                 appendPQExpBuffer(q, ",");
7492                         appendPQExpBuffer(q, "\n    ");
7493                         appendStringLiteralAH(q, label, fout);
7494                 }
7495         }
7496
7497         appendPQExpBuffer(q, "\n);\n");
7498
7499         if (binary_upgrade)
7500         {
7501                 /* Labels with dump-assigned (preserved) oids */
7502                 for (i = 0; i < num; i++)
7503                 {
7504                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7505                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7506
7507                         if (i == 0)
7508                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7509                         appendPQExpBuffer(q,
7510                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7511                                                           enum_oid);
7512                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7513                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7514                         appendPQExpBuffer(q, "%s ADD VALUE ",
7515                                                           fmtId(tyinfo->dobj.name));
7516                         appendStringLiteralAH(q, label, fout);
7517                         appendPQExpBuffer(q, ";\n\n");
7518                 }
7519         }
7520
7521         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7522
7523         if (binary_upgrade)
7524                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7525
7526         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7527                                  tyinfo->dobj.name,
7528                                  tyinfo->dobj.namespace->dobj.name,
7529                                  NULL,
7530                                  tyinfo->rolname, false,
7531                                  "TYPE", SECTION_PRE_DATA,
7532                                  q->data, delq->data, NULL,
7533                                  NULL, 0,
7534                                  NULL, NULL);
7535
7536         /* Dump Type Comments and Security Labels */
7537         dumpComment(fout, labelq->data,
7538                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7539                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7540         dumpSecLabel(fout, labelq->data,
7541                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7542                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7543
7544         PQclear(res);
7545         destroyPQExpBuffer(q);
7546         destroyPQExpBuffer(delq);
7547         destroyPQExpBuffer(labelq);
7548         destroyPQExpBuffer(query);
7549 }
7550
7551 /*
7552  * dumpRangeType
7553  *        writes out to fout the queries to recreate a user-defined range type
7554  */
7555 static void
7556 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7557 {
7558         PQExpBuffer q = createPQExpBuffer();
7559         PQExpBuffer delq = createPQExpBuffer();
7560         PQExpBuffer labelq = createPQExpBuffer();
7561         PQExpBuffer query = createPQExpBuffer();
7562         PGresult   *res;
7563         Oid                     collationOid;
7564         char       *procname;
7565
7566         /*
7567          * select appropriate schema to ensure names in CREATE are properly
7568          * qualified
7569          */
7570         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7571
7572         appendPQExpBuffer(query,
7573                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7574                                           "opc.opcname AS opcname, "
7575                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7576                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7577                                           "opc.opcdefault, "
7578                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7579                                           "     ELSE rngcollation END AS collation, "
7580                                           "rngcanonical, rngsubdiff "
7581                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7582                                           "     pg_catalog.pg_opclass opc "
7583                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7584                                           "rngtypid = '%u'",
7585                                           tyinfo->dobj.catId.oid);
7586
7587         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7588
7589         /*
7590          * DROP must be fully qualified in case same name appears in pg_catalog.
7591          * CASCADE shouldn't be required here as for normal types since the I/O
7592          * functions are generic and do not get dropped.
7593          */
7594         appendPQExpBuffer(delq, "DROP TYPE %s.",
7595                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7596         appendPQExpBuffer(delq, "%s;\n",
7597                                           fmtId(tyinfo->dobj.name));
7598
7599         if (binary_upgrade)
7600                 binary_upgrade_set_type_oids_by_type_oid(fout,
7601                                                                                                  q, tyinfo->dobj.catId.oid);
7602
7603         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7604                                           fmtId(tyinfo->dobj.name));
7605
7606         appendPQExpBuffer(q, "\n    subtype = %s",
7607                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7608
7609         /* print subtype_opclass only if not default for subtype */
7610         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7611         {
7612                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7613                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7614
7615                 /* always schema-qualify, don't try to be smart */
7616                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7617                                                   fmtId(nspname));
7618                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7619         }
7620
7621         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7622         if (OidIsValid(collationOid))
7623         {
7624                 CollInfo   *coll = findCollationByOid(collationOid);
7625
7626                 if (coll)
7627                 {
7628                         /* always schema-qualify, don't try to be smart */
7629                         appendPQExpBuffer(q, ",\n    collation = %s.",
7630                                                           fmtId(coll->dobj.namespace->dobj.name));
7631                         appendPQExpBuffer(q, "%s",
7632                                                           fmtId(coll->dobj.name));
7633                 }
7634         }
7635
7636         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7637         if (strcmp(procname, "-") != 0)
7638                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7639
7640         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7641         if (strcmp(procname, "-") != 0)
7642                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7643
7644         appendPQExpBuffer(q, "\n);\n");
7645
7646         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7647
7648         if (binary_upgrade)
7649                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7650
7651         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7652                                  tyinfo->dobj.name,
7653                                  tyinfo->dobj.namespace->dobj.name,
7654                                  NULL,
7655                                  tyinfo->rolname, false,
7656                                  "TYPE", SECTION_PRE_DATA,
7657                                  q->data, delq->data, NULL,
7658                                  NULL, 0,
7659                                  NULL, NULL);
7660
7661         /* Dump Type Comments and Security Labels */
7662         dumpComment(fout, labelq->data,
7663                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7664                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7665         dumpSecLabel(fout, labelq->data,
7666                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7667                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7668
7669         PQclear(res);
7670         destroyPQExpBuffer(q);
7671         destroyPQExpBuffer(delq);
7672         destroyPQExpBuffer(labelq);
7673         destroyPQExpBuffer(query);
7674 }
7675
7676 /*
7677  * dumpBaseType
7678  *        writes out to fout the queries to recreate a user-defined base type
7679  */
7680 static void
7681 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7682 {
7683         PQExpBuffer q = createPQExpBuffer();
7684         PQExpBuffer delq = createPQExpBuffer();
7685         PQExpBuffer labelq = createPQExpBuffer();
7686         PQExpBuffer query = createPQExpBuffer();
7687         PGresult   *res;
7688         char       *typlen;
7689         char       *typinput;
7690         char       *typoutput;
7691         char       *typreceive;
7692         char       *typsend;
7693         char       *typmodin;
7694         char       *typmodout;
7695         char       *typanalyze;
7696         Oid                     typreceiveoid;
7697         Oid                     typsendoid;
7698         Oid                     typmodinoid;
7699         Oid                     typmodoutoid;
7700         Oid                     typanalyzeoid;
7701         char       *typcategory;
7702         char       *typispreferred;
7703         char       *typdelim;
7704         char       *typbyval;
7705         char       *typalign;
7706         char       *typstorage;
7707         char       *typcollatable;
7708         char       *typdefault;
7709         bool            typdefault_is_literal = false;
7710
7711         /* Set proper schema search path so regproc references list correctly */
7712         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7713
7714         /* Fetch type-specific details */
7715         if (fout->remoteVersion >= 90100)
7716         {
7717                 appendPQExpBuffer(query, "SELECT typlen, "
7718                                                   "typinput, typoutput, typreceive, typsend, "
7719                                                   "typmodin, typmodout, typanalyze, "
7720                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7721                                                   "typsend::pg_catalog.oid AS typsendoid, "
7722                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7723                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7724                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7725                                                   "typcategory, typispreferred, "
7726                                                   "typdelim, typbyval, typalign, typstorage, "
7727                                                   "(typcollation <> 0) AS typcollatable, "
7728                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7729                                                   "FROM pg_catalog.pg_type "
7730                                                   "WHERE oid = '%u'::pg_catalog.oid",
7731                                                   tyinfo->dobj.catId.oid);
7732         }
7733         else if (fout->remoteVersion >= 80400)
7734         {
7735                 appendPQExpBuffer(query, "SELECT typlen, "
7736                                                   "typinput, typoutput, typreceive, typsend, "
7737                                                   "typmodin, typmodout, typanalyze, "
7738                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7739                                                   "typsend::pg_catalog.oid AS typsendoid, "
7740                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7741                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7742                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7743                                                   "typcategory, typispreferred, "
7744                                                   "typdelim, typbyval, typalign, typstorage, "
7745                                                   "false AS typcollatable, "
7746                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7747                                                   "FROM pg_catalog.pg_type "
7748                                                   "WHERE oid = '%u'::pg_catalog.oid",
7749                                                   tyinfo->dobj.catId.oid);
7750         }
7751         else if (fout->remoteVersion >= 80300)
7752         {
7753                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7754                 appendPQExpBuffer(query, "SELECT typlen, "
7755                                                   "typinput, typoutput, typreceive, typsend, "
7756                                                   "typmodin, typmodout, typanalyze, "
7757                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7758                                                   "typsend::pg_catalog.oid AS typsendoid, "
7759                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7760                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7761                                                   "typanalyze::pg_catalog.oid 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 >= 80000)
7771         {
7772                 appendPQExpBuffer(query, "SELECT typlen, "
7773                                                   "typinput, typoutput, typreceive, typsend, "
7774                                                   "'-' AS typmodin, '-' AS typmodout, "
7775                                                   "typanalyze, "
7776                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7777                                                   "typsend::pg_catalog.oid AS typsendoid, "
7778                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7779                                                   "typanalyze::pg_catalog.oid 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 >= 70400)
7789         {
7790                 appendPQExpBuffer(query, "SELECT typlen, "
7791                                                   "typinput, typoutput, typreceive, typsend, "
7792                                                   "'-' AS typmodin, '-' AS typmodout, "
7793                                                   "'-' AS typanalyze, "
7794                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7795                                                   "typsend::pg_catalog.oid AS typsendoid, "
7796                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7797                                                   "0 AS typanalyzeoid, "
7798                                                   "'U' AS typcategory, false AS typispreferred, "
7799                                                   "typdelim, typbyval, typalign, typstorage, "
7800                                                   "false AS typcollatable, "
7801                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7802                                                   "FROM pg_catalog.pg_type "
7803                                                   "WHERE oid = '%u'::pg_catalog.oid",
7804                                                   tyinfo->dobj.catId.oid);
7805         }
7806         else if (fout->remoteVersion >= 70300)
7807         {
7808                 appendPQExpBuffer(query, "SELECT typlen, "
7809                                                   "typinput, typoutput, "
7810                                                   "'-' AS typreceive, '-' AS typsend, "
7811                                                   "'-' AS typmodin, '-' AS typmodout, "
7812                                                   "'-' AS typanalyze, "
7813                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7814                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7815                                                   "0 AS typanalyzeoid, "
7816                                                   "'U' AS typcategory, false AS typispreferred, "
7817                                                   "typdelim, typbyval, typalign, typstorage, "
7818                                                   "false AS typcollatable, "
7819                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7820                                                   "FROM pg_catalog.pg_type "
7821                                                   "WHERE oid = '%u'::pg_catalog.oid",
7822                                                   tyinfo->dobj.catId.oid);
7823         }
7824         else if (fout->remoteVersion >= 70200)
7825         {
7826                 /*
7827                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7828                  * ignore them because they are not right.
7829                  */
7830                 appendPQExpBuffer(query, "SELECT typlen, "
7831                                                   "typinput, typoutput, "
7832                                                   "'-' AS typreceive, '-' AS typsend, "
7833                                                   "'-' AS typmodin, '-' AS typmodout, "
7834                                                   "'-' AS typanalyze, "
7835                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7836                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7837                                                   "0 AS typanalyzeoid, "
7838                                                   "'U' AS typcategory, false AS typispreferred, "
7839                                                   "typdelim, typbyval, typalign, typstorage, "
7840                                                   "false AS typcollatable, "
7841                                                   "NULL AS typdefaultbin, typdefault "
7842                                                   "FROM pg_type "
7843                                                   "WHERE oid = '%u'::oid",
7844                                                   tyinfo->dobj.catId.oid);
7845         }
7846         else if (fout->remoteVersion >= 70100)
7847         {
7848                 /*
7849                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7850                  * representation.
7851                  */
7852                 appendPQExpBuffer(query, "SELECT typlen, "
7853                                                   "typinput, typoutput, "
7854                                                   "'-' AS typreceive, '-' AS typsend, "
7855                                                   "'-' AS typmodin, '-' AS typmodout, "
7856                                                   "'-' AS typanalyze, "
7857                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7858                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7859                                                   "0 AS typanalyzeoid, "
7860                                                   "'U' AS typcategory, false AS typispreferred, "
7861                                                   "typdelim, typbyval, typalign, typstorage, "
7862                                                   "false AS typcollatable, "
7863                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7864                                                   "FROM pg_type "
7865                                                   "WHERE oid = '%u'::oid",
7866                                                   tyinfo->dobj.catId.oid);
7867         }
7868         else
7869         {
7870                 appendPQExpBuffer(query, "SELECT typlen, "
7871                                                   "typinput, typoutput, "
7872                                                   "'-' AS typreceive, '-' AS typsend, "
7873                                                   "'-' AS typmodin, '-' AS typmodout, "
7874                                                   "'-' AS typanalyze, "
7875                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7876                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7877                                                   "0 AS typanalyzeoid, "
7878                                                   "'U' AS typcategory, false AS typispreferred, "
7879                                                   "typdelim, typbyval, typalign, "
7880                                                   "'p'::char AS typstorage, "
7881                                                   "false AS typcollatable, "
7882                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7883                                                   "FROM pg_type "
7884                                                   "WHERE oid = '%u'::oid",
7885                                                   tyinfo->dobj.catId.oid);
7886         }
7887
7888         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7889
7890         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7891         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7892         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7893         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7894         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7895         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7896         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7897         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7898         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7899         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7900         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7901         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7902         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7903         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7904         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7905         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7906         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7907         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7908         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7909         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7910         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7911                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7912         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7913         {
7914                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7915                 typdefault_is_literal = true;   /* it needs quotes */
7916         }
7917         else
7918                 typdefault = NULL;
7919
7920         /*
7921          * DROP must be fully qualified in case same name appears in pg_catalog.
7922          * The reason we include CASCADE is that the circular dependency between
7923          * the type and its I/O functions makes it impossible to drop the type any
7924          * other way.
7925          */
7926         appendPQExpBuffer(delq, "DROP TYPE %s.",
7927                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7928         appendPQExpBuffer(delq, "%s CASCADE;\n",
7929                                           fmtId(tyinfo->dobj.name));
7930
7931         /* We might already have a shell type, but setting pg_type_oid is harmless */
7932         if (binary_upgrade)
7933                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7934                                                                                                  tyinfo->dobj.catId.oid);
7935
7936         appendPQExpBuffer(q,
7937                                           "CREATE TYPE %s (\n"
7938                                           "    INTERNALLENGTH = %s",
7939                                           fmtId(tyinfo->dobj.name),
7940                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7941
7942         if (fout->remoteVersion >= 70300)
7943         {
7944                 /* regproc result is correctly quoted as of 7.3 */
7945                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
7946                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
7947                 if (OidIsValid(typreceiveoid))
7948                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
7949                 if (OidIsValid(typsendoid))
7950                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
7951                 if (OidIsValid(typmodinoid))
7952                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
7953                 if (OidIsValid(typmodoutoid))
7954                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
7955                 if (OidIsValid(typanalyzeoid))
7956                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
7957         }
7958         else
7959         {
7960                 /* regproc delivers an unquoted name before 7.3 */
7961                 /* cannot combine these because fmtId uses static result area */
7962                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
7963                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7964                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7965         }
7966
7967         if (strcmp(typcollatable, "t") == 0)
7968                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
7969
7970         if (typdefault != NULL)
7971         {
7972                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7973                 if (typdefault_is_literal)
7974                         appendStringLiteralAH(q, typdefault, fout);
7975                 else
7976                         appendPQExpBufferStr(q, typdefault);
7977         }
7978
7979         if (OidIsValid(tyinfo->typelem))
7980         {
7981                 char       *elemType;
7982
7983                 /* reselect schema in case changed by function dump */
7984                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7985                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7986                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
7987                 free(elemType);
7988         }
7989
7990         if (strcmp(typcategory, "U") != 0)
7991         {
7992                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
7993                 appendStringLiteralAH(q, typcategory, fout);
7994         }
7995
7996         if (strcmp(typispreferred, "t") == 0)
7997                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
7998
7999         if (typdelim && strcmp(typdelim, ",") != 0)
8000         {
8001                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8002                 appendStringLiteralAH(q, typdelim, fout);
8003         }
8004
8005         if (strcmp(typalign, "c") == 0)
8006                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8007         else if (strcmp(typalign, "s") == 0)
8008                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8009         else if (strcmp(typalign, "i") == 0)
8010                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8011         else if (strcmp(typalign, "d") == 0)
8012                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8013
8014         if (strcmp(typstorage, "p") == 0)
8015                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8016         else if (strcmp(typstorage, "e") == 0)
8017                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8018         else if (strcmp(typstorage, "x") == 0)
8019                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8020         else if (strcmp(typstorage, "m") == 0)
8021                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8022
8023         if (strcmp(typbyval, "t") == 0)
8024                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8025
8026         appendPQExpBuffer(q, "\n);\n");
8027
8028         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8029
8030         if (binary_upgrade)
8031                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8032
8033         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8034                                  tyinfo->dobj.name,
8035                                  tyinfo->dobj.namespace->dobj.name,
8036                                  NULL,
8037                                  tyinfo->rolname, false,
8038                                  "TYPE", SECTION_PRE_DATA,
8039                                  q->data, delq->data, NULL,
8040                                  NULL, 0,
8041                                  NULL, NULL);
8042
8043         /* Dump Type Comments and Security Labels */
8044         dumpComment(fout, labelq->data,
8045                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8046                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8047         dumpSecLabel(fout, labelq->data,
8048                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8049                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8050
8051         PQclear(res);
8052         destroyPQExpBuffer(q);
8053         destroyPQExpBuffer(delq);
8054         destroyPQExpBuffer(labelq);
8055         destroyPQExpBuffer(query);
8056 }
8057
8058 /*
8059  * dumpDomain
8060  *        writes out to fout the queries to recreate a user-defined domain
8061  */
8062 static void
8063 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8064 {
8065         PQExpBuffer q = createPQExpBuffer();
8066         PQExpBuffer delq = createPQExpBuffer();
8067         PQExpBuffer labelq = createPQExpBuffer();
8068         PQExpBuffer query = createPQExpBuffer();
8069         PGresult   *res;
8070         int                     i;
8071         char       *typnotnull;
8072         char       *typdefn;
8073         char       *typdefault;
8074         Oid                     typcollation;
8075         bool            typdefault_is_literal = false;
8076
8077         /* Set proper schema search path so type references list correctly */
8078         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8079
8080         /* Fetch domain specific details */
8081         if (fout->remoteVersion >= 90100)
8082         {
8083                 /* typcollation is new in 9.1 */
8084                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8085                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8086                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8087                                                   "t.typdefault, "
8088                                                   "CASE WHEN t.typcollation <> u.typcollation "
8089                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8090                                                   "FROM pg_catalog.pg_type t "
8091                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8092                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8093                                                   tyinfo->dobj.catId.oid);
8094         }
8095         else
8096         {
8097                 /* We assume here that remoteVersion must be at least 70300 */
8098                 appendPQExpBuffer(query, "SELECT typnotnull, "
8099                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8100                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8101                                                   "typdefault, 0 AS typcollation "
8102                                                   "FROM pg_catalog.pg_type "
8103                                                   "WHERE oid = '%u'::pg_catalog.oid",
8104                                                   tyinfo->dobj.catId.oid);
8105         }
8106
8107         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8108
8109         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8110         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8111         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8112                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8113         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8114         {
8115                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8116                 typdefault_is_literal = true;   /* it needs quotes */
8117         }
8118         else
8119                 typdefault = NULL;
8120         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8121
8122         if (binary_upgrade)
8123                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8124                                                                                                  tyinfo->dobj.catId.oid);
8125
8126         appendPQExpBuffer(q,
8127                                           "CREATE DOMAIN %s AS %s",
8128                                           fmtId(tyinfo->dobj.name),
8129                                           typdefn);
8130
8131         /* Print collation only if different from base type's collation */
8132         if (OidIsValid(typcollation))
8133         {
8134                 CollInfo   *coll;
8135
8136                 coll = findCollationByOid(typcollation);
8137                 if (coll)
8138                 {
8139                         /* always schema-qualify, don't try to be smart */
8140                         appendPQExpBuffer(q, " COLLATE %s.",
8141                                                           fmtId(coll->dobj.namespace->dobj.name));
8142                         appendPQExpBuffer(q, "%s",
8143                                                           fmtId(coll->dobj.name));
8144                 }
8145         }
8146
8147         if (typnotnull[0] == 't')
8148                 appendPQExpBuffer(q, " NOT NULL");
8149
8150         if (typdefault != NULL)
8151         {
8152                 appendPQExpBuffer(q, " DEFAULT ");
8153                 if (typdefault_is_literal)
8154                         appendStringLiteralAH(q, typdefault, fout);
8155                 else
8156                         appendPQExpBufferStr(q, typdefault);
8157         }
8158
8159         PQclear(res);
8160
8161         /*
8162          * Add any CHECK constraints for the domain
8163          */
8164         for (i = 0; i < tyinfo->nDomChecks; i++)
8165         {
8166                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8167
8168                 if (!domcheck->separate)
8169                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8170                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8171         }
8172
8173         appendPQExpBuffer(q, ";\n");
8174
8175         /*
8176          * DROP must be fully qualified in case same name appears in pg_catalog
8177          */
8178         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8179                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8180         appendPQExpBuffer(delq, "%s;\n",
8181                                           fmtId(tyinfo->dobj.name));
8182
8183         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8184
8185         if (binary_upgrade)
8186                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8187
8188         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8189                                  tyinfo->dobj.name,
8190                                  tyinfo->dobj.namespace->dobj.name,
8191                                  NULL,
8192                                  tyinfo->rolname, false,
8193                                  "DOMAIN", SECTION_PRE_DATA,
8194                                  q->data, delq->data, NULL,
8195                                  NULL, 0,
8196                                  NULL, NULL);
8197
8198         /* Dump Domain Comments and Security Labels */
8199         dumpComment(fout, labelq->data,
8200                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8201                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8202         dumpSecLabel(fout, labelq->data,
8203                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8204                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8205
8206         destroyPQExpBuffer(q);
8207         destroyPQExpBuffer(delq);
8208         destroyPQExpBuffer(labelq);
8209         destroyPQExpBuffer(query);
8210 }
8211
8212 /*
8213  * dumpCompositeType
8214  *        writes out to fout the queries to recreate a user-defined stand-alone
8215  *        composite type
8216  */
8217 static void
8218 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8219 {
8220         PQExpBuffer q = createPQExpBuffer();
8221         PQExpBuffer dropped = createPQExpBuffer();
8222         PQExpBuffer delq = createPQExpBuffer();
8223         PQExpBuffer labelq = createPQExpBuffer();
8224         PQExpBuffer query = createPQExpBuffer();
8225         PGresult   *res;
8226         int                     ntups;
8227         int                     i_attname;
8228         int                     i_atttypdefn;
8229         int                     i_attlen;
8230         int                     i_attalign;
8231         int                     i_attisdropped;
8232         int                     i_attcollation;
8233         int                     i_typrelid;
8234         int                     i;
8235         int                     actual_atts;
8236
8237         /* Set proper schema search path so type references list correctly */
8238         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8239
8240         /* Fetch type specific details */
8241         if (fout->remoteVersion >= 90100)
8242         {
8243                 /*
8244                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8245                  * clauses for attributes whose collation is different from their
8246                  * type's default, we use a CASE here to suppress uninteresting
8247                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8248                  * collation does not matter for those.
8249                  */
8250                 appendPQExpBuffer(query, "SELECT a.attname, "
8251                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8252                                                   "a.attlen, a.attalign, a.attisdropped, "
8253                                                   "CASE WHEN a.attcollation <> at.typcollation "
8254                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8255                                                   "ct.typrelid "
8256                                                   "FROM pg_catalog.pg_type ct "
8257                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8258                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8259                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8260                                                   "ORDER BY a.attnum ",
8261                                                   tyinfo->dobj.catId.oid);
8262         }
8263         else
8264         {
8265                 /*
8266                  * We assume here that remoteVersion must be at least 70300.  Since
8267                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8268                  * always be false.
8269                  */
8270                 appendPQExpBuffer(query, "SELECT a.attname, "
8271                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8272                                                   "a.attlen, a.attalign, a.attisdropped, "
8273                                                   "0 AS attcollation, "
8274                                                   "ct.typrelid "
8275                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8276                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8277                                                   "AND a.attrelid = ct.typrelid "
8278                                                   "ORDER BY a.attnum ",
8279                                                   tyinfo->dobj.catId.oid);
8280         }
8281
8282         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8283
8284         ntups = PQntuples(res);
8285
8286         i_attname = PQfnumber(res, "attname");
8287         i_atttypdefn = PQfnumber(res, "atttypdefn");
8288         i_attlen = PQfnumber(res, "attlen");
8289         i_attalign = PQfnumber(res, "attalign");
8290         i_attisdropped = PQfnumber(res, "attisdropped");
8291         i_attcollation = PQfnumber(res, "attcollation");
8292         i_typrelid = PQfnumber(res, "typrelid");
8293
8294         if (binary_upgrade)
8295         {
8296                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8297
8298                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8299                                                                                                  tyinfo->dobj.catId.oid);
8300                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8301         }
8302
8303         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8304                                           fmtId(tyinfo->dobj.name));
8305
8306         actual_atts = 0;
8307         for (i = 0; i < ntups; i++)
8308         {
8309                 char       *attname;
8310                 char       *atttypdefn;
8311                 char       *attlen;
8312                 char       *attalign;
8313                 bool            attisdropped;
8314                 Oid                     attcollation;
8315
8316                 attname = PQgetvalue(res, i, i_attname);
8317                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8318                 attlen = PQgetvalue(res, i, i_attlen);
8319                 attalign = PQgetvalue(res, i, i_attalign);
8320                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8321                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8322
8323                 if (attisdropped && !binary_upgrade)
8324                         continue;
8325
8326                 /* Format properly if not first attr */
8327                 if (actual_atts++ > 0)
8328                         appendPQExpBuffer(q, ",");
8329                 appendPQExpBuffer(q, "\n\t");
8330
8331                 if (!attisdropped)
8332                 {
8333                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8334
8335                         /* Add collation if not default for the column type */
8336                         if (OidIsValid(attcollation))
8337                         {
8338                                 CollInfo   *coll;
8339
8340                                 coll = findCollationByOid(attcollation);
8341                                 if (coll)
8342                                 {
8343                                         /* always schema-qualify, don't try to be smart */
8344                                         appendPQExpBuffer(q, " COLLATE %s.",
8345                                                                           fmtId(coll->dobj.namespace->dobj.name));
8346                                         appendPQExpBuffer(q, "%s",
8347                                                                           fmtId(coll->dobj.name));
8348                                 }
8349                         }
8350                 }
8351                 else
8352                 {
8353                         /*
8354                          * This is a dropped attribute and we're in binary_upgrade mode.
8355                          * Insert a placeholder for it in the CREATE TYPE command, and set
8356                          * length and alignment with direct UPDATE to the catalogs
8357                          * afterwards. See similar code in dumpTableSchema().
8358                          */
8359                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8360
8361                         /* stash separately for insertion after the CREATE TYPE */
8362                         appendPQExpBuffer(dropped,
8363                                           "\n-- For binary upgrade, recreate dropped column.\n");
8364                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8365                                                           "SET attlen = %s, "
8366                                                           "attalign = '%s', attbyval = false\n"
8367                                                           "WHERE attname = ", attlen, attalign);
8368                         appendStringLiteralAH(dropped, attname, fout);
8369                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8370                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8371                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8372
8373                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8374                                                           fmtId(tyinfo->dobj.name));
8375                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8376                                                           fmtId(attname));
8377                 }
8378         }
8379         appendPQExpBuffer(q, "\n);\n");
8380         appendPQExpBufferStr(q, dropped->data);
8381
8382         /*
8383          * DROP must be fully qualified in case same name appears in pg_catalog
8384          */
8385         appendPQExpBuffer(delq, "DROP TYPE %s.",
8386                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8387         appendPQExpBuffer(delq, "%s;\n",
8388                                           fmtId(tyinfo->dobj.name));
8389
8390         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8391
8392         if (binary_upgrade)
8393                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8394
8395         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8396                                  tyinfo->dobj.name,
8397                                  tyinfo->dobj.namespace->dobj.name,
8398                                  NULL,
8399                                  tyinfo->rolname, false,
8400                                  "TYPE", SECTION_PRE_DATA,
8401                                  q->data, delq->data, NULL,
8402                                  NULL, 0,
8403                                  NULL, NULL);
8404
8405
8406         /* Dump Type Comments and Security Labels */
8407         dumpComment(fout, labelq->data,
8408                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8409                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8410         dumpSecLabel(fout, labelq->data,
8411                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8412                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8413
8414         PQclear(res);
8415         destroyPQExpBuffer(q);
8416         destroyPQExpBuffer(dropped);
8417         destroyPQExpBuffer(delq);
8418         destroyPQExpBuffer(labelq);
8419         destroyPQExpBuffer(query);
8420
8421         /* Dump any per-column comments */
8422         dumpCompositeTypeColComments(fout, tyinfo);
8423 }
8424
8425 /*
8426  * dumpCompositeTypeColComments
8427  *        writes out to fout the queries to recreate comments on the columns of
8428  *        a user-defined stand-alone composite type
8429  */
8430 static void
8431 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8432 {
8433         CommentItem *comments;
8434         int                     ncomments;
8435         PGresult   *res;
8436         PQExpBuffer query;
8437         PQExpBuffer target;
8438         Oid                     pgClassOid;
8439         int                     i;
8440         int                     ntups;
8441         int                     i_attname;
8442         int                     i_attnum;
8443
8444         query = createPQExpBuffer();
8445
8446         /* We assume here that remoteVersion must be at least 70300 */
8447         appendPQExpBuffer(query,
8448                                           "SELECT c.tableoid, a.attname, a.attnum "
8449                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8450                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8451                                           "  AND NOT a.attisdropped "
8452                                           "ORDER BY a.attnum ",
8453                                           tyinfo->typrelid);
8454
8455         /* Fetch column attnames */
8456         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8457
8458         ntups = PQntuples(res);
8459         if (ntups < 1)
8460         {
8461                 PQclear(res);
8462                 destroyPQExpBuffer(query);
8463                 return;
8464         }
8465
8466         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8467
8468         /* Search for comments associated with type's pg_class OID */
8469         ncomments = findComments(fout,
8470                                                          pgClassOid,
8471                                                          tyinfo->typrelid,
8472                                                          &comments);
8473
8474         /* If no comments exist, we're done */
8475         if (ncomments <= 0)
8476         {
8477                 PQclear(res);
8478                 destroyPQExpBuffer(query);
8479                 return;
8480         }
8481
8482         /* Build COMMENT ON statements */
8483         target = createPQExpBuffer();
8484
8485         i_attnum = PQfnumber(res, "attnum");
8486         i_attname = PQfnumber(res, "attname");
8487         while (ncomments > 0)
8488         {
8489                 const char *attname;
8490
8491                 attname = NULL;
8492                 for (i = 0; i < ntups; i++)
8493                 {
8494                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8495                         {
8496                                 attname = PQgetvalue(res, i, i_attname);
8497                                 break;
8498                         }
8499                 }
8500                 if (attname)                    /* just in case we don't find it */
8501                 {
8502                         const char *descr = comments->descr;
8503
8504                         resetPQExpBuffer(target);
8505                         appendPQExpBuffer(target, "COLUMN %s.",
8506                                                           fmtId(tyinfo->dobj.name));
8507                         appendPQExpBuffer(target, "%s",
8508                                                           fmtId(attname));
8509
8510                         resetPQExpBuffer(query);
8511                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8512                         appendStringLiteralAH(query, descr, fout);
8513                         appendPQExpBuffer(query, ";\n");
8514
8515                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8516                                                  target->data,
8517                                                  tyinfo->dobj.namespace->dobj.name,
8518                                                  NULL, tyinfo->rolname,
8519                                                  false, "COMMENT", SECTION_NONE,
8520                                                  query->data, "", NULL,
8521                                                  &(tyinfo->dobj.dumpId), 1,
8522                                                  NULL, NULL);
8523                 }
8524
8525                 comments++;
8526                 ncomments--;
8527         }
8528
8529         PQclear(res);
8530         destroyPQExpBuffer(query);
8531         destroyPQExpBuffer(target);
8532 }
8533
8534 /*
8535  * dumpShellType
8536  *        writes out to fout the queries to create a shell type
8537  *
8538  * We dump a shell definition in advance of the I/O functions for the type.
8539  */
8540 static void
8541 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8542 {
8543         PQExpBuffer q;
8544
8545         /* Skip if not to be dumped */
8546         if (!stinfo->dobj.dump || dataOnly)
8547                 return;
8548
8549         q = createPQExpBuffer();
8550
8551         /*
8552          * Note the lack of a DROP command for the shell type; any required DROP
8553          * is driven off the base type entry, instead.  This interacts with
8554          * _printTocEntry()'s use of the presence of a DROP command to decide
8555          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8556          * the shell type's owner immediately on creation; that should happen only
8557          * after it's filled in, otherwise the backend complains.
8558          */
8559
8560         if (binary_upgrade)
8561                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8562                                                                                    stinfo->baseType->dobj.catId.oid);
8563
8564         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8565                                           fmtId(stinfo->dobj.name));
8566
8567         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8568                                  stinfo->dobj.name,
8569                                  stinfo->dobj.namespace->dobj.name,
8570                                  NULL,
8571                                  stinfo->baseType->rolname, false,
8572                                  "SHELL TYPE", SECTION_PRE_DATA,
8573                                  q->data, "", NULL,
8574                                  NULL, 0,
8575                                  NULL, NULL);
8576
8577         destroyPQExpBuffer(q);
8578 }
8579
8580 /*
8581  * Determine whether we want to dump definitions for procedural languages.
8582  * Since the languages themselves don't have schemas, we can't rely on
8583  * the normal schema-based selection mechanism.  We choose to dump them
8584  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8585  * the dump flag of the PL's call handler function, but in 8.1 this will
8586  * probably always be false since call handlers are created in pg_catalog.)
8587  *
8588  * For some backwards compatibility with the older behavior, we forcibly
8589  * dump a PL if its handler function (and validator if any) are in a
8590  * dumpable namespace.  That case is not checked here.
8591  *
8592  * Also, if the PL belongs to an extension, we do not use this heuristic.
8593  * That case isn't checked here either.
8594  */
8595 static bool
8596 shouldDumpProcLangs(void)
8597 {
8598         if (!include_everything)
8599                 return false;
8600         /* And they're schema not data */
8601         if (dataOnly)
8602                 return false;
8603         return true;
8604 }
8605
8606 /*
8607  * dumpProcLang
8608  *                writes out to fout the queries to recreate a user-defined
8609  *                procedural language
8610  */
8611 static void
8612 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8613 {
8614         PQExpBuffer defqry;
8615         PQExpBuffer delqry;
8616         PQExpBuffer labelq;
8617         bool            useParams;
8618         char       *qlanname;
8619         char       *lanschema;
8620         FuncInfo   *funcInfo;
8621         FuncInfo   *inlineInfo = NULL;
8622         FuncInfo   *validatorInfo = NULL;
8623
8624         /* Skip if not to be dumped */
8625         if (!plang->dobj.dump || dataOnly)
8626                 return;
8627
8628         /*
8629          * Try to find the support function(s).  It is not an error if we don't
8630          * find them --- if the functions are in the pg_catalog schema, as is
8631          * standard in 8.1 and up, then we won't have loaded them. (In this case
8632          * we will emit a parameterless CREATE LANGUAGE command, which will
8633          * require PL template knowledge in the backend to reload.)
8634          */
8635
8636         funcInfo = findFuncByOid(plang->lanplcallfoid);
8637         if (funcInfo != NULL && !funcInfo->dobj.dump)
8638                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8639
8640         if (OidIsValid(plang->laninline))
8641         {
8642                 inlineInfo = findFuncByOid(plang->laninline);
8643                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8644                         inlineInfo = NULL;
8645         }
8646
8647         if (OidIsValid(plang->lanvalidator))
8648         {
8649                 validatorInfo = findFuncByOid(plang->lanvalidator);
8650                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8651                         validatorInfo = NULL;
8652         }
8653
8654         /*
8655          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8656          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8657          * dump it.
8658          *
8659          * However, for a language that belongs to an extension, we must not use
8660          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8661          * told to (via dobj.dump).  Generally the support functions will belong
8662          * to the same extension and so have the same dump flags ... if they
8663          * don't, this might not work terribly nicely.
8664          */
8665         useParams = (funcInfo != NULL &&
8666                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8667                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8668
8669         if (!plang->dobj.ext_member)
8670         {
8671                 if (!useParams && !shouldDumpProcLangs())
8672                         return;
8673         }
8674
8675         defqry = createPQExpBuffer();
8676         delqry = createPQExpBuffer();
8677         labelq = createPQExpBuffer();
8678
8679         qlanname = pg_strdup(fmtId(plang->dobj.name));
8680
8681         /*
8682          * If dumping a HANDLER clause, treat the language as being in the handler
8683          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8684          * it doesn't really have a schema.
8685          */
8686         if (useParams)
8687                 lanschema = funcInfo->dobj.namespace->dobj.name;
8688         else
8689                 lanschema = NULL;
8690
8691         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8692                                           qlanname);
8693
8694         if (useParams)
8695         {
8696                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8697                                                   plang->lanpltrusted ? "TRUSTED " : "",
8698                                                   qlanname);
8699                 appendPQExpBuffer(defqry, " HANDLER %s",
8700                                                   fmtId(funcInfo->dobj.name));
8701                 if (OidIsValid(plang->laninline))
8702                 {
8703                         appendPQExpBuffer(defqry, " INLINE ");
8704                         /* Cope with possibility that inline is in different schema */
8705                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8706                                 appendPQExpBuffer(defqry, "%s.",
8707                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8708                         appendPQExpBuffer(defqry, "%s",
8709                                                           fmtId(inlineInfo->dobj.name));
8710                 }
8711                 if (OidIsValid(plang->lanvalidator))
8712                 {
8713                         appendPQExpBuffer(defqry, " VALIDATOR ");
8714                         /* Cope with possibility that validator is in different schema */
8715                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8716                                 appendPQExpBuffer(defqry, "%s.",
8717                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8718                         appendPQExpBuffer(defqry, "%s",
8719                                                           fmtId(validatorInfo->dobj.name));
8720                 }
8721         }
8722         else
8723         {
8724                 /*
8725                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8726                  * command will not fail if the language is preinstalled in the target
8727                  * database.  We restrict the use of REPLACE to this case so as to
8728                  * eliminate the risk of replacing a language with incompatible
8729                  * parameter settings: this command will only succeed at all if there
8730                  * is a pg_pltemplate entry, and if there is one, the existing entry
8731                  * must match it too.
8732                  */
8733                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8734                                                   qlanname);
8735         }
8736         appendPQExpBuffer(defqry, ";\n");
8737
8738         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8739
8740         if (binary_upgrade)
8741                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8742
8743         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8744                                  plang->dobj.name,
8745                                  lanschema, NULL, plang->lanowner,
8746                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8747                                  defqry->data, delqry->data, NULL,
8748                                  NULL, 0,
8749                                  NULL, NULL);
8750
8751         /* Dump Proc Lang Comments and Security Labels */
8752         dumpComment(fout, labelq->data,
8753                                 NULL, "",
8754                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8755         dumpSecLabel(fout, labelq->data,
8756                                  NULL, "",
8757                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8758
8759         if (plang->lanpltrusted)
8760                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8761                                 qlanname, NULL, plang->dobj.name,
8762                                 lanschema,
8763                                 plang->lanowner, plang->lanacl);
8764
8765         free(qlanname);
8766
8767         destroyPQExpBuffer(defqry);
8768         destroyPQExpBuffer(delqry);
8769         destroyPQExpBuffer(labelq);
8770 }
8771
8772 /*
8773  * format_function_arguments: generate function name and argument list
8774  *
8775  * This is used when we can rely on pg_get_function_arguments to format
8776  * the argument list.
8777  */
8778 static char *
8779 format_function_arguments(FuncInfo *finfo, char *funcargs)
8780 {
8781         PQExpBufferData fn;
8782
8783         initPQExpBuffer(&fn);
8784         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8785         return fn.data;
8786 }
8787
8788 /*
8789  * format_function_arguments_old: generate function name and argument list
8790  *
8791  * The argument type names are qualified if needed.  The function name
8792  * is never qualified.
8793  *
8794  * This is used only with pre-8.4 servers, so we aren't expecting to see
8795  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8796  *
8797  * Any or all of allargtypes, argmodes, argnames may be NULL.
8798  */
8799 static char *
8800 format_function_arguments_old(Archive *fout,
8801                                                           FuncInfo *finfo, int nallargs,
8802                                                           char **allargtypes,
8803                                                           char **argmodes,
8804                                                           char **argnames)
8805 {
8806         PQExpBufferData fn;
8807         int                     j;
8808
8809         initPQExpBuffer(&fn);
8810         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8811         for (j = 0; j < nallargs; j++)
8812         {
8813                 Oid                     typid;
8814                 char       *typname;
8815                 const char *argmode;
8816                 const char *argname;
8817
8818                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8819                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8820
8821                 if (argmodes)
8822                 {
8823                         switch (argmodes[j][0])
8824                         {
8825                                 case PROARGMODE_IN:
8826                                         argmode = "";
8827                                         break;
8828                                 case PROARGMODE_OUT:
8829                                         argmode = "OUT ";
8830                                         break;
8831                                 case PROARGMODE_INOUT:
8832                                         argmode = "INOUT ";
8833                                         break;
8834                                 default:
8835                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8836                                         argmode = "";
8837                                         break;
8838                         }
8839                 }
8840                 else
8841                         argmode = "";
8842
8843                 argname = argnames ? argnames[j] : (char *) NULL;
8844                 if (argname && argname[0] == '\0')
8845                         argname = NULL;
8846
8847                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8848                                                   (j > 0) ? ", " : "",
8849                                                   argmode,
8850                                                   argname ? fmtId(argname) : "",
8851                                                   argname ? " " : "",
8852                                                   typname);
8853                 free(typname);
8854         }
8855         appendPQExpBuffer(&fn, ")");
8856         return fn.data;
8857 }
8858
8859 /*
8860  * format_function_signature: generate function name and argument list
8861  *
8862  * This is like format_function_arguments_old except that only a minimal
8863  * list of input argument types is generated; this is sufficient to
8864  * reference the function, but not to define it.
8865  *
8866  * If honor_quotes is false then the function name is never quoted.
8867  * This is appropriate for use in TOC tags, but not in SQL commands.
8868  */
8869 static char *
8870 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8871 {
8872         PQExpBufferData fn;
8873         int                     j;
8874
8875         initPQExpBuffer(&fn);
8876         if (honor_quotes)
8877                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8878         else
8879                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8880         for (j = 0; j < finfo->nargs; j++)
8881         {
8882                 char       *typname;
8883
8884                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8885                                                                            zeroAsOpaque);
8886
8887                 appendPQExpBuffer(&fn, "%s%s",
8888                                                   (j > 0) ? ", " : "",
8889                                                   typname);
8890                 free(typname);
8891         }
8892         appendPQExpBuffer(&fn, ")");
8893         return fn.data;
8894 }
8895
8896
8897 /*
8898  * dumpFunc:
8899  *        dump out one function
8900  */
8901 static void
8902 dumpFunc(Archive *fout, FuncInfo *finfo)
8903 {
8904         PQExpBuffer query;
8905         PQExpBuffer q;
8906         PQExpBuffer delqry;
8907         PQExpBuffer labelq;
8908         PQExpBuffer asPart;
8909         PGresult   *res;
8910         char       *funcsig;            /* identity signature */
8911         char       *funcfullsig;        /* full signature */
8912         char       *funcsig_tag;
8913         char       *proretset;
8914         char       *prosrc;
8915         char       *probin;
8916         char       *funcargs;
8917         char       *funciargs;
8918         char       *funcresult;
8919         char       *proallargtypes;
8920         char       *proargmodes;
8921         char       *proargnames;
8922         char       *proiswindow;
8923         char       *provolatile;
8924         char       *proisstrict;
8925         char       *prosecdef;
8926         char       *proleakproof;
8927         char       *proconfig;
8928         char       *procost;
8929         char       *prorows;
8930         char       *lanname;
8931         char       *rettypename;
8932         int                     nallargs;
8933         char      **allargtypes = NULL;
8934         char      **argmodes = NULL;
8935         char      **argnames = NULL;
8936         char      **configitems = NULL;
8937         int                     nconfigitems = 0;
8938         int                     i;
8939
8940         /* Skip if not to be dumped */
8941         if (!finfo->dobj.dump || dataOnly)
8942                 return;
8943
8944         query = createPQExpBuffer();
8945         q = createPQExpBuffer();
8946         delqry = createPQExpBuffer();
8947         labelq = createPQExpBuffer();
8948         asPart = createPQExpBuffer();
8949
8950         /* Set proper schema search path so type references list correctly */
8951         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8952
8953         /* Fetch function-specific details */
8954         if (fout->remoteVersion >= 90200)
8955         {
8956                 /*
8957                  * proleakproof was added at v9.2
8958                  */
8959                 appendPQExpBuffer(query,
8960                                                   "SELECT proretset, prosrc, probin, "
8961                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8962                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8963                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8964                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8965                                                   "proleakproof, proconfig, procost, prorows, "
8966                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8967                                                   "FROM pg_catalog.pg_proc "
8968                                                   "WHERE oid = '%u'::pg_catalog.oid",
8969                                                   finfo->dobj.catId.oid);
8970         }
8971         else if (fout->remoteVersion >= 80400)
8972         {
8973                 /*
8974                  * In 8.4 and up we rely on pg_get_function_arguments and
8975                  * pg_get_function_result instead of examining proallargtypes etc.
8976                  */
8977                 appendPQExpBuffer(query,
8978                                                   "SELECT proretset, prosrc, probin, "
8979                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8980                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8981                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8982                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8983                                                   "false AS proleakproof, "
8984                                                   " proconfig, procost, prorows, "
8985                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8986                                                   "FROM pg_catalog.pg_proc "
8987                                                   "WHERE oid = '%u'::pg_catalog.oid",
8988                                                   finfo->dobj.catId.oid);
8989         }
8990         else if (fout->remoteVersion >= 80300)
8991         {
8992                 appendPQExpBuffer(query,
8993                                                   "SELECT proretset, prosrc, probin, "
8994                                                   "proallargtypes, proargmodes, proargnames, "
8995                                                   "false AS proiswindow, "
8996                                                   "provolatile, proisstrict, prosecdef, "
8997                                                   "false AS proleakproof, "
8998                                                   "proconfig, procost, prorows, "
8999                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9000                                                   "FROM pg_catalog.pg_proc "
9001                                                   "WHERE oid = '%u'::pg_catalog.oid",
9002                                                   finfo->dobj.catId.oid);
9003         }
9004         else if (fout->remoteVersion >= 80100)
9005         {
9006                 appendPQExpBuffer(query,
9007                                                   "SELECT proretset, prosrc, probin, "
9008                                                   "proallargtypes, proargmodes, proargnames, "
9009                                                   "false AS proiswindow, "
9010                                                   "provolatile, proisstrict, prosecdef, "
9011                                                   "false AS proleakproof, "
9012                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9013                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9014                                                   "FROM pg_catalog.pg_proc "
9015                                                   "WHERE oid = '%u'::pg_catalog.oid",
9016                                                   finfo->dobj.catId.oid);
9017         }
9018         else if (fout->remoteVersion >= 80000)
9019         {
9020                 appendPQExpBuffer(query,
9021                                                   "SELECT proretset, prosrc, probin, "
9022                                                   "null AS proallargtypes, "
9023                                                   "null AS proargmodes, "
9024                                                   "proargnames, "
9025                                                   "false AS proiswindow, "
9026                                                   "provolatile, proisstrict, prosecdef, "
9027                                                   "false AS proleakproof, "
9028                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9029                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9030                                                   "FROM pg_catalog.pg_proc "
9031                                                   "WHERE oid = '%u'::pg_catalog.oid",
9032                                                   finfo->dobj.catId.oid);
9033         }
9034         else if (fout->remoteVersion >= 70300)
9035         {
9036                 appendPQExpBuffer(query,
9037                                                   "SELECT proretset, prosrc, probin, "
9038                                                   "null AS proallargtypes, "
9039                                                   "null AS proargmodes, "
9040                                                   "null AS proargnames, "
9041                                                   "false AS proiswindow, "
9042                                                   "provolatile, proisstrict, prosecdef, "
9043                                                   "false AS proleakproof, "
9044                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9045                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9046                                                   "FROM pg_catalog.pg_proc "
9047                                                   "WHERE oid = '%u'::pg_catalog.oid",
9048                                                   finfo->dobj.catId.oid);
9049         }
9050         else if (fout->remoteVersion >= 70100)
9051         {
9052                 appendPQExpBuffer(query,
9053                                                   "SELECT proretset, prosrc, probin, "
9054                                                   "null AS proallargtypes, "
9055                                                   "null AS proargmodes, "
9056                                                   "null AS proargnames, "
9057                                                   "false AS proiswindow, "
9058                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9059                                                   "proisstrict, "
9060                                                   "false AS prosecdef, "
9061                                                   "false AS proleakproof, "
9062                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9063                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9064                                                   "FROM pg_proc "
9065                                                   "WHERE oid = '%u'::oid",
9066                                                   finfo->dobj.catId.oid);
9067         }
9068         else
9069         {
9070                 appendPQExpBuffer(query,
9071                                                   "SELECT proretset, prosrc, probin, "
9072                                                   "null AS proallargtypes, "
9073                                                   "null AS proargmodes, "
9074                                                   "null AS proargnames, "
9075                                                   "false AS proiswindow, "
9076                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9077                                                   "false AS proisstrict, "
9078                                                   "false AS prosecdef, "
9079                                                   "false AS proleakproof, "
9080                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9081                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9082                                                   "FROM pg_proc "
9083                                                   "WHERE oid = '%u'::oid",
9084                                                   finfo->dobj.catId.oid);
9085         }
9086
9087         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9088
9089         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9090         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9091         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9092         if (fout->remoteVersion >= 80400)
9093         {
9094                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9095                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9096                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9097                 proallargtypes = proargmodes = proargnames = NULL;
9098         }
9099         else
9100         {
9101                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9102                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9103                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9104                 funcargs = funciargs = funcresult = NULL;
9105         }
9106         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9107         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9108         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9109         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9110         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9111         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9112         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9113         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9114         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9115
9116         /*
9117          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9118          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9119          * versions would set it to "-".  There are no known cases in which prosrc
9120          * is unused, so the tests below for "-" are probably useless.
9121          */
9122         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9123         {
9124                 appendPQExpBuffer(asPart, "AS ");
9125                 appendStringLiteralAH(asPart, probin, fout);
9126                 if (strcmp(prosrc, "-") != 0)
9127                 {
9128                         appendPQExpBuffer(asPart, ", ");
9129
9130                         /*
9131                          * where we have bin, use dollar quoting if allowed and src
9132                          * contains quote or backslash; else use regular quoting.
9133                          */
9134                         if (disable_dollar_quoting ||
9135                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9136                                 appendStringLiteralAH(asPart, prosrc, fout);
9137                         else
9138                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9139                 }
9140         }
9141         else
9142         {
9143                 if (strcmp(prosrc, "-") != 0)
9144                 {
9145                         appendPQExpBuffer(asPart, "AS ");
9146                         /* with no bin, dollar quote src unconditionally if allowed */
9147                         if (disable_dollar_quoting)
9148                                 appendStringLiteralAH(asPart, prosrc, fout);
9149                         else
9150                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9151                 }
9152         }
9153
9154         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9155
9156         if (proallargtypes && *proallargtypes)
9157         {
9158                 int                     nitems = 0;
9159
9160                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9161                         nitems < finfo->nargs)
9162                 {
9163                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9164                         if (allargtypes)
9165                                 free(allargtypes);
9166                         allargtypes = NULL;
9167                 }
9168                 else
9169                         nallargs = nitems;
9170         }
9171
9172         if (proargmodes && *proargmodes)
9173         {
9174                 int                     nitems = 0;
9175
9176                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9177                         nitems != nallargs)
9178                 {
9179                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9180                         if (argmodes)
9181                                 free(argmodes);
9182                         argmodes = NULL;
9183                 }
9184         }
9185
9186         if (proargnames && *proargnames)
9187         {
9188                 int                     nitems = 0;
9189
9190                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9191                         nitems != nallargs)
9192                 {
9193                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9194                         if (argnames)
9195                                 free(argnames);
9196                         argnames = NULL;
9197                 }
9198         }
9199
9200         if (proconfig && *proconfig)
9201         {
9202                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9203                 {
9204                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9205                         if (configitems)
9206                                 free(configitems);
9207                         configitems = NULL;
9208                         nconfigitems = 0;
9209                 }
9210         }
9211
9212         if (funcargs)
9213         {
9214                 /* 8.4 or later; we rely on server-side code for most of the work */
9215                 funcfullsig = format_function_arguments(finfo, funcargs);
9216                 funcsig = format_function_arguments(finfo, funciargs);
9217         }
9218         else
9219         {
9220                 /* pre-8.4, do it ourselves */
9221                 funcsig = format_function_arguments_old(fout,
9222                                                                                                 finfo, nallargs, allargtypes,
9223                                                                                                 argmodes, argnames);
9224                 funcfullsig = funcsig;
9225         }
9226
9227         funcsig_tag = format_function_signature(fout, finfo, false);
9228
9229         /*
9230          * DROP must be fully qualified in case same name appears in pg_catalog
9231          */
9232         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9233                                           fmtId(finfo->dobj.namespace->dobj.name),
9234                                           funcsig);
9235
9236         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9237         if (funcresult)
9238                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9239         else
9240         {
9241                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9242                                                                                    zeroAsOpaque);
9243                 appendPQExpBuffer(q, "RETURNS %s%s",
9244                                                   (proretset[0] == 't') ? "SETOF " : "",
9245                                                   rettypename);
9246                 free(rettypename);
9247         }
9248
9249         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9250
9251         if (proiswindow[0] == 't')
9252                 appendPQExpBuffer(q, " WINDOW");
9253
9254         if (provolatile[0] != PROVOLATILE_VOLATILE)
9255         {
9256                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9257                         appendPQExpBuffer(q, " IMMUTABLE");
9258                 else if (provolatile[0] == PROVOLATILE_STABLE)
9259                         appendPQExpBuffer(q, " STABLE");
9260                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9261                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9262                                                   finfo->dobj.name);
9263         }
9264
9265         if (proisstrict[0] == 't')
9266                 appendPQExpBuffer(q, " STRICT");
9267
9268         if (prosecdef[0] == 't')
9269                 appendPQExpBuffer(q, " SECURITY DEFINER");
9270
9271         if (proleakproof[0] == 't')
9272                 appendPQExpBuffer(q, " LEAKPROOF");
9273
9274         /*
9275          * COST and ROWS are emitted only if present and not default, so as not to
9276          * break backwards-compatibility of the dump without need.      Keep this code
9277          * in sync with the defaults in functioncmds.c.
9278          */
9279         if (strcmp(procost, "0") != 0)
9280         {
9281                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9282                 {
9283                         /* default cost is 1 */
9284                         if (strcmp(procost, "1") != 0)
9285                                 appendPQExpBuffer(q, " COST %s", procost);
9286                 }
9287                 else
9288                 {
9289                         /* default cost is 100 */
9290                         if (strcmp(procost, "100") != 0)
9291                                 appendPQExpBuffer(q, " COST %s", procost);
9292                 }
9293         }
9294         if (proretset[0] == 't' &&
9295                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9296                 appendPQExpBuffer(q, " ROWS %s", prorows);
9297
9298         for (i = 0; i < nconfigitems; i++)
9299         {
9300                 /* we feel free to scribble on configitems[] here */
9301                 char       *configitem = configitems[i];
9302                 char       *pos;
9303
9304                 pos = strchr(configitem, '=');
9305                 if (pos == NULL)
9306                         continue;
9307                 *pos++ = '\0';
9308                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9309
9310                 /*
9311                  * Some GUC variable names are 'LIST' type and hence must not be
9312                  * quoted.
9313                  */
9314                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9315                         || pg_strcasecmp(configitem, "search_path") == 0)
9316                         appendPQExpBuffer(q, "%s", pos);
9317                 else
9318                         appendStringLiteralAH(q, pos, fout);
9319         }
9320
9321         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9322
9323         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9324
9325         if (binary_upgrade)
9326                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9327
9328         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9329                                  funcsig_tag,
9330                                  finfo->dobj.namespace->dobj.name,
9331                                  NULL,
9332                                  finfo->rolname, false,
9333                                  "FUNCTION", SECTION_PRE_DATA,
9334                                  q->data, delqry->data, NULL,
9335                                  NULL, 0,
9336                                  NULL, NULL);
9337
9338         /* Dump Function Comments and Security Labels */
9339         dumpComment(fout, labelq->data,
9340                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9341                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9342         dumpSecLabel(fout, labelq->data,
9343                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9344                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9345
9346         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9347                         funcsig, NULL, funcsig_tag,
9348                         finfo->dobj.namespace->dobj.name,
9349                         finfo->rolname, finfo->proacl);
9350
9351         PQclear(res);
9352
9353         destroyPQExpBuffer(query);
9354         destroyPQExpBuffer(q);
9355         destroyPQExpBuffer(delqry);
9356         destroyPQExpBuffer(labelq);
9357         destroyPQExpBuffer(asPart);
9358         free(funcsig);
9359         free(funcsig_tag);
9360         if (allargtypes)
9361                 free(allargtypes);
9362         if (argmodes)
9363                 free(argmodes);
9364         if (argnames)
9365                 free(argnames);
9366         if (configitems)
9367                 free(configitems);
9368 }
9369
9370
9371 /*
9372  * Dump a user-defined cast
9373  */
9374 static void
9375 dumpCast(Archive *fout, CastInfo *cast)
9376 {
9377         PQExpBuffer defqry;
9378         PQExpBuffer delqry;
9379         PQExpBuffer labelq;
9380         FuncInfo   *funcInfo = NULL;
9381
9382         /* Skip if not to be dumped */
9383         if (!cast->dobj.dump || dataOnly)
9384                 return;
9385
9386         /* Cannot dump if we don't have the cast function's info */
9387         if (OidIsValid(cast->castfunc))
9388         {
9389                 funcInfo = findFuncByOid(cast->castfunc);
9390                 if (funcInfo == NULL)
9391                         return;
9392         }
9393
9394         /*
9395          * As per discussion we dump casts if one or more of the underlying
9396          * objects (the conversion function and the two data types) are not
9397          * builtin AND if all of the non-builtin objects are included in the dump.
9398          * Builtin meaning, the namespace name does not start with "pg_".
9399          *
9400          * However, for a cast that belongs to an extension, we must not use this
9401          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9402          */
9403         if (!cast->dobj.ext_member)
9404         {
9405                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9406                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9407
9408                 if (sourceInfo == NULL || targetInfo == NULL)
9409                         return;
9410
9411                 /*
9412                  * Skip this cast if all objects are from pg_
9413                  */
9414                 if ((funcInfo == NULL ||
9415                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9416                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9417                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9418                         return;
9419
9420                 /*
9421                  * Skip cast if function isn't from pg_ and is not to be dumped.
9422                  */
9423                 if (funcInfo &&
9424                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9425                         !funcInfo->dobj.dump)
9426                         return;
9427
9428                 /*
9429                  * Same for the source type
9430                  */
9431                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9432                         !sourceInfo->dobj.dump)
9433                         return;
9434
9435                 /*
9436                  * and the target type.
9437                  */
9438                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9439                         !targetInfo->dobj.dump)
9440                         return;
9441         }
9442
9443         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9444         selectSourceSchema(fout, "pg_catalog");
9445
9446         defqry = createPQExpBuffer();
9447         delqry = createPQExpBuffer();
9448         labelq = createPQExpBuffer();
9449
9450         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9451                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9452                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9453
9454         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9455                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9456                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9457
9458         switch (cast->castmethod)
9459         {
9460                 case COERCION_METHOD_BINARY:
9461                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9462                         break;
9463                 case COERCION_METHOD_INOUT:
9464                         appendPQExpBuffer(defqry, "WITH INOUT");
9465                         break;
9466                 case COERCION_METHOD_FUNCTION:
9467                         if (funcInfo)
9468                         {
9469                                 char       *fsig = format_function_signature(fout, funcInfo, true);
9470
9471                                 /*
9472                                  * Always qualify the function name, in case it is not in
9473                                  * pg_catalog schema (format_function_signature won't qualify
9474                                  * it).
9475                                  */
9476                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9477                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9478                                 free(fsig);
9479                         }
9480                         else
9481                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9482                         break;
9483                 default:
9484                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9485         }
9486
9487         if (cast->castcontext == 'a')
9488                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9489         else if (cast->castcontext == 'i')
9490                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9491         appendPQExpBuffer(defqry, ";\n");
9492
9493         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9494                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9495                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9496
9497         if (binary_upgrade)
9498                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9499
9500         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9501                                  labelq->data,
9502                                  "pg_catalog", NULL, "",
9503                                  false, "CAST", SECTION_PRE_DATA,
9504                                  defqry->data, delqry->data, NULL,
9505                                  NULL, 0,
9506                                  NULL, NULL);
9507
9508         /* Dump Cast Comments */
9509         dumpComment(fout, labelq->data,
9510                                 NULL, "",
9511                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9512
9513         destroyPQExpBuffer(defqry);
9514         destroyPQExpBuffer(delqry);
9515         destroyPQExpBuffer(labelq);
9516 }
9517
9518 /*
9519  * dumpOpr
9520  *        write out a single operator definition
9521  */
9522 static void
9523 dumpOpr(Archive *fout, OprInfo *oprinfo)
9524 {
9525         PQExpBuffer query;
9526         PQExpBuffer q;
9527         PQExpBuffer delq;
9528         PQExpBuffer labelq;
9529         PQExpBuffer oprid;
9530         PQExpBuffer details;
9531         const char *name;
9532         PGresult   *res;
9533         int                     i_oprkind;
9534         int                     i_oprcode;
9535         int                     i_oprleft;
9536         int                     i_oprright;
9537         int                     i_oprcom;
9538         int                     i_oprnegate;
9539         int                     i_oprrest;
9540         int                     i_oprjoin;
9541         int                     i_oprcanmerge;
9542         int                     i_oprcanhash;
9543         char       *oprkind;
9544         char       *oprcode;
9545         char       *oprleft;
9546         char       *oprright;
9547         char       *oprcom;
9548         char       *oprnegate;
9549         char       *oprrest;
9550         char       *oprjoin;
9551         char       *oprcanmerge;
9552         char       *oprcanhash;
9553
9554         /* Skip if not to be dumped */
9555         if (!oprinfo->dobj.dump || dataOnly)
9556                 return;
9557
9558         /*
9559          * some operators are invalid because they were the result of user
9560          * defining operators before commutators exist
9561          */
9562         if (!OidIsValid(oprinfo->oprcode))
9563                 return;
9564
9565         query = createPQExpBuffer();
9566         q = createPQExpBuffer();
9567         delq = createPQExpBuffer();
9568         labelq = createPQExpBuffer();
9569         oprid = createPQExpBuffer();
9570         details = createPQExpBuffer();
9571
9572         /* Make sure we are in proper schema so regoperator works correctly */
9573         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9574
9575         if (fout->remoteVersion >= 80300)
9576         {
9577                 appendPQExpBuffer(query, "SELECT oprkind, "
9578                                                   "oprcode::pg_catalog.regprocedure, "
9579                                                   "oprleft::pg_catalog.regtype, "
9580                                                   "oprright::pg_catalog.regtype, "
9581                                                   "oprcom::pg_catalog.regoperator, "
9582                                                   "oprnegate::pg_catalog.regoperator, "
9583                                                   "oprrest::pg_catalog.regprocedure, "
9584                                                   "oprjoin::pg_catalog.regprocedure, "
9585                                                   "oprcanmerge, oprcanhash "
9586                                                   "FROM pg_catalog.pg_operator "
9587                                                   "WHERE oid = '%u'::pg_catalog.oid",
9588                                                   oprinfo->dobj.catId.oid);
9589         }
9590         else if (fout->remoteVersion >= 70300)
9591         {
9592                 appendPQExpBuffer(query, "SELECT oprkind, "
9593                                                   "oprcode::pg_catalog.regprocedure, "
9594                                                   "oprleft::pg_catalog.regtype, "
9595                                                   "oprright::pg_catalog.regtype, "
9596                                                   "oprcom::pg_catalog.regoperator, "
9597                                                   "oprnegate::pg_catalog.regoperator, "
9598                                                   "oprrest::pg_catalog.regprocedure, "
9599                                                   "oprjoin::pg_catalog.regprocedure, "
9600                                                   "(oprlsortop != 0) AS oprcanmerge, "
9601                                                   "oprcanhash "
9602                                                   "FROM pg_catalog.pg_operator "
9603                                                   "WHERE oid = '%u'::pg_catalog.oid",
9604                                                   oprinfo->dobj.catId.oid);
9605         }
9606         else if (fout->remoteVersion >= 70100)
9607         {
9608                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9609                                                   "CASE WHEN oprleft = 0 THEN '-' "
9610                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9611                                                   "CASE WHEN oprright = 0 THEN '-' "
9612                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9613                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9614                                                   "(oprlsortop != 0) AS oprcanmerge, "
9615                                                   "oprcanhash "
9616                                                   "FROM pg_operator "
9617                                                   "WHERE oid = '%u'::oid",
9618                                                   oprinfo->dobj.catId.oid);
9619         }
9620         else
9621         {
9622                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9623                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9624                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9625                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9626                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9627                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9628                                                   "(oprlsortop != 0) AS oprcanmerge, "
9629                                                   "oprcanhash "
9630                                                   "FROM pg_operator "
9631                                                   "WHERE oid = '%u'::oid",
9632                                                   oprinfo->dobj.catId.oid);
9633         }
9634
9635         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9636
9637         i_oprkind = PQfnumber(res, "oprkind");
9638         i_oprcode = PQfnumber(res, "oprcode");
9639         i_oprleft = PQfnumber(res, "oprleft");
9640         i_oprright = PQfnumber(res, "oprright");
9641         i_oprcom = PQfnumber(res, "oprcom");
9642         i_oprnegate = PQfnumber(res, "oprnegate");
9643         i_oprrest = PQfnumber(res, "oprrest");
9644         i_oprjoin = PQfnumber(res, "oprjoin");
9645         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9646         i_oprcanhash = PQfnumber(res, "oprcanhash");
9647
9648         oprkind = PQgetvalue(res, 0, i_oprkind);
9649         oprcode = PQgetvalue(res, 0, i_oprcode);
9650         oprleft = PQgetvalue(res, 0, i_oprleft);
9651         oprright = PQgetvalue(res, 0, i_oprright);
9652         oprcom = PQgetvalue(res, 0, i_oprcom);
9653         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9654         oprrest = PQgetvalue(res, 0, i_oprrest);
9655         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9656         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9657         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9658
9659         appendPQExpBuffer(details, "    PROCEDURE = %s",
9660                                           convertRegProcReference(fout, oprcode));
9661
9662         appendPQExpBuffer(oprid, "%s (",
9663                                           oprinfo->dobj.name);
9664
9665         /*
9666          * right unary means there's a left arg and left unary means there's a
9667          * right arg
9668          */
9669         if (strcmp(oprkind, "r") == 0 ||
9670                 strcmp(oprkind, "b") == 0)
9671         {
9672                 if (fout->remoteVersion >= 70100)
9673                         name = oprleft;
9674                 else
9675                         name = fmtId(oprleft);
9676                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9677                 appendPQExpBuffer(oprid, "%s", name);
9678         }
9679         else
9680                 appendPQExpBuffer(oprid, "NONE");
9681
9682         if (strcmp(oprkind, "l") == 0 ||
9683                 strcmp(oprkind, "b") == 0)
9684         {
9685                 if (fout->remoteVersion >= 70100)
9686                         name = oprright;
9687                 else
9688                         name = fmtId(oprright);
9689                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9690                 appendPQExpBuffer(oprid, ", %s)", name);
9691         }
9692         else
9693                 appendPQExpBuffer(oprid, ", NONE)");
9694
9695         name = convertOperatorReference(fout, oprcom);
9696         if (name)
9697                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9698
9699         name = convertOperatorReference(fout, oprnegate);
9700         if (name)
9701                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9702
9703         if (strcmp(oprcanmerge, "t") == 0)
9704                 appendPQExpBuffer(details, ",\n    MERGES");
9705
9706         if (strcmp(oprcanhash, "t") == 0)
9707                 appendPQExpBuffer(details, ",\n    HASHES");
9708
9709         name = convertRegProcReference(fout, oprrest);
9710         if (name)
9711                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9712
9713         name = convertRegProcReference(fout, oprjoin);
9714         if (name)
9715                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9716
9717         /*
9718          * DROP must be fully qualified in case same name appears in pg_catalog
9719          */
9720         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9721                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9722                                           oprid->data);
9723
9724         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9725                                           oprinfo->dobj.name, details->data);
9726
9727         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9728
9729         if (binary_upgrade)
9730                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9731
9732         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9733                                  oprinfo->dobj.name,
9734                                  oprinfo->dobj.namespace->dobj.name,
9735                                  NULL,
9736                                  oprinfo->rolname,
9737                                  false, "OPERATOR", SECTION_PRE_DATA,
9738                                  q->data, delq->data, NULL,
9739                                  NULL, 0,
9740                                  NULL, NULL);
9741
9742         /* Dump Operator Comments */
9743         dumpComment(fout, labelq->data,
9744                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9745                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9746
9747         PQclear(res);
9748
9749         destroyPQExpBuffer(query);
9750         destroyPQExpBuffer(q);
9751         destroyPQExpBuffer(delq);
9752         destroyPQExpBuffer(labelq);
9753         destroyPQExpBuffer(oprid);
9754         destroyPQExpBuffer(details);
9755 }
9756
9757 /*
9758  * Convert a function reference obtained from pg_operator
9759  *
9760  * Returns what to print, or NULL if function references is InvalidOid
9761  *
9762  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9763  * argument-types part.  In prior versions, the input is a REGPROC display.
9764  */
9765 static const char *
9766 convertRegProcReference(Archive *fout, const char *proc)
9767 {
9768         /* In all cases "-" means a null reference */
9769         if (strcmp(proc, "-") == 0)
9770                 return NULL;
9771
9772         if (fout->remoteVersion >= 70300)
9773         {
9774                 char       *name;
9775                 char       *paren;
9776                 bool            inquote;
9777
9778                 name = pg_strdup(proc);
9779                 /* find non-double-quoted left paren */
9780                 inquote = false;
9781                 for (paren = name; *paren; paren++)
9782                 {
9783                         if (*paren == '(' && !inquote)
9784                         {
9785                                 *paren = '\0';
9786                                 break;
9787                         }
9788                         if (*paren == '"')
9789                                 inquote = !inquote;
9790                 }
9791                 return name;
9792         }
9793
9794         /* REGPROC before 7.3 does not quote its result */
9795         return fmtId(proc);
9796 }
9797
9798 /*
9799  * Convert an operator cross-reference obtained from pg_operator
9800  *
9801  * Returns what to print, or NULL to print nothing
9802  *
9803  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9804  * argument-types part, and add OPERATOR() decoration if the name is
9805  * schema-qualified.  In older versions, the input is just a numeric OID,
9806  * which we search our operator list for.
9807  */
9808 static const char *
9809 convertOperatorReference(Archive *fout, const char *opr)
9810 {
9811         OprInfo    *oprInfo;
9812
9813         /* In all cases "0" means a null reference */
9814         if (strcmp(opr, "0") == 0)
9815                 return NULL;
9816
9817         if (fout->remoteVersion >= 70300)
9818         {
9819                 char       *name;
9820                 char       *oname;
9821                 char       *ptr;
9822                 bool            inquote;
9823                 bool            sawdot;
9824
9825                 name = pg_strdup(opr);
9826                 /* find non-double-quoted left paren, and check for non-quoted dot */
9827                 inquote = false;
9828                 sawdot = false;
9829                 for (ptr = name; *ptr; ptr++)
9830                 {
9831                         if (*ptr == '"')
9832                                 inquote = !inquote;
9833                         else if (*ptr == '.' && !inquote)
9834                                 sawdot = true;
9835                         else if (*ptr == '(' && !inquote)
9836                         {
9837                                 *ptr = '\0';
9838                                 break;
9839                         }
9840                 }
9841                 /* If not schema-qualified, don't need to add OPERATOR() */
9842                 if (!sawdot)
9843                         return name;
9844                 oname = pg_malloc(strlen(name) + 11);
9845                 sprintf(oname, "OPERATOR(%s)", name);
9846                 free(name);
9847                 return oname;
9848         }
9849
9850         oprInfo = findOprByOid(atooid(opr));
9851         if (oprInfo == NULL)
9852         {
9853                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9854                                   opr);
9855                 return NULL;
9856         }
9857         return oprInfo->dobj.name;
9858 }
9859
9860 /*
9861  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9862  *
9863  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9864  * argument lists of these functions are predetermined.  Note that the
9865  * caller should ensure we are in the proper schema, because the results
9866  * are search path dependent!
9867  */
9868 static const char *
9869 convertTSFunction(Archive *fout, Oid funcOid)
9870 {
9871         char       *result;
9872         char            query[128];
9873         PGresult   *res;
9874
9875         snprintf(query, sizeof(query),
9876                          "SELECT '%u'::pg_catalog.regproc", funcOid);
9877         res = ExecuteSqlQueryForSingleRow(fout, query);
9878
9879         result = pg_strdup(PQgetvalue(res, 0, 0));
9880
9881         PQclear(res);
9882
9883         return result;
9884 }
9885
9886
9887 /*
9888  * dumpOpclass
9889  *        write out a single operator class definition
9890  */
9891 static void
9892 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9893 {
9894         PQExpBuffer query;
9895         PQExpBuffer q;
9896         PQExpBuffer delq;
9897         PQExpBuffer labelq;
9898         PGresult   *res;
9899         int                     ntups;
9900         int                     i_opcintype;
9901         int                     i_opckeytype;
9902         int                     i_opcdefault;
9903         int                     i_opcfamily;
9904         int                     i_opcfamilyname;
9905         int                     i_opcfamilynsp;
9906         int                     i_amname;
9907         int                     i_amopstrategy;
9908         int                     i_amopreqcheck;
9909         int                     i_amopopr;
9910         int                     i_sortfamily;
9911         int                     i_sortfamilynsp;
9912         int                     i_amprocnum;
9913         int                     i_amproc;
9914         int                     i_amproclefttype;
9915         int                     i_amprocrighttype;
9916         char       *opcintype;
9917         char       *opckeytype;
9918         char       *opcdefault;
9919         char       *opcfamily;
9920         char       *opcfamilyname;
9921         char       *opcfamilynsp;
9922         char       *amname;
9923         char       *amopstrategy;
9924         char       *amopreqcheck;
9925         char       *amopopr;
9926         char       *sortfamily;
9927         char       *sortfamilynsp;
9928         char       *amprocnum;
9929         char       *amproc;
9930         char       *amproclefttype;
9931         char       *amprocrighttype;
9932         bool            needComma;
9933         int                     i;
9934
9935         /* Skip if not to be dumped */
9936         if (!opcinfo->dobj.dump || dataOnly)
9937                 return;
9938
9939         /*
9940          * XXX currently we do not implement dumping of operator classes from
9941          * pre-7.3 databases.  This could be done but it seems not worth the
9942          * trouble.
9943          */
9944         if (fout->remoteVersion < 70300)
9945                 return;
9946
9947         query = createPQExpBuffer();
9948         q = createPQExpBuffer();
9949         delq = createPQExpBuffer();
9950         labelq = createPQExpBuffer();
9951
9952         /* Make sure we are in proper schema so regoperator works correctly */
9953         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9954
9955         /* Get additional fields from the pg_opclass row */
9956         if (fout->remoteVersion >= 80300)
9957         {
9958                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9959                                                   "opckeytype::pg_catalog.regtype, "
9960                                                   "opcdefault, opcfamily, "
9961                                                   "opfname AS opcfamilyname, "
9962                                                   "nspname AS opcfamilynsp, "
9963                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9964                                                   "FROM pg_catalog.pg_opclass c "
9965                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9966                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9967                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
9968                                                   opcinfo->dobj.catId.oid);
9969         }
9970         else
9971         {
9972                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9973                                                   "opckeytype::pg_catalog.regtype, "
9974                                                   "opcdefault, NULL AS opcfamily, "
9975                                                   "NULL AS opcfamilyname, "
9976                                                   "NULL AS opcfamilynsp, "
9977                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9978                                                   "FROM pg_catalog.pg_opclass "
9979                                                   "WHERE oid = '%u'::pg_catalog.oid",
9980                                                   opcinfo->dobj.catId.oid);
9981         }
9982
9983         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9984
9985         i_opcintype = PQfnumber(res, "opcintype");
9986         i_opckeytype = PQfnumber(res, "opckeytype");
9987         i_opcdefault = PQfnumber(res, "opcdefault");
9988         i_opcfamily = PQfnumber(res, "opcfamily");
9989         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9990         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9991         i_amname = PQfnumber(res, "amname");
9992
9993         opcintype = PQgetvalue(res, 0, i_opcintype);
9994         opckeytype = PQgetvalue(res, 0, i_opckeytype);
9995         opcdefault = PQgetvalue(res, 0, i_opcdefault);
9996         /* opcfamily will still be needed after we PQclear res */
9997         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9998         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9999         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10000         /* amname will still be needed after we PQclear res */
10001         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10002
10003         /*
10004          * DROP must be fully qualified in case same name appears in pg_catalog
10005          */
10006         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10007                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10008         appendPQExpBuffer(delq, ".%s",
10009                                           fmtId(opcinfo->dobj.name));
10010         appendPQExpBuffer(delq, " USING %s;\n",
10011                                           fmtId(amname));
10012
10013         /* Build the fixed portion of the CREATE command */
10014         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10015                                           fmtId(opcinfo->dobj.name));
10016         if (strcmp(opcdefault, "t") == 0)
10017                 appendPQExpBuffer(q, "DEFAULT ");
10018         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10019                                           opcintype,
10020                                           fmtId(amname));
10021         if (strlen(opcfamilyname) > 0 &&
10022                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10023                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10024         {
10025                 appendPQExpBuffer(q, " FAMILY ");
10026                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10027                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10028                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10029         }
10030         appendPQExpBuffer(q, " AS\n    ");
10031
10032         needComma = false;
10033
10034         if (strcmp(opckeytype, "-") != 0)
10035         {
10036                 appendPQExpBuffer(q, "STORAGE %s",
10037                                                   opckeytype);
10038                 needComma = true;
10039         }
10040
10041         PQclear(res);
10042
10043         /*
10044          * Now fetch and print the OPERATOR entries (pg_amop rows).
10045          *
10046          * Print only those opfamily members that are tied to the opclass by
10047          * pg_depend entries.
10048          *
10049          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10050          * older server's opclass in which it is used.  This is to avoid
10051          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10052          * older server and then reload into that old version.  This can go away
10053          * once 8.3 is so old as to not be of interest to anyone.
10054          */
10055         resetPQExpBuffer(query);
10056
10057         if (fout->remoteVersion >= 90100)
10058         {
10059                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10060                                                   "amopopr::pg_catalog.regoperator, "
10061                                                   "opfname AS sortfamily, "
10062                                                   "nspname AS sortfamilynsp "
10063                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10064                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10065                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10066                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10067                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10068                                                   "AND refobjid = '%u'::pg_catalog.oid "
10069                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10070                                                   "ORDER BY amopstrategy",
10071                                                   opcinfo->dobj.catId.oid,
10072                                                   opcfamily);
10073         }
10074         else if (fout->remoteVersion >= 80400)
10075         {
10076                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10077                                                   "amopopr::pg_catalog.regoperator, "
10078                                                   "NULL AS sortfamily, "
10079                                                   "NULL AS sortfamilynsp "
10080                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10081                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10082                                                   "AND refobjid = '%u'::pg_catalog.oid "
10083                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10084                                                   "AND objid = ao.oid "
10085                                                   "ORDER BY amopstrategy",
10086                                                   opcinfo->dobj.catId.oid);
10087         }
10088         else if (fout->remoteVersion >= 80300)
10089         {
10090                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10091                                                   "amopopr::pg_catalog.regoperator, "
10092                                                   "NULL AS sortfamily, "
10093                                                   "NULL AS sortfamilynsp "
10094                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10095                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10096                                                   "AND refobjid = '%u'::pg_catalog.oid "
10097                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10098                                                   "AND objid = ao.oid "
10099                                                   "ORDER BY amopstrategy",
10100                                                   opcinfo->dobj.catId.oid);
10101         }
10102         else
10103         {
10104                 /*
10105                  * Here, we print all entries since there are no opfamilies and hence
10106                  * no loose operators to worry about.
10107                  */
10108                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10109                                                   "amopopr::pg_catalog.regoperator, "
10110                                                   "NULL AS sortfamily, "
10111                                                   "NULL AS sortfamilynsp "
10112                                                   "FROM pg_catalog.pg_amop "
10113                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10114                                                   "ORDER BY amopstrategy",
10115                                                   opcinfo->dobj.catId.oid);
10116         }
10117
10118         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10119
10120         ntups = PQntuples(res);
10121
10122         i_amopstrategy = PQfnumber(res, "amopstrategy");
10123         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10124         i_amopopr = PQfnumber(res, "amopopr");
10125         i_sortfamily = PQfnumber(res, "sortfamily");
10126         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10127
10128         for (i = 0; i < ntups; i++)
10129         {
10130                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10131                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10132                 amopopr = PQgetvalue(res, i, i_amopopr);
10133                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10134                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10135
10136                 if (needComma)
10137                         appendPQExpBuffer(q, " ,\n    ");
10138
10139                 appendPQExpBuffer(q, "OPERATOR %s %s",
10140                                                   amopstrategy, amopopr);
10141
10142                 if (strlen(sortfamily) > 0)
10143                 {
10144                         appendPQExpBuffer(q, " FOR ORDER BY ");
10145                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10146                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10147                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10148                 }
10149
10150                 if (strcmp(amopreqcheck, "t") == 0)
10151                         appendPQExpBuffer(q, " RECHECK");
10152
10153                 needComma = true;
10154         }
10155
10156         PQclear(res);
10157
10158         /*
10159          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10160          *
10161          * Print only those opfamily members that are tied to the opclass by
10162          * pg_depend entries.
10163          *
10164          * We print the amproclefttype/amprocrighttype even though in most cases
10165          * the backend could deduce the right values, because of the corner case
10166          * of a btree sort support function for a cross-type comparison.  That's
10167          * only allowed in 9.2 and later, but for simplicity print them in all
10168          * versions that have the columns.
10169          */
10170         resetPQExpBuffer(query);
10171
10172         if (fout->remoteVersion >= 80300)
10173         {
10174                 appendPQExpBuffer(query, "SELECT amprocnum, "
10175                                                   "amproc::pg_catalog.regprocedure, "
10176                                                   "amproclefttype::pg_catalog.regtype, "
10177                                                   "amprocrighttype::pg_catalog.regtype "
10178                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10179                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10180                                                   "AND refobjid = '%u'::pg_catalog.oid "
10181                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10182                                                   "AND objid = ap.oid "
10183                                                   "ORDER BY amprocnum",
10184                                                   opcinfo->dobj.catId.oid);
10185         }
10186         else
10187         {
10188                 appendPQExpBuffer(query, "SELECT amprocnum, "
10189                                                   "amproc::pg_catalog.regprocedure, "
10190                                                   "'' AS amproclefttype, "
10191                                                   "'' AS amprocrighttype "
10192                                                   "FROM pg_catalog.pg_amproc "
10193                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10194                                                   "ORDER BY amprocnum",
10195                                                   opcinfo->dobj.catId.oid);
10196         }
10197
10198         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10199
10200         ntups = PQntuples(res);
10201
10202         i_amprocnum = PQfnumber(res, "amprocnum");
10203         i_amproc = PQfnumber(res, "amproc");
10204         i_amproclefttype = PQfnumber(res, "amproclefttype");
10205         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10206
10207         for (i = 0; i < ntups; i++)
10208         {
10209                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10210                 amproc = PQgetvalue(res, i, i_amproc);
10211                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10212                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10213
10214                 if (needComma)
10215                         appendPQExpBuffer(q, " ,\n    ");
10216
10217                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10218
10219                 if (*amproclefttype && *amprocrighttype)
10220                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10221
10222                 appendPQExpBuffer(q, " %s", amproc);
10223
10224                 needComma = true;
10225         }
10226
10227         PQclear(res);
10228
10229         appendPQExpBuffer(q, ";\n");
10230
10231         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10232                                           fmtId(opcinfo->dobj.name));
10233         appendPQExpBuffer(labelq, " USING %s",
10234                                           fmtId(amname));
10235
10236         if (binary_upgrade)
10237                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10238
10239         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10240                                  opcinfo->dobj.name,
10241                                  opcinfo->dobj.namespace->dobj.name,
10242                                  NULL,
10243                                  opcinfo->rolname,
10244                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10245                                  q->data, delq->data, NULL,
10246                                  NULL, 0,
10247                                  NULL, NULL);
10248
10249         /* Dump Operator Class Comments */
10250         dumpComment(fout, labelq->data,
10251                                 NULL, opcinfo->rolname,
10252                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10253
10254         free(amname);
10255         destroyPQExpBuffer(query);
10256         destroyPQExpBuffer(q);
10257         destroyPQExpBuffer(delq);
10258         destroyPQExpBuffer(labelq);
10259 }
10260
10261 /*
10262  * dumpOpfamily
10263  *        write out a single operator family definition
10264  *
10265  * Note: this also dumps any "loose" operator members that aren't bound to a
10266  * specific opclass within the opfamily.
10267  */
10268 static void
10269 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10270 {
10271         PQExpBuffer query;
10272         PQExpBuffer q;
10273         PQExpBuffer delq;
10274         PQExpBuffer labelq;
10275         PGresult   *res;
10276         PGresult   *res_ops;
10277         PGresult   *res_procs;
10278         int                     ntups;
10279         int                     i_amname;
10280         int                     i_amopstrategy;
10281         int                     i_amopreqcheck;
10282         int                     i_amopopr;
10283         int                     i_sortfamily;
10284         int                     i_sortfamilynsp;
10285         int                     i_amprocnum;
10286         int                     i_amproc;
10287         int                     i_amproclefttype;
10288         int                     i_amprocrighttype;
10289         char       *amname;
10290         char       *amopstrategy;
10291         char       *amopreqcheck;
10292         char       *amopopr;
10293         char       *sortfamily;
10294         char       *sortfamilynsp;
10295         char       *amprocnum;
10296         char       *amproc;
10297         char       *amproclefttype;
10298         char       *amprocrighttype;
10299         bool            needComma;
10300         int                     i;
10301
10302         /* Skip if not to be dumped */
10303         if (!opfinfo->dobj.dump || dataOnly)
10304                 return;
10305
10306         /*
10307          * We want to dump the opfamily only if (1) it contains "loose" operators
10308          * or functions, or (2) it contains an opclass with a different name or
10309          * owner.  Otherwise it's sufficient to let it be created during creation
10310          * of the contained opclass, and not dumping it improves portability of
10311          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10312          * that first.
10313          */
10314
10315         query = createPQExpBuffer();
10316         q = createPQExpBuffer();
10317         delq = createPQExpBuffer();
10318         labelq = createPQExpBuffer();
10319
10320         /* Make sure we are in proper schema so regoperator works correctly */
10321         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10322
10323         /*
10324          * Fetch only those opfamily members that are tied directly to the
10325          * opfamily by pg_depend entries.
10326          *
10327          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10328          * older server's opclass in which it is used.  This is to avoid
10329          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10330          * older server and then reload into that old version.  This can go away
10331          * once 8.3 is so old as to not be of interest to anyone.
10332          */
10333         if (fout->remoteVersion >= 90100)
10334         {
10335                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10336                                                   "amopopr::pg_catalog.regoperator, "
10337                                                   "opfname AS sortfamily, "
10338                                                   "nspname AS sortfamilynsp "
10339                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10340                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10341                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10342                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10343                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10344                                                   "AND refobjid = '%u'::pg_catalog.oid "
10345                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10346                                                   "ORDER BY amopstrategy",
10347                                                   opfinfo->dobj.catId.oid,
10348                                                   opfinfo->dobj.catId.oid);
10349         }
10350         else if (fout->remoteVersion >= 80400)
10351         {
10352                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10353                                                   "amopopr::pg_catalog.regoperator, "
10354                                                   "NULL AS sortfamily, "
10355                                                   "NULL AS sortfamilynsp "
10356                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10357                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10358                                                   "AND refobjid = '%u'::pg_catalog.oid "
10359                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10360                                                   "AND objid = ao.oid "
10361                                                   "ORDER BY amopstrategy",
10362                                                   opfinfo->dobj.catId.oid);
10363         }
10364         else
10365         {
10366                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10367                                                   "amopopr::pg_catalog.regoperator, "
10368                                                   "NULL AS sortfamily, "
10369                                                   "NULL AS sortfamilynsp "
10370                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10371                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10372                                                   "AND refobjid = '%u'::pg_catalog.oid "
10373                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10374                                                   "AND objid = ao.oid "
10375                                                   "ORDER BY amopstrategy",
10376                                                   opfinfo->dobj.catId.oid);
10377         }
10378
10379         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10380
10381         resetPQExpBuffer(query);
10382
10383         appendPQExpBuffer(query, "SELECT amprocnum, "
10384                                           "amproc::pg_catalog.regprocedure, "
10385                                           "amproclefttype::pg_catalog.regtype, "
10386                                           "amprocrighttype::pg_catalog.regtype "
10387                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10388                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10389                                           "AND refobjid = '%u'::pg_catalog.oid "
10390                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10391                                           "AND objid = ap.oid "
10392                                           "ORDER BY amprocnum",
10393                                           opfinfo->dobj.catId.oid);
10394
10395         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10396
10397         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10398         {
10399                 /* No loose members, so check contained opclasses */
10400                 resetPQExpBuffer(query);
10401
10402                 appendPQExpBuffer(query, "SELECT 1 "
10403                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10404                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10405                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10406                                                   "AND refobjid = f.oid "
10407                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10408                                                   "AND objid = c.oid "
10409                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10410                                                   "LIMIT 1",
10411                                                   opfinfo->dobj.catId.oid);
10412
10413                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10414
10415                 if (PQntuples(res) == 0)
10416                 {
10417                         /* no need to dump it, so bail out */
10418                         PQclear(res);
10419                         PQclear(res_ops);
10420                         PQclear(res_procs);
10421                         destroyPQExpBuffer(query);
10422                         destroyPQExpBuffer(q);
10423                         destroyPQExpBuffer(delq);
10424                         destroyPQExpBuffer(labelq);
10425                         return;
10426                 }
10427
10428                 PQclear(res);
10429         }
10430
10431         /* Get additional fields from the pg_opfamily row */
10432         resetPQExpBuffer(query);
10433
10434         appendPQExpBuffer(query, "SELECT "
10435          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10436                                           "FROM pg_catalog.pg_opfamily "
10437                                           "WHERE oid = '%u'::pg_catalog.oid",
10438                                           opfinfo->dobj.catId.oid);
10439
10440         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10441
10442         i_amname = PQfnumber(res, "amname");
10443
10444         /* amname will still be needed after we PQclear res */
10445         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10446
10447         /*
10448          * DROP must be fully qualified in case same name appears in pg_catalog
10449          */
10450         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10451                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10452         appendPQExpBuffer(delq, ".%s",
10453                                           fmtId(opfinfo->dobj.name));
10454         appendPQExpBuffer(delq, " USING %s;\n",
10455                                           fmtId(amname));
10456
10457         /* Build the fixed portion of the CREATE command */
10458         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10459                                           fmtId(opfinfo->dobj.name));
10460         appendPQExpBuffer(q, " USING %s;\n",
10461                                           fmtId(amname));
10462
10463         PQclear(res);
10464
10465         /* Do we need an ALTER to add loose members? */
10466         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10467         {
10468                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10469                                                   fmtId(opfinfo->dobj.name));
10470                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10471                                                   fmtId(amname));
10472
10473                 needComma = false;
10474
10475                 /*
10476                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10477                  */
10478                 ntups = PQntuples(res_ops);
10479
10480                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10481                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10482                 i_amopopr = PQfnumber(res_ops, "amopopr");
10483                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10484                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10485
10486                 for (i = 0; i < ntups; i++)
10487                 {
10488                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10489                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10490                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10491                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10492                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10493
10494                         if (needComma)
10495                                 appendPQExpBuffer(q, " ,\n    ");
10496
10497                         appendPQExpBuffer(q, "OPERATOR %s %s",
10498                                                           amopstrategy, amopopr);
10499
10500                         if (strlen(sortfamily) > 0)
10501                         {
10502                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10503                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10504                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10505                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10506                         }
10507
10508                         if (strcmp(amopreqcheck, "t") == 0)
10509                                 appendPQExpBuffer(q, " RECHECK");
10510
10511                         needComma = true;
10512                 }
10513
10514                 /*
10515                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10516                  */
10517                 ntups = PQntuples(res_procs);
10518
10519                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10520                 i_amproc = PQfnumber(res_procs, "amproc");
10521                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10522                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10523
10524                 for (i = 0; i < ntups; i++)
10525                 {
10526                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10527                         amproc = PQgetvalue(res_procs, i, i_amproc);
10528                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10529                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10530
10531                         if (needComma)
10532                                 appendPQExpBuffer(q, " ,\n    ");
10533
10534                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10535                                                           amprocnum, amproclefttype, amprocrighttype,
10536                                                           amproc);
10537
10538                         needComma = true;
10539                 }
10540
10541                 appendPQExpBuffer(q, ";\n");
10542         }
10543
10544         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10545                                           fmtId(opfinfo->dobj.name));
10546         appendPQExpBuffer(labelq, " USING %s",
10547                                           fmtId(amname));
10548
10549         if (binary_upgrade)
10550                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10551
10552         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10553                                  opfinfo->dobj.name,
10554                                  opfinfo->dobj.namespace->dobj.name,
10555                                  NULL,
10556                                  opfinfo->rolname,
10557                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10558                                  q->data, delq->data, NULL,
10559                                  NULL, 0,
10560                                  NULL, NULL);
10561
10562         /* Dump Operator Family Comments */
10563         dumpComment(fout, labelq->data,
10564                                 NULL, opfinfo->rolname,
10565                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10566
10567         free(amname);
10568         PQclear(res_ops);
10569         PQclear(res_procs);
10570         destroyPQExpBuffer(query);
10571         destroyPQExpBuffer(q);
10572         destroyPQExpBuffer(delq);
10573         destroyPQExpBuffer(labelq);
10574 }
10575
10576 /*
10577  * dumpCollation
10578  *        write out a single collation definition
10579  */
10580 static void
10581 dumpCollation(Archive *fout, CollInfo *collinfo)
10582 {
10583         PQExpBuffer query;
10584         PQExpBuffer q;
10585         PQExpBuffer delq;
10586         PQExpBuffer labelq;
10587         PGresult   *res;
10588         int                     i_collcollate;
10589         int                     i_collctype;
10590         const char *collcollate;
10591         const char *collctype;
10592
10593         /* Skip if not to be dumped */
10594         if (!collinfo->dobj.dump || dataOnly)
10595                 return;
10596
10597         query = createPQExpBuffer();
10598         q = createPQExpBuffer();
10599         delq = createPQExpBuffer();
10600         labelq = createPQExpBuffer();
10601
10602         /* Make sure we are in proper schema */
10603         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10604
10605         /* Get conversion-specific details */
10606         appendPQExpBuffer(query, "SELECT "
10607                                           "collcollate, "
10608                                           "collctype "
10609                                           "FROM pg_catalog.pg_collation c "
10610                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10611                                           collinfo->dobj.catId.oid);
10612
10613         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10614
10615         i_collcollate = PQfnumber(res, "collcollate");
10616         i_collctype = PQfnumber(res, "collctype");
10617
10618         collcollate = PQgetvalue(res, 0, i_collcollate);
10619         collctype = PQgetvalue(res, 0, i_collctype);
10620
10621         /*
10622          * DROP must be fully qualified in case same name appears in pg_catalog
10623          */
10624         appendPQExpBuffer(delq, "DROP COLLATION %s",
10625                                           fmtId(collinfo->dobj.namespace->dobj.name));
10626         appendPQExpBuffer(delq, ".%s;\n",
10627                                           fmtId(collinfo->dobj.name));
10628
10629         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10630                                           fmtId(collinfo->dobj.name));
10631         appendStringLiteralAH(q, collcollate, fout);
10632         appendPQExpBuffer(q, ", lc_ctype = ");
10633         appendStringLiteralAH(q, collctype, fout);
10634         appendPQExpBuffer(q, ");\n");
10635
10636         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10637
10638         if (binary_upgrade)
10639                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10640
10641         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10642                                  collinfo->dobj.name,
10643                                  collinfo->dobj.namespace->dobj.name,
10644                                  NULL,
10645                                  collinfo->rolname,
10646                                  false, "COLLATION", SECTION_PRE_DATA,
10647                                  q->data, delq->data, NULL,
10648                                  NULL, 0,
10649                                  NULL, NULL);
10650
10651         /* Dump Collation Comments */
10652         dumpComment(fout, labelq->data,
10653                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10654                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10655
10656         PQclear(res);
10657
10658         destroyPQExpBuffer(query);
10659         destroyPQExpBuffer(q);
10660         destroyPQExpBuffer(delq);
10661         destroyPQExpBuffer(labelq);
10662 }
10663
10664 /*
10665  * dumpConversion
10666  *        write out a single conversion definition
10667  */
10668 static void
10669 dumpConversion(Archive *fout, ConvInfo *convinfo)
10670 {
10671         PQExpBuffer query;
10672         PQExpBuffer q;
10673         PQExpBuffer delq;
10674         PQExpBuffer labelq;
10675         PGresult   *res;
10676         int                     i_conforencoding;
10677         int                     i_contoencoding;
10678         int                     i_conproc;
10679         int                     i_condefault;
10680         const char *conforencoding;
10681         const char *contoencoding;
10682         const char *conproc;
10683         bool            condefault;
10684
10685         /* Skip if not to be dumped */
10686         if (!convinfo->dobj.dump || dataOnly)
10687                 return;
10688
10689         query = createPQExpBuffer();
10690         q = createPQExpBuffer();
10691         delq = createPQExpBuffer();
10692         labelq = createPQExpBuffer();
10693
10694         /* Make sure we are in proper schema */
10695         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10696
10697         /* Get conversion-specific details */
10698         appendPQExpBuffer(query, "SELECT "
10699                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10700                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10701                                           "conproc, condefault "
10702                                           "FROM pg_catalog.pg_conversion c "
10703                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10704                                           convinfo->dobj.catId.oid);
10705
10706         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10707
10708         i_conforencoding = PQfnumber(res, "conforencoding");
10709         i_contoencoding = PQfnumber(res, "contoencoding");
10710         i_conproc = PQfnumber(res, "conproc");
10711         i_condefault = PQfnumber(res, "condefault");
10712
10713         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10714         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10715         conproc = PQgetvalue(res, 0, i_conproc);
10716         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10717
10718         /*
10719          * DROP must be fully qualified in case same name appears in pg_catalog
10720          */
10721         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10722                                           fmtId(convinfo->dobj.namespace->dobj.name));
10723         appendPQExpBuffer(delq, ".%s;\n",
10724                                           fmtId(convinfo->dobj.name));
10725
10726         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10727                                           (condefault) ? "DEFAULT " : "",
10728                                           fmtId(convinfo->dobj.name));
10729         appendStringLiteralAH(q, conforencoding, fout);
10730         appendPQExpBuffer(q, " TO ");
10731         appendStringLiteralAH(q, contoencoding, fout);
10732         /* regproc is automatically quoted in 7.3 and above */
10733         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10734
10735         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10736
10737         if (binary_upgrade)
10738                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10739
10740         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10741                                  convinfo->dobj.name,
10742                                  convinfo->dobj.namespace->dobj.name,
10743                                  NULL,
10744                                  convinfo->rolname,
10745                                  false, "CONVERSION", SECTION_PRE_DATA,
10746                                  q->data, delq->data, NULL,
10747                                  NULL, 0,
10748                                  NULL, NULL);
10749
10750         /* Dump Conversion Comments */
10751         dumpComment(fout, labelq->data,
10752                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10753                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10754
10755         PQclear(res);
10756
10757         destroyPQExpBuffer(query);
10758         destroyPQExpBuffer(q);
10759         destroyPQExpBuffer(delq);
10760         destroyPQExpBuffer(labelq);
10761 }
10762
10763 /*
10764  * format_aggregate_signature: generate aggregate name and argument list
10765  *
10766  * The argument type names are qualified if needed.  The aggregate name
10767  * is never qualified.
10768  */
10769 static char *
10770 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10771 {
10772         PQExpBufferData buf;
10773         int                     j;
10774
10775         initPQExpBuffer(&buf);
10776         if (honor_quotes)
10777                 appendPQExpBuffer(&buf, "%s",
10778                                                   fmtId(agginfo->aggfn.dobj.name));
10779         else
10780                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10781
10782         if (agginfo->aggfn.nargs == 0)
10783                 appendPQExpBuffer(&buf, "(*)");
10784         else
10785         {
10786                 appendPQExpBuffer(&buf, "(");
10787                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10788                 {
10789                         char       *typname;
10790
10791                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10792                                                                                    zeroAsOpaque);
10793
10794                         appendPQExpBuffer(&buf, "%s%s",
10795                                                           (j > 0) ? ", " : "",
10796                                                           typname);
10797                         free(typname);
10798                 }
10799                 appendPQExpBuffer(&buf, ")");
10800         }
10801         return buf.data;
10802 }
10803
10804 /*
10805  * dumpAgg
10806  *        write out a single aggregate definition
10807  */
10808 static void
10809 dumpAgg(Archive *fout, AggInfo *agginfo)
10810 {
10811         PQExpBuffer query;
10812         PQExpBuffer q;
10813         PQExpBuffer delq;
10814         PQExpBuffer labelq;
10815         PQExpBuffer details;
10816         char       *aggsig;
10817         char       *aggsig_tag;
10818         PGresult   *res;
10819         int                     i_aggtransfn;
10820         int                     i_aggfinalfn;
10821         int                     i_aggsortop;
10822         int                     i_aggtranstype;
10823         int                     i_agginitval;
10824         int                     i_convertok;
10825         const char *aggtransfn;
10826         const char *aggfinalfn;
10827         const char *aggsortop;
10828         const char *aggtranstype;
10829         const char *agginitval;
10830         bool            convertok;
10831
10832         /* Skip if not to be dumped */
10833         if (!agginfo->aggfn.dobj.dump || dataOnly)
10834                 return;
10835
10836         query = createPQExpBuffer();
10837         q = createPQExpBuffer();
10838         delq = createPQExpBuffer();
10839         labelq = createPQExpBuffer();
10840         details = createPQExpBuffer();
10841
10842         /* Make sure we are in proper schema */
10843         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10844
10845         /* Get aggregate-specific details */
10846         if (fout->remoteVersion >= 80100)
10847         {
10848                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10849                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10850                                                   "aggsortop::pg_catalog.regoperator, "
10851                                                   "agginitval, "
10852                                                   "'t'::boolean AS convertok "
10853                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10854                                                   "WHERE a.aggfnoid = p.oid "
10855                                                   "AND p.oid = '%u'::pg_catalog.oid",
10856                                                   agginfo->aggfn.dobj.catId.oid);
10857         }
10858         else if (fout->remoteVersion >= 70300)
10859         {
10860                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10861                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10862                                                   "0 AS aggsortop, "
10863                                                   "agginitval, "
10864                                                   "'t'::boolean AS convertok "
10865                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10866                                                   "WHERE a.aggfnoid = p.oid "
10867                                                   "AND p.oid = '%u'::pg_catalog.oid",
10868                                                   agginfo->aggfn.dobj.catId.oid);
10869         }
10870         else if (fout->remoteVersion >= 70100)
10871         {
10872                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10873                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
10874                                                   "0 AS aggsortop, "
10875                                                   "agginitval, "
10876                                                   "'t'::boolean AS convertok "
10877                                                   "FROM pg_aggregate "
10878                                                   "WHERE oid = '%u'::oid",
10879                                                   agginfo->aggfn.dobj.catId.oid);
10880         }
10881         else
10882         {
10883                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10884                                                   "aggfinalfn, "
10885                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10886                                                   "0 AS aggsortop, "
10887                                                   "agginitval1 AS agginitval, "
10888                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10889                                                   "FROM pg_aggregate "
10890                                                   "WHERE oid = '%u'::oid",
10891                                                   agginfo->aggfn.dobj.catId.oid);
10892         }
10893
10894         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10895
10896         i_aggtransfn = PQfnumber(res, "aggtransfn");
10897         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10898         i_aggsortop = PQfnumber(res, "aggsortop");
10899         i_aggtranstype = PQfnumber(res, "aggtranstype");
10900         i_agginitval = PQfnumber(res, "agginitval");
10901         i_convertok = PQfnumber(res, "convertok");
10902
10903         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10904         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10905         aggsortop = PQgetvalue(res, 0, i_aggsortop);
10906         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10907         agginitval = PQgetvalue(res, 0, i_agginitval);
10908         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10909
10910         aggsig = format_aggregate_signature(agginfo, fout, true);
10911         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10912
10913         if (!convertok)
10914         {
10915                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10916                                   aggsig);
10917                 return;
10918         }
10919
10920         if (fout->remoteVersion >= 70300)
10921         {
10922                 /* If using 7.3's regproc or regtype, data is already quoted */
10923                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10924                                                   aggtransfn,
10925                                                   aggtranstype);
10926         }
10927         else if (fout->remoteVersion >= 70100)
10928         {
10929                 /* format_type quotes, regproc does not */
10930                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10931                                                   fmtId(aggtransfn),
10932                                                   aggtranstype);
10933         }
10934         else
10935         {
10936                 /* need quotes all around */
10937                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
10938                                                   fmtId(aggtransfn));
10939                 appendPQExpBuffer(details, "    STYPE = %s",
10940                                                   fmtId(aggtranstype));
10941         }
10942
10943         if (!PQgetisnull(res, 0, i_agginitval))
10944         {
10945                 appendPQExpBuffer(details, ",\n    INITCOND = ");
10946                 appendStringLiteralAH(details, agginitval, fout);
10947         }
10948
10949         if (strcmp(aggfinalfn, "-") != 0)
10950         {
10951                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
10952                                                   aggfinalfn);
10953         }
10954
10955         aggsortop = convertOperatorReference(fout, aggsortop);
10956         if (aggsortop)
10957         {
10958                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
10959                                                   aggsortop);
10960         }
10961
10962         /*
10963          * DROP must be fully qualified in case same name appears in pg_catalog
10964          */
10965         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10966                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10967                                           aggsig);
10968
10969         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10970                                           aggsig, details->data);
10971
10972         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10973
10974         if (binary_upgrade)
10975                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10976
10977         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10978                                  aggsig_tag,
10979                                  agginfo->aggfn.dobj.namespace->dobj.name,
10980                                  NULL,
10981                                  agginfo->aggfn.rolname,
10982                                  false, "AGGREGATE", SECTION_PRE_DATA,
10983                                  q->data, delq->data, NULL,
10984                                  NULL, 0,
10985                                  NULL, NULL);
10986
10987         /* Dump Aggregate Comments */
10988         dumpComment(fout, labelq->data,
10989                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10990                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10991         dumpSecLabel(fout, labelq->data,
10992                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10993                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10994
10995         /*
10996          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10997          * command look like a function's GRANT; in particular this affects the
10998          * syntax for zero-argument aggregates.
10999          */
11000         free(aggsig);
11001         free(aggsig_tag);
11002
11003         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11004         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11005
11006         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11007                         "FUNCTION",
11008                         aggsig, NULL, aggsig_tag,
11009                         agginfo->aggfn.dobj.namespace->dobj.name,
11010                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11011
11012         free(aggsig);
11013         free(aggsig_tag);
11014
11015         PQclear(res);
11016
11017         destroyPQExpBuffer(query);
11018         destroyPQExpBuffer(q);
11019         destroyPQExpBuffer(delq);
11020         destroyPQExpBuffer(labelq);
11021         destroyPQExpBuffer(details);
11022 }
11023
11024 /*
11025  * dumpTSParser
11026  *        write out a single text search parser
11027  */
11028 static void
11029 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11030 {
11031         PQExpBuffer q;
11032         PQExpBuffer delq;
11033         PQExpBuffer labelq;
11034
11035         /* Skip if not to be dumped */
11036         if (!prsinfo->dobj.dump || dataOnly)
11037                 return;
11038
11039         q = createPQExpBuffer();
11040         delq = createPQExpBuffer();
11041         labelq = createPQExpBuffer();
11042
11043         /* Make sure we are in proper schema */
11044         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11045
11046         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11047                                           fmtId(prsinfo->dobj.name));
11048
11049         appendPQExpBuffer(q, "    START = %s,\n",
11050                                           convertTSFunction(fout, prsinfo->prsstart));
11051         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11052                                           convertTSFunction(fout, prsinfo->prstoken));
11053         appendPQExpBuffer(q, "    END = %s,\n",
11054                                           convertTSFunction(fout, prsinfo->prsend));
11055         if (prsinfo->prsheadline != InvalidOid)
11056                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11057                                                   convertTSFunction(fout, prsinfo->prsheadline));
11058         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11059                                           convertTSFunction(fout, prsinfo->prslextype));
11060
11061         /*
11062          * DROP must be fully qualified in case same name appears in pg_catalog
11063          */
11064         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11065                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11066         appendPQExpBuffer(delq, ".%s;\n",
11067                                           fmtId(prsinfo->dobj.name));
11068
11069         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11070                                           fmtId(prsinfo->dobj.name));
11071
11072         if (binary_upgrade)
11073                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11074
11075         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11076                                  prsinfo->dobj.name,
11077                                  prsinfo->dobj.namespace->dobj.name,
11078                                  NULL,
11079                                  "",
11080                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11081                                  q->data, delq->data, NULL,
11082                                  NULL, 0,
11083                                  NULL, NULL);
11084
11085         /* Dump Parser Comments */
11086         dumpComment(fout, labelq->data,
11087                                 NULL, "",
11088                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11089
11090         destroyPQExpBuffer(q);
11091         destroyPQExpBuffer(delq);
11092         destroyPQExpBuffer(labelq);
11093 }
11094
11095 /*
11096  * dumpTSDictionary
11097  *        write out a single text search dictionary
11098  */
11099 static void
11100 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11101 {
11102         PQExpBuffer q;
11103         PQExpBuffer delq;
11104         PQExpBuffer labelq;
11105         PQExpBuffer query;
11106         PGresult   *res;
11107         char       *nspname;
11108         char       *tmplname;
11109
11110         /* Skip if not to be dumped */
11111         if (!dictinfo->dobj.dump || dataOnly)
11112                 return;
11113
11114         q = createPQExpBuffer();
11115         delq = createPQExpBuffer();
11116         labelq = createPQExpBuffer();
11117         query = createPQExpBuffer();
11118
11119         /* Fetch name and namespace of the dictionary's template */
11120         selectSourceSchema(fout, "pg_catalog");
11121         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11122                                           "FROM pg_ts_template p, pg_namespace n "
11123                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11124                                           dictinfo->dicttemplate);
11125         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11126         nspname = PQgetvalue(res, 0, 0);
11127         tmplname = PQgetvalue(res, 0, 1);
11128
11129         /* Make sure we are in proper schema */
11130         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11131
11132         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11133                                           fmtId(dictinfo->dobj.name));
11134
11135         appendPQExpBuffer(q, "    TEMPLATE = ");
11136         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11137                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11138         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11139
11140         PQclear(res);
11141
11142         /* the dictinitoption can be dumped straight into the command */
11143         if (dictinfo->dictinitoption)
11144                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11145
11146         appendPQExpBuffer(q, " );\n");
11147
11148         /*
11149          * DROP must be fully qualified in case same name appears in pg_catalog
11150          */
11151         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11152                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11153         appendPQExpBuffer(delq, ".%s;\n",
11154                                           fmtId(dictinfo->dobj.name));
11155
11156         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11157                                           fmtId(dictinfo->dobj.name));
11158
11159         if (binary_upgrade)
11160                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11161
11162         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11163                                  dictinfo->dobj.name,
11164                                  dictinfo->dobj.namespace->dobj.name,
11165                                  NULL,
11166                                  dictinfo->rolname,
11167                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11168                                  q->data, delq->data, NULL,
11169                                  NULL, 0,
11170                                  NULL, NULL);
11171
11172         /* Dump Dictionary Comments */
11173         dumpComment(fout, labelq->data,
11174                                 NULL, dictinfo->rolname,
11175                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11176
11177         destroyPQExpBuffer(q);
11178         destroyPQExpBuffer(delq);
11179         destroyPQExpBuffer(labelq);
11180         destroyPQExpBuffer(query);
11181 }
11182
11183 /*
11184  * dumpTSTemplate
11185  *        write out a single text search template
11186  */
11187 static void
11188 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11189 {
11190         PQExpBuffer q;
11191         PQExpBuffer delq;
11192         PQExpBuffer labelq;
11193
11194         /* Skip if not to be dumped */
11195         if (!tmplinfo->dobj.dump || dataOnly)
11196                 return;
11197
11198         q = createPQExpBuffer();
11199         delq = createPQExpBuffer();
11200         labelq = createPQExpBuffer();
11201
11202         /* Make sure we are in proper schema */
11203         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11204
11205         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11206                                           fmtId(tmplinfo->dobj.name));
11207
11208         if (tmplinfo->tmplinit != InvalidOid)
11209                 appendPQExpBuffer(q, "    INIT = %s,\n",
11210                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11211         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11212                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11213
11214         /*
11215          * DROP must be fully qualified in case same name appears in pg_catalog
11216          */
11217         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11218                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11219         appendPQExpBuffer(delq, ".%s;\n",
11220                                           fmtId(tmplinfo->dobj.name));
11221
11222         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11223                                           fmtId(tmplinfo->dobj.name));
11224
11225         if (binary_upgrade)
11226                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11227
11228         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11229                                  tmplinfo->dobj.name,
11230                                  tmplinfo->dobj.namespace->dobj.name,
11231                                  NULL,
11232                                  "",
11233                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11234                                  q->data, delq->data, NULL,
11235                                  NULL, 0,
11236                                  NULL, NULL);
11237
11238         /* Dump Template Comments */
11239         dumpComment(fout, labelq->data,
11240                                 NULL, "",
11241                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11242
11243         destroyPQExpBuffer(q);
11244         destroyPQExpBuffer(delq);
11245         destroyPQExpBuffer(labelq);
11246 }
11247
11248 /*
11249  * dumpTSConfig
11250  *        write out a single text search configuration
11251  */
11252 static void
11253 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11254 {
11255         PQExpBuffer q;
11256         PQExpBuffer delq;
11257         PQExpBuffer labelq;
11258         PQExpBuffer query;
11259         PGresult   *res;
11260         char       *nspname;
11261         char       *prsname;
11262         int                     ntups,
11263                                 i;
11264         int                     i_tokenname;
11265         int                     i_dictname;
11266
11267         /* Skip if not to be dumped */
11268         if (!cfginfo->dobj.dump || dataOnly)
11269                 return;
11270
11271         q = createPQExpBuffer();
11272         delq = createPQExpBuffer();
11273         labelq = createPQExpBuffer();
11274         query = createPQExpBuffer();
11275
11276         /* Fetch name and namespace of the config's parser */
11277         selectSourceSchema(fout, "pg_catalog");
11278         appendPQExpBuffer(query, "SELECT nspname, prsname "
11279                                           "FROM pg_ts_parser p, pg_namespace n "
11280                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11281                                           cfginfo->cfgparser);
11282         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11283         nspname = PQgetvalue(res, 0, 0);
11284         prsname = PQgetvalue(res, 0, 1);
11285
11286         /* Make sure we are in proper schema */
11287         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11288
11289         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11290                                           fmtId(cfginfo->dobj.name));
11291
11292         appendPQExpBuffer(q, "    PARSER = ");
11293         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11294                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11295         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11296
11297         PQclear(res);
11298
11299         resetPQExpBuffer(query);
11300         appendPQExpBuffer(query,
11301                                           "SELECT \n"
11302                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11303                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11304                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11305                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11306                                           "WHERE m.mapcfg = '%u' \n"
11307                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11308                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11309
11310         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11311         ntups = PQntuples(res);
11312
11313         i_tokenname = PQfnumber(res, "tokenname");
11314         i_dictname = PQfnumber(res, "dictname");
11315
11316         for (i = 0; i < ntups; i++)
11317         {
11318                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11319                 char       *dictname = PQgetvalue(res, i, i_dictname);
11320
11321                 if (i == 0 ||
11322                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11323                 {
11324                         /* starting a new token type, so start a new command */
11325                         if (i > 0)
11326                                 appendPQExpBuffer(q, ";\n");
11327                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11328                                                           fmtId(cfginfo->dobj.name));
11329                         /* tokenname needs quoting, dictname does NOT */
11330                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11331                                                           fmtId(tokenname), dictname);
11332                 }
11333                 else
11334                         appendPQExpBuffer(q, ", %s", dictname);
11335         }
11336
11337         if (ntups > 0)
11338                 appendPQExpBuffer(q, ";\n");
11339
11340         PQclear(res);
11341
11342         /*
11343          * DROP must be fully qualified in case same name appears in pg_catalog
11344          */
11345         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11346                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11347         appendPQExpBuffer(delq, ".%s;\n",
11348                                           fmtId(cfginfo->dobj.name));
11349
11350         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11351                                           fmtId(cfginfo->dobj.name));
11352
11353         if (binary_upgrade)
11354                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11355
11356         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11357                                  cfginfo->dobj.name,
11358                                  cfginfo->dobj.namespace->dobj.name,
11359                                  NULL,
11360                                  cfginfo->rolname,
11361                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11362                                  q->data, delq->data, NULL,
11363                                  NULL, 0,
11364                                  NULL, NULL);
11365
11366         /* Dump Configuration Comments */
11367         dumpComment(fout, labelq->data,
11368                                 NULL, cfginfo->rolname,
11369                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11370
11371         destroyPQExpBuffer(q);
11372         destroyPQExpBuffer(delq);
11373         destroyPQExpBuffer(labelq);
11374         destroyPQExpBuffer(query);
11375 }
11376
11377 /*
11378  * dumpForeignDataWrapper
11379  *        write out a single foreign-data wrapper definition
11380  */
11381 static void
11382 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11383 {
11384         PQExpBuffer q;
11385         PQExpBuffer delq;
11386         PQExpBuffer labelq;
11387         char       *qfdwname;
11388
11389         /* Skip if not to be dumped */
11390         if (!fdwinfo->dobj.dump || dataOnly)
11391                 return;
11392
11393         /*
11394          * FDWs that belong to an extension are dumped based on their "dump"
11395          * field. Otherwise omit them if we are only dumping some specific object.
11396          */
11397         if (!fdwinfo->dobj.ext_member)
11398                 if (!include_everything)
11399                         return;
11400
11401         q = createPQExpBuffer();
11402         delq = createPQExpBuffer();
11403         labelq = createPQExpBuffer();
11404
11405         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11406
11407         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11408                                           qfdwname);
11409
11410         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11411                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11412
11413         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11414                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11415
11416         if (strlen(fdwinfo->fdwoptions) > 0)
11417                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11418
11419         appendPQExpBuffer(q, ";\n");
11420
11421         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11422                                           qfdwname);
11423
11424         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11425                                           qfdwname);
11426
11427         if (binary_upgrade)
11428                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11429
11430         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11431                                  fdwinfo->dobj.name,
11432                                  NULL,
11433                                  NULL,
11434                                  fdwinfo->rolname,
11435                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11436                                  q->data, delq->data, NULL,
11437                                  NULL, 0,
11438                                  NULL, NULL);
11439
11440         /* Handle the ACL */
11441         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11442                         "FOREIGN DATA WRAPPER",
11443                         qfdwname, NULL, fdwinfo->dobj.name,
11444                         NULL, fdwinfo->rolname,
11445                         fdwinfo->fdwacl);
11446
11447         /* Dump Foreign Data Wrapper Comments */
11448         dumpComment(fout, labelq->data,
11449                                 NULL, fdwinfo->rolname,
11450                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11451
11452         free(qfdwname);
11453
11454         destroyPQExpBuffer(q);
11455         destroyPQExpBuffer(delq);
11456         destroyPQExpBuffer(labelq);
11457 }
11458
11459 /*
11460  * dumpForeignServer
11461  *        write out a foreign server definition
11462  */
11463 static void
11464 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11465 {
11466         PQExpBuffer q;
11467         PQExpBuffer delq;
11468         PQExpBuffer labelq;
11469         PQExpBuffer query;
11470         PGresult   *res;
11471         char       *qsrvname;
11472         char       *fdwname;
11473
11474         /* Skip if not to be dumped */
11475         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11476                 return;
11477
11478         q = createPQExpBuffer();
11479         delq = createPQExpBuffer();
11480         labelq = createPQExpBuffer();
11481         query = createPQExpBuffer();
11482
11483         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11484
11485         /* look up the foreign-data wrapper */
11486         selectSourceSchema(fout, "pg_catalog");
11487         appendPQExpBuffer(query, "SELECT fdwname "
11488                                           "FROM pg_foreign_data_wrapper w "
11489                                           "WHERE w.oid = '%u'",
11490                                           srvinfo->srvfdw);
11491         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11492         fdwname = PQgetvalue(res, 0, 0);
11493
11494         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11495         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11496         {
11497                 appendPQExpBuffer(q, " TYPE ");
11498                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11499         }
11500         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11501         {
11502                 appendPQExpBuffer(q, " VERSION ");
11503                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11504         }
11505
11506         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11507         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11508
11509         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11510                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11511
11512         appendPQExpBuffer(q, ";\n");
11513
11514         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11515                                           qsrvname);
11516
11517         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11518
11519         if (binary_upgrade)
11520                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11521
11522         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11523                                  srvinfo->dobj.name,
11524                                  NULL,
11525                                  NULL,
11526                                  srvinfo->rolname,
11527                                  false, "SERVER", SECTION_PRE_DATA,
11528                                  q->data, delq->data, NULL,
11529                                  NULL, 0,
11530                                  NULL, NULL);
11531
11532         /* Handle the ACL */
11533         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11534                         "FOREIGN SERVER",
11535                         qsrvname, NULL, srvinfo->dobj.name,
11536                         NULL, srvinfo->rolname,
11537                         srvinfo->srvacl);
11538
11539         /* Dump user mappings */
11540         dumpUserMappings(fout,
11541                                          srvinfo->dobj.name, NULL,
11542                                          srvinfo->rolname,
11543                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11544
11545         /* Dump Foreign Server Comments */
11546         dumpComment(fout, labelq->data,
11547                                 NULL, srvinfo->rolname,
11548                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11549
11550         free(qsrvname);
11551
11552         destroyPQExpBuffer(q);
11553         destroyPQExpBuffer(delq);
11554         destroyPQExpBuffer(labelq);
11555 }
11556
11557 /*
11558  * dumpUserMappings
11559  *
11560  * This routine is used to dump any user mappings associated with the
11561  * server handed to this routine. Should be called after ArchiveEntry()
11562  * for the server.
11563  */
11564 static void
11565 dumpUserMappings(Archive *fout,
11566                                  const char *servername, const char *namespace,
11567                                  const char *owner,
11568                                  CatalogId catalogId, DumpId dumpId)
11569 {
11570         PQExpBuffer q;
11571         PQExpBuffer delq;
11572         PQExpBuffer query;
11573         PQExpBuffer tag;
11574         PGresult   *res;
11575         int                     ntups;
11576         int                     i_usename;
11577         int                     i_umoptions;
11578         int                     i;
11579
11580         q = createPQExpBuffer();
11581         tag = createPQExpBuffer();
11582         delq = createPQExpBuffer();
11583         query = createPQExpBuffer();
11584
11585         /*
11586          * We read from the publicly accessible view pg_user_mappings, so as not
11587          * to fail if run by a non-superuser.  Note that the view will show
11588          * umoptions as null if the user hasn't got privileges for the associated
11589          * server; this means that pg_dump will dump such a mapping, but with no
11590          * OPTIONS clause.      A possible alternative is to skip such mappings
11591          * altogether, but it's not clear that that's an improvement.
11592          */
11593         selectSourceSchema(fout, "pg_catalog");
11594
11595         appendPQExpBuffer(query,
11596                                           "SELECT usename, "
11597                                           "array_to_string(ARRAY("
11598                                           "SELECT quote_ident(option_name) || ' ' || "
11599                                           "quote_literal(option_value) "
11600                                           "FROM pg_options_to_table(umoptions) "
11601                                           "ORDER BY option_name"
11602                                           "), E',\n    ') AS umoptions "
11603                                           "FROM pg_user_mappings "
11604                                           "WHERE srvid = '%u' "
11605                                           "ORDER BY usename",
11606                                           catalogId.oid);
11607
11608         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11609
11610         ntups = PQntuples(res);
11611         i_usename = PQfnumber(res, "usename");
11612         i_umoptions = PQfnumber(res, "umoptions");
11613
11614         for (i = 0; i < ntups; i++)
11615         {
11616                 char       *usename;
11617                 char       *umoptions;
11618
11619                 usename = PQgetvalue(res, i, i_usename);
11620                 umoptions = PQgetvalue(res, i, i_umoptions);
11621
11622                 resetPQExpBuffer(q);
11623                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11624                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11625
11626                 if (umoptions && strlen(umoptions) > 0)
11627                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11628
11629                 appendPQExpBuffer(q, ";\n");
11630
11631                 resetPQExpBuffer(delq);
11632                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11633                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11634
11635                 resetPQExpBuffer(tag);
11636                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11637                                                   usename, servername);
11638
11639                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11640                                          tag->data,
11641                                          namespace,
11642                                          NULL,
11643                                          owner, false,
11644                                          "USER MAPPING", SECTION_PRE_DATA,
11645                                          q->data, delq->data, NULL,
11646                                          &dumpId, 1,
11647                                          NULL, NULL);
11648         }
11649
11650         PQclear(res);
11651
11652         destroyPQExpBuffer(query);
11653         destroyPQExpBuffer(delq);
11654         destroyPQExpBuffer(q);
11655 }
11656
11657 /*
11658  * Write out default privileges information
11659  */
11660 static void
11661 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11662 {
11663         PQExpBuffer q;
11664         PQExpBuffer tag;
11665         const char *type;
11666
11667         /* Skip if not to be dumped */
11668         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11669                 return;
11670
11671         q = createPQExpBuffer();
11672         tag = createPQExpBuffer();
11673
11674         switch (daclinfo->defaclobjtype)
11675         {
11676                 case DEFACLOBJ_RELATION:
11677                         type = "TABLES";
11678                         break;
11679                 case DEFACLOBJ_SEQUENCE:
11680                         type = "SEQUENCES";
11681                         break;
11682                 case DEFACLOBJ_FUNCTION:
11683                         type = "FUNCTIONS";
11684                         break;
11685                 default:
11686                         /* shouldn't get here */
11687                         exit_horribly(NULL,
11688                                                   "unknown object type (%d) in default privileges\n",
11689                                                   (int) daclinfo->defaclobjtype);
11690                         type = "";                      /* keep compiler quiet */
11691         }
11692
11693         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11694
11695         /* build the actual command(s) for this tuple */
11696         if (!buildDefaultACLCommands(type,
11697                                                                  daclinfo->dobj.namespace != NULL ?
11698                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11699                                                                  daclinfo->defaclacl,
11700                                                                  daclinfo->defaclrole,
11701                                                                  fout->remoteVersion,
11702                                                                  q))
11703                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11704                                           daclinfo->defaclacl);
11705
11706         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11707                                  tag->data,
11708            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11709                                  NULL,
11710                                  daclinfo->defaclrole,
11711                                  false, "DEFAULT ACL", SECTION_POST_DATA,
11712                                  q->data, "", NULL,
11713                                  NULL, 0,
11714                                  NULL, NULL);
11715
11716         destroyPQExpBuffer(tag);
11717         destroyPQExpBuffer(q);
11718 }
11719
11720 /*----------
11721  * Write out grant/revoke information
11722  *
11723  * 'objCatId' is the catalog ID of the underlying object.
11724  * 'objDumpId' is the dump ID of the underlying object.
11725  * 'type' must be one of
11726  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11727  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11728  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11729  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11730  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11731  * 'nspname' is the namespace the object is in (NULL if none).
11732  * 'owner' is the owner, NULL if there is no owner (for languages).
11733  * 'acls' is the string read out of the fooacl system catalog field;
11734  *              it will be parsed here.
11735  *----------
11736  */
11737 static void
11738 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11739                 const char *type, const char *name, const char *subname,
11740                 const char *tag, const char *nspname, const char *owner,
11741                 const char *acls)
11742 {
11743         PQExpBuffer sql;
11744
11745         /* Do nothing if ACL dump is not enabled */
11746         if (aclsSkip)
11747                 return;
11748
11749         /* --data-only skips ACLs *except* BLOB ACLs */
11750         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11751                 return;
11752
11753         sql = createPQExpBuffer();
11754
11755         if (!buildACLCommands(name, subname, type, acls, owner,
11756                                                   "", fout->remoteVersion, sql))
11757                 exit_horribly(NULL,
11758                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11759                                           acls, name, type);
11760
11761         if (sql->len > 0)
11762                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11763                                          tag, nspname,
11764                                          NULL,
11765                                          owner ? owner : "",
11766                                          false, "ACL", SECTION_NONE,
11767                                          sql->data, "", NULL,
11768                                          &(objDumpId), 1,
11769                                          NULL, NULL);
11770
11771         destroyPQExpBuffer(sql);
11772 }
11773
11774 /*
11775  * dumpSecLabel
11776  *
11777  * This routine is used to dump any security labels associated with the
11778  * object handed to this routine. The routine takes a constant character
11779  * string for the target part of the security-label command, plus
11780  * the namespace and owner of the object (for labeling the ArchiveEntry),
11781  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11782  * plus the dump ID for the object (for setting a dependency).
11783  * If a matching pg_seclabel entry is found, it is dumped.
11784  *
11785  * Note: although this routine takes a dumpId for dependency purposes,
11786  * that purpose is just to mark the dependency in the emitted dump file
11787  * for possible future use by pg_restore.  We do NOT use it for determining
11788  * ordering of the label in the dump file, because this routine is called
11789  * after dependency sorting occurs.  This routine should be called just after
11790  * calling ArchiveEntry() for the specified object.
11791  */
11792 static void
11793 dumpSecLabel(Archive *fout, const char *target,
11794                          const char *namespace, const char *owner,
11795                          CatalogId catalogId, int subid, DumpId dumpId)
11796 {
11797         SecLabelItem *labels;
11798         int                     nlabels;
11799         int                     i;
11800         PQExpBuffer query;
11801
11802         /* do nothing, if --no-security-labels is supplied */
11803         if (no_security_labels)
11804                 return;
11805
11806         /* Comments are schema not data ... except blob comments are data */
11807         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11808         {
11809                 if (dataOnly)
11810                         return;
11811         }
11812         else
11813         {
11814                 if (schemaOnly)
11815                         return;
11816         }
11817
11818         /* Search for security labels associated with catalogId, using table */
11819         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11820
11821         query = createPQExpBuffer();
11822
11823         for (i = 0; i < nlabels; i++)
11824         {
11825                 /*
11826                  * Ignore label entries for which the subid doesn't match.
11827                  */
11828                 if (labels[i].objsubid != subid)
11829                         continue;
11830
11831                 appendPQExpBuffer(query,
11832                                                   "SECURITY LABEL FOR %s ON %s IS ",
11833                                                   fmtId(labels[i].provider), target);
11834                 appendStringLiteralAH(query, labels[i].label, fout);
11835                 appendPQExpBuffer(query, ";\n");
11836         }
11837
11838         if (query->len > 0)
11839         {
11840                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11841                                          target, namespace, NULL, owner,
11842                                          false, "SECURITY LABEL", SECTION_NONE,
11843                                          query->data, "", NULL,
11844                                          &(dumpId), 1,
11845                                          NULL, NULL);
11846         }
11847         destroyPQExpBuffer(query);
11848 }
11849
11850 /*
11851  * dumpTableSecLabel
11852  *
11853  * As above, but dump security label for both the specified table (or view)
11854  * and its columns.
11855  */
11856 static void
11857 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11858 {
11859         SecLabelItem *labels;
11860         int                     nlabels;
11861         int                     i;
11862         PQExpBuffer query;
11863         PQExpBuffer target;
11864
11865         /* do nothing, if --no-security-labels is supplied */
11866         if (no_security_labels)
11867                 return;
11868
11869         /* SecLabel are SCHEMA not data */
11870         if (dataOnly)
11871                 return;
11872
11873         /* Search for comments associated with relation, using table */
11874         nlabels = findSecLabels(fout,
11875                                                         tbinfo->dobj.catId.tableoid,
11876                                                         tbinfo->dobj.catId.oid,
11877                                                         &labels);
11878
11879         /* If security labels exist, build SECURITY LABEL statements */
11880         if (nlabels <= 0)
11881                 return;
11882
11883         query = createPQExpBuffer();
11884         target = createPQExpBuffer();
11885
11886         for (i = 0; i < nlabels; i++)
11887         {
11888                 const char *colname;
11889                 const char *provider = labels[i].provider;
11890                 const char *label = labels[i].label;
11891                 int                     objsubid = labels[i].objsubid;
11892
11893                 resetPQExpBuffer(target);
11894                 if (objsubid == 0)
11895                 {
11896                         appendPQExpBuffer(target, "%s %s", reltypename,
11897                                                           fmtId(tbinfo->dobj.name));
11898                 }
11899                 else
11900                 {
11901                         colname = getAttrName(objsubid, tbinfo);
11902                         /* first fmtId result must be consumed before calling it again */
11903                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11904                         appendPQExpBuffer(target, ".%s", fmtId(colname));
11905                 }
11906                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11907                                                   fmtId(provider), target->data);
11908                 appendStringLiteralAH(query, label, fout);
11909                 appendPQExpBuffer(query, ";\n");
11910         }
11911         if (query->len > 0)
11912         {
11913                 resetPQExpBuffer(target);
11914                 appendPQExpBuffer(target, "%s %s", reltypename,
11915                                                   fmtId(tbinfo->dobj.name));
11916                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11917                                          target->data,
11918                                          tbinfo->dobj.namespace->dobj.name,
11919                                          NULL, tbinfo->rolname,
11920                                          false, "SECURITY LABEL", SECTION_NONE,
11921                                          query->data, "", NULL,
11922                                          &(tbinfo->dobj.dumpId), 1,
11923                                          NULL, NULL);
11924         }
11925         destroyPQExpBuffer(query);
11926         destroyPQExpBuffer(target);
11927 }
11928
11929 /*
11930  * findSecLabels
11931  *
11932  * Find the security label(s), if any, associated with the given object.
11933  * All the objsubid values associated with the given classoid/objoid are
11934  * found with one search.
11935  */
11936 static int
11937 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11938 {
11939         /* static storage for table of security labels */
11940         static SecLabelItem *labels = NULL;
11941         static int      nlabels = -1;
11942
11943         SecLabelItem *middle = NULL;
11944         SecLabelItem *low;
11945         SecLabelItem *high;
11946         int                     nmatch;
11947
11948         /* Get security labels if we didn't already */
11949         if (nlabels < 0)
11950                 nlabels = collectSecLabels(fout, &labels);
11951
11952         if (nlabels <= 0)                       /* no labels, so no match is possible */
11953         {
11954                 *items = NULL;
11955                 return 0;
11956         }
11957
11958         /*
11959          * Do binary search to find some item matching the object.
11960          */
11961         low = &labels[0];
11962         high = &labels[nlabels - 1];
11963         while (low <= high)
11964         {
11965                 middle = low + (high - low) / 2;
11966
11967                 if (classoid < middle->classoid)
11968                         high = middle - 1;
11969                 else if (classoid > middle->classoid)
11970                         low = middle + 1;
11971                 else if (objoid < middle->objoid)
11972                         high = middle - 1;
11973                 else if (objoid > middle->objoid)
11974                         low = middle + 1;
11975                 else
11976                         break;                          /* found a match */
11977         }
11978
11979         if (low > high)                         /* no matches */
11980         {
11981                 *items = NULL;
11982                 return 0;
11983         }
11984
11985         /*
11986          * Now determine how many items match the object.  The search loop
11987          * invariant still holds: only items between low and high inclusive could
11988          * match.
11989          */
11990         nmatch = 1;
11991         while (middle > low)
11992         {
11993                 if (classoid != middle[-1].classoid ||
11994                         objoid != middle[-1].objoid)
11995                         break;
11996                 middle--;
11997                 nmatch++;
11998         }
11999
12000         *items = middle;
12001
12002         middle += nmatch;
12003         while (middle <= high)
12004         {
12005                 if (classoid != middle->classoid ||
12006                         objoid != middle->objoid)
12007                         break;
12008                 middle++;
12009                 nmatch++;
12010         }
12011
12012         return nmatch;
12013 }
12014
12015 /*
12016  * collectSecLabels
12017  *
12018  * Construct a table of all security labels available for database objects.
12019  * It's much faster to pull them all at once.
12020  *
12021  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12022  */
12023 static int
12024 collectSecLabels(Archive *fout, SecLabelItem **items)
12025 {
12026         PGresult   *res;
12027         PQExpBuffer query;
12028         int                     i_label;
12029         int                     i_provider;
12030         int                     i_classoid;
12031         int                     i_objoid;
12032         int                     i_objsubid;
12033         int                     ntups;
12034         int                     i;
12035         SecLabelItem *labels;
12036
12037         query = createPQExpBuffer();
12038
12039         appendPQExpBuffer(query,
12040                                           "SELECT label, provider, classoid, objoid, objsubid "
12041                                           "FROM pg_catalog.pg_seclabel "
12042                                           "ORDER BY classoid, objoid, objsubid");
12043
12044         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12045
12046         /* Construct lookup table containing OIDs in numeric form */
12047         i_label = PQfnumber(res, "label");
12048         i_provider = PQfnumber(res, "provider");
12049         i_classoid = PQfnumber(res, "classoid");
12050         i_objoid = PQfnumber(res, "objoid");
12051         i_objsubid = PQfnumber(res, "objsubid");
12052
12053         ntups = PQntuples(res);
12054
12055         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12056
12057         for (i = 0; i < ntups; i++)
12058         {
12059                 labels[i].label = PQgetvalue(res, i, i_label);
12060                 labels[i].provider = PQgetvalue(res, i, i_provider);
12061                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12062                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12063                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12064         }
12065
12066         /* Do NOT free the PGresult since we are keeping pointers into it */
12067         destroyPQExpBuffer(query);
12068
12069         *items = labels;
12070         return ntups;
12071 }
12072
12073 /*
12074  * dumpTable
12075  *        write out to fout the declarations (not data) of a user-defined table
12076  */
12077 static void
12078 dumpTable(Archive *fout, TableInfo *tbinfo)
12079 {
12080         if (tbinfo->dobj.dump)
12081         {
12082                 char       *namecopy;
12083
12084                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12085                         dumpSequence(fout, tbinfo);
12086                 else if (!dataOnly)
12087                         dumpTableSchema(fout, tbinfo);
12088
12089                 /* Handle the ACL here */
12090                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12091                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12092                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12093                                 "TABLE",
12094                                 namecopy, NULL, tbinfo->dobj.name,
12095                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12096                                 tbinfo->relacl);
12097
12098                 /*
12099                  * Handle column ACLs, if any.  Note: we pull these with a separate
12100                  * query rather than trying to fetch them during getTableAttrs, so
12101                  * that we won't miss ACLs on system columns.
12102                  */
12103                 if (fout->remoteVersion >= 80400)
12104                 {
12105                         PQExpBuffer query = createPQExpBuffer();
12106                         PGresult   *res;
12107                         int                     i;
12108
12109                         appendPQExpBuffer(query,
12110                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12111                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12112                                                           "ORDER BY attnum",
12113                                                           tbinfo->dobj.catId.oid);
12114                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12115
12116                         for (i = 0; i < PQntuples(res); i++)
12117                         {
12118                                 char       *attname = PQgetvalue(res, i, 0);
12119                                 char       *attacl = PQgetvalue(res, i, 1);
12120                                 char       *attnamecopy;
12121                                 char       *acltag;
12122
12123                                 attnamecopy = pg_strdup(fmtId(attname));
12124                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12125                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12126                                 /* Column's GRANT type is always TABLE */
12127                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12128                                                 namecopy, attnamecopy, acltag,
12129                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12130                                                 attacl);
12131                                 free(attnamecopy);
12132                                 free(acltag);
12133                         }
12134                         PQclear(res);
12135                         destroyPQExpBuffer(query);
12136                 }
12137
12138                 free(namecopy);
12139         }
12140 }
12141
12142 /*
12143  * dumpTableSchema
12144  *        write the declaration (not data) of one user-defined table or view
12145  */
12146 static void
12147 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12148 {
12149         PQExpBuffer query = createPQExpBuffer();
12150         PQExpBuffer q = createPQExpBuffer();
12151         PQExpBuffer delq = createPQExpBuffer();
12152         PQExpBuffer labelq = createPQExpBuffer();
12153         PGresult   *res;
12154         int                     numParents;
12155         TableInfo **parents;
12156         int                     actual_atts;    /* number of attrs in this CREATE statement */
12157         const char *reltypename;
12158         char       *storage;
12159         char       *srvname;
12160         char       *ftoptions;
12161         int                     j,
12162                                 k;
12163
12164         /* Make sure we are in proper schema */
12165         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12166
12167         if (binary_upgrade)
12168                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12169                                                                                                 tbinfo->dobj.catId.oid);
12170
12171         /* Is it a table or a view? */
12172         if (tbinfo->relkind == RELKIND_VIEW)
12173         {
12174                 char       *viewdef;
12175
12176                 reltypename = "VIEW";
12177
12178                 /* Fetch the view definition */
12179                 if (fout->remoteVersion >= 70300)
12180                 {
12181                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12182                         appendPQExpBuffer(query,
12183                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12184                                                           tbinfo->dobj.catId.oid);
12185                 }
12186                 else
12187                 {
12188                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12189                                                           "FROM pg_views WHERE viewname = ");
12190                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12191                         appendPQExpBuffer(query, ";");
12192                 }
12193
12194                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12195
12196                 if (PQntuples(res) != 1)
12197                 {
12198                         if (PQntuples(res) < 1)
12199                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12200                                                           tbinfo->dobj.name);
12201                         else
12202                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12203                                                           tbinfo->dobj.name);
12204                 }
12205
12206                 viewdef = PQgetvalue(res, 0, 0);
12207
12208                 if (strlen(viewdef) == 0)
12209                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12210                                                   tbinfo->dobj.name);
12211
12212                 /*
12213                  * DROP must be fully qualified in case same name appears in
12214                  * pg_catalog
12215                  */
12216                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12217                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12218                 appendPQExpBuffer(delq, "%s;\n",
12219                                                   fmtId(tbinfo->dobj.name));
12220
12221                 if (binary_upgrade)
12222                         binary_upgrade_set_pg_class_oids(fout, q,
12223                                                                                          tbinfo->dobj.catId.oid, false);
12224
12225                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12226                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12227                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12228                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12229
12230                 appendPQExpBuffer(labelq, "VIEW %s",
12231                                                   fmtId(tbinfo->dobj.name));
12232
12233                 PQclear(res);
12234         }
12235         else
12236         {
12237                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12238                 {
12239                         int                     i_srvname;
12240                         int                     i_ftoptions;
12241
12242                         reltypename = "FOREIGN TABLE";
12243
12244                         /* retrieve name of foreign server and generic options */
12245                         appendPQExpBuffer(query,
12246                                                           "SELECT fs.srvname, "
12247                                                           "pg_catalog.array_to_string(ARRAY("
12248                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12249                                                           "' ' || pg_catalog.quote_literal(option_value) "
12250                                                         "FROM pg_catalog.pg_options_to_table(ftoptions) "
12251                                                           "ORDER BY option_name"
12252                                                           "), E',\n    ') AS ftoptions "
12253                                                           "FROM pg_catalog.pg_foreign_table ft "
12254                                                           "JOIN pg_catalog.pg_foreign_server fs "
12255                                                           "ON (fs.oid = ft.ftserver) "
12256                                                           "WHERE ft.ftrelid = '%u'",
12257                                                           tbinfo->dobj.catId.oid);
12258                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12259                         i_srvname = PQfnumber(res, "srvname");
12260                         i_ftoptions = PQfnumber(res, "ftoptions");
12261                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12262                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12263                         PQclear(res);
12264                 }
12265                 else
12266                 {
12267                         reltypename = "TABLE";
12268                         srvname = NULL;
12269                         ftoptions = NULL;
12270                 }
12271                 numParents = tbinfo->numParents;
12272                 parents = tbinfo->parents;
12273
12274                 /*
12275                  * DROP must be fully qualified in case same name appears in
12276                  * pg_catalog
12277                  */
12278                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12279                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12280                 appendPQExpBuffer(delq, "%s;\n",
12281                                                   fmtId(tbinfo->dobj.name));
12282
12283                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12284                                                   fmtId(tbinfo->dobj.name));
12285
12286                 if (binary_upgrade)
12287                         binary_upgrade_set_pg_class_oids(fout, q,
12288                                                                                          tbinfo->dobj.catId.oid, false);
12289
12290                 appendPQExpBuffer(q, "CREATE %s%s %s",
12291                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12292                                                   "UNLOGGED " : "",
12293                                                   reltypename,
12294                                                   fmtId(tbinfo->dobj.name));
12295
12296                 /*
12297                  * Attach to type, if reloftype; except in case of a binary upgrade,
12298                  * we dump the table normally and attach it to the type afterward.
12299                  */
12300                 if (tbinfo->reloftype && !binary_upgrade)
12301                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12302
12303                 /* Dump the attributes */
12304                 actual_atts = 0;
12305                 for (j = 0; j < tbinfo->numatts; j++)
12306                 {
12307                         /*
12308                          * Normally, dump if it's locally defined in this table, and not
12309                          * dropped.  But for binary upgrade, we'll dump all the columns,
12310                          * and then fix up the dropped and nonlocal cases below.
12311                          */
12312                         if (shouldPrintColumn(tbinfo, j))
12313                         {
12314                                 /*
12315                                  * Default value --- suppress if to be printed separately.
12316                                  */
12317                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12318                                                                                    !tbinfo->attrdefs[j]->separate);
12319
12320                                 /*
12321                                  * Not Null constraint --- suppress if inherited, except in
12322                                  * binary-upgrade case where that won't work.
12323                                  */
12324                                 bool            has_notnull = (tbinfo->notnull[j] &&
12325                                                                                    (!tbinfo->inhNotNull[j] ||
12326                                                                                         binary_upgrade));
12327
12328                                 /* Skip column if fully defined by reloftype */
12329                                 if (tbinfo->reloftype &&
12330                                         !has_default && !has_notnull && !binary_upgrade)
12331                                         continue;
12332
12333                                 /* Format properly if not first attr */
12334                                 if (actual_atts == 0)
12335                                         appendPQExpBuffer(q, " (");
12336                                 else
12337                                         appendPQExpBuffer(q, ",");
12338                                 appendPQExpBuffer(q, "\n    ");
12339                                 actual_atts++;
12340
12341                                 /* Attribute name */
12342                                 appendPQExpBuffer(q, "%s ",
12343                                                                   fmtId(tbinfo->attnames[j]));
12344
12345                                 if (tbinfo->attisdropped[j])
12346                                 {
12347                                         /*
12348                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12349                                          * so we will not have gotten a valid type name; insert
12350                                          * INTEGER as a stopgap.  We'll clean things up later.
12351                                          */
12352                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12353                                         /* Skip all the rest, too */
12354                                         continue;
12355                                 }
12356
12357                                 /* Attribute type */
12358                                 if (tbinfo->reloftype && !binary_upgrade)
12359                                 {
12360                                         appendPQExpBuffer(q, "WITH OPTIONS");
12361                                 }
12362                                 else if (fout->remoteVersion >= 70100)
12363                                 {
12364                                         appendPQExpBuffer(q, "%s",
12365                                                                           tbinfo->atttypnames[j]);
12366                                 }
12367                                 else
12368                                 {
12369                                         /* If no format_type, fake it */
12370                                         appendPQExpBuffer(q, "%s",
12371                                                                           myFormatType(tbinfo->atttypnames[j],
12372                                                                                                    tbinfo->atttypmod[j]));
12373                                 }
12374
12375                                 /* Add collation if not default for the type */
12376                                 if (OidIsValid(tbinfo->attcollation[j]))
12377                                 {
12378                                         CollInfo   *coll;
12379
12380                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12381                                         if (coll)
12382                                         {
12383                                                 /* always schema-qualify, don't try to be smart */
12384                                                 appendPQExpBuffer(q, " COLLATE %s.",
12385                                                                          fmtId(coll->dobj.namespace->dobj.name));
12386                                                 appendPQExpBuffer(q, "%s",
12387                                                                                   fmtId(coll->dobj.name));
12388                                         }
12389                                 }
12390
12391                                 if (has_default)
12392                                         appendPQExpBuffer(q, " DEFAULT %s",
12393                                                                           tbinfo->attrdefs[j]->adef_expr);
12394
12395                                 if (has_notnull)
12396                                         appendPQExpBuffer(q, " NOT NULL");
12397                         }
12398                 }
12399
12400                 /*
12401                  * Add non-inherited CHECK constraints, if any.
12402                  */
12403                 for (j = 0; j < tbinfo->ncheck; j++)
12404                 {
12405                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12406
12407                         if (constr->separate || !constr->conislocal)
12408                                 continue;
12409
12410                         if (actual_atts == 0)
12411                                 appendPQExpBuffer(q, " (\n    ");
12412                         else
12413                                 appendPQExpBuffer(q, ",\n    ");
12414
12415                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12416                                                           fmtId(constr->dobj.name));
12417                         appendPQExpBuffer(q, "%s", constr->condef);
12418
12419                         actual_atts++;
12420                 }
12421
12422                 if (actual_atts)
12423                         appendPQExpBuffer(q, "\n)");
12424                 else if (!(tbinfo->reloftype && !binary_upgrade))
12425                 {
12426                         /*
12427                          * We must have a parenthesized attribute list, even though empty,
12428                          * when not using the OF TYPE syntax.
12429                          */
12430                         appendPQExpBuffer(q, " (\n)");
12431                 }
12432
12433                 if (numParents > 0 && !binary_upgrade)
12434                 {
12435                         appendPQExpBuffer(q, "\nINHERITS (");
12436                         for (k = 0; k < numParents; k++)
12437                         {
12438                                 TableInfo  *parentRel = parents[k];
12439
12440                                 if (k > 0)
12441                                         appendPQExpBuffer(q, ", ");
12442                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12443                                         appendPQExpBuffer(q, "%s.",
12444                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12445                                 appendPQExpBuffer(q, "%s",
12446                                                                   fmtId(parentRel->dobj.name));
12447                         }
12448                         appendPQExpBuffer(q, ")");
12449                 }
12450
12451                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12452                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12453
12454                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12455                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12456                 {
12457                         bool            addcomma = false;
12458
12459                         appendPQExpBuffer(q, "\nWITH (");
12460                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12461                         {
12462                                 addcomma = true;
12463                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12464                         }
12465                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12466                         {
12467                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12468                                                                   tbinfo->toast_reloptions);
12469                         }
12470                         appendPQExpBuffer(q, ")");
12471                 }
12472
12473                 /* Dump generic options if any */
12474                 if (ftoptions && ftoptions[0])
12475                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12476
12477                 appendPQExpBuffer(q, ";\n");
12478
12479                 /*
12480                  * To create binary-compatible heap files, we have to ensure the same
12481                  * physical column order, including dropped columns, as in the
12482                  * original.  Therefore, we create dropped columns above and drop them
12483                  * here, also updating their attlen/attalign values so that the
12484                  * dropped column can be skipped properly.      (We do not bother with
12485                  * restoring the original attbyval setting.)  Also, inheritance
12486                  * relationships are set up by doing ALTER INHERIT rather than using
12487                  * an INHERITS clause --- the latter would possibly mess up the column
12488                  * order.  That also means we have to take care about setting
12489                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12490                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12491                  */
12492                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12493                 {
12494                         for (j = 0; j < tbinfo->numatts; j++)
12495                         {
12496                                 if (tbinfo->attisdropped[j])
12497                                 {
12498                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12499                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12500                                                                           "SET attlen = %d, "
12501                                                                           "attalign = '%c', attbyval = false\n"
12502                                                                           "WHERE attname = ",
12503                                                                           tbinfo->attlen[j],
12504                                                                           tbinfo->attalign[j]);
12505                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12506                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12507                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12508                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12509
12510                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12511                                                                           fmtId(tbinfo->dobj.name));
12512                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12513                                                                           fmtId(tbinfo->attnames[j]));
12514                                 }
12515                                 else if (!tbinfo->attislocal[j])
12516                                 {
12517                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12518                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12519                                                                           "SET attislocal = false\n"
12520                                                                           "WHERE attname = ");
12521                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12522                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12523                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12524                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12525                                 }
12526                         }
12527
12528                         for (k = 0; k < tbinfo->ncheck; k++)
12529                         {
12530                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12531
12532                                 if (constr->separate || constr->conislocal)
12533                                         continue;
12534
12535                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12536                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12537                                                                   fmtId(tbinfo->dobj.name));
12538                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12539                                                                   fmtId(constr->dobj.name));
12540                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12541                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12542                                                                   "SET conislocal = false\n"
12543                                                                   "WHERE contype = 'c' AND conname = ");
12544                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12545                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12546                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12547                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12548                         }
12549
12550                         if (numParents > 0)
12551                         {
12552                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12553                                 for (k = 0; k < numParents; k++)
12554                                 {
12555                                         TableInfo  *parentRel = parents[k];
12556
12557                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12558                                                                           fmtId(tbinfo->dobj.name));
12559                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12560                                                 appendPQExpBuffer(q, "%s.",
12561                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12562                                         appendPQExpBuffer(q, "%s;\n",
12563                                                                           fmtId(parentRel->dobj.name));
12564                                 }
12565                         }
12566
12567                         if (tbinfo->reloftype)
12568                         {
12569                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12570                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12571                                                                   fmtId(tbinfo->dobj.name),
12572                                                                   tbinfo->reloftype);
12573                         }
12574
12575                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12576                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12577                                                           "SET relfrozenxid = '%u'\n"
12578                                                           "WHERE oid = ",
12579                                                           tbinfo->frozenxid);
12580                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12581                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12582
12583                         if (tbinfo->toast_oid)
12584                         {
12585                                 /* We preserve the toast oids, so we can use it during restore */
12586                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12587                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12588                                                                   "SET relfrozenxid = '%u'\n"
12589                                                                   "WHERE oid = '%u';\n",
12590                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12591                         }
12592                 }
12593
12594                 /*
12595                  * Dump additional per-column properties that we can't handle in the
12596                  * main CREATE TABLE command.
12597                  */
12598                 for (j = 0; j < tbinfo->numatts; j++)
12599                 {
12600                         /* None of this applies to dropped columns */
12601                         if (tbinfo->attisdropped[j])
12602                                 continue;
12603
12604                         /*
12605                          * If we didn't dump the column definition explicitly above, and
12606                          * it is NOT NULL and did not inherit that property from a parent,
12607                          * we have to mark it separately.
12608                          */
12609                         if (!shouldPrintColumn(tbinfo, j) &&
12610                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12611                         {
12612                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12613                                                                   fmtId(tbinfo->dobj.name));
12614                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12615                                                                   fmtId(tbinfo->attnames[j]));
12616                         }
12617
12618                         /*
12619                          * Dump per-column statistics information. We only issue an ALTER
12620                          * TABLE statement if the attstattarget entry for this column is
12621                          * non-negative (i.e. it's not the default value)
12622                          */
12623                         if (tbinfo->attstattarget[j] >= 0)
12624                         {
12625                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12626                                                                   fmtId(tbinfo->dobj.name));
12627                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12628                                                                   fmtId(tbinfo->attnames[j]));
12629                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12630                                                                   tbinfo->attstattarget[j]);
12631                         }
12632
12633                         /*
12634                          * Dump per-column storage information.  The statement is only
12635                          * dumped if the storage has been changed from the type's default.
12636                          */
12637                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12638                         {
12639                                 switch (tbinfo->attstorage[j])
12640                                 {
12641                                         case 'p':
12642                                                 storage = "PLAIN";
12643                                                 break;
12644                                         case 'e':
12645                                                 storage = "EXTERNAL";
12646                                                 break;
12647                                         case 'm':
12648                                                 storage = "MAIN";
12649                                                 break;
12650                                         case 'x':
12651                                                 storage = "EXTENDED";
12652                                                 break;
12653                                         default:
12654                                                 storage = NULL;
12655                                 }
12656
12657                                 /*
12658                                  * Only dump the statement if it's a storage type we recognize
12659                                  */
12660                                 if (storage != NULL)
12661                                 {
12662                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12663                                                                           fmtId(tbinfo->dobj.name));
12664                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12665                                                                           fmtId(tbinfo->attnames[j]));
12666                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12667                                                                           storage);
12668                                 }
12669                         }
12670
12671                         /*
12672                          * Dump per-column attributes.
12673                          */
12674                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12675                         {
12676                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12677                                                                   fmtId(tbinfo->dobj.name));
12678                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12679                                                                   fmtId(tbinfo->attnames[j]));
12680                                 appendPQExpBuffer(q, "SET (%s);\n",
12681                                                                   tbinfo->attoptions[j]);
12682                         }
12683
12684                         /*
12685                          * Dump per-column fdw options.
12686                          */
12687                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12688                                 tbinfo->attfdwoptions[j] &&
12689                                 tbinfo->attfdwoptions[j][0] != '\0')
12690                         {
12691                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12692                                                                   fmtId(tbinfo->dobj.name));
12693                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12694                                                                   fmtId(tbinfo->attnames[j]));
12695                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12696                                                                   tbinfo->attfdwoptions[j]);
12697                         }
12698                 }
12699         }
12700
12701         if (binary_upgrade)
12702                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12703
12704         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12705                                  tbinfo->dobj.name,
12706                                  tbinfo->dobj.namespace->dobj.name,
12707                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12708                                  tbinfo->rolname,
12709                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12710                                  reltypename, SECTION_PRE_DATA,
12711                                  q->data, delq->data, NULL,
12712                                  NULL, 0,
12713                                  NULL, NULL);
12714
12715
12716         /* Dump Table Comments */
12717         dumpTableComment(fout, tbinfo, reltypename);
12718
12719         /* Dump Table Security Labels */
12720         dumpTableSecLabel(fout, tbinfo, reltypename);
12721
12722         /* Dump comments on inlined table constraints */
12723         for (j = 0; j < tbinfo->ncheck; j++)
12724         {
12725                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12726
12727                 if (constr->separate || !constr->conislocal)
12728                         continue;
12729
12730                 dumpTableConstraintComment(fout, constr);
12731         }
12732
12733         destroyPQExpBuffer(query);
12734         destroyPQExpBuffer(q);
12735         destroyPQExpBuffer(delq);
12736         destroyPQExpBuffer(labelq);
12737 }
12738
12739 /*
12740  * dumpAttrDef --- dump an attribute's default-value declaration
12741  */
12742 static void
12743 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12744 {
12745         TableInfo  *tbinfo = adinfo->adtable;
12746         int                     adnum = adinfo->adnum;
12747         PQExpBuffer q;
12748         PQExpBuffer delq;
12749
12750         /* Skip if table definition not to be dumped */
12751         if (!tbinfo->dobj.dump || dataOnly)
12752                 return;
12753
12754         /* Skip if not "separate"; it was dumped in the table's definition */
12755         if (!adinfo->separate)
12756                 return;
12757
12758         q = createPQExpBuffer();
12759         delq = createPQExpBuffer();
12760
12761         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12762                                           fmtId(tbinfo->dobj.name));
12763         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12764                                           fmtId(tbinfo->attnames[adnum - 1]),
12765                                           adinfo->adef_expr);
12766
12767         /*
12768          * DROP must be fully qualified in case same name appears in pg_catalog
12769          */
12770         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12771                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12772         appendPQExpBuffer(delq, "%s ",
12773                                           fmtId(tbinfo->dobj.name));
12774         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12775                                           fmtId(tbinfo->attnames[adnum - 1]));
12776
12777         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12778                                  tbinfo->attnames[adnum - 1],
12779                                  tbinfo->dobj.namespace->dobj.name,
12780                                  NULL,
12781                                  tbinfo->rolname,
12782                                  false, "DEFAULT", SECTION_PRE_DATA,
12783                                  q->data, delq->data, NULL,
12784                                  NULL, 0,
12785                                  NULL, NULL);
12786
12787         destroyPQExpBuffer(q);
12788         destroyPQExpBuffer(delq);
12789 }
12790
12791 /*
12792  * getAttrName: extract the correct name for an attribute
12793  *
12794  * The array tblInfo->attnames[] only provides names of user attributes;
12795  * if a system attribute number is supplied, we have to fake it.
12796  * We also do a little bit of bounds checking for safety's sake.
12797  */
12798 static const char *
12799 getAttrName(int attrnum, TableInfo *tblInfo)
12800 {
12801         if (attrnum > 0 && attrnum <= tblInfo->numatts)
12802                 return tblInfo->attnames[attrnum - 1];
12803         switch (attrnum)
12804         {
12805                 case SelfItemPointerAttributeNumber:
12806                         return "ctid";
12807                 case ObjectIdAttributeNumber:
12808                         return "oid";
12809                 case MinTransactionIdAttributeNumber:
12810                         return "xmin";
12811                 case MinCommandIdAttributeNumber:
12812                         return "cmin";
12813                 case MaxTransactionIdAttributeNumber:
12814                         return "xmax";
12815                 case MaxCommandIdAttributeNumber:
12816                         return "cmax";
12817                 case TableOidAttributeNumber:
12818                         return "tableoid";
12819         }
12820         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12821                                   attrnum, tblInfo->dobj.name);
12822         return NULL;                            /* keep compiler quiet */
12823 }
12824
12825 /*
12826  * dumpIndex
12827  *        write out to fout a user-defined index
12828  */
12829 static void
12830 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12831 {
12832         TableInfo  *tbinfo = indxinfo->indextable;
12833         PQExpBuffer q;
12834         PQExpBuffer delq;
12835         PQExpBuffer labelq;
12836
12837         if (dataOnly)
12838                 return;
12839
12840         q = createPQExpBuffer();
12841         delq = createPQExpBuffer();
12842         labelq = createPQExpBuffer();
12843
12844         appendPQExpBuffer(labelq, "INDEX %s",
12845                                           fmtId(indxinfo->dobj.name));
12846
12847         /*
12848          * If there's an associated constraint, don't dump the index per se, but
12849          * do dump any comment for it.  (This is safe because dependency ordering
12850          * will have ensured the constraint is emitted first.)
12851          */
12852         if (indxinfo->indexconstraint == 0)
12853         {
12854                 if (binary_upgrade)
12855                         binary_upgrade_set_pg_class_oids(fout, q,
12856                                                                                          indxinfo->dobj.catId.oid, true);
12857
12858                 /* Plain secondary index */
12859                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12860
12861                 /* If the index is clustered, we need to record that. */
12862                 if (indxinfo->indisclustered)
12863                 {
12864                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12865                                                           fmtId(tbinfo->dobj.name));
12866                         appendPQExpBuffer(q, " ON %s;\n",
12867                                                           fmtId(indxinfo->dobj.name));
12868                 }
12869
12870                 /*
12871                  * DROP must be fully qualified in case same name appears in
12872                  * pg_catalog
12873                  */
12874                 appendPQExpBuffer(delq, "DROP INDEX %s.",
12875                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12876                 appendPQExpBuffer(delq, "%s;\n",
12877                                                   fmtId(indxinfo->dobj.name));
12878
12879                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12880                                          indxinfo->dobj.name,
12881                                          tbinfo->dobj.namespace->dobj.name,
12882                                          indxinfo->tablespace,
12883                                          tbinfo->rolname, false,
12884                                          "INDEX", SECTION_POST_DATA,
12885                                          q->data, delq->data, NULL,
12886                                          NULL, 0,
12887                                          NULL, NULL);
12888         }
12889
12890         /* Dump Index Comments */
12891         dumpComment(fout, labelq->data,
12892                                 tbinfo->dobj.namespace->dobj.name,
12893                                 tbinfo->rolname,
12894                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12895
12896         destroyPQExpBuffer(q);
12897         destroyPQExpBuffer(delq);
12898         destroyPQExpBuffer(labelq);
12899 }
12900
12901 /*
12902  * dumpConstraint
12903  *        write out to fout a user-defined constraint
12904  */
12905 static void
12906 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12907 {
12908         TableInfo  *tbinfo = coninfo->contable;
12909         PQExpBuffer q;
12910         PQExpBuffer delq;
12911
12912         /* Skip if not to be dumped */
12913         if (!coninfo->dobj.dump || dataOnly)
12914                 return;
12915
12916         q = createPQExpBuffer();
12917         delq = createPQExpBuffer();
12918
12919         if (coninfo->contype == 'p' ||
12920                 coninfo->contype == 'u' ||
12921                 coninfo->contype == 'x')
12922         {
12923                 /* Index-related constraint */
12924                 IndxInfo   *indxinfo;
12925                 int                     k;
12926
12927                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12928
12929                 if (indxinfo == NULL)
12930                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12931                                                   coninfo->dobj.name);
12932
12933                 if (binary_upgrade)
12934                         binary_upgrade_set_pg_class_oids(fout, q,
12935                                                                                          indxinfo->dobj.catId.oid, true);
12936
12937                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12938                                                   fmtId(tbinfo->dobj.name));
12939                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
12940                                                   fmtId(coninfo->dobj.name));
12941
12942                 if (coninfo->condef)
12943                 {
12944                         /* pg_get_constraintdef should have provided everything */
12945                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12946                 }
12947                 else
12948                 {
12949                         appendPQExpBuffer(q, "%s (",
12950                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12951                         for (k = 0; k < indxinfo->indnkeys; k++)
12952                         {
12953                                 int                     indkey = (int) indxinfo->indkeys[k];
12954                                 const char *attname;
12955
12956                                 if (indkey == InvalidAttrNumber)
12957                                         break;
12958                                 attname = getAttrName(indkey, tbinfo);
12959
12960                                 appendPQExpBuffer(q, "%s%s",
12961                                                                   (k == 0) ? "" : ", ",
12962                                                                   fmtId(attname));
12963                         }
12964
12965                         appendPQExpBuffer(q, ")");
12966
12967                         if (indxinfo->options && strlen(indxinfo->options) > 0)
12968                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12969
12970                         if (coninfo->condeferrable)
12971                         {
12972                                 appendPQExpBuffer(q, " DEFERRABLE");
12973                                 if (coninfo->condeferred)
12974                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
12975                         }
12976
12977                         appendPQExpBuffer(q, ";\n");
12978                 }
12979
12980                 /* If the index is clustered, we need to record that. */
12981                 if (indxinfo->indisclustered)
12982                 {
12983                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12984                                                           fmtId(tbinfo->dobj.name));
12985                         appendPQExpBuffer(q, " ON %s;\n",
12986                                                           fmtId(indxinfo->dobj.name));
12987                 }
12988
12989                 /*
12990                  * DROP must be fully qualified in case same name appears in
12991                  * pg_catalog
12992                  */
12993                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12994                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12995                 appendPQExpBuffer(delq, "%s ",
12996                                                   fmtId(tbinfo->dobj.name));
12997                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12998                                                   fmtId(coninfo->dobj.name));
12999
13000                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13001                                          coninfo->dobj.name,
13002                                          tbinfo->dobj.namespace->dobj.name,
13003                                          indxinfo->tablespace,
13004                                          tbinfo->rolname, false,
13005                                          "CONSTRAINT", SECTION_POST_DATA,
13006                                          q->data, delq->data, NULL,
13007                                          NULL, 0,
13008                                          NULL, NULL);
13009         }
13010         else if (coninfo->contype == 'f')
13011         {
13012                 /*
13013                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13014                  * current table data is not processed
13015                  */
13016                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13017                                                   fmtId(tbinfo->dobj.name));
13018                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13019                                                   fmtId(coninfo->dobj.name),
13020                                                   coninfo->condef);
13021
13022                 /*
13023                  * DROP must be fully qualified in case same name appears in
13024                  * pg_catalog
13025                  */
13026                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13027                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13028                 appendPQExpBuffer(delq, "%s ",
13029                                                   fmtId(tbinfo->dobj.name));
13030                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13031                                                   fmtId(coninfo->dobj.name));
13032
13033                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13034                                          coninfo->dobj.name,
13035                                          tbinfo->dobj.namespace->dobj.name,
13036                                          NULL,
13037                                          tbinfo->rolname, false,
13038                                          "FK CONSTRAINT", SECTION_POST_DATA,
13039                                          q->data, delq->data, NULL,
13040                                          NULL, 0,
13041                                          NULL, NULL);
13042         }
13043         else if (coninfo->contype == 'c' && tbinfo)
13044         {
13045                 /* CHECK constraint on a table */
13046
13047                 /* Ignore if not to be dumped separately */
13048                 if (coninfo->separate)
13049                 {
13050                         /* not ONLY since we want it to propagate to children */
13051                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13052                                                           fmtId(tbinfo->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 TABLE %s.",
13062                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13063                         appendPQExpBuffer(delq, "%s ",
13064                                                           fmtId(tbinfo->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                                                  tbinfo->dobj.namespace->dobj.name,
13071                                                  NULL,
13072                                                  tbinfo->rolname, false,
13073                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13074                                                  q->data, delq->data, NULL,
13075                                                  NULL, 0,
13076                                                  NULL, NULL);
13077                 }
13078         }
13079         else if (coninfo->contype == 'c' && tbinfo == NULL)
13080         {
13081                 /* CHECK constraint on a domain */
13082                 TypeInfo   *tyinfo = coninfo->condomain;
13083
13084                 /* Ignore if not to be dumped separately */
13085                 if (coninfo->separate)
13086                 {
13087                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13088                                                           fmtId(tyinfo->dobj.name));
13089                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13090                                                           fmtId(coninfo->dobj.name),
13091                                                           coninfo->condef);
13092
13093                         /*
13094                          * DROP must be fully qualified in case same name appears in
13095                          * pg_catalog
13096                          */
13097                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13098                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13099                         appendPQExpBuffer(delq, "%s ",
13100                                                           fmtId(tyinfo->dobj.name));
13101                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13102                                                           fmtId(coninfo->dobj.name));
13103
13104                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13105                                                  coninfo->dobj.name,
13106                                                  tyinfo->dobj.namespace->dobj.name,
13107                                                  NULL,
13108                                                  tyinfo->rolname, false,
13109                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13110                                                  q->data, delq->data, NULL,
13111                                                  NULL, 0,
13112                                                  NULL, NULL);
13113                 }
13114         }
13115         else
13116         {
13117                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13118                                           coninfo->contype);
13119         }
13120
13121         /* Dump Constraint Comments --- only works for table constraints */
13122         if (tbinfo && coninfo->separate)
13123                 dumpTableConstraintComment(fout, coninfo);
13124
13125         destroyPQExpBuffer(q);
13126         destroyPQExpBuffer(delq);
13127 }
13128
13129 /*
13130  * dumpTableConstraintComment --- dump a constraint's comment if any
13131  *
13132  * This is split out because we need the function in two different places
13133  * depending on whether the constraint is dumped as part of CREATE TABLE
13134  * or as a separate ALTER command.
13135  */
13136 static void
13137 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13138 {
13139         TableInfo  *tbinfo = coninfo->contable;
13140         PQExpBuffer labelq = createPQExpBuffer();
13141
13142         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13143                                           fmtId(coninfo->dobj.name));
13144         appendPQExpBuffer(labelq, "ON %s",
13145                                           fmtId(tbinfo->dobj.name));
13146         dumpComment(fout, labelq->data,
13147                                 tbinfo->dobj.namespace->dobj.name,
13148                                 tbinfo->rolname,
13149                                 coninfo->dobj.catId, 0,
13150                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13151
13152         destroyPQExpBuffer(labelq);
13153 }
13154
13155 /*
13156  * findLastBuiltInOid -
13157  * find the last built in oid
13158  *
13159  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13160  * pg_database entry for the current database
13161  */
13162 static Oid
13163 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13164 {
13165         PGresult   *res;
13166         Oid                     last_oid;
13167         PQExpBuffer query = createPQExpBuffer();
13168
13169         resetPQExpBuffer(query);
13170         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13171         appendStringLiteralAH(query, dbname, fout);
13172
13173         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13174         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13175         PQclear(res);
13176         destroyPQExpBuffer(query);
13177         return last_oid;
13178 }
13179
13180 /*
13181  * findLastBuiltInOid -
13182  * find the last built in oid
13183  *
13184  * For 7.0, we do this by assuming that the last thing that initdb does is to
13185  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13186  * initdb won't be changing anymore, it'll do.
13187  */
13188 static Oid
13189 findLastBuiltinOid_V70(Archive *fout)
13190 {
13191         PGresult   *res;
13192         int                     last_oid;
13193
13194         res = ExecuteSqlQueryForSingleRow(fout,
13195                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13196         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13197         PQclear(res);
13198         return last_oid;
13199 }
13200
13201 static void
13202 dumpSequence(Archive *fout, TableInfo *tbinfo)
13203 {
13204         PGresult   *res;
13205         char       *startv,
13206                            *last,
13207                            *incby,
13208                            *maxv = NULL,
13209                            *minv = NULL,
13210                            *cache;
13211         char            bufm[100],
13212                                 bufx[100];
13213         bool            cycled,
13214                                 called;
13215         PQExpBuffer query = createPQExpBuffer();
13216         PQExpBuffer delqry = createPQExpBuffer();
13217         PQExpBuffer labelq = createPQExpBuffer();
13218
13219         /* Make sure we are in proper schema */
13220         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13221
13222         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13223         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13224
13225         if (fout->remoteVersion >= 80400)
13226         {
13227                 appendPQExpBuffer(query,
13228                                                   "SELECT sequence_name, "
13229                                                   "start_value, last_value, increment_by, "
13230                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13231                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13232                                                   "     ELSE max_value "
13233                                                   "END AS max_value, "
13234                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13235                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13236                                                   "     ELSE min_value "
13237                                                   "END AS min_value, "
13238                                                   "cache_value, is_cycled, is_called from %s",
13239                                                   bufx, bufm,
13240                                                   fmtId(tbinfo->dobj.name));
13241         }
13242         else
13243         {
13244                 appendPQExpBuffer(query,
13245                                                   "SELECT sequence_name, "
13246                                                   "0 AS start_value, last_value, increment_by, "
13247                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13248                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13249                                                   "     ELSE max_value "
13250                                                   "END AS max_value, "
13251                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13252                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13253                                                   "     ELSE min_value "
13254                                                   "END AS min_value, "
13255                                                   "cache_value, is_cycled, is_called from %s",
13256                                                   bufx, bufm,
13257                                                   fmtId(tbinfo->dobj.name));
13258         }
13259
13260         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13261
13262         if (PQntuples(res) != 1)
13263         {
13264                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13265                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13266                                                                  PQntuples(res)),
13267                                   tbinfo->dobj.name, PQntuples(res));
13268                 exit_nicely(1);
13269         }
13270
13271         /* Disable this check: it fails if sequence has been renamed */
13272 #ifdef NOT_USED
13273         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13274         {
13275                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13276                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13277                 exit_nicely(1);
13278         }
13279 #endif
13280
13281         startv = PQgetvalue(res, 0, 1);
13282         last = PQgetvalue(res, 0, 2);
13283         incby = PQgetvalue(res, 0, 3);
13284         if (!PQgetisnull(res, 0, 4))
13285                 maxv = PQgetvalue(res, 0, 4);
13286         if (!PQgetisnull(res, 0, 5))
13287                 minv = PQgetvalue(res, 0, 5);
13288         cache = PQgetvalue(res, 0, 6);
13289         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13290         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13291
13292         /*
13293          * The logic we use for restoring sequences is as follows:
13294          *
13295          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13296          * last_val for start if called is false, else use min_val for start_val).
13297          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13298          * BY command for it.
13299          *
13300          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13301          */
13302         if (!dataOnly)
13303         {
13304                 /*
13305                  * DROP must be fully qualified in case same name appears in
13306                  * pg_catalog
13307                  */
13308                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13309                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13310                 appendPQExpBuffer(delqry, "%s;\n",
13311                                                   fmtId(tbinfo->dobj.name));
13312
13313                 resetPQExpBuffer(query);
13314
13315                 if (binary_upgrade)
13316                 {
13317                         binary_upgrade_set_pg_class_oids(fout, query,
13318                                                                                          tbinfo->dobj.catId.oid, false);
13319                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13320                                                                                                         tbinfo->dobj.catId.oid);
13321                 }
13322
13323                 appendPQExpBuffer(query,
13324                                                   "CREATE SEQUENCE %s\n",
13325                                                   fmtId(tbinfo->dobj.name));
13326
13327                 if (fout->remoteVersion >= 80400)
13328                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13329                 else
13330                 {
13331                         /*
13332                          * Versions before 8.4 did not remember the true start value.  If
13333                          * is_called is false then the sequence has never been incremented
13334                          * so we can use last_val.      Otherwise punt and let it default.
13335                          */
13336                         if (!called)
13337                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13338                 }
13339
13340                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13341
13342                 if (minv)
13343                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13344                 else
13345                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13346
13347                 if (maxv)
13348                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13349                 else
13350                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13351
13352                 appendPQExpBuffer(query,
13353                                                   "    CACHE %s%s",
13354                                                   cache, (cycled ? "\n    CYCLE" : ""));
13355
13356                 appendPQExpBuffer(query, ";\n");
13357
13358                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13359
13360                 /* binary_upgrade:      no need to clear TOAST table oid */
13361
13362                 if (binary_upgrade)
13363                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13364                                                                                         labelq->data);
13365
13366                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13367                                          tbinfo->dobj.name,
13368                                          tbinfo->dobj.namespace->dobj.name,
13369                                          NULL,
13370                                          tbinfo->rolname,
13371                                          false, "SEQUENCE", SECTION_PRE_DATA,
13372                                          query->data, delqry->data, NULL,
13373                                          NULL, 0,
13374                                          NULL, NULL);
13375
13376                 /*
13377                  * If the sequence is owned by a table column, emit the ALTER for it
13378                  * as a separate TOC entry immediately following the sequence's own
13379                  * entry.  It's OK to do this rather than using full sorting logic,
13380                  * because the dependency that tells us it's owned will have forced
13381                  * the table to be created first.  We can't just include the ALTER in
13382                  * the TOC entry because it will fail if we haven't reassigned the
13383                  * sequence owner to match the table's owner.
13384                  *
13385                  * We need not schema-qualify the table reference because both
13386                  * sequence and table must be in the same schema.
13387                  */
13388                 if (OidIsValid(tbinfo->owning_tab))
13389                 {
13390                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13391
13392                         if (owning_tab && owning_tab->dobj.dump)
13393                         {
13394                                 resetPQExpBuffer(query);
13395                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13396                                                                   fmtId(tbinfo->dobj.name));
13397                                 appendPQExpBuffer(query, " OWNED BY %s",
13398                                                                   fmtId(owning_tab->dobj.name));
13399                                 appendPQExpBuffer(query, ".%s;\n",
13400                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13401
13402                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13403                                                          tbinfo->dobj.name,
13404                                                          tbinfo->dobj.namespace->dobj.name,
13405                                                          NULL,
13406                                                          tbinfo->rolname,
13407                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13408                                                          query->data, "", NULL,
13409                                                          &(tbinfo->dobj.dumpId), 1,
13410                                                          NULL, NULL);
13411                         }
13412                 }
13413
13414                 /* Dump Sequence Comments and Security Labels */
13415                 dumpComment(fout, labelq->data,
13416                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13417                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13418                 dumpSecLabel(fout, labelq->data,
13419                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13420                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13421         }
13422
13423         if (!schemaOnly)
13424         {
13425                 resetPQExpBuffer(query);
13426                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13427                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13428                 appendPQExpBuffer(query, ", %s, %s);\n",
13429                                                   last, (called ? "true" : "false"));
13430
13431                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13432                                          tbinfo->dobj.name,
13433                                          tbinfo->dobj.namespace->dobj.name,
13434                                          NULL,
13435                                          tbinfo->rolname,
13436                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13437                                          query->data, "", NULL,
13438                                          &(tbinfo->dobj.dumpId), 1,
13439                                          NULL, NULL);
13440         }
13441
13442         PQclear(res);
13443
13444         destroyPQExpBuffer(query);
13445         destroyPQExpBuffer(delqry);
13446         destroyPQExpBuffer(labelq);
13447 }
13448
13449 static void
13450 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13451 {
13452         TableInfo  *tbinfo = tginfo->tgtable;
13453         PQExpBuffer query;
13454         PQExpBuffer delqry;
13455         PQExpBuffer labelq;
13456         char       *tgargs;
13457         size_t          lentgargs;
13458         const char *p;
13459         int                     findx;
13460
13461         if (dataOnly)
13462                 return;
13463
13464         query = createPQExpBuffer();
13465         delqry = createPQExpBuffer();
13466         labelq = createPQExpBuffer();
13467
13468         /*
13469          * DROP must be fully qualified in case same name appears in pg_catalog
13470          */
13471         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13472                                           fmtId(tginfo->dobj.name));
13473         appendPQExpBuffer(delqry, "ON %s.",
13474                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13475         appendPQExpBuffer(delqry, "%s;\n",
13476                                           fmtId(tbinfo->dobj.name));
13477
13478         if (tginfo->tgdef)
13479         {
13480                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13481         }
13482         else
13483         {
13484                 if (tginfo->tgisconstraint)
13485                 {
13486                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13487                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13488                 }
13489                 else
13490                 {
13491                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13492                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13493                 }
13494                 appendPQExpBuffer(query, "\n    ");
13495
13496                 /* Trigger type */
13497                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13498                         appendPQExpBuffer(query, "BEFORE");
13499                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13500                         appendPQExpBuffer(query, "AFTER");
13501                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13502                         appendPQExpBuffer(query, "INSTEAD OF");
13503                 else
13504                 {
13505                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13506                         exit_nicely(1);
13507                 }
13508
13509                 findx = 0;
13510                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13511                 {
13512                         appendPQExpBuffer(query, " INSERT");
13513                         findx++;
13514                 }
13515                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13516                 {
13517                         if (findx > 0)
13518                                 appendPQExpBuffer(query, " OR DELETE");
13519                         else
13520                                 appendPQExpBuffer(query, " DELETE");
13521                         findx++;
13522                 }
13523                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13524                 {
13525                         if (findx > 0)
13526                                 appendPQExpBuffer(query, " OR UPDATE");
13527                         else
13528                                 appendPQExpBuffer(query, " UPDATE");
13529                         findx++;
13530                 }
13531                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13532                 {
13533                         if (findx > 0)
13534                                 appendPQExpBuffer(query, " OR TRUNCATE");
13535                         else
13536                                 appendPQExpBuffer(query, " TRUNCATE");
13537                         findx++;
13538                 }
13539                 appendPQExpBuffer(query, " ON %s\n",
13540                                                   fmtId(tbinfo->dobj.name));
13541
13542                 if (tginfo->tgisconstraint)
13543                 {
13544                         if (OidIsValid(tginfo->tgconstrrelid))
13545                         {
13546                                 /* If we are using regclass, name is already quoted */
13547                                 if (fout->remoteVersion >= 70300)
13548                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13549                                                                           tginfo->tgconstrrelname);
13550                                 else
13551                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13552                                                                           fmtId(tginfo->tgconstrrelname));
13553                         }
13554                         if (!tginfo->tgdeferrable)
13555                                 appendPQExpBuffer(query, "NOT ");
13556                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13557                         if (tginfo->tginitdeferred)
13558                                 appendPQExpBuffer(query, "DEFERRED\n");
13559                         else
13560                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13561                 }
13562
13563                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13564                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13565                 else
13566                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13567
13568                 /* In 7.3, result of regproc is already quoted */
13569                 if (fout->remoteVersion >= 70300)
13570                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13571                                                           tginfo->tgfname);
13572                 else
13573                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13574                                                           fmtId(tginfo->tgfname));
13575
13576                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13577                                                                                   &lentgargs);
13578                 p = tgargs;
13579                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13580                 {
13581                         /* find the embedded null that terminates this trigger argument */
13582                         size_t          tlen = strlen(p);
13583
13584                         if (p + tlen >= tgargs + lentgargs)
13585                         {
13586                                 /* hm, not found before end of bytea value... */
13587                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13588                                                   tginfo->tgargs,
13589                                                   tginfo->dobj.name,
13590                                                   tbinfo->dobj.name);
13591                                 exit_nicely(1);
13592                         }
13593
13594                         if (findx > 0)
13595                                 appendPQExpBuffer(query, ", ");
13596                         appendStringLiteralAH(query, p, fout);
13597                         p += tlen + 1;
13598                 }
13599                 free(tgargs);
13600                 appendPQExpBuffer(query, ");\n");
13601         }
13602
13603         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13604         {
13605                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13606                                                   fmtId(tbinfo->dobj.name));
13607                 switch (tginfo->tgenabled)
13608                 {
13609                         case 'D':
13610                         case 'f':
13611                                 appendPQExpBuffer(query, "DISABLE");
13612                                 break;
13613                         case 'A':
13614                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13615                                 break;
13616                         case 'R':
13617                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13618                                 break;
13619                         default:
13620                                 appendPQExpBuffer(query, "ENABLE");
13621                                 break;
13622                 }
13623                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13624                                                   fmtId(tginfo->dobj.name));
13625         }
13626
13627         appendPQExpBuffer(labelq, "TRIGGER %s ",
13628                                           fmtId(tginfo->dobj.name));
13629         appendPQExpBuffer(labelq, "ON %s",
13630                                           fmtId(tbinfo->dobj.name));
13631
13632         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13633                                  tginfo->dobj.name,
13634                                  tbinfo->dobj.namespace->dobj.name,
13635                                  NULL,
13636                                  tbinfo->rolname, false,
13637                                  "TRIGGER", SECTION_POST_DATA,
13638                                  query->data, delqry->data, NULL,
13639                                  NULL, 0,
13640                                  NULL, NULL);
13641
13642         dumpComment(fout, labelq->data,
13643                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13644                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13645
13646         destroyPQExpBuffer(query);
13647         destroyPQExpBuffer(delqry);
13648         destroyPQExpBuffer(labelq);
13649 }
13650
13651 /*
13652  * dumpRule
13653  *              Dump a rule
13654  */
13655 static void
13656 dumpRule(Archive *fout, RuleInfo *rinfo)
13657 {
13658         TableInfo  *tbinfo = rinfo->ruletable;
13659         PQExpBuffer query;
13660         PQExpBuffer cmd;
13661         PQExpBuffer delcmd;
13662         PQExpBuffer labelq;
13663         PGresult   *res;
13664
13665         /* Skip if not to be dumped */
13666         if (!rinfo->dobj.dump || dataOnly)
13667                 return;
13668
13669         /*
13670          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13671          * we do not want to dump it as a separate object.
13672          */
13673         if (!rinfo->separate)
13674                 return;
13675
13676         /*
13677          * Make sure we are in proper schema.
13678          */
13679         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13680
13681         query = createPQExpBuffer();
13682         cmd = createPQExpBuffer();
13683         delcmd = createPQExpBuffer();
13684         labelq = createPQExpBuffer();
13685
13686         if (fout->remoteVersion >= 70300)
13687         {
13688                 appendPQExpBuffer(query,
13689                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13690                                                   rinfo->dobj.catId.oid);
13691         }
13692         else
13693         {
13694                 /* Rule name was unique before 7.3 ... */
13695                 appendPQExpBuffer(query,
13696                                                   "SELECT pg_get_ruledef('%s') AS definition",
13697                                                   rinfo->dobj.name);
13698         }
13699
13700         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13701
13702         if (PQntuples(res) != 1)
13703         {
13704                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13705                                   rinfo->dobj.name, tbinfo->dobj.name);
13706                 exit_nicely(1);
13707         }
13708
13709         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13710
13711         /*
13712          * Add the command to alter the rules replication firing semantics if it
13713          * differs from the default.
13714          */
13715         if (rinfo->ev_enabled != 'O')
13716         {
13717                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13718                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13719                 appendPQExpBuffer(cmd, "%s ",
13720                                                   fmtId(tbinfo->dobj.name));
13721                 switch (rinfo->ev_enabled)
13722                 {
13723                         case 'A':
13724                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13725                                                                   fmtId(rinfo->dobj.name));
13726                                 break;
13727                         case 'R':
13728                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13729                                                                   fmtId(rinfo->dobj.name));
13730                                 break;
13731                         case 'D':
13732                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13733                                                                   fmtId(rinfo->dobj.name));
13734                                 break;
13735                 }
13736         }
13737
13738         /*
13739          * DROP must be fully qualified in case same name appears in pg_catalog
13740          */
13741         appendPQExpBuffer(delcmd, "DROP RULE %s ",
13742                                           fmtId(rinfo->dobj.name));
13743         appendPQExpBuffer(delcmd, "ON %s.",
13744                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13745         appendPQExpBuffer(delcmd, "%s;\n",
13746                                           fmtId(tbinfo->dobj.name));
13747
13748         appendPQExpBuffer(labelq, "RULE %s",
13749                                           fmtId(rinfo->dobj.name));
13750         appendPQExpBuffer(labelq, " ON %s",
13751                                           fmtId(tbinfo->dobj.name));
13752
13753         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13754                                  rinfo->dobj.name,
13755                                  tbinfo->dobj.namespace->dobj.name,
13756                                  NULL,
13757                                  tbinfo->rolname, false,
13758                                  "RULE", SECTION_POST_DATA,
13759                                  cmd->data, delcmd->data, NULL,
13760                                  NULL, 0,
13761                                  NULL, NULL);
13762
13763         /* Dump rule comments */
13764         dumpComment(fout, labelq->data,
13765                                 tbinfo->dobj.namespace->dobj.name,
13766                                 tbinfo->rolname,
13767                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13768
13769         PQclear(res);
13770
13771         destroyPQExpBuffer(query);
13772         destroyPQExpBuffer(cmd);
13773         destroyPQExpBuffer(delcmd);
13774         destroyPQExpBuffer(labelq);
13775 }
13776
13777 /*
13778  * getExtensionMembership --- obtain extension membership data
13779  */
13780 void
13781 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13782                                            int numExtensions)
13783 {
13784         PQExpBuffer query;
13785         PGresult   *res;
13786         int                     ntups,
13787                                 i;
13788         int                     i_classid,
13789                                 i_objid,
13790                                 i_refclassid,
13791                                 i_refobjid;
13792         DumpableObject *dobj,
13793                            *refdobj;
13794
13795         /* Nothing to do if no extensions */
13796         if (numExtensions == 0)
13797                 return;
13798
13799         /* Make sure we are in proper schema */
13800         selectSourceSchema(fout, "pg_catalog");
13801
13802         query = createPQExpBuffer();
13803
13804         /* refclassid constraint is redundant but may speed the search */
13805         appendPQExpBuffer(query, "SELECT "
13806                                           "classid, objid, refclassid, refobjid "
13807                                           "FROM pg_depend "
13808                                           "WHERE refclassid = 'pg_extension'::regclass "
13809                                           "AND deptype = 'e' "
13810                                           "ORDER BY 3,4");
13811
13812         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13813
13814         ntups = PQntuples(res);
13815
13816         i_classid = PQfnumber(res, "classid");
13817         i_objid = PQfnumber(res, "objid");
13818         i_refclassid = PQfnumber(res, "refclassid");
13819         i_refobjid = PQfnumber(res, "refobjid");
13820
13821         /*
13822          * Since we ordered the SELECT by referenced ID, we can expect that
13823          * multiple entries for the same extension will appear together; this
13824          * saves on searches.
13825          */
13826         refdobj = NULL;
13827
13828         for (i = 0; i < ntups; i++)
13829         {
13830                 CatalogId       objId;
13831                 CatalogId       refobjId;
13832
13833                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13834                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13835                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13836                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13837
13838                 if (refdobj == NULL ||
13839                         refdobj->catId.tableoid != refobjId.tableoid ||
13840                         refdobj->catId.oid != refobjId.oid)
13841                         refdobj = findObjectByCatalogId(refobjId);
13842
13843                 /*
13844                  * Failure to find objects mentioned in pg_depend is not unexpected,
13845                  * since for example we don't collect info about TOAST tables.
13846                  */
13847                 if (refdobj == NULL)
13848                 {
13849 #ifdef NOT_USED
13850                         fprintf(stderr, "no referenced object %u %u\n",
13851                                         refobjId.tableoid, refobjId.oid);
13852 #endif
13853                         continue;
13854                 }
13855
13856                 dobj = findObjectByCatalogId(objId);
13857
13858                 if (dobj == NULL)
13859                 {
13860 #ifdef NOT_USED
13861                         fprintf(stderr, "no referencing object %u %u\n",
13862                                         objId.tableoid, objId.oid);
13863 #endif
13864                         continue;
13865                 }
13866
13867                 /* Record dependency so that getDependencies needn't repeat this */
13868                 addObjectDependency(dobj, refdobj->dumpId);
13869
13870                 dobj->ext_member = true;
13871
13872                 /*
13873                  * Normally, mark the member object as not to be dumped.  But in
13874                  * binary upgrades, we still dump the members individually, since the
13875                  * idea is to exactly reproduce the database contents rather than
13876                  * replace the extension contents with something different.
13877                  */
13878                 if (!binary_upgrade)
13879                         dobj->dump = false;
13880                 else
13881                         dobj->dump = refdobj->dump;
13882         }
13883
13884         PQclear(res);
13885
13886         /*
13887          * Now identify extension configuration tables and create TableDataInfo
13888          * objects for them, ensuring their data will be dumped even though the
13889          * tables themselves won't be.
13890          *
13891          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13892          * user data in a configuration table is treated like schema data. This
13893          * seems appropriate since system data in a config table would get
13894          * reloaded by CREATE EXTENSION.
13895          */
13896         for (i = 0; i < numExtensions; i++)
13897         {
13898                 ExtensionInfo *curext = &(extinfo[i]);
13899                 char       *extconfig = curext->extconfig;
13900                 char       *extcondition = curext->extcondition;
13901                 char      **extconfigarray = NULL;
13902                 char      **extconditionarray = NULL;
13903                 int                     nconfigitems;
13904                 int                     nconditionitems;
13905
13906                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13907                 if (!curext->dobj.dump)
13908                         continue;
13909
13910                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13911                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13912                         nconfigitems == nconditionitems)
13913                 {
13914                         int                     j;
13915
13916                         for (j = 0; j < nconfigitems; j++)
13917                         {
13918                                 TableInfo  *configtbl;
13919
13920                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
13921                                 if (configtbl == NULL)
13922                                         continue;
13923
13924                                 /*
13925                                  * Note: config tables are dumped without OIDs regardless of
13926                                  * the --oids setting.  This is because row filtering
13927                                  * conditions aren't compatible with dumping OIDs.
13928                                  */
13929                                 makeTableDataInfo(configtbl, false);
13930                                 if (configtbl->dataObj != NULL)
13931                                 {
13932                                         if (strlen(extconditionarray[j]) > 0)
13933                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13934                                 }
13935                         }
13936                 }
13937                 if (extconfigarray)
13938                         free(extconfigarray);
13939                 if (extconditionarray)
13940                         free(extconditionarray);
13941         }
13942
13943         destroyPQExpBuffer(query);
13944 }
13945
13946 /*
13947  * getDependencies --- obtain available dependency data
13948  */
13949 static void
13950 getDependencies(Archive *fout)
13951 {
13952         PQExpBuffer query;
13953         PGresult   *res;
13954         int                     ntups,
13955                                 i;
13956         int                     i_classid,
13957                                 i_objid,
13958                                 i_refclassid,
13959                                 i_refobjid,
13960                                 i_deptype;
13961         DumpableObject *dobj,
13962                            *refdobj;
13963
13964         /* No dependency info available before 7.3 */
13965         if (fout->remoteVersion < 70300)
13966                 return;
13967
13968         if (g_verbose)
13969                 write_msg(NULL, "reading dependency data\n");
13970
13971         /* Make sure we are in proper schema */
13972         selectSourceSchema(fout, "pg_catalog");
13973
13974         query = createPQExpBuffer();
13975
13976         /*
13977          * PIN dependencies aren't interesting, and EXTENSION dependencies were
13978          * already processed by getExtensionMembership.
13979          */
13980         appendPQExpBuffer(query, "SELECT "
13981                                           "classid, objid, refclassid, refobjid, deptype "
13982                                           "FROM pg_depend "
13983                                           "WHERE deptype != 'p' AND deptype != 'e' "
13984                                           "ORDER BY 1,2");
13985
13986         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13987
13988         ntups = PQntuples(res);
13989
13990         i_classid = PQfnumber(res, "classid");
13991         i_objid = PQfnumber(res, "objid");
13992         i_refclassid = PQfnumber(res, "refclassid");
13993         i_refobjid = PQfnumber(res, "refobjid");
13994         i_deptype = PQfnumber(res, "deptype");
13995
13996         /*
13997          * Since we ordered the SELECT by referencing ID, we can expect that
13998          * multiple entries for the same object will appear together; this saves
13999          * on searches.
14000          */
14001         dobj = NULL;
14002
14003         for (i = 0; i < ntups; i++)
14004         {
14005                 CatalogId       objId;
14006                 CatalogId       refobjId;
14007                 char            deptype;
14008
14009                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14010                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14011                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14012                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14013                 deptype = *(PQgetvalue(res, i, i_deptype));
14014
14015                 if (dobj == NULL ||
14016                         dobj->catId.tableoid != objId.tableoid ||
14017                         dobj->catId.oid != objId.oid)
14018                         dobj = findObjectByCatalogId(objId);
14019
14020                 /*
14021                  * Failure to find objects mentioned in pg_depend is not unexpected,
14022                  * since for example we don't collect info about TOAST tables.
14023                  */
14024                 if (dobj == NULL)
14025                 {
14026 #ifdef NOT_USED
14027                         fprintf(stderr, "no referencing object %u %u\n",
14028                                         objId.tableoid, objId.oid);
14029 #endif
14030                         continue;
14031                 }
14032
14033                 refdobj = findObjectByCatalogId(refobjId);
14034
14035                 if (refdobj == NULL)
14036                 {
14037 #ifdef NOT_USED
14038                         fprintf(stderr, "no referenced object %u %u\n",
14039                                         refobjId.tableoid, refobjId.oid);
14040 #endif
14041                         continue;
14042                 }
14043
14044                 /*
14045                  * Ordinarily, table rowtypes have implicit dependencies on their
14046                  * tables.      However, for a composite type the implicit dependency goes
14047                  * the other way in pg_depend; which is the right thing for DROP but
14048                  * it doesn't produce the dependency ordering we need. So in that one
14049                  * case, we reverse the direction of the dependency.
14050                  */
14051                 if (deptype == 'i' &&
14052                         dobj->objType == DO_TABLE &&
14053                         refdobj->objType == DO_TYPE)
14054                         addObjectDependency(refdobj, dobj->dumpId);
14055                 else
14056                         /* normal case */
14057                         addObjectDependency(dobj, refdobj->dumpId);
14058         }
14059
14060         PQclear(res);
14061
14062         destroyPQExpBuffer(query);
14063 }
14064
14065
14066 /*
14067  * createBoundaryObjects - create dummy DumpableObjects to represent
14068  * dump section boundaries.
14069  */
14070 static DumpableObject *
14071 createBoundaryObjects(void)
14072 {
14073         DumpableObject *dobjs;
14074
14075         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14076
14077         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14078         dobjs[0].catId = nilCatalogId;
14079         AssignDumpId(dobjs + 0);
14080         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14081
14082         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14083         dobjs[1].catId = nilCatalogId;
14084         AssignDumpId(dobjs + 1);
14085         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14086
14087         return dobjs;
14088 }
14089
14090 /*
14091  * addBoundaryDependencies - add dependencies as needed to enforce the dump
14092  * section boundaries.
14093  */
14094 static void
14095 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14096                                                 DumpableObject *boundaryObjs)
14097 {
14098         DumpableObject *preDataBound = boundaryObjs + 0;
14099         DumpableObject *postDataBound = boundaryObjs + 1;
14100         int                     i;
14101
14102         for (i = 0; i < numObjs; i++)
14103         {
14104                 DumpableObject *dobj = dobjs[i];
14105
14106                 /*
14107                  * The classification of object types here must match the SECTION_xxx
14108                  * values assigned during subsequent ArchiveEntry calls!
14109                  */
14110                 switch (dobj->objType)
14111                 {
14112                         case DO_NAMESPACE:
14113                         case DO_EXTENSION:
14114                         case DO_TYPE:
14115                         case DO_SHELL_TYPE:
14116                         case DO_FUNC:
14117                         case DO_AGG:
14118                         case DO_OPERATOR:
14119                         case DO_OPCLASS:
14120                         case DO_OPFAMILY:
14121                         case DO_COLLATION:
14122                         case DO_CONVERSION:
14123                         case DO_TABLE:
14124                         case DO_ATTRDEF:
14125                         case DO_PROCLANG:
14126                         case DO_CAST:
14127                         case DO_DUMMY_TYPE:
14128                         case DO_TSPARSER:
14129                         case DO_TSDICT:
14130                         case DO_TSTEMPLATE:
14131                         case DO_TSCONFIG:
14132                         case DO_FDW:
14133                         case DO_FOREIGN_SERVER:
14134                         case DO_BLOB:
14135                                 /* Pre-data objects: must come before the pre-data boundary */
14136                                 addObjectDependency(preDataBound, dobj->dumpId);
14137                                 break;
14138                         case DO_TABLE_DATA:
14139                         case DO_BLOB_DATA:
14140                                 /* Data objects: must come between the boundaries */
14141                                 addObjectDependency(dobj, preDataBound->dumpId);
14142                                 addObjectDependency(postDataBound, dobj->dumpId);
14143                                 break;
14144                         case DO_INDEX:
14145                         case DO_TRIGGER:
14146                         case DO_DEFAULT_ACL:
14147                                 /* Post-data objects: must come after the post-data boundary */
14148                                 addObjectDependency(dobj, postDataBound->dumpId);
14149                                 break;
14150                         case DO_RULE:
14151                                 /* Rules are post-data, but only if dumped separately */
14152                                 if (((RuleInfo *) dobj)->separate)
14153                                         addObjectDependency(dobj, postDataBound->dumpId);
14154                                 break;
14155                         case DO_CONSTRAINT:
14156                         case DO_FK_CONSTRAINT:
14157                                 /* Constraints are post-data, but only if dumped separately */
14158                                 if (((ConstraintInfo *) dobj)->separate)
14159                                         addObjectDependency(dobj, postDataBound->dumpId);
14160                                 break;
14161                         case DO_PRE_DATA_BOUNDARY:
14162                                 /* nothing to do */
14163                                 break;
14164                         case DO_POST_DATA_BOUNDARY:
14165                                 /* must come after the pre-data boundary */
14166                                 addObjectDependency(dobj, preDataBound->dumpId);
14167                                 break;
14168                 }
14169         }
14170 }
14171
14172
14173 /*
14174  * BuildArchiveDependencies - create dependency data for archive TOC entries
14175  *
14176  * The raw dependency data obtained by getDependencies() is not terribly
14177  * useful in an archive dump, because in many cases there are dependency
14178  * chains linking through objects that don't appear explicitly in the dump.
14179  * For example, a view will depend on its _RETURN rule while the _RETURN rule
14180  * will depend on other objects --- but the rule will not appear as a separate
14181  * object in the dump.  We need to adjust the view's dependencies to include
14182  * whatever the rule depends on that is included in the dump.
14183  *
14184  * Just to make things more complicated, there are also "special" dependencies
14185  * such as the dependency of a TABLE DATA item on its TABLE, which we must
14186  * not rearrange because pg_restore knows that TABLE DATA only depends on
14187  * its table.  In these cases we must leave the dependencies strictly as-is
14188  * even if they refer to not-to-be-dumped objects.
14189  *
14190  * To handle this, the convention is that "special" dependencies are created
14191  * during ArchiveEntry calls, and an archive TOC item that has any such
14192  * entries will not be touched here.  Otherwise, we recursively search the
14193  * DumpableObject data structures to build the correct dependencies for each
14194  * archive TOC item.
14195  */
14196 static void
14197 BuildArchiveDependencies(Archive *fout)
14198 {
14199         ArchiveHandle *AH = (ArchiveHandle *) fout;
14200         TocEntry   *te;
14201
14202         /* Scan all TOC entries in the archive */
14203         for (te = AH->toc->next; te != AH->toc; te = te->next)
14204         {
14205                 DumpableObject *dobj;
14206                 DumpId     *dependencies;
14207                 int                     nDeps;
14208                 int                     allocDeps;
14209
14210                 /* No need to process entries that will not be dumped */
14211                 if (te->reqs == 0)
14212                         continue;
14213                 /* Ignore entries that already have "special" dependencies */
14214                 if (te->nDeps > 0)
14215                         continue;
14216                 /* Otherwise, look up the item's original DumpableObject, if any */
14217                 dobj = findObjectByDumpId(te->dumpId);
14218                 if (dobj == NULL)
14219                         continue;
14220                 /* No work if it has no dependencies */
14221                 if (dobj->nDeps <= 0)
14222                         continue;
14223                 /* Set up work array */
14224                 allocDeps = 64;
14225                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14226                 nDeps = 0;
14227                 /* Recursively find all dumpable dependencies */
14228                 findDumpableDependencies(AH, dobj,
14229                                                                  &dependencies, &nDeps, &allocDeps);
14230                 /* And save 'em ... */
14231                 if (nDeps > 0)
14232                 {
14233                         dependencies = (DumpId *) pg_realloc(dependencies,
14234                                                                                                  nDeps * sizeof(DumpId));
14235                         te->dependencies = dependencies;
14236                         te->nDeps = nDeps;
14237                 }
14238                 else
14239                         free(dependencies);
14240         }
14241 }
14242
14243 /* Recursive search subroutine for BuildArchiveDependencies */
14244 static void
14245 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14246                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
14247 {
14248         int                     i;
14249
14250         /*
14251          * Ignore section boundary objects: if we search through them, we'll
14252          * report lots of bogus dependencies.
14253          */
14254         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14255                 dobj->objType == DO_POST_DATA_BOUNDARY)
14256                 return;
14257
14258         for (i = 0; i < dobj->nDeps; i++)
14259         {
14260                 DumpId          depid = dobj->dependencies[i];
14261
14262                 if (TocIDRequired(AH, depid) != 0)
14263                 {
14264                         /* Object will be dumped, so just reference it as a dependency */
14265                         if (*nDeps >= *allocDeps)
14266                         {
14267                                 *allocDeps *= 2;
14268                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
14269                                                                                           *allocDeps * sizeof(DumpId));
14270                         }
14271                         (*dependencies)[*nDeps] = depid;
14272                         (*nDeps)++;
14273                 }
14274                 else
14275                 {
14276                         /*
14277                          * Object will not be dumped, so recursively consider its deps.
14278                          * We rely on the assumption that sortDumpableObjects already
14279                          * broke any dependency loops, else we might recurse infinitely.
14280                          */
14281                         DumpableObject *otherdobj = findObjectByDumpId(depid);
14282
14283                         if (otherdobj)
14284                                 findDumpableDependencies(AH, otherdobj,
14285                                                                                  dependencies, nDeps, allocDeps);
14286                 }
14287         }
14288 }
14289
14290
14291 /*
14292  * selectSourceSchema - make the specified schema the active search path
14293  * in the source database.
14294  *
14295  * NB: pg_catalog is explicitly searched after the specified schema;
14296  * so user names are only qualified if they are cross-schema references,
14297  * and system names are only qualified if they conflict with a user name
14298  * in the current schema.
14299  *
14300  * Whenever the selected schema is not pg_catalog, be careful to qualify
14301  * references to system catalogs and types in our emitted commands!
14302  */
14303 static void
14304 selectSourceSchema(Archive *fout, const char *schemaName)
14305 {
14306         static char *curSchemaName = NULL;
14307         PQExpBuffer query;
14308
14309         /* Not relevant if fetching from pre-7.3 DB */
14310         if (fout->remoteVersion < 70300)
14311                 return;
14312         /* Ignore null schema names */
14313         if (schemaName == NULL || *schemaName == '\0')
14314                 return;
14315         /* Optimize away repeated selection of same schema */
14316         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14317                 return;
14318
14319         query = createPQExpBuffer();
14320         appendPQExpBuffer(query, "SET search_path = %s",
14321                                           fmtId(schemaName));
14322         if (strcmp(schemaName, "pg_catalog") != 0)
14323                 appendPQExpBuffer(query, ", pg_catalog");
14324
14325         ExecuteSqlStatement(fout, query->data);
14326
14327         destroyPQExpBuffer(query);
14328         if (curSchemaName)
14329                 free(curSchemaName);
14330         curSchemaName = pg_strdup(schemaName);
14331 }
14332
14333 /*
14334  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14335  * given type name.
14336  *
14337  * NB: in 7.3 and up the result may depend on the currently-selected
14338  * schema; this is why we don't try to cache the names.
14339  */
14340 static char *
14341 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14342 {
14343         char       *result;
14344         PQExpBuffer query;
14345         PGresult   *res;
14346
14347         if (oid == 0)
14348         {
14349                 if ((opts & zeroAsOpaque) != 0)
14350                         return pg_strdup(g_opaque_type);
14351                 else if ((opts & zeroAsAny) != 0)
14352                         return pg_strdup("'any'");
14353                 else if ((opts & zeroAsStar) != 0)
14354                         return pg_strdup("*");
14355                 else if ((opts & zeroAsNone) != 0)
14356                         return pg_strdup("NONE");
14357         }
14358
14359         query = createPQExpBuffer();
14360         if (fout->remoteVersion >= 70300)
14361         {
14362                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14363                                                   oid);
14364         }
14365         else if (fout->remoteVersion >= 70100)
14366         {
14367                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14368                                                   oid);
14369         }
14370         else
14371         {
14372                 appendPQExpBuffer(query, "SELECT typname "
14373                                                   "FROM pg_type "
14374                                                   "WHERE oid = '%u'::oid",
14375                                                   oid);
14376         }
14377
14378         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14379
14380         if (fout->remoteVersion >= 70100)
14381         {
14382                 /* already quoted */
14383                 result = pg_strdup(PQgetvalue(res, 0, 0));
14384         }
14385         else
14386         {
14387                 /* may need to quote it */
14388                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14389         }
14390
14391         PQclear(res);
14392         destroyPQExpBuffer(query);
14393
14394         return result;
14395 }
14396
14397 /*
14398  * myFormatType --- local implementation of format_type for use with 7.0.
14399  */
14400 static char *
14401 myFormatType(const char *typname, int32 typmod)
14402 {
14403         char       *result;
14404         bool            isarray = false;
14405         PQExpBuffer buf = createPQExpBuffer();
14406
14407         /* Handle array types */
14408         if (typname[0] == '_')
14409         {
14410                 isarray = true;
14411                 typname++;
14412         }
14413
14414         /* Show lengths on bpchar and varchar */
14415         if (strcmp(typname, "bpchar") == 0)
14416         {
14417                 int                     len = (typmod - VARHDRSZ);
14418
14419                 appendPQExpBuffer(buf, "character");
14420                 if (len > 1)
14421                         appendPQExpBuffer(buf, "(%d)",
14422                                                           typmod - VARHDRSZ);
14423         }
14424         else if (strcmp(typname, "varchar") == 0)
14425         {
14426                 appendPQExpBuffer(buf, "character varying");
14427                 if (typmod != -1)
14428                         appendPQExpBuffer(buf, "(%d)",
14429                                                           typmod - VARHDRSZ);
14430         }
14431         else if (strcmp(typname, "numeric") == 0)
14432         {
14433                 appendPQExpBuffer(buf, "numeric");
14434                 if (typmod != -1)
14435                 {
14436                         int32           tmp_typmod;
14437                         int                     precision;
14438                         int                     scale;
14439
14440                         tmp_typmod = typmod - VARHDRSZ;
14441                         precision = (tmp_typmod >> 16) & 0xffff;
14442                         scale = tmp_typmod & 0xffff;
14443                         appendPQExpBuffer(buf, "(%d,%d)",
14444                                                           precision, scale);
14445                 }
14446         }
14447
14448         /*
14449          * char is an internal single-byte data type; Let's make sure we force it
14450          * through with quotes. - thomas 1998-12-13
14451          */
14452         else if (strcmp(typname, "char") == 0)
14453                 appendPQExpBuffer(buf, "\"char\"");
14454         else
14455                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14456
14457         /* Append array qualifier for array types */
14458         if (isarray)
14459                 appendPQExpBuffer(buf, "[]");
14460
14461         result = pg_strdup(buf->data);
14462         destroyPQExpBuffer(buf);
14463
14464         return result;
14465 }
14466
14467 /*
14468  * fmtQualifiedId - convert a qualified name to the proper format for
14469  * the source database.
14470  *
14471  * Like fmtId, use the result before calling again.
14472  */
14473 static const char *
14474 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14475 {
14476         static PQExpBuffer id_return = NULL;
14477
14478         if (id_return)                          /* first time through? */
14479                 resetPQExpBuffer(id_return);
14480         else
14481                 id_return = createPQExpBuffer();
14482
14483         /* Suppress schema name if fetching from pre-7.3 DB */
14484         if (fout->remoteVersion >= 70300 && schema && *schema)
14485         {
14486                 appendPQExpBuffer(id_return, "%s.",
14487                                                   fmtId(schema));
14488         }
14489         appendPQExpBuffer(id_return, "%s",
14490                                           fmtId(id));
14491
14492         return id_return->data;
14493 }
14494
14495 /*
14496  * Return a column list clause for the given relation.
14497  *
14498  * Special case: if there are no undropped columns in the relation, return
14499  * "", not an invalid "()" column list.
14500  */
14501 static const char *
14502 fmtCopyColumnList(const TableInfo *ti)
14503 {
14504         static PQExpBuffer q = NULL;
14505         int                     numatts = ti->numatts;
14506         char      **attnames = ti->attnames;
14507         bool       *attisdropped = ti->attisdropped;
14508         bool            needComma;
14509         int                     i;
14510
14511         if (q)                                          /* first time through? */
14512                 resetPQExpBuffer(q);
14513         else
14514                 q = createPQExpBuffer();
14515
14516         appendPQExpBuffer(q, "(");
14517         needComma = false;
14518         for (i = 0; i < numatts; i++)
14519         {
14520                 if (attisdropped[i])
14521                         continue;
14522                 if (needComma)
14523                         appendPQExpBuffer(q, ", ");
14524                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14525                 needComma = true;
14526         }
14527
14528         if (!needComma)
14529                 return "";                              /* no undropped columns */
14530
14531         appendPQExpBuffer(q, ")");
14532         return q->data;
14533 }
14534
14535 /*
14536  * Execute an SQL query and verify that we got exactly one row back.
14537  */
14538 static PGresult *
14539 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14540 {
14541         PGresult   *res;
14542         int                     ntups;
14543
14544         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14545
14546         /* Expecting a single result only */
14547         ntups = PQntuples(res);
14548         if (ntups != 1)
14549                 exit_horribly(NULL,
14550                                           ngettext("query returned %d row instead of one: %s\n",
14551                                                            "query returned %d rows instead of one: %s\n",
14552                                                            ntups),
14553                                           ntups, query);
14554
14555         return res;
14556 }