]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Fix assorted bugs in privileges-for-types patch.
[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_event_trigger.h"
53 #include "catalog/pg_largeobject.h"
54 #include "catalog/pg_largeobject_metadata.h"
55 #include "catalog/pg_proc.h"
56 #include "catalog/pg_trigger.h"
57 #include "catalog/pg_type.h"
58 #include "libpq/libpq-fs.h"
59
60 #include "pg_backup_archiver.h"
61 #include "pg_backup_db.h"
62 #include "dumpmem.h"
63 #include "dumputils.h"
64
65 extern char *optarg;
66 extern int      optind,
67                         opterr;
68
69
70 typedef struct
71 {
72         const char *descr;                      /* comment for an object */
73         Oid                     classoid;               /* object class (catalog OID) */
74         Oid                     objoid;                 /* object OID */
75         int                     objsubid;               /* subobject (table column #) */
76 } CommentItem;
77
78 typedef struct
79 {
80         const char *provider;           /* label provider of this security label */
81         const char *label;                      /* security label for an object */
82         Oid                     classoid;               /* object class (catalog OID) */
83         Oid                     objoid;                 /* object OID */
84         int                     objsubid;               /* subobject (table column #) */
85 } SecLabelItem;
86
87 /* global decls */
88 bool            g_verbose;                      /* User wants verbose narration of our
89                                                                  * activities. */
90
91 /* various user-settable parameters */
92 bool            schemaOnly;
93 bool            dataOnly;
94 int                     dumpSections;           /* bitmask of chosen sections */
95 bool            aclsSkip;
96 const char *lockWaitTimeout;
97
98 /* subquery used to convert user ID (eg, datdba) to user name */
99 static const char *username_subquery;
100
101 /* obsolete as of 7.3: */
102 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
103
104 /*
105  * Object inclusion/exclusion lists
106  *
107  * The string lists record the patterns given by command-line switches,
108  * which we then convert to lists of OIDs of matching objects.
109  */
110 static SimpleStringList schema_include_patterns = {NULL, NULL};
111 static SimpleOidList schema_include_oids = {NULL, NULL};
112 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
113 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114
115 static SimpleStringList table_include_patterns = {NULL, NULL};
116 static SimpleOidList table_include_oids = {NULL, NULL};
117 static SimpleStringList table_exclude_patterns = {NULL, NULL};
118 static SimpleOidList table_exclude_oids = {NULL, NULL};
119 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
120 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
121
122 /* default, if no "inclusion" switches appear, is to dump everything */
123 static bool include_everything = true;
124
125 char            g_opaque_type[10];      /* name for the opaque type */
126
127 /* placeholders for the delimiters for comments */
128 char            g_comment_start[10];
129 char            g_comment_end[10];
130
131 static const CatalogId nilCatalogId = {0, 0};
132
133 /* flags for various command-line long options */
134 static int      binary_upgrade = 0;
135 static int      disable_dollar_quoting = 0;
136 static int      dump_inserts = 0;
137 static int      column_inserts = 0;
138 static int      no_security_labels = 0;
139 static int      no_unlogged_table_data = 0;
140 static int      serializable_deferrable = 0;
141
142
143 static void help(const char *progname);
144 static void setup_connection(Archive *AH, const char *dumpencoding,
145                                  char *use_role);
146 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
147 static void expand_schema_name_patterns(Archive *fout,
148                                                         SimpleStringList *patterns,
149                                                         SimpleOidList *oids);
150 static void expand_table_name_patterns(Archive *fout,
151                                                    SimpleStringList *patterns,
152                                                    SimpleOidList *oids);
153 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
154 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
155 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
156 static void dumpComment(Archive *fout, const char *target,
157                         const char *namespace, const char *owner,
158                         CatalogId catalogId, int subid, DumpId dumpId);
159 static int findComments(Archive *fout, Oid classoid, Oid objoid,
160                          CommentItem **items);
161 static int      collectComments(Archive *fout, CommentItem **items);
162 static void dumpSecLabel(Archive *fout, const char *target,
163                          const char *namespace, const char *owner,
164                          CatalogId catalogId, int subid, DumpId dumpId);
165 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
166                           SecLabelItem **items);
167 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
168 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
169 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
170 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
171 static void dumpType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
178 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
179 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
180 static void dumpFunc(Archive *fout, FuncInfo *finfo);
181 static void dumpCast(Archive *fout, CastInfo *cast);
182 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
183 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
184 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
185 static void dumpCollation(Archive *fout, CollInfo *convinfo);
186 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
187 static void dumpRule(Archive *fout, RuleInfo *rinfo);
188 static void dumpAgg(Archive *fout, AggInfo *agginfo);
189 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
190 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
191 static void dumpTable(Archive *fout, TableInfo *tbinfo);
192 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
193 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
194 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
195 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
196 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
197 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
198 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
199 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
200 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
201 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
202 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
203 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
204 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
205 static void dumpUserMappings(Archive *fout,
206                                  const char *servername, const char *namespace,
207                                  const char *owner, CatalogId catalogId, DumpId dumpId);
208 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
209
210 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
211                 const char *type, const char *name, const char *subname,
212                 const char *tag, const char *nspname, const char *owner,
213                 const char *acls);
214
215 static void getDependencies(Archive *fout);
216 static void BuildArchiveDependencies(Archive *fout);
217 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
218                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
219
220 static DumpableObject *createBoundaryObjects(void);
221 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
222                                                 DumpableObject *boundaryObjs);
223
224 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
225 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
226 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
227 static void getTableDataFKConstraints(void);
228 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
229 static char *format_function_arguments_old(Archive *fout,
230                                                           FuncInfo *finfo, int nallargs,
231                                                           char **allargtypes,
232                                                           char **argmodes,
233                                                           char **argnames);
234 static char *format_function_signature(Archive *fout,
235                                                   FuncInfo *finfo, bool honor_quotes);
236 static const char *convertRegProcReference(Archive *fout,
237                                                 const char *proc);
238 static const char *convertOperatorReference(Archive *fout, const char *opr);
239 static const char *convertTSFunction(Archive *fout, Oid funcOid);
240 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
241 static Oid      findLastBuiltinOid_V70(Archive *fout);
242 static void selectSourceSchema(Archive *fout, const char *schemaName);
243 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
244 static char *myFormatType(const char *typname, int32 typmod);
245 static const char *fmtQualifiedId(Archive *fout,
246                            const char *schema, const char *id);
247 static void getBlobs(Archive *fout);
248 static void dumpBlob(Archive *fout, BlobInfo *binfo);
249 static int      dumpBlobs(Archive *fout, void *arg);
250 static void dumpDatabase(Archive *AH);
251 static void dumpEncoding(Archive *AH);
252 static void dumpStdStrings(Archive *AH);
253 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
254                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
255 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
256                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
257 static void binary_upgrade_set_pg_class_oids(Archive *fout,
258                                                                  PQExpBuffer upgrade_buffer,
259                                                                  Oid pg_class_oid, bool is_index);
260 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
261                                                                 DumpableObject *dobj,
262                                                                 const char *objlabel);
263 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
264 static const char *fmtCopyColumnList(const TableInfo *ti);
265 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
266
267
268 int
269 main(int argc, char **argv)
270 {
271         int                     c;
272         const char *filename = NULL;
273         const char *format = "p";
274         const char *dbname = NULL;
275         const char *pghost = NULL;
276         const char *pgport = NULL;
277         const char *username = NULL;
278         const char *dumpencoding = NULL;
279         bool            oids = false;
280         TableInfo  *tblinfo;
281         int                     numTables;
282         DumpableObject **dobjs;
283         int                     numObjs;
284         DumpableObject *boundaryObjs;
285         int                     i;
286         enum trivalue prompt_password = TRI_DEFAULT;
287         int                     compressLevel = -1;
288         int                     plainText = 0;
289         int                     outputClean = 0;
290         int                     outputCreateDB = 0;
291         bool            outputBlobs = false;
292         int                     outputNoOwner = 0;
293         char       *outputSuperuser = NULL;
294         char       *use_role = NULL;
295         int                     my_version;
296         int                     optindex;
297         RestoreOptions *ropt;
298         ArchiveFormat archiveFormat = archUnknown;
299         ArchiveMode archiveMode;
300         Archive    *fout;                       /* the script file */
301
302         static int      disable_triggers = 0;
303         static int      outputNoTablespaces = 0;
304         static int      use_setsessauth = 0;
305
306         static struct option long_options[] = {
307                 {"data-only", no_argument, NULL, 'a'},
308                 {"blobs", no_argument, NULL, 'b'},
309                 {"clean", no_argument, NULL, 'c'},
310                 {"create", no_argument, NULL, 'C'},
311                 {"file", required_argument, NULL, 'f'},
312                 {"format", required_argument, NULL, 'F'},
313                 {"host", required_argument, NULL, 'h'},
314                 {"ignore-version", no_argument, NULL, 'i'},
315                 {"no-reconnect", no_argument, NULL, 'R'},
316                 {"oids", no_argument, NULL, 'o'},
317                 {"no-owner", no_argument, NULL, 'O'},
318                 {"port", required_argument, NULL, 'p'},
319                 {"schema", required_argument, NULL, 'n'},
320                 {"exclude-schema", required_argument, NULL, 'N'},
321                 {"schema-only", no_argument, NULL, 's'},
322                 {"superuser", required_argument, NULL, 'S'},
323                 {"table", required_argument, NULL, 't'},
324                 {"exclude-table", required_argument, NULL, 'T'},
325                 {"no-password", no_argument, NULL, 'w'},
326                 {"password", no_argument, NULL, 'W'},
327                 {"username", required_argument, NULL, 'U'},
328                 {"verbose", no_argument, NULL, 'v'},
329                 {"no-privileges", no_argument, NULL, 'x'},
330                 {"no-acl", no_argument, NULL, 'x'},
331                 {"compress", required_argument, NULL, 'Z'},
332                 {"encoding", required_argument, NULL, 'E'},
333                 {"help", no_argument, NULL, '?'},
334                 {"version", no_argument, NULL, 'V'},
335
336                 /*
337                  * the following options don't have an equivalent short option letter
338                  */
339                 {"attribute-inserts", no_argument, &column_inserts, 1},
340                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
341                 {"column-inserts", no_argument, &column_inserts, 1},
342                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
343                 {"disable-triggers", no_argument, &disable_triggers, 1},
344                 {"exclude-table-data", required_argument, NULL, 4},
345                 {"inserts", no_argument, &dump_inserts, 1},
346                 {"lock-wait-timeout", required_argument, NULL, 2},
347                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
348                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
349                 {"role", required_argument, NULL, 3},
350                 {"section", required_argument, NULL, 5},
351                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
352                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
353                 {"no-security-labels", no_argument, &no_security_labels, 1},
354                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
355
356                 {NULL, 0, NULL, 0}
357         };
358
359         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
360
361         g_verbose = false;
362
363         strcpy(g_comment_start, "-- ");
364         g_comment_end[0] = '\0';
365         strcpy(g_opaque_type, "opaque");
366
367         dataOnly = schemaOnly = false;
368         dumpSections = DUMP_UNSECTIONED;
369         lockWaitTimeout = NULL;
370
371         progname = get_progname(argv[0]);
372
373         /* Set default options based on progname */
374         if (strcmp(progname, "pg_backup") == 0)
375                 format = "c";
376
377         if (argc > 1)
378         {
379                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
380                 {
381                         help(progname);
382                         exit_nicely(0);
383                 }
384                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
385                 {
386                         puts("pg_dump (PostgreSQL) " PG_VERSION);
387                         exit_nicely(0);
388                 }
389         }
390
391         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
392                                                         long_options, &optindex)) != -1)
393         {
394                 switch (c)
395                 {
396                         case 'a':                       /* Dump data only */
397                                 dataOnly = true;
398                                 break;
399
400                         case 'b':                       /* Dump blobs */
401                                 outputBlobs = true;
402                                 break;
403
404                         case 'c':                       /* clean (i.e., drop) schema prior to create */
405                                 outputClean = 1;
406                                 break;
407
408                         case 'C':                       /* Create DB */
409                                 outputCreateDB = 1;
410                                 break;
411
412                         case 'E':                       /* Dump encoding */
413                                 dumpencoding = pg_strdup(optarg);
414                                 break;
415
416                         case 'f':
417                                 filename = pg_strdup(optarg);
418                                 break;
419
420                         case 'F':
421                                 format = pg_strdup(optarg);
422                                 break;
423
424                         case 'h':                       /* server host */
425                                 pghost = pg_strdup(optarg);
426                                 break;
427
428                         case 'i':
429                                 /* ignored, deprecated option */
430                                 break;
431
432                         case 'n':                       /* include schema(s) */
433                                 simple_string_list_append(&schema_include_patterns, optarg);
434                                 include_everything = false;
435                                 break;
436
437                         case 'N':                       /* exclude schema(s) */
438                                 simple_string_list_append(&schema_exclude_patterns, optarg);
439                                 break;
440
441                         case 'o':                       /* Dump oids */
442                                 oids = true;
443                                 break;
444
445                         case 'O':                       /* Don't reconnect to match owner */
446                                 outputNoOwner = 1;
447                                 break;
448
449                         case 'p':                       /* server port */
450                                 pgport = pg_strdup(optarg);
451                                 break;
452
453                         case 'R':
454                                 /* no-op, still accepted for backwards compatibility */
455                                 break;
456
457                         case 's':                       /* dump schema only */
458                                 schemaOnly = true;
459                                 break;
460
461                         case 'S':                       /* Username for superuser in plain text output */
462                                 outputSuperuser = pg_strdup(optarg);
463                                 break;
464
465                         case 't':                       /* include table(s) */
466                                 simple_string_list_append(&table_include_patterns, optarg);
467                                 include_everything = false;
468                                 break;
469
470                         case 'T':                       /* exclude table(s) */
471                                 simple_string_list_append(&table_exclude_patterns, optarg);
472                                 break;
473
474                         case 'U':
475                                 username = pg_strdup(optarg);
476                                 break;
477
478                         case 'v':                       /* verbose */
479                                 g_verbose = true;
480                                 break;
481
482                         case 'w':
483                                 prompt_password = TRI_NO;
484                                 break;
485
486                         case 'W':
487                                 prompt_password = TRI_YES;
488                                 break;
489
490                         case 'x':                       /* skip ACL dump */
491                                 aclsSkip = true;
492                                 break;
493
494                         case 'Z':                       /* Compression Level */
495                                 compressLevel = atoi(optarg);
496                                 break;
497
498                         case 0:
499                                 /* This covers the long options. */
500                                 break;
501
502                         case 2:                         /* lock-wait-timeout */
503                                 lockWaitTimeout = pg_strdup(optarg);
504                                 break;
505
506                         case 3:                         /* SET ROLE */
507                                 use_role = pg_strdup(optarg);
508                                 break;
509
510                         case 4:                         /* exclude table(s) data */
511                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
512                                 break;
513
514                         case 5:                         /* section */
515                                 set_dump_section(optarg, &dumpSections);
516                                 break;
517
518                         default:
519                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
520                                 exit_nicely(1);
521                 }
522         }
523
524         /* Get database name from command line */
525         if (optind < argc)
526                 dbname = argv[optind++];
527
528         /* Complain if any arguments remain */
529         if (optind < argc)
530         {
531                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
532                                 progname, argv[optind]);
533                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
534                                 progname);
535                 exit_nicely(1);
536         }
537
538         /* --column-inserts implies --inserts */
539         if (column_inserts)
540                 dump_inserts = 1;
541
542         if (dataOnly && schemaOnly)
543                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
544
545         if (dataOnly && outputClean)
546                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
547
548         if (dump_inserts && oids)
549         {
550                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
551                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
552                 exit_nicely(1);
553         }
554
555         /* Identify archive format to emit */
556         archiveFormat = parseArchiveFormat(format, &archiveMode);
557
558         /* archiveFormat specific setup */
559         if (archiveFormat == archNull)
560                 plainText = 1;
561
562         /* Custom and directory formats are compressed by default, others not */
563         if (compressLevel == -1)
564         {
565                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
566                         compressLevel = Z_DEFAULT_COMPRESSION;
567                 else
568                         compressLevel = 0;
569         }
570
571         /* Open the output file */
572         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
573
574         /* Register the cleanup hook */
575         on_exit_close_archive(fout);
576
577         if (fout == NULL)
578                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
579
580         /* Let the archiver know how noisy to be */
581         fout->verbose = g_verbose;
582
583         my_version = parse_version(PG_VERSION);
584         if (my_version < 0)
585                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
586
587         /*
588          * We allow the server to be back to 7.0, and up to any minor release of
589          * our own major version.  (See also version check in pg_dumpall.c.)
590          */
591         fout->minRemoteVersion = 70000;
592         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
593
594         /*
595          * Open the database using the Archiver, so it knows about it. Errors mean
596          * death.
597          */
598         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
599         setup_connection(fout, dumpencoding, use_role);
600
601         /*
602          * Disable security label support if server version < v9.1.x (prevents
603          * access to nonexistent pg_seclabel catalog)
604          */
605         if (fout->remoteVersion < 90100)
606                 no_security_labels = 1;
607
608         /*
609          * Start transaction-snapshot mode transaction to dump consistent data.
610          */
611         ExecuteSqlStatement(fout, "BEGIN");
612         if (fout->remoteVersion >= 90100)
613         {
614                 if (serializable_deferrable)
615                         ExecuteSqlStatement(fout,
616                                                                 "SET TRANSACTION ISOLATION LEVEL "
617                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
618                 else
619                         ExecuteSqlStatement(fout,
620                                                                 "SET TRANSACTION ISOLATION LEVEL "
621                                                                 "REPEATABLE READ");
622         }
623         else
624                 ExecuteSqlStatement(fout,
625                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
626
627         /* Select the appropriate subquery to convert user IDs to names */
628         if (fout->remoteVersion >= 80100)
629                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
630         else if (fout->remoteVersion >= 70300)
631                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
632         else
633                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
634
635         /* Find the last built-in OID, if needed */
636         if (fout->remoteVersion < 70300)
637         {
638                 if (fout->remoteVersion >= 70100)
639                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
640                                                                                                   PQdb(GetConnection(fout)));
641                 else
642                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
643                 if (g_verbose)
644                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
645         }
646
647         /* Expand schema selection patterns into OID lists */
648         if (schema_include_patterns.head != NULL)
649         {
650                 expand_schema_name_patterns(fout, &schema_include_patterns,
651                                                                         &schema_include_oids);
652                 if (schema_include_oids.head == NULL)
653                         exit_horribly(NULL, "No matching schemas were found\n");
654         }
655         expand_schema_name_patterns(fout, &schema_exclude_patterns,
656                                                                 &schema_exclude_oids);
657         /* non-matching exclusion patterns aren't an error */
658
659         /* Expand table selection patterns into OID lists */
660         if (table_include_patterns.head != NULL)
661         {
662                 expand_table_name_patterns(fout, &table_include_patterns,
663                                                                    &table_include_oids);
664                 if (table_include_oids.head == NULL)
665                         exit_horribly(NULL, "No matching tables were found\n");
666         }
667         expand_table_name_patterns(fout, &table_exclude_patterns,
668                                                            &table_exclude_oids);
669
670         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
671                                                            &tabledata_exclude_oids);
672
673         /* non-matching exclusion patterns aren't an error */
674
675         /*
676          * Dumping blobs is now default unless we saw an inclusion switch or -s
677          * ... but even if we did see one of these, -b turns it back on.
678          */
679         if (include_everything && !schemaOnly)
680                 outputBlobs = true;
681
682         /*
683          * Now scan the database and create DumpableObject structs for all the
684          * objects we intend to dump.
685          */
686         tblinfo = getSchemaData(fout, &numTables);
687
688         if (fout->remoteVersion < 80400)
689                 guessConstraintInheritance(tblinfo, numTables);
690
691         if (!schemaOnly)
692         {
693                 getTableData(tblinfo, numTables, oids);
694                 if (dataOnly)
695                         getTableDataFKConstraints();
696         }
697
698         if (outputBlobs)
699                 getBlobs(fout);
700
701         /*
702          * Collect dependency data to assist in ordering the objects.
703          */
704         getDependencies(fout);
705
706         /* Lastly, create dummy objects to represent the section boundaries */
707         boundaryObjs = createBoundaryObjects();
708
709         /* Get pointers to all the known DumpableObjects */
710         getDumpableObjects(&dobjs, &numObjs);
711
712         /*
713          * Add dummy dependencies to enforce the dump section ordering.
714          */
715         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
716
717         /*
718          * Sort the objects into a safe dump order (no forward references).
719          *
720          * In 7.3 or later, we can rely on dependency information to help us
721          * determine a safe order, so the initial sort is mostly for cosmetic
722          * purposes: we sort by name to ensure that logically identical schemas
723          * will dump identically.  Before 7.3 we don't have dependencies and we
724          * use OID ordering as an (unreliable) guide to creation order.
725          */
726         if (fout->remoteVersion >= 70300)
727                 sortDumpableObjectsByTypeName(dobjs, numObjs);
728         else
729                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
730
731         sortDumpableObjects(dobjs, numObjs,
732                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
733
734         /*
735          * Create archive TOC entries for all the objects to be dumped, in a safe
736          * order.
737          */
738
739         /* First the special ENCODING and STDSTRINGS entries. */
740         dumpEncoding(fout);
741         dumpStdStrings(fout);
742
743         /* The database item is always next, unless we don't want it at all */
744         if (include_everything && !dataOnly)
745                 dumpDatabase(fout);
746
747         /* Now the rearrangeable objects. */
748         for (i = 0; i < numObjs; i++)
749                 dumpDumpableObject(fout, dobjs[i]);
750
751         /*
752          * Set up options info to ensure we dump what we want.
753          */
754         ropt = NewRestoreOptions();
755         ropt->filename = filename;
756         ropt->dropSchema = outputClean;
757         ropt->dataOnly = dataOnly;
758         ropt->schemaOnly = schemaOnly;
759         ropt->dumpSections = dumpSections;
760         ropt->aclsSkip = aclsSkip;
761         ropt->superuser = outputSuperuser;
762         ropt->createDB = outputCreateDB;
763         ropt->noOwner = outputNoOwner;
764         ropt->noTablespace = outputNoTablespaces;
765         ropt->disable_triggers = disable_triggers;
766         ropt->use_setsessauth = use_setsessauth;
767
768         if (compressLevel == -1)
769                 ropt->compression = 0;
770         else
771                 ropt->compression = compressLevel;
772
773         ropt->suppressDumpWarnings = true;      /* We've already shown them */
774
775         SetArchiveRestoreOptions(fout, ropt);
776
777         /*
778          * The archive's TOC entries are now marked as to which ones will
779          * actually be output, so we can set up their dependency lists properly.
780          * This isn't necessary for plain-text output, though.
781          */
782         if (!plainText)
783                 BuildArchiveDependencies(fout);
784
785         /*
786          * And finally we can do the actual output.
787          *
788          * Note: for non-plain-text output formats, the output file is written
789          * inside CloseArchive().  This is, um, bizarre; but not worth changing
790          * right now.
791          */
792         if (plainText)
793                 RestoreArchive(fout);
794
795         CloseArchive(fout);
796
797         exit_nicely(0);
798 }
799
800
801 static void
802 help(const char *progname)
803 {
804         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
805         printf(_("Usage:\n"));
806         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
807
808         printf(_("\nGeneral options:\n"));
809         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
810         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
811                          "                               plain text (default))\n"));
812         printf(_("  -v, --verbose                verbose mode\n"));
813         printf(_("  -V, --version                output version information, then exit\n"));
814         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
815         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
816         printf(_("  -?, --help                   show this help, then exit\n"));
817
818         printf(_("\nOptions controlling the output content:\n"));
819         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
820         printf(_("  -b, --blobs                  include large objects in dump\n"));
821         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
822         printf(_("  -C, --create                 include commands to create database in dump\n"));
823         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
824         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
825         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
826         printf(_("  -o, --oids                   include OIDs in dump\n"));
827         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
828                          "                               plain-text format\n"));
829         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
830         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
831         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
832         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
833         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
834         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
835         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
836         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
837         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
838         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
839         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
840         printf(_("  --no-security-labels         do not dump security label assignments\n"));
841         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
842         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
843         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
844         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
845         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
846         printf(_("  --use-set-session-authorization\n"
847                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
848                          "                               ALTER OWNER commands to set ownership\n"));
849
850         printf(_("\nConnection options:\n"));
851         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
852         printf(_("  -p, --port=PORT          database server port number\n"));
853         printf(_("  -U, --username=NAME      connect as specified database user\n"));
854         printf(_("  -w, --no-password        never prompt for password\n"));
855         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
856         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
857
858         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
859                          "variable value is used.\n\n"));
860         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
861 }
862
863 static void
864 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
865 {
866         PGconn     *conn = GetConnection(AH);
867         const char *std_strings;
868
869         /* Set the client encoding if requested */
870         if (dumpencoding)
871         {
872                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
873                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
874                                                   dumpencoding);
875         }
876
877         /*
878          * Get the active encoding and the standard_conforming_strings setting, so
879          * we know how to escape strings.
880          */
881         AH->encoding = PQclientEncoding(conn);
882
883         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
884         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
885
886         /* Set the role if requested */
887         if (use_role && AH->remoteVersion >= 80100)
888         {
889                 PQExpBuffer query = createPQExpBuffer();
890
891                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
892                 ExecuteSqlStatement(AH, query->data);
893                 destroyPQExpBuffer(query);
894         }
895
896         /* Set the datestyle to ISO to ensure the dump's portability */
897         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
898
899         /* Likewise, avoid using sql_standard intervalstyle */
900         if (AH->remoteVersion >= 80400)
901                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
902
903         /*
904          * If supported, set extra_float_digits so that we can dump float data
905          * exactly (given correctly implemented float I/O code, anyway)
906          */
907         if (AH->remoteVersion >= 90000)
908                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
909         else if (AH->remoteVersion >= 70400)
910                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
911
912         /*
913          * If synchronized scanning is supported, disable it, to prevent
914          * unpredictable changes in row ordering across a dump and reload.
915          */
916         if (AH->remoteVersion >= 80300)
917                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
918
919         /*
920          * Disable timeouts if supported.
921          */
922         if (AH->remoteVersion >= 70300)
923                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
924
925         /*
926          * Quote all identifiers, if requested.
927          */
928         if (quote_all_identifiers && AH->remoteVersion >= 90100)
929                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
930 }
931
932 static ArchiveFormat
933 parseArchiveFormat(const char *format, ArchiveMode *mode)
934 {
935         ArchiveFormat archiveFormat;
936
937         *mode = archModeWrite;
938
939         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
940         {
941                 /* This is used by pg_dumpall, and is not documented */
942                 archiveFormat = archNull;
943                 *mode = archModeAppend;
944         }
945         else if (pg_strcasecmp(format, "c") == 0)
946                 archiveFormat = archCustom;
947         else if (pg_strcasecmp(format, "custom") == 0)
948                 archiveFormat = archCustom;
949         else if (pg_strcasecmp(format, "d") == 0)
950                 archiveFormat = archDirectory;
951         else if (pg_strcasecmp(format, "directory") == 0)
952                 archiveFormat = archDirectory;
953         else if (pg_strcasecmp(format, "p") == 0)
954                 archiveFormat = archNull;
955         else if (pg_strcasecmp(format, "plain") == 0)
956                 archiveFormat = archNull;
957         else if (pg_strcasecmp(format, "t") == 0)
958                 archiveFormat = archTar;
959         else if (pg_strcasecmp(format, "tar") == 0)
960                 archiveFormat = archTar;
961         else
962                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
963         return archiveFormat;
964 }
965
966 /*
967  * Find the OIDs of all schemas matching the given list of patterns,
968  * and append them to the given OID list.
969  */
970 static void
971 expand_schema_name_patterns(Archive *fout,
972                                                         SimpleStringList *patterns,
973                                                         SimpleOidList *oids)
974 {
975         PQExpBuffer query;
976         PGresult   *res;
977         SimpleStringListCell *cell;
978         int                     i;
979
980         if (patterns->head == NULL)
981                 return;                                 /* nothing to do */
982
983         if (fout->remoteVersion < 70300)
984                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
985
986         query = createPQExpBuffer();
987
988         /*
989          * We use UNION ALL rather than UNION; this might sometimes result in
990          * duplicate entries in the OID list, but we don't care.
991          */
992
993         for (cell = patterns->head; cell; cell = cell->next)
994         {
995                 if (cell != patterns->head)
996                         appendPQExpBuffer(query, "UNION ALL\n");
997                 appendPQExpBuffer(query,
998                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
999                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1000                                                           false, NULL, "n.nspname", NULL, NULL);
1001         }
1002
1003         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1004
1005         for (i = 0; i < PQntuples(res); i++)
1006         {
1007                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1008         }
1009
1010         PQclear(res);
1011         destroyPQExpBuffer(query);
1012 }
1013
1014 /*
1015  * Find the OIDs of all tables matching the given list of patterns,
1016  * and append them to the given OID list.
1017  */
1018 static void
1019 expand_table_name_patterns(Archive *fout,
1020                                                    SimpleStringList *patterns, SimpleOidList *oids)
1021 {
1022         PQExpBuffer query;
1023         PGresult   *res;
1024         SimpleStringListCell *cell;
1025         int                     i;
1026
1027         if (patterns->head == NULL)
1028                 return;                                 /* nothing to do */
1029
1030         query = createPQExpBuffer();
1031
1032         /*
1033          * We use UNION ALL rather than UNION; this might sometimes result in
1034          * duplicate entries in the OID list, but we don't care.
1035          */
1036
1037         for (cell = patterns->head; cell; cell = cell->next)
1038         {
1039                 if (cell != patterns->head)
1040                         appendPQExpBuffer(query, "UNION ALL\n");
1041                 appendPQExpBuffer(query,
1042                                                   "SELECT c.oid"
1043                                                   "\nFROM pg_catalog.pg_class c"
1044                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1045                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1046                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1047                                                   RELKIND_FOREIGN_TABLE);
1048                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1049                                                           false, "n.nspname", "c.relname", NULL,
1050                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1051         }
1052
1053         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1054
1055         for (i = 0; i < PQntuples(res); i++)
1056         {
1057                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1058         }
1059
1060         PQclear(res);
1061         destroyPQExpBuffer(query);
1062 }
1063
1064 /*
1065  * selectDumpableNamespace: policy-setting subroutine
1066  *              Mark a namespace as to be dumped or not
1067  */
1068 static void
1069 selectDumpableNamespace(NamespaceInfo *nsinfo)
1070 {
1071         /*
1072          * If specific tables are being dumped, do not dump any complete
1073          * namespaces. If specific namespaces are being dumped, dump just those
1074          * namespaces. Otherwise, dump all non-system namespaces.
1075          */
1076         if (table_include_oids.head != NULL)
1077                 nsinfo->dobj.dump = false;
1078         else if (schema_include_oids.head != NULL)
1079                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1080                                                                                                    nsinfo->dobj.catId.oid);
1081         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1082                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1083                 nsinfo->dobj.dump = false;
1084         else
1085                 nsinfo->dobj.dump = true;
1086
1087         /*
1088          * In any case, a namespace can be excluded by an exclusion switch
1089          */
1090         if (nsinfo->dobj.dump &&
1091                 simple_oid_list_member(&schema_exclude_oids,
1092                                                            nsinfo->dobj.catId.oid))
1093                 nsinfo->dobj.dump = false;
1094 }
1095
1096 /*
1097  * selectDumpableTable: policy-setting subroutine
1098  *              Mark a table as to be dumped or not
1099  */
1100 static void
1101 selectDumpableTable(TableInfo *tbinfo)
1102 {
1103         /*
1104          * If specific tables are being dumped, dump just those tables; else, dump
1105          * according to the parent namespace's dump flag.
1106          */
1107         if (table_include_oids.head != NULL)
1108                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1109                                                                                                    tbinfo->dobj.catId.oid);
1110         else
1111                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1112
1113         /*
1114          * In any case, a table can be excluded by an exclusion switch
1115          */
1116         if (tbinfo->dobj.dump &&
1117                 simple_oid_list_member(&table_exclude_oids,
1118                                                            tbinfo->dobj.catId.oid))
1119                 tbinfo->dobj.dump = false;
1120 }
1121
1122 /*
1123  * selectDumpableType: policy-setting subroutine
1124  *              Mark a type as to be dumped or not
1125  *
1126  * If it's a table's rowtype or an autogenerated array type, we also apply a
1127  * special type code to facilitate sorting into the desired order.      (We don't
1128  * want to consider those to be ordinary types because that would bring tables
1129  * up into the datatype part of the dump order.)  We still set the object's
1130  * dump flag; that's not going to cause the dummy type to be dumped, but we
1131  * need it so that casts involving such types will be dumped correctly -- see
1132  * dumpCast.  This means the flag should be set the same as for the underlying
1133  * object (the table or base type).
1134  */
1135 static void
1136 selectDumpableType(TypeInfo *tyinfo)
1137 {
1138         /* skip complex types, except for standalone composite types */
1139         if (OidIsValid(tyinfo->typrelid) &&
1140                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1141         {
1142                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1143
1144                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1145                 if (tytable != NULL)
1146                         tyinfo->dobj.dump = tytable->dobj.dump;
1147                 else
1148                         tyinfo->dobj.dump = false;
1149                 return;
1150         }
1151
1152         /* skip auto-generated array types */
1153         if (tyinfo->isArray)
1154         {
1155                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1156
1157                 /*
1158                  * Fall through to set the dump flag; we assume that the subsequent
1159                  * rules will do the same thing as they would for the array's base
1160                  * type.  (We cannot reliably look up the base type here, since
1161                  * getTypes may not have processed it yet.)
1162                  */
1163         }
1164
1165         /* dump only types in dumpable namespaces */
1166         if (!tyinfo->dobj.namespace->dobj.dump)
1167                 tyinfo->dobj.dump = false;
1168
1169         /* skip undefined placeholder types */
1170         else if (!tyinfo->isDefined)
1171                 tyinfo->dobj.dump = false;
1172
1173         else
1174                 tyinfo->dobj.dump = true;
1175 }
1176
1177 /*
1178  * selectDumpableDefaultACL: policy-setting subroutine
1179  *              Mark a default ACL as to be dumped or not
1180  *
1181  * For per-schema default ACLs, dump if the schema is to be dumped.
1182  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1183  * and aclsSkip are checked separately.
1184  */
1185 static void
1186 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1187 {
1188         if (dinfo->dobj.namespace)
1189                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1190         else
1191                 dinfo->dobj.dump = include_everything;
1192 }
1193
1194 /*
1195  * selectDumpableExtension: policy-setting subroutine
1196  *              Mark an extension as to be dumped or not
1197  *
1198  * Normally, we dump all extensions, or none of them if include_everything
1199  * is false (i.e., a --schema or --table switch was given).  However, in
1200  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1201  * assume those will already be installed in the target database.  We identify
1202  * such extensions by their having OIDs in the range reserved for initdb.
1203  */
1204 static void
1205 selectDumpableExtension(ExtensionInfo *extinfo)
1206 {
1207         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1208                 extinfo->dobj.dump = false;
1209         else
1210                 extinfo->dobj.dump = include_everything;
1211 }
1212
1213 /*
1214  * selectDumpableObject: policy-setting subroutine
1215  *              Mark a generic dumpable object as to be dumped or not
1216  *
1217  * Use this only for object types without a special-case routine above.
1218  */
1219 static void
1220 selectDumpableObject(DumpableObject *dobj)
1221 {
1222         /*
1223          * Default policy is to dump if parent namespace is dumpable, or always
1224          * for non-namespace-associated items.
1225          */
1226         if (dobj->namespace)
1227                 dobj->dump = dobj->namespace->dobj.dump;
1228         else
1229                 dobj->dump = true;
1230 }
1231
1232 /*
1233  *      Dump a table's contents for loading using the COPY command
1234  *      - this routine is called by the Archiver when it wants the table
1235  *        to be dumped.
1236  */
1237
1238 static int
1239 dumpTableData_copy(Archive *fout, void *dcontext)
1240 {
1241         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1242         TableInfo  *tbinfo = tdinfo->tdtable;
1243         const char *classname = tbinfo->dobj.name;
1244         const bool      hasoids = tbinfo->hasoids;
1245         const bool      oids = tdinfo->oids;
1246         PQExpBuffer q = createPQExpBuffer();
1247         PGconn     *conn = GetConnection(fout);
1248         PGresult   *res;
1249         int                     ret;
1250         char       *copybuf;
1251         const char *column_list;
1252
1253         if (g_verbose)
1254                 write_msg(NULL, "dumping contents of table %s\n", classname);
1255
1256         /*
1257          * Make sure we are in proper schema.  We will qualify the table name
1258          * below anyway (in case its name conflicts with a pg_catalog table); but
1259          * this ensures reproducible results in case the table contains regproc,
1260          * regclass, etc columns.
1261          */
1262         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1263
1264         /*
1265          * If possible, specify the column list explicitly so that we have no
1266          * possibility of retrieving data in the wrong column order.  (The default
1267          * column ordering of COPY will not be what we want in certain corner
1268          * cases involving ADD COLUMN and inheritance.)
1269          */
1270         if (fout->remoteVersion >= 70300)
1271                 column_list = fmtCopyColumnList(tbinfo);
1272         else
1273                 column_list = "";               /* can't select columns in COPY */
1274
1275         if (oids && hasoids)
1276         {
1277                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1278                                                   fmtQualifiedId(fout,
1279                                                                                  tbinfo->dobj.namespace->dobj.name,
1280                                                                                  classname),
1281                                                   column_list);
1282         }
1283         else if (tdinfo->filtercond)
1284         {
1285                 /* Note: this syntax is only supported in 8.2 and up */
1286                 appendPQExpBufferStr(q, "COPY (SELECT ");
1287                 /* klugery to get rid of parens in column list */
1288                 if (strlen(column_list) > 2)
1289                 {
1290                         appendPQExpBufferStr(q, column_list + 1);
1291                         q->data[q->len - 1] = ' ';
1292                 }
1293                 else
1294                         appendPQExpBufferStr(q, "* ");
1295                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1296                                                   fmtQualifiedId(fout,
1297                                                                                  tbinfo->dobj.namespace->dobj.name,
1298                                                                                  classname),
1299                                                   tdinfo->filtercond);
1300         }
1301         else
1302         {
1303                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1304                                                   fmtQualifiedId(fout,
1305                                                                                  tbinfo->dobj.namespace->dobj.name,
1306                                                                                  classname),
1307                                                   column_list);
1308         }
1309         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1310         PQclear(res);
1311
1312         for (;;)
1313         {
1314                 ret = PQgetCopyData(conn, &copybuf, 0);
1315
1316                 if (ret < 0)
1317                         break;                          /* done or error */
1318
1319                 if (copybuf)
1320                 {
1321                         WriteData(fout, copybuf, ret);
1322                         PQfreemem(copybuf);
1323                 }
1324
1325                 /* ----------
1326                  * THROTTLE:
1327                  *
1328                  * There was considerable discussion in late July, 2000 regarding
1329                  * slowing down pg_dump when backing up large tables. Users with both
1330                  * slow & fast (multi-processor) machines experienced performance
1331                  * degradation when doing a backup.
1332                  *
1333                  * Initial attempts based on sleeping for a number of ms for each ms
1334                  * of work were deemed too complex, then a simple 'sleep in each loop'
1335                  * implementation was suggested. The latter failed because the loop
1336                  * was too tight. Finally, the following was implemented:
1337                  *
1338                  * If throttle is non-zero, then
1339                  *              See how long since the last sleep.
1340                  *              Work out how long to sleep (based on ratio).
1341                  *              If sleep is more than 100ms, then
1342                  *                      sleep
1343                  *                      reset timer
1344                  *              EndIf
1345                  * EndIf
1346                  *
1347                  * where the throttle value was the number of ms to sleep per ms of
1348                  * work. The calculation was done in each loop.
1349                  *
1350                  * Most of the hard work is done in the backend, and this solution
1351                  * still did not work particularly well: on slow machines, the ratio
1352                  * was 50:1, and on medium paced machines, 1:1, and on fast
1353                  * multi-processor machines, it had little or no effect, for reasons
1354                  * that were unclear.
1355                  *
1356                  * Further discussion ensued, and the proposal was dropped.
1357                  *
1358                  * For those people who want this feature, it can be implemented using
1359                  * gettimeofday in each loop, calculating the time since last sleep,
1360                  * multiplying that by the sleep ratio, then if the result is more
1361                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1362                  * function to sleep for a subsecond period ie.
1363                  *
1364                  * select(0, NULL, NULL, NULL, &tvi);
1365                  *
1366                  * This will return after the interval specified in the structure tvi.
1367                  * Finally, call gettimeofday again to save the 'last sleep time'.
1368                  * ----------
1369                  */
1370         }
1371         archprintf(fout, "\\.\n\n\n");
1372
1373         if (ret == -2)
1374         {
1375                 /* copy data transfer failed */
1376                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1377                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1378                 write_msg(NULL, "The command was: %s\n", q->data);
1379                 exit_nicely(1);
1380         }
1381
1382         /* Check command status and return to normal libpq state */
1383         res = PQgetResult(conn);
1384         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1385         {
1386                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1387                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1388                 write_msg(NULL, "The command was: %s\n", q->data);
1389                 exit_nicely(1);
1390         }
1391         PQclear(res);
1392
1393         destroyPQExpBuffer(q);
1394         return 1;
1395 }
1396
1397 /*
1398  * Dump table data using INSERT commands.
1399  *
1400  * Caution: when we restore from an archive file direct to database, the
1401  * INSERT commands emitted by this function have to be parsed by
1402  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1403  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1404  */
1405 static int
1406 dumpTableData_insert(Archive *fout, void *dcontext)
1407 {
1408         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1409         TableInfo  *tbinfo = tdinfo->tdtable;
1410         const char *classname = tbinfo->dobj.name;
1411         PQExpBuffer q = createPQExpBuffer();
1412         PGresult   *res;
1413         int                     tuple;
1414         int                     nfields;
1415         int                     field;
1416
1417         /*
1418          * Make sure we are in proper schema.  We will qualify the table name
1419          * below anyway (in case its name conflicts with a pg_catalog table); but
1420          * this ensures reproducible results in case the table contains regproc,
1421          * regclass, etc columns.
1422          */
1423         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1424
1425         if (fout->remoteVersion >= 70100)
1426         {
1427                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1428                                                   "SELECT * FROM ONLY %s",
1429                                                   fmtQualifiedId(fout,
1430                                                                                  tbinfo->dobj.namespace->dobj.name,
1431                                                                                  classname));
1432         }
1433         else
1434         {
1435                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1436                                                   "SELECT * FROM %s",
1437                                                   fmtQualifiedId(fout,
1438                                                                                  tbinfo->dobj.namespace->dobj.name,
1439                                                                                  classname));
1440         }
1441         if (tdinfo->filtercond)
1442                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1443
1444         ExecuteSqlStatement(fout, q->data);
1445
1446         while (1)
1447         {
1448                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1449                                                           PGRES_TUPLES_OK);
1450                 nfields = PQnfields(res);
1451                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1452                 {
1453                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1454                         if (nfields == 0)
1455                         {
1456                                 /* corner case for zero-column table */
1457                                 archprintf(fout, "DEFAULT VALUES;\n");
1458                                 continue;
1459                         }
1460                         if (column_inserts)
1461                         {
1462                                 resetPQExpBuffer(q);
1463                                 appendPQExpBuffer(q, "(");
1464                                 for (field = 0; field < nfields; field++)
1465                                 {
1466                                         if (field > 0)
1467                                                 appendPQExpBuffer(q, ", ");
1468                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1469                                 }
1470                                 appendPQExpBuffer(q, ") ");
1471                                 archputs(q->data, fout);
1472                         }
1473                         archprintf(fout, "VALUES (");
1474                         for (field = 0; field < nfields; field++)
1475                         {
1476                                 if (field > 0)
1477                                         archprintf(fout, ", ");
1478                                 if (PQgetisnull(res, tuple, field))
1479                                 {
1480                                         archprintf(fout, "NULL");
1481                                         continue;
1482                                 }
1483
1484                                 /* XXX This code is partially duplicated in ruleutils.c */
1485                                 switch (PQftype(res, field))
1486                                 {
1487                                         case INT2OID:
1488                                         case INT4OID:
1489                                         case INT8OID:
1490                                         case OIDOID:
1491                                         case FLOAT4OID:
1492                                         case FLOAT8OID:
1493                                         case NUMERICOID:
1494                                                 {
1495                                                         /*
1496                                                          * These types are printed without quotes unless
1497                                                          * they contain values that aren't accepted by the
1498                                                          * scanner unquoted (e.g., 'NaN').      Note that
1499                                                          * strtod() and friends might accept NaN, so we
1500                                                          * can't use that to test.
1501                                                          *
1502                                                          * In reality we only need to defend against
1503                                                          * infinity and NaN, so we need not get too crazy
1504                                                          * about pattern matching here.
1505                                                          */
1506                                                         const char *s = PQgetvalue(res, tuple, field);
1507
1508                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1509                                                                 archprintf(fout, "%s", s);
1510                                                         else
1511                                                                 archprintf(fout, "'%s'", s);
1512                                                 }
1513                                                 break;
1514
1515                                         case BITOID:
1516                                         case VARBITOID:
1517                                                 archprintf(fout, "B'%s'",
1518                                                                    PQgetvalue(res, tuple, field));
1519                                                 break;
1520
1521                                         case BOOLOID:
1522                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1523                                                         archprintf(fout, "true");
1524                                                 else
1525                                                         archprintf(fout, "false");
1526                                                 break;
1527
1528                                         default:
1529                                                 /* All other types are printed as string literals. */
1530                                                 resetPQExpBuffer(q);
1531                                                 appendStringLiteralAH(q,
1532                                                                                           PQgetvalue(res, tuple, field),
1533                                                                                           fout);
1534                                                 archputs(q->data, fout);
1535                                                 break;
1536                                 }
1537                         }
1538                         archprintf(fout, ");\n");
1539                 }
1540
1541                 if (PQntuples(res) <= 0)
1542                 {
1543                         PQclear(res);
1544                         break;
1545                 }
1546                 PQclear(res);
1547         }
1548
1549         archprintf(fout, "\n\n");
1550
1551         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1552
1553         destroyPQExpBuffer(q);
1554         return 1;
1555 }
1556
1557
1558 /*
1559  * dumpTableData -
1560  *        dump the contents of a single table
1561  *
1562  * Actually, this just makes an ArchiveEntry for the table contents.
1563  */
1564 static void
1565 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1566 {
1567         TableInfo  *tbinfo = tdinfo->tdtable;
1568         PQExpBuffer copyBuf = createPQExpBuffer();
1569         DataDumperPtr dumpFn;
1570         char       *copyStmt;
1571
1572         if (!dump_inserts)
1573         {
1574                 /* Dump/restore using COPY */
1575                 dumpFn = dumpTableData_copy;
1576                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1577                 appendPQExpBuffer(copyBuf, "COPY %s ",
1578                                                   fmtId(tbinfo->dobj.name));
1579                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1580                                                   fmtCopyColumnList(tbinfo),
1581                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1582                 copyStmt = copyBuf->data;
1583         }
1584         else
1585         {
1586                 /* Restore using INSERT */
1587                 dumpFn = dumpTableData_insert;
1588                 copyStmt = NULL;
1589         }
1590
1591         /*
1592          * Note: although the TableDataInfo is a full DumpableObject, we treat its
1593          * dependency on its table as "special" and pass it to ArchiveEntry now.
1594          * See comments for BuildArchiveDependencies.
1595          */
1596         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1597                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1598                                  NULL, tbinfo->rolname,
1599                                  false, "TABLE DATA", SECTION_DATA,
1600                                  "", "", copyStmt,
1601                                  &(tbinfo->dobj.dumpId), 1,
1602                                  dumpFn, tdinfo);
1603
1604         destroyPQExpBuffer(copyBuf);
1605 }
1606
1607 /*
1608  * getTableData -
1609  *        set up dumpable objects representing the contents of tables
1610  */
1611 static void
1612 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1613 {
1614         int                     i;
1615
1616         for (i = 0; i < numTables; i++)
1617         {
1618                 if (tblinfo[i].dobj.dump)
1619                         makeTableDataInfo(&(tblinfo[i]), oids);
1620         }
1621 }
1622
1623 /*
1624  * Make a dumpable object for the data of this specific table
1625  *
1626  * Note: we make a TableDataInfo if and only if we are going to dump the
1627  * table data; the "dump" flag in such objects isn't used.
1628  */
1629 static void
1630 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1631 {
1632         TableDataInfo *tdinfo;
1633
1634         /*
1635          * Nothing to do if we already decided to dump the table.  This will
1636          * happen for "config" tables.
1637          */
1638         if (tbinfo->dataObj != NULL)
1639                 return;
1640
1641         /* Skip VIEWs (no data to dump) */
1642         if (tbinfo->relkind == RELKIND_VIEW)
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_typacl;
2824         int                     i_rolname;
2825         int                     i_typinput;
2826         int                     i_typoutput;
2827         int                     i_typelem;
2828         int                     i_typrelid;
2829         int                     i_typrelkind;
2830         int                     i_typtype;
2831         int                     i_typisdefined;
2832         int                     i_isarray;
2833
2834         /*
2835          * we include even the built-in types because those may be used as array
2836          * elements by user-defined types
2837          *
2838          * we filter out the built-in types when we dump out the types
2839          *
2840          * same approach for undefined (shell) types and array types
2841          *
2842          * Note: as of 8.3 we can reliably detect whether a type is an
2843          * auto-generated array type by checking the element type's typarray.
2844          * (Before that the test is capable of generating false positives.) We
2845          * still check for name beginning with '_', though, so as to avoid the
2846          * cost of the subselect probe for all standard types.  This would have to
2847          * be revisited if the backend ever allows renaming of array types.
2848          */
2849
2850         /* Make sure we are in proper schema */
2851         selectSourceSchema(fout, "pg_catalog");
2852
2853         if (fout->remoteVersion >= 90200)
2854         {
2855                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2856                                                   "typnamespace, typacl, "
2857                                                   "(%s typowner) AS rolname, "
2858                                                   "typinput::oid AS typinput, "
2859                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2860                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2861                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2862                                                   "typtype, typisdefined, "
2863                                                   "typname[0] = '_' AND typelem != 0 AND "
2864                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2865                                                   "FROM pg_type",
2866                                                   username_subquery);
2867         }
2868         else if (fout->remoteVersion >= 80300)
2869         {
2870                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2871                                                   "typnamespace, '{=U}' AS typacl, "
2872                                                   "(%s typowner) AS rolname, "
2873                                                   "typinput::oid AS typinput, "
2874                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2875                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2876                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2877                                                   "typtype, typisdefined, "
2878                                                   "typname[0] = '_' AND typelem != 0 AND "
2879                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2880                                                   "FROM pg_type",
2881                                                   username_subquery);
2882         }
2883         else if (fout->remoteVersion >= 70300)
2884         {
2885                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2886                                                   "typnamespace, '{=U}' AS typacl, "
2887                                                   "(%s typowner) AS rolname, "
2888                                                   "typinput::oid AS typinput, "
2889                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2890                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2891                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2892                                                   "typtype, typisdefined, "
2893                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2894                                                   "FROM pg_type",
2895                                                   username_subquery);
2896         }
2897         else if (fout->remoteVersion >= 70100)
2898         {
2899                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2900                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
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         else
2912         {
2913                 appendPQExpBuffer(query, "SELECT "
2914                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2915                                                   "oid, typname, "
2916                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
2917                                                   "(%s typowner) AS rolname, "
2918                                                   "typinput::oid AS typinput, "
2919                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2920                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2921                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2922                                                   "typtype, typisdefined, "
2923                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2924                                                   "FROM pg_type",
2925                                                   username_subquery);
2926         }
2927
2928         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2929
2930         ntups = PQntuples(res);
2931
2932         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2933
2934         i_tableoid = PQfnumber(res, "tableoid");
2935         i_oid = PQfnumber(res, "oid");
2936         i_typname = PQfnumber(res, "typname");
2937         i_typnamespace = PQfnumber(res, "typnamespace");
2938         i_typacl = PQfnumber(res, "typacl");
2939         i_rolname = PQfnumber(res, "rolname");
2940         i_typinput = PQfnumber(res, "typinput");
2941         i_typoutput = PQfnumber(res, "typoutput");
2942         i_typelem = PQfnumber(res, "typelem");
2943         i_typrelid = PQfnumber(res, "typrelid");
2944         i_typrelkind = PQfnumber(res, "typrelkind");
2945         i_typtype = PQfnumber(res, "typtype");
2946         i_typisdefined = PQfnumber(res, "typisdefined");
2947         i_isarray = PQfnumber(res, "isarray");
2948
2949         for (i = 0; i < ntups; i++)
2950         {
2951                 tyinfo[i].dobj.objType = DO_TYPE;
2952                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2953                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2954                 AssignDumpId(&tyinfo[i].dobj);
2955                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2956                 tyinfo[i].dobj.namespace =
2957                         findNamespace(fout,
2958                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2959                                                   tyinfo[i].dobj.catId.oid);
2960                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2961                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
2962                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2963                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2964                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2965                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2966                 tyinfo[i].shellType = NULL;
2967
2968                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2969                         tyinfo[i].isDefined = true;
2970                 else
2971                         tyinfo[i].isDefined = false;
2972
2973                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2974                         tyinfo[i].isArray = true;
2975                 else
2976                         tyinfo[i].isArray = false;
2977
2978                 /* Decide whether we want to dump it */
2979                 selectDumpableType(&tyinfo[i]);
2980
2981                 /*
2982                  * If it's a domain, fetch info about its constraints, if any
2983                  */
2984                 tyinfo[i].nDomChecks = 0;
2985                 tyinfo[i].domChecks = NULL;
2986                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2987                         getDomainConstraints(fout, &(tyinfo[i]));
2988
2989                 /*
2990                  * If it's a base type, make a DumpableObject representing a shell
2991                  * definition of the type.      We will need to dump that ahead of the I/O
2992                  * functions for the type.      Similarly, range types need a shell
2993                  * definition in case they have a canonicalize function.
2994                  *
2995                  * Note: the shell type doesn't have a catId.  You might think it
2996                  * should copy the base type's catId, but then it might capture the
2997                  * pg_depend entries for the type, which we don't want.
2998                  */
2999                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3000                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
3001                 {
3002                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3003                         stinfo->dobj.objType = DO_SHELL_TYPE;
3004                         stinfo->dobj.catId = nilCatalogId;
3005                         AssignDumpId(&stinfo->dobj);
3006                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3007                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3008                         stinfo->baseType = &(tyinfo[i]);
3009                         tyinfo[i].shellType = stinfo;
3010
3011                         /*
3012                          * Initially mark the shell type as not to be dumped.  We'll only
3013                          * dump it if the I/O or canonicalize functions need to be dumped;
3014                          * this is taken care of while sorting dependencies.
3015                          */
3016                         stinfo->dobj.dump = false;
3017
3018                         /*
3019                          * However, if dumping from pre-7.3, there will be no dependency
3020                          * info so we have to fake it here.  We only need to worry about
3021                          * typinput and typoutput since the other functions only exist
3022                          * post-7.3.
3023                          */
3024                         if (fout->remoteVersion < 70300)
3025                         {
3026                                 Oid                     typinput;
3027                                 Oid                     typoutput;
3028                                 FuncInfo   *funcInfo;
3029
3030                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3031                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3032
3033                                 funcInfo = findFuncByOid(typinput);
3034                                 if (funcInfo && funcInfo->dobj.dump)
3035                                 {
3036                                         /* base type depends on function */
3037                                         addObjectDependency(&tyinfo[i].dobj,
3038                                                                                 funcInfo->dobj.dumpId);
3039                                         /* function depends on shell type */
3040                                         addObjectDependency(&funcInfo->dobj,
3041                                                                                 stinfo->dobj.dumpId);
3042                                         /* mark shell type as to be dumped */
3043                                         stinfo->dobj.dump = true;
3044                                 }
3045
3046                                 funcInfo = findFuncByOid(typoutput);
3047                                 if (funcInfo && funcInfo->dobj.dump)
3048                                 {
3049                                         /* base type depends on function */
3050                                         addObjectDependency(&tyinfo[i].dobj,
3051                                                                                 funcInfo->dobj.dumpId);
3052                                         /* function depends on shell type */
3053                                         addObjectDependency(&funcInfo->dobj,
3054                                                                                 stinfo->dobj.dumpId);
3055                                         /* mark shell type as to be dumped */
3056                                         stinfo->dobj.dump = true;
3057                                 }
3058                         }
3059                 }
3060
3061                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3062                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3063                                           tyinfo[i].dobj.name);
3064         }
3065
3066         *numTypes = ntups;
3067
3068         PQclear(res);
3069
3070         destroyPQExpBuffer(query);
3071
3072         return tyinfo;
3073 }
3074
3075 /*
3076  * getOperators:
3077  *        read all operators in the system catalogs and return them in the
3078  * OprInfo* structure
3079  *
3080  *      numOprs is set to the number of operators read in
3081  */
3082 OprInfo *
3083 getOperators(Archive *fout, int *numOprs)
3084 {
3085         PGresult   *res;
3086         int                     ntups;
3087         int                     i;
3088         PQExpBuffer query = createPQExpBuffer();
3089         OprInfo    *oprinfo;
3090         int                     i_tableoid;
3091         int                     i_oid;
3092         int                     i_oprname;
3093         int                     i_oprnamespace;
3094         int                     i_rolname;
3095         int                     i_oprkind;
3096         int                     i_oprcode;
3097
3098         /*
3099          * find all operators, including builtin operators; we filter out
3100          * system-defined operators at dump-out time.
3101          */
3102
3103         /* Make sure we are in proper schema */
3104         selectSourceSchema(fout, "pg_catalog");
3105
3106         if (fout->remoteVersion >= 70300)
3107         {
3108                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3109                                                   "oprnamespace, "
3110                                                   "(%s oprowner) AS rolname, "
3111                                                   "oprkind, "
3112                                                   "oprcode::oid AS oprcode "
3113                                                   "FROM pg_operator",
3114                                                   username_subquery);
3115         }
3116         else if (fout->remoteVersion >= 70100)
3117         {
3118                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3119                                                   "0::oid AS oprnamespace, "
3120                                                   "(%s oprowner) AS rolname, "
3121                                                   "oprkind, "
3122                                                   "oprcode::oid AS oprcode "
3123                                                   "FROM pg_operator",
3124                                                   username_subquery);
3125         }
3126         else
3127         {
3128                 appendPQExpBuffer(query, "SELECT "
3129                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3130                                                   "oid, oprname, "
3131                                                   "0::oid AS oprnamespace, "
3132                                                   "(%s oprowner) AS rolname, "
3133                                                   "oprkind, "
3134                                                   "oprcode::oid AS oprcode "
3135                                                   "FROM pg_operator",
3136                                                   username_subquery);
3137         }
3138
3139         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3140
3141         ntups = PQntuples(res);
3142         *numOprs = ntups;
3143
3144         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3145
3146         i_tableoid = PQfnumber(res, "tableoid");
3147         i_oid = PQfnumber(res, "oid");
3148         i_oprname = PQfnumber(res, "oprname");
3149         i_oprnamespace = PQfnumber(res, "oprnamespace");
3150         i_rolname = PQfnumber(res, "rolname");
3151         i_oprkind = PQfnumber(res, "oprkind");
3152         i_oprcode = PQfnumber(res, "oprcode");
3153
3154         for (i = 0; i < ntups; i++)
3155         {
3156                 oprinfo[i].dobj.objType = DO_OPERATOR;
3157                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3158                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3159                 AssignDumpId(&oprinfo[i].dobj);
3160                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3161                 oprinfo[i].dobj.namespace =
3162                         findNamespace(fout,
3163                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3164                                                   oprinfo[i].dobj.catId.oid);
3165                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3166                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3167                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3168
3169                 /* Decide whether we want to dump it */
3170                 selectDumpableObject(&(oprinfo[i].dobj));
3171
3172                 if (strlen(oprinfo[i].rolname) == 0)
3173                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3174                                           oprinfo[i].dobj.name);
3175         }
3176
3177         PQclear(res);
3178
3179         destroyPQExpBuffer(query);
3180
3181         return oprinfo;
3182 }
3183
3184 /*
3185  * getCollations:
3186  *        read all collations in the system catalogs and return them in the
3187  * CollInfo* structure
3188  *
3189  *      numCollations is set to the number of collations read in
3190  */
3191 CollInfo *
3192 getCollations(Archive *fout, int *numCollations)
3193 {
3194         PGresult   *res;
3195         int                     ntups;
3196         int                     i;
3197         PQExpBuffer query;
3198         CollInfo   *collinfo;
3199         int                     i_tableoid;
3200         int                     i_oid;
3201         int                     i_collname;
3202         int                     i_collnamespace;
3203         int                     i_rolname;
3204
3205         /* Collations didn't exist pre-9.1 */
3206         if (fout->remoteVersion < 90100)
3207         {
3208                 *numCollations = 0;
3209                 return NULL;
3210         }
3211
3212         query = createPQExpBuffer();
3213
3214         /*
3215          * find all collations, including builtin collations; we filter out
3216          * system-defined collations at dump-out time.
3217          */
3218
3219         /* Make sure we are in proper schema */
3220         selectSourceSchema(fout, "pg_catalog");
3221
3222         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3223                                           "collnamespace, "
3224                                           "(%s collowner) AS rolname "
3225                                           "FROM pg_collation",
3226                                           username_subquery);
3227
3228         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3229
3230         ntups = PQntuples(res);
3231         *numCollations = ntups;
3232
3233         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3234
3235         i_tableoid = PQfnumber(res, "tableoid");
3236         i_oid = PQfnumber(res, "oid");
3237         i_collname = PQfnumber(res, "collname");
3238         i_collnamespace = PQfnumber(res, "collnamespace");
3239         i_rolname = PQfnumber(res, "rolname");
3240
3241         for (i = 0; i < ntups; i++)
3242         {
3243                 collinfo[i].dobj.objType = DO_COLLATION;
3244                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3245                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3246                 AssignDumpId(&collinfo[i].dobj);
3247                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3248                 collinfo[i].dobj.namespace =
3249                         findNamespace(fout,
3250                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3251                                                   collinfo[i].dobj.catId.oid);
3252                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3253
3254                 /* Decide whether we want to dump it */
3255                 selectDumpableObject(&(collinfo[i].dobj));
3256         }
3257
3258         PQclear(res);
3259
3260         destroyPQExpBuffer(query);
3261
3262         return collinfo;
3263 }
3264
3265 /*
3266  * getConversions:
3267  *        read all conversions in the system catalogs and return them in the
3268  * ConvInfo* structure
3269  *
3270  *      numConversions is set to the number of conversions read in
3271  */
3272 ConvInfo *
3273 getConversions(Archive *fout, int *numConversions)
3274 {
3275         PGresult   *res;
3276         int                     ntups;
3277         int                     i;
3278         PQExpBuffer query = createPQExpBuffer();
3279         ConvInfo   *convinfo;
3280         int                     i_tableoid;
3281         int                     i_oid;
3282         int                     i_conname;
3283         int                     i_connamespace;
3284         int                     i_rolname;
3285
3286         /* Conversions didn't exist pre-7.3 */
3287         if (fout->remoteVersion < 70300)
3288         {
3289                 *numConversions = 0;
3290                 return NULL;
3291         }
3292
3293         /*
3294          * find all conversions, including builtin conversions; we filter out
3295          * system-defined conversions at dump-out time.
3296          */
3297
3298         /* Make sure we are in proper schema */
3299         selectSourceSchema(fout, "pg_catalog");
3300
3301         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3302                                           "connamespace, "
3303                                           "(%s conowner) AS rolname "
3304                                           "FROM pg_conversion",
3305                                           username_subquery);
3306
3307         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3308
3309         ntups = PQntuples(res);
3310         *numConversions = ntups;
3311
3312         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3313
3314         i_tableoid = PQfnumber(res, "tableoid");
3315         i_oid = PQfnumber(res, "oid");
3316         i_conname = PQfnumber(res, "conname");
3317         i_connamespace = PQfnumber(res, "connamespace");
3318         i_rolname = PQfnumber(res, "rolname");
3319
3320         for (i = 0; i < ntups; i++)
3321         {
3322                 convinfo[i].dobj.objType = DO_CONVERSION;
3323                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3324                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3325                 AssignDumpId(&convinfo[i].dobj);
3326                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3327                 convinfo[i].dobj.namespace =
3328                         findNamespace(fout,
3329                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3330                                                   convinfo[i].dobj.catId.oid);
3331                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3332
3333                 /* Decide whether we want to dump it */
3334                 selectDumpableObject(&(convinfo[i].dobj));
3335         }
3336
3337         PQclear(res);
3338
3339         destroyPQExpBuffer(query);
3340
3341         return convinfo;
3342 }
3343
3344 /*
3345  * getOpclasses:
3346  *        read all opclasses in the system catalogs and return them in the
3347  * OpclassInfo* structure
3348  *
3349  *      numOpclasses is set to the number of opclasses read in
3350  */
3351 OpclassInfo *
3352 getOpclasses(Archive *fout, int *numOpclasses)
3353 {
3354         PGresult   *res;
3355         int                     ntups;
3356         int                     i;
3357         PQExpBuffer query = createPQExpBuffer();
3358         OpclassInfo *opcinfo;
3359         int                     i_tableoid;
3360         int                     i_oid;
3361         int                     i_opcname;
3362         int                     i_opcnamespace;
3363         int                     i_rolname;
3364
3365         /*
3366          * find all opclasses, including builtin opclasses; we filter out
3367          * system-defined opclasses at dump-out time.
3368          */
3369
3370         /* Make sure we are in proper schema */
3371         selectSourceSchema(fout, "pg_catalog");
3372
3373         if (fout->remoteVersion >= 70300)
3374         {
3375                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3376                                                   "opcnamespace, "
3377                                                   "(%s opcowner) AS rolname "
3378                                                   "FROM pg_opclass",
3379                                                   username_subquery);
3380         }
3381         else if (fout->remoteVersion >= 70100)
3382         {
3383                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3384                                                   "0::oid AS opcnamespace, "
3385                                                   "''::name AS rolname "
3386                                                   "FROM pg_opclass");
3387         }
3388         else
3389         {
3390                 appendPQExpBuffer(query, "SELECT "
3391                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3392                                                   "oid, opcname, "
3393                                                   "0::oid AS opcnamespace, "
3394                                                   "''::name AS rolname "
3395                                                   "FROM pg_opclass");
3396         }
3397
3398         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3399
3400         ntups = PQntuples(res);
3401         *numOpclasses = ntups;
3402
3403         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3404
3405         i_tableoid = PQfnumber(res, "tableoid");
3406         i_oid = PQfnumber(res, "oid");
3407         i_opcname = PQfnumber(res, "opcname");
3408         i_opcnamespace = PQfnumber(res, "opcnamespace");
3409         i_rolname = PQfnumber(res, "rolname");
3410
3411         for (i = 0; i < ntups; i++)
3412         {
3413                 opcinfo[i].dobj.objType = DO_OPCLASS;
3414                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3415                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3416                 AssignDumpId(&opcinfo[i].dobj);
3417                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3418                 opcinfo[i].dobj.namespace =
3419                         findNamespace(fout,
3420                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3421                                                   opcinfo[i].dobj.catId.oid);
3422                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3423
3424                 /* Decide whether we want to dump it */
3425                 selectDumpableObject(&(opcinfo[i].dobj));
3426
3427                 if (fout->remoteVersion >= 70300)
3428                 {
3429                         if (strlen(opcinfo[i].rolname) == 0)
3430                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3431                                                   opcinfo[i].dobj.name);
3432                 }
3433         }
3434
3435         PQclear(res);
3436
3437         destroyPQExpBuffer(query);
3438
3439         return opcinfo;
3440 }
3441
3442 /*
3443  * getOpfamilies:
3444  *        read all opfamilies in the system catalogs and return them in the
3445  * OpfamilyInfo* structure
3446  *
3447  *      numOpfamilies is set to the number of opfamilies read in
3448  */
3449 OpfamilyInfo *
3450 getOpfamilies(Archive *fout, int *numOpfamilies)
3451 {
3452         PGresult   *res;
3453         int                     ntups;
3454         int                     i;
3455         PQExpBuffer query;
3456         OpfamilyInfo *opfinfo;
3457         int                     i_tableoid;
3458         int                     i_oid;
3459         int                     i_opfname;
3460         int                     i_opfnamespace;
3461         int                     i_rolname;
3462
3463         /* Before 8.3, there is no separate concept of opfamilies */
3464         if (fout->remoteVersion < 80300)
3465         {
3466                 *numOpfamilies = 0;
3467                 return NULL;
3468         }
3469
3470         query = createPQExpBuffer();
3471
3472         /*
3473          * find all opfamilies, including builtin opfamilies; we filter out
3474          * system-defined opfamilies at dump-out time.
3475          */
3476
3477         /* Make sure we are in proper schema */
3478         selectSourceSchema(fout, "pg_catalog");
3479
3480         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3481                                           "opfnamespace, "
3482                                           "(%s opfowner) AS rolname "
3483                                           "FROM pg_opfamily",
3484                                           username_subquery);
3485
3486         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3487
3488         ntups = PQntuples(res);
3489         *numOpfamilies = ntups;
3490
3491         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3492
3493         i_tableoid = PQfnumber(res, "tableoid");
3494         i_oid = PQfnumber(res, "oid");
3495         i_opfname = PQfnumber(res, "opfname");
3496         i_opfnamespace = PQfnumber(res, "opfnamespace");
3497         i_rolname = PQfnumber(res, "rolname");
3498
3499         for (i = 0; i < ntups; i++)
3500         {
3501                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3502                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3503                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3504                 AssignDumpId(&opfinfo[i].dobj);
3505                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3506                 opfinfo[i].dobj.namespace =
3507                         findNamespace(fout,
3508                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3509                                                   opfinfo[i].dobj.catId.oid);
3510                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3511
3512                 /* Decide whether we want to dump it */
3513                 selectDumpableObject(&(opfinfo[i].dobj));
3514
3515                 if (fout->remoteVersion >= 70300)
3516                 {
3517                         if (strlen(opfinfo[i].rolname) == 0)
3518                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3519                                                   opfinfo[i].dobj.name);
3520                 }
3521         }
3522
3523         PQclear(res);
3524
3525         destroyPQExpBuffer(query);
3526
3527         return opfinfo;
3528 }
3529
3530 /*
3531  * getAggregates:
3532  *        read all the user-defined aggregates in the system catalogs and
3533  * return them in the AggInfo* structure
3534  *
3535  * numAggs is set to the number of aggregates read in
3536  */
3537 AggInfo *
3538 getAggregates(Archive *fout, int *numAggs)
3539 {
3540         PGresult   *res;
3541         int                     ntups;
3542         int                     i;
3543         PQExpBuffer query = createPQExpBuffer();
3544         AggInfo    *agginfo;
3545         int                     i_tableoid;
3546         int                     i_oid;
3547         int                     i_aggname;
3548         int                     i_aggnamespace;
3549         int                     i_pronargs;
3550         int                     i_proargtypes;
3551         int                     i_rolname;
3552         int                     i_aggacl;
3553         int                     i_proiargs;
3554
3555         /* Make sure we are in proper schema */
3556         selectSourceSchema(fout, "pg_catalog");
3557
3558         /*
3559          * Find all user-defined aggregates.  See comment in getFuncs() for the
3560          * rationale behind the filtering logic.
3561          */
3562
3563         if (fout->remoteVersion >= 80400)
3564         {
3565                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3566                                                   "pronamespace AS aggnamespace, "
3567                                                   "pronargs, proargtypes, "
3568                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3569                                                   "(%s proowner) AS rolname, "
3570                                                   "proacl AS aggacl "
3571                                                   "FROM pg_proc p "
3572                                                   "WHERE proisagg AND ("
3573                                                   "pronamespace != "
3574                                                   "(SELECT oid FROM pg_namespace "
3575                                                   "WHERE nspname = 'pg_catalog')",
3576                                                   username_subquery);
3577                 if (binary_upgrade && fout->remoteVersion >= 90100)
3578                         appendPQExpBuffer(query,
3579                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3580                                                           "classid = 'pg_proc'::regclass AND "
3581                                                           "objid = p.oid AND "
3582                                                           "refclassid = 'pg_extension'::regclass AND "
3583                                                           "deptype = 'e')");
3584                 appendPQExpBuffer(query, ")");
3585         }
3586         else if (fout->remoteVersion >= 80200)
3587         {
3588                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3589                                                   "pronamespace AS aggnamespace, "
3590                                                   "pronargs, proargtypes, "
3591                                                   "NULL::text AS proiargs,"
3592                                                   "(%s proowner) AS rolname, "
3593                                                   "proacl AS aggacl "
3594                                                   "FROM pg_proc p "
3595                                                   "WHERE proisagg AND ("
3596                                                   "pronamespace != "
3597                                                   "(SELECT oid FROM pg_namespace "
3598                                                   "WHERE nspname = 'pg_catalog'))",
3599                                                   username_subquery);
3600         }
3601         else if (fout->remoteVersion >= 70300)
3602         {
3603                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3604                                                   "pronamespace AS aggnamespace, "
3605                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3606                                                   "proargtypes, "
3607                                                   "NULL::text AS proiargs, "
3608                                                   "(%s proowner) AS rolname, "
3609                                                   "proacl AS aggacl "
3610                                                   "FROM pg_proc "
3611                                                   "WHERE proisagg "
3612                                                   "AND pronamespace != "
3613                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3614                                                   username_subquery);
3615         }
3616         else if (fout->remoteVersion >= 70100)
3617         {
3618                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3619                                                   "0::oid AS aggnamespace, "
3620                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3621                                                   "aggbasetype AS proargtypes, "
3622                                                   "NULL::text AS proiargs, "
3623                                                   "(%s aggowner) AS rolname, "
3624                                                   "'{=X}' AS aggacl "
3625                                                   "FROM pg_aggregate "
3626                                                   "where oid > '%u'::oid",
3627                                                   username_subquery,
3628                                                   g_last_builtin_oid);
3629         }
3630         else
3631         {
3632                 appendPQExpBuffer(query, "SELECT "
3633                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3634                                                   "oid, aggname, "
3635                                                   "0::oid AS aggnamespace, "
3636                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3637                                                   "aggbasetype AS proargtypes, "
3638                                                   "NULL::text AS proiargs, "
3639                                                   "(%s aggowner) AS rolname, "
3640                                                   "'{=X}' AS aggacl "
3641                                                   "FROM pg_aggregate "
3642                                                   "where oid > '%u'::oid",
3643                                                   username_subquery,
3644                                                   g_last_builtin_oid);
3645         }
3646
3647         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3648
3649         ntups = PQntuples(res);
3650         *numAggs = ntups;
3651
3652         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3653
3654         i_tableoid = PQfnumber(res, "tableoid");
3655         i_oid = PQfnumber(res, "oid");
3656         i_aggname = PQfnumber(res, "aggname");
3657         i_aggnamespace = PQfnumber(res, "aggnamespace");
3658         i_pronargs = PQfnumber(res, "pronargs");
3659         i_proargtypes = PQfnumber(res, "proargtypes");
3660         i_rolname = PQfnumber(res, "rolname");
3661         i_aggacl = PQfnumber(res, "aggacl");
3662         i_proiargs = PQfnumber(res, "proiargs");
3663
3664         for (i = 0; i < ntups; i++)
3665         {
3666                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3667                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3668                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3669                 AssignDumpId(&agginfo[i].aggfn.dobj);
3670                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3671                 agginfo[i].aggfn.dobj.namespace =
3672                         findNamespace(fout,
3673                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3674                                                   agginfo[i].aggfn.dobj.catId.oid);
3675                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3676                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3677                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3678                                           agginfo[i].aggfn.dobj.name);
3679                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3680                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3681                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3682                 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3683                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3684                 if (agginfo[i].aggfn.nargs == 0)
3685                         agginfo[i].aggfn.argtypes = NULL;
3686                 else
3687                 {
3688                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3689                         if (fout->remoteVersion >= 70300)
3690                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3691                                                           agginfo[i].aggfn.argtypes,
3692                                                           agginfo[i].aggfn.nargs);
3693                         else
3694                                 /* it's just aggbasetype */
3695                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3696                 }
3697
3698                 /* Decide whether we want to dump it */
3699                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3700         }
3701
3702         PQclear(res);
3703
3704         destroyPQExpBuffer(query);
3705
3706         return agginfo;
3707 }
3708
3709 /*
3710  * getFuncs:
3711  *        read all the user-defined functions in the system catalogs and
3712  * return them in the FuncInfo* structure
3713  *
3714  * numFuncs is set to the number of functions read in
3715  */
3716 FuncInfo *
3717 getFuncs(Archive *fout, int *numFuncs)
3718 {
3719         PGresult   *res;
3720         int                     ntups;
3721         int                     i;
3722         PQExpBuffer query = createPQExpBuffer();
3723         FuncInfo   *finfo;
3724         int                     i_tableoid;
3725         int                     i_oid;
3726         int                     i_proname;
3727         int                     i_pronamespace;
3728         int                     i_rolname;
3729         int                     i_prolang;
3730         int                     i_pronargs;
3731         int                     i_proargtypes;
3732         int                     i_prorettype;
3733         int                     i_proacl;
3734         int                     i_proiargs;
3735
3736         /* Make sure we are in proper schema */
3737         selectSourceSchema(fout, "pg_catalog");
3738
3739         /*
3740          * Find all user-defined functions.  Normally we can exclude functions in
3741          * pg_catalog, which is worth doing since there are several thousand of
3742          * 'em.  However, there are some extensions that create functions in
3743          * pg_catalog.  In normal dumps we can still ignore those --- but in
3744          * binary-upgrade mode, we must dump the member objects of the extension,
3745          * so be sure to fetch any such functions.
3746          *
3747          * Also, in 9.2 and up, exclude functions that are internally dependent on
3748          * something else, since presumably those will be created as a result of
3749          * creating the something else.  This currently only acts to suppress
3750          * constructor functions for range types.  Note that this is OK only
3751          * because the constructors don't have any dependencies the range type
3752          * doesn't have; otherwise we might not get creation ordering correct.
3753          */
3754
3755         if (fout->remoteVersion >= 80400)
3756         {
3757                 appendPQExpBuffer(query,
3758                                                   "SELECT tableoid, oid, proname, prolang, "
3759                                                   "pronargs, proargtypes, prorettype, proacl, "
3760                                                   "pronamespace, "
3761                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3762                                                   "(%s proowner) AS rolname "
3763                                                   "FROM pg_proc p "
3764                                                   "WHERE NOT proisagg AND ("
3765                                                   "pronamespace != "
3766                                                   "(SELECT oid FROM pg_namespace "
3767                                                   "WHERE nspname = 'pg_catalog')",
3768                                                   username_subquery);
3769                 if (fout->remoteVersion >= 90200)
3770                         appendPQExpBuffer(query,
3771                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3772                                                           "WHERE classid = 'pg_proc'::regclass AND "
3773                                                           "objid = p.oid AND deptype = 'i')");
3774                 if (binary_upgrade && fout->remoteVersion >= 90100)
3775                         appendPQExpBuffer(query,
3776                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3777                                                           "classid = 'pg_proc'::regclass AND "
3778                                                           "objid = p.oid AND "
3779                                                           "refclassid = 'pg_extension'::regclass AND "
3780                                                           "deptype = 'e')");
3781                 appendPQExpBuffer(query, ")");
3782         }
3783         else if (fout->remoteVersion >= 70300)
3784         {
3785                 appendPQExpBuffer(query,
3786                                                   "SELECT tableoid, oid, proname, prolang, "
3787                                                   "pronargs, proargtypes, prorettype, proacl, "
3788                                                   "pronamespace, "
3789                                                   "NULL::text AS proiargs,"
3790                                                   "(%s proowner) AS rolname "
3791                                                   "FROM pg_proc p "
3792                                                   "WHERE NOT proisagg AND ("
3793                                                   "pronamespace != "
3794                                                   "(SELECT oid FROM pg_namespace "
3795                                                   "WHERE nspname = 'pg_catalog'))",
3796                                                   username_subquery);
3797         }
3798         else if (fout->remoteVersion >= 70100)
3799         {
3800                 appendPQExpBuffer(query,
3801                                                   "SELECT tableoid, oid, proname, prolang, "
3802                                                   "pronargs, proargtypes, prorettype, "
3803                                                   "'{=X}' AS proacl, "
3804                                                   "0::oid AS pronamespace, "
3805                                                   "NULL::text AS proiargs,"
3806                                                   "(%s proowner) AS rolname "
3807                                                   "FROM pg_proc "
3808                                                   "WHERE pg_proc.oid > '%u'::oid",
3809                                                   username_subquery,
3810                                                   g_last_builtin_oid);
3811         }
3812         else
3813         {
3814                 appendPQExpBuffer(query,
3815                                                   "SELECT "
3816                                                   "(SELECT oid FROM pg_class "
3817                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3818                                                   "oid, proname, prolang, "
3819                                                   "pronargs, proargtypes, prorettype, "
3820                                                   "'{=X}' AS proacl, "
3821                                                   "0::oid AS pronamespace, "
3822                                                   "NULL::text AS proiargs,"
3823                                                   "(%s proowner) AS rolname "
3824                                                   "FROM pg_proc "
3825                                                   "where pg_proc.oid > '%u'::oid",
3826                                                   username_subquery,
3827                                                   g_last_builtin_oid);
3828         }
3829
3830         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3831
3832         ntups = PQntuples(res);
3833
3834         *numFuncs = ntups;
3835
3836         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
3837
3838         i_tableoid = PQfnumber(res, "tableoid");
3839         i_oid = PQfnumber(res, "oid");
3840         i_proname = PQfnumber(res, "proname");
3841         i_pronamespace = PQfnumber(res, "pronamespace");
3842         i_rolname = PQfnumber(res, "rolname");
3843         i_prolang = PQfnumber(res, "prolang");
3844         i_pronargs = PQfnumber(res, "pronargs");
3845         i_proargtypes = PQfnumber(res, "proargtypes");
3846         i_prorettype = PQfnumber(res, "prorettype");
3847         i_proacl = PQfnumber(res, "proacl");
3848         i_proiargs = PQfnumber(res, "proiargs");
3849
3850         for (i = 0; i < ntups; i++)
3851         {
3852                 finfo[i].dobj.objType = DO_FUNC;
3853                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3854                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3855                 AssignDumpId(&finfo[i].dobj);
3856                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3857                 finfo[i].dobj.namespace =
3858                         findNamespace(fout,
3859                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3860                                                   finfo[i].dobj.catId.oid);
3861                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3862                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3863                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3864                 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3865                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3866                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3867                 if (finfo[i].nargs == 0)
3868                         finfo[i].argtypes = NULL;
3869                 else
3870                 {
3871                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3872                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3873                                                   finfo[i].argtypes, finfo[i].nargs);
3874                 }
3875
3876                 /* Decide whether we want to dump it */
3877                 selectDumpableObject(&(finfo[i].dobj));
3878
3879                 if (strlen(finfo[i].rolname) == 0)
3880                         write_msg(NULL,
3881                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3882                                           finfo[i].dobj.name);
3883         }
3884
3885         PQclear(res);
3886
3887         destroyPQExpBuffer(query);
3888
3889         return finfo;
3890 }
3891
3892 /*
3893  * getTables
3894  *        read all the user-defined tables (no indexes, no catalogs)
3895  * in the system catalogs return them in the TableInfo* structure
3896  *
3897  * numTables is set to the number of tables read in
3898  */
3899 TableInfo *
3900 getTables(Archive *fout, int *numTables)
3901 {
3902         PGresult   *res;
3903         int                     ntups;
3904         int                     i;
3905         PQExpBuffer query = createPQExpBuffer();
3906         TableInfo  *tblinfo;
3907         int                     i_reltableoid;
3908         int                     i_reloid;
3909         int                     i_relname;
3910         int                     i_relnamespace;
3911         int                     i_relkind;
3912         int                     i_relacl;
3913         int                     i_rolname;
3914         int                     i_relchecks;
3915         int                     i_relhastriggers;
3916         int                     i_relhasindex;
3917         int                     i_relhasrules;
3918         int                     i_relhasoids;
3919         int                     i_relfrozenxid;
3920         int                     i_toastoid;
3921         int                     i_toastfrozenxid;
3922         int                     i_relpersistence;
3923         int                     i_owning_tab;
3924         int                     i_owning_col;
3925         int                     i_reltablespace;
3926         int                     i_reloptions;
3927         int                     i_toastreloptions;
3928         int                     i_reloftype;
3929
3930         /* Make sure we are in proper schema */
3931         selectSourceSchema(fout, "pg_catalog");
3932
3933         /*
3934          * Find all the tables and table-like objects.
3935          *
3936          * We include system catalogs, so that we can work if a user table is
3937          * defined to inherit from a system catalog (pretty weird, but...)
3938          *
3939          * We ignore relations that are not ordinary tables, sequences, views,
3940          * composite types, or foreign tables.
3941          *
3942          * Composite-type table entries won't be dumped as such, but we have to
3943          * make a DumpableObject for them so that we can track dependencies of the
3944          * composite type (pg_depend entries for columns of the composite type
3945          * link to the pg_class entry not the pg_type entry).
3946          *
3947          * Note: in this phase we should collect only a minimal amount of
3948          * information about each table, basically just enough to decide if it is
3949          * interesting. We must fetch all tables in this phase because otherwise
3950          * we cannot correctly identify inherited columns, owned sequences, etc.
3951          */
3952
3953         if (fout->remoteVersion >= 90100)
3954         {
3955                 /*
3956                  * Left join to pick up dependency info linking sequences to their
3957                  * owning column, if any (note this dependency is AUTO as of 8.2)
3958                  */
3959                 appendPQExpBuffer(query,
3960                                                   "SELECT c.tableoid, c.oid, c.relname, "
3961                                                   "c.relacl, c.relkind, c.relnamespace, "
3962                                                   "(%s c.relowner) AS rolname, "
3963                                                   "c.relchecks, c.relhastriggers, "
3964                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3965                                                   "c.relfrozenxid, tc.oid AS toid, "
3966                                                   "tc.relfrozenxid AS tfrozenxid, "
3967                                                   "c.relpersistence, "
3968                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3969                                                   "d.refobjid AS owning_tab, "
3970                                                   "d.refobjsubid AS owning_col, "
3971                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3972                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3973                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3974                                                   "FROM pg_class c "
3975                                                   "LEFT JOIN pg_depend d ON "
3976                                                   "(c.relkind = '%c' AND "
3977                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3978                                                   "d.objsubid = 0 AND "
3979                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3980                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3981                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3982                                                   "ORDER BY c.oid",
3983                                                   username_subquery,
3984                                                   RELKIND_SEQUENCE,
3985                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3986                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3987                                                   RELKIND_FOREIGN_TABLE);
3988         }
3989         else if (fout->remoteVersion >= 90000)
3990         {
3991                 /*
3992                  * Left join to pick up dependency info linking sequences to their
3993                  * owning column, if any (note this dependency is AUTO as of 8.2)
3994                  */
3995                 appendPQExpBuffer(query,
3996                                                   "SELECT c.tableoid, c.oid, c.relname, "
3997                                                   "c.relacl, c.relkind, c.relnamespace, "
3998                                                   "(%s c.relowner) AS rolname, "
3999                                                   "c.relchecks, c.relhastriggers, "
4000                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4001                                                   "c.relfrozenxid, tc.oid AS toid, "
4002                                                   "tc.relfrozenxid AS tfrozenxid, "
4003                                                   "'p' AS relpersistence, "
4004                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4005                                                   "d.refobjid AS owning_tab, "
4006                                                   "d.refobjsubid AS owning_col, "
4007                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4008                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4009                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4010                                                   "FROM pg_class c "
4011                                                   "LEFT JOIN pg_depend d ON "
4012                                                   "(c.relkind = '%c' AND "
4013                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4014                                                   "d.objsubid = 0 AND "
4015                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4016                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4017                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4018                                                   "ORDER BY c.oid",
4019                                                   username_subquery,
4020                                                   RELKIND_SEQUENCE,
4021                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4022                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4023         }
4024         else if (fout->remoteVersion >= 80400)
4025         {
4026                 /*
4027                  * Left join to pick up dependency info linking sequences to their
4028                  * owning column, if any (note this dependency is AUTO as of 8.2)
4029                  */
4030                 appendPQExpBuffer(query,
4031                                                   "SELECT c.tableoid, c.oid, c.relname, "
4032                                                   "c.relacl, c.relkind, c.relnamespace, "
4033                                                   "(%s c.relowner) AS rolname, "
4034                                                   "c.relchecks, c.relhastriggers, "
4035                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4036                                                   "c.relfrozenxid, tc.oid AS toid, "
4037                                                   "tc.relfrozenxid AS tfrozenxid, "
4038                                                   "'p' AS relpersistence, "
4039                                                   "NULL AS reloftype, "
4040                                                   "d.refobjid AS owning_tab, "
4041                                                   "d.refobjsubid AS owning_col, "
4042                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4043                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4044                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4045                                                   "FROM pg_class c "
4046                                                   "LEFT JOIN pg_depend d ON "
4047                                                   "(c.relkind = '%c' AND "
4048                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4049                                                   "d.objsubid = 0 AND "
4050                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4051                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4052                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4053                                                   "ORDER BY c.oid",
4054                                                   username_subquery,
4055                                                   RELKIND_SEQUENCE,
4056                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4057                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4058         }
4059         else if (fout->remoteVersion >= 80200)
4060         {
4061                 /*
4062                  * Left join to pick up dependency info linking sequences to their
4063                  * owning column, if any (note this dependency is AUTO as of 8.2)
4064                  */
4065                 appendPQExpBuffer(query,
4066                                                   "SELECT c.tableoid, c.oid, c.relname, "
4067                                                   "c.relacl, c.relkind, c.relnamespace, "
4068                                                   "(%s c.relowner) AS rolname, "
4069                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4070                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4071                                                   "c.relfrozenxid, tc.oid AS toid, "
4072                                                   "tc.relfrozenxid AS tfrozenxid, "
4073                                                   "'p' AS relpersistence, "
4074                                                   "NULL AS reloftype, "
4075                                                   "d.refobjid AS owning_tab, "
4076                                                   "d.refobjsubid AS owning_col, "
4077                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4078                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4079                                                   "NULL AS toast_reloptions "
4080                                                   "FROM pg_class c "
4081                                                   "LEFT JOIN pg_depend d ON "
4082                                                   "(c.relkind = '%c' AND "
4083                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4084                                                   "d.objsubid = 0 AND "
4085                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4086                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4087                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4088                                                   "ORDER BY c.oid",
4089                                                   username_subquery,
4090                                                   RELKIND_SEQUENCE,
4091                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4092                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4093         }
4094         else if (fout->remoteVersion >= 80000)
4095         {
4096                 /*
4097                  * Left join to pick up dependency info linking sequences to their
4098                  * owning column, if any
4099                  */
4100                 appendPQExpBuffer(query,
4101                                                   "SELECT c.tableoid, c.oid, relname, "
4102                                                   "relacl, relkind, relnamespace, "
4103                                                   "(%s relowner) AS rolname, "
4104                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4105                                                   "relhasindex, relhasrules, relhasoids, "
4106                                                   "0 AS relfrozenxid, "
4107                                                   "0 AS toid, "
4108                                                   "0 AS tfrozenxid, "
4109                                                   "'p' AS relpersistence, "
4110                                                   "NULL AS reloftype, "
4111                                                   "d.refobjid AS owning_tab, "
4112                                                   "d.refobjsubid AS owning_col, "
4113                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4114                                                   "NULL AS reloptions, "
4115                                                   "NULL AS toast_reloptions "
4116                                                   "FROM pg_class c "
4117                                                   "LEFT JOIN pg_depend d ON "
4118                                                   "(c.relkind = '%c' AND "
4119                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4120                                                   "d.objsubid = 0 AND "
4121                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4122                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4123                                                   "ORDER BY c.oid",
4124                                                   username_subquery,
4125                                                   RELKIND_SEQUENCE,
4126                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4127                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4128         }
4129         else if (fout->remoteVersion >= 70300)
4130         {
4131                 /*
4132                  * Left join to pick up dependency info linking sequences to their
4133                  * owning column, if any
4134                  */
4135                 appendPQExpBuffer(query,
4136                                                   "SELECT c.tableoid, c.oid, relname, "
4137                                                   "relacl, relkind, relnamespace, "
4138                                                   "(%s relowner) AS rolname, "
4139                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4140                                                   "relhasindex, relhasrules, relhasoids, "
4141                                                   "0 AS relfrozenxid, "
4142                                                   "0 AS toid, "
4143                                                   "0 AS tfrozenxid, "
4144                                                   "'p' AS relpersistence, "
4145                                                   "NULL AS reloftype, "
4146                                                   "d.refobjid AS owning_tab, "
4147                                                   "d.refobjsubid AS owning_col, "
4148                                                   "NULL AS reltablespace, "
4149                                                   "NULL AS reloptions, "
4150                                                   "NULL AS toast_reloptions "
4151                                                   "FROM pg_class c "
4152                                                   "LEFT JOIN pg_depend d ON "
4153                                                   "(c.relkind = '%c' AND "
4154                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4155                                                   "d.objsubid = 0 AND "
4156                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4157                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4158                                                   "ORDER BY c.oid",
4159                                                   username_subquery,
4160                                                   RELKIND_SEQUENCE,
4161                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4162                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4163         }
4164         else if (fout->remoteVersion >= 70200)
4165         {
4166                 appendPQExpBuffer(query,
4167                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4168                                                   "0::oid AS relnamespace, "
4169                                                   "(%s relowner) AS rolname, "
4170                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4171                                                   "relhasindex, relhasrules, relhasoids, "
4172                                                   "0 AS relfrozenxid, "
4173                                                   "0 AS toid, "
4174                                                   "0 AS tfrozenxid, "
4175                                                   "'p' AS relpersistence, "
4176                                                   "NULL AS reloftype, "
4177                                                   "NULL::oid AS owning_tab, "
4178                                                   "NULL::int4 AS owning_col, "
4179                                                   "NULL AS reltablespace, "
4180                                                   "NULL AS reloptions, "
4181                                                   "NULL AS toast_reloptions "
4182                                                   "FROM pg_class "
4183                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4184                                                   "ORDER BY oid",
4185                                                   username_subquery,
4186                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4187         }
4188         else if (fout->remoteVersion >= 70100)
4189         {
4190                 /* all tables have oids in 7.1 */
4191                 appendPQExpBuffer(query,
4192                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4193                                                   "0::oid AS relnamespace, "
4194                                                   "(%s relowner) AS rolname, "
4195                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4196                                                   "relhasindex, relhasrules, "
4197                                                   "'t'::bool AS relhasoids, "
4198                                                   "0 AS relfrozenxid, "
4199                                                   "0 AS toid, "
4200                                                   "0 AS tfrozenxid, "
4201                                                   "'p' AS relpersistence, "
4202                                                   "NULL AS reloftype, "
4203                                                   "NULL::oid AS owning_tab, "
4204                                                   "NULL::int4 AS owning_col, "
4205                                                   "NULL AS reltablespace, "
4206                                                   "NULL AS reloptions, "
4207                                                   "NULL AS toast_reloptions "
4208                                                   "FROM pg_class "
4209                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4210                                                   "ORDER BY oid",
4211                                                   username_subquery,
4212                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4213         }
4214         else
4215         {
4216                 /*
4217                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4218                  * have a view by looking for a rule in pg_rewrite.
4219                  */
4220                 appendPQExpBuffer(query,
4221                                                   "SELECT "
4222                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4223                                                   "oid, relname, relacl, "
4224                                                   "CASE WHEN relhasrules and relkind = 'r' "
4225                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4226                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4227                                                   "THEN '%c'::\"char\" "
4228                                                   "ELSE relkind END AS relkind,"
4229                                                   "0::oid AS relnamespace, "
4230                                                   "(%s relowner) AS rolname, "
4231                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4232                                                   "relhasindex, relhasrules, "
4233                                                   "'t'::bool AS relhasoids, "
4234                                                   "0 as relfrozenxid, "
4235                                                   "0 AS toid, "
4236                                                   "0 AS tfrozenxid, "
4237                                                   "'p' AS relpersistence, "
4238                                                   "NULL AS reloftype, "
4239                                                   "NULL::oid AS owning_tab, "
4240                                                   "NULL::int4 AS owning_col, "
4241                                                   "NULL AS reltablespace, "
4242                                                   "NULL AS reloptions, "
4243                                                   "NULL AS toast_reloptions "
4244                                                   "FROM pg_class c "
4245                                                   "WHERE relkind IN ('%c', '%c') "
4246                                                   "ORDER BY oid",
4247                                                   RELKIND_VIEW,
4248                                                   username_subquery,
4249                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4250         }
4251
4252         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4253
4254         ntups = PQntuples(res);
4255
4256         *numTables = ntups;
4257
4258         /*
4259          * Extract data from result and lock dumpable tables.  We do the locking
4260          * before anything else, to minimize the window wherein a table could
4261          * disappear under us.
4262          *
4263          * Note that we have to save info about all tables here, even when dumping
4264          * only one, because we don't yet know which tables might be inheritance
4265          * ancestors of the target table.
4266          */
4267         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4268
4269         i_reltableoid = PQfnumber(res, "tableoid");
4270         i_reloid = PQfnumber(res, "oid");
4271         i_relname = PQfnumber(res, "relname");
4272         i_relnamespace = PQfnumber(res, "relnamespace");
4273         i_relacl = PQfnumber(res, "relacl");
4274         i_relkind = PQfnumber(res, "relkind");
4275         i_rolname = PQfnumber(res, "rolname");
4276         i_relchecks = PQfnumber(res, "relchecks");
4277         i_relhastriggers = PQfnumber(res, "relhastriggers");
4278         i_relhasindex = PQfnumber(res, "relhasindex");
4279         i_relhasrules = PQfnumber(res, "relhasrules");
4280         i_relhasoids = PQfnumber(res, "relhasoids");
4281         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4282         i_toastoid = PQfnumber(res, "toid");
4283         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4284         i_relpersistence = PQfnumber(res, "relpersistence");
4285         i_owning_tab = PQfnumber(res, "owning_tab");
4286         i_owning_col = PQfnumber(res, "owning_col");
4287         i_reltablespace = PQfnumber(res, "reltablespace");
4288         i_reloptions = PQfnumber(res, "reloptions");
4289         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4290         i_reloftype = PQfnumber(res, "reloftype");
4291
4292         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4293         {
4294                 /*
4295                  * Arrange to fail instead of waiting forever for a table lock.
4296                  *
4297                  * NB: this coding assumes that the only queries issued within the
4298                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4299                  * applied to other things too.
4300                  */
4301                 resetPQExpBuffer(query);
4302                 appendPQExpBuffer(query, "SET statement_timeout = ");
4303                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4304                 ExecuteSqlStatement(fout, query->data);
4305         }
4306
4307         for (i = 0; i < ntups; i++)
4308         {
4309                 tblinfo[i].dobj.objType = DO_TABLE;
4310                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4311                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4312                 AssignDumpId(&tblinfo[i].dobj);
4313                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4314                 tblinfo[i].dobj.namespace =
4315                         findNamespace(fout,
4316                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4317                                                   tblinfo[i].dobj.catId.oid);
4318                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4319                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4320                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4321                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4322                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4323                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4324                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4325                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4326                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4327                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4328                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4329                 if (PQgetisnull(res, i, i_reloftype))
4330                         tblinfo[i].reloftype = NULL;
4331                 else
4332                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4333                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4334                 if (PQgetisnull(res, i, i_owning_tab))
4335                 {
4336                         tblinfo[i].owning_tab = InvalidOid;
4337                         tblinfo[i].owning_col = 0;
4338                 }
4339                 else
4340                 {
4341                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4342                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4343                 }
4344                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4345                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4346                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4347
4348                 /* other fields were zeroed above */
4349
4350                 /*
4351                  * Decide whether we want to dump this table.
4352                  */
4353                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4354                         tblinfo[i].dobj.dump = false;
4355                 else
4356                         selectDumpableTable(&tblinfo[i]);
4357                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4358
4359                 /*
4360                  * Read-lock target tables to make sure they aren't DROPPED or altered
4361                  * in schema before we get around to dumping them.
4362                  *
4363                  * Note that we don't explicitly lock parents of the target tables; we
4364                  * assume our lock on the child is enough to prevent schema
4365                  * alterations to parent tables.
4366                  *
4367                  * NOTE: it'd be kinda nice to lock other relations too, not only
4368                  * plain tables, but the backend doesn't presently allow that.
4369                  */
4370                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4371                 {
4372                         resetPQExpBuffer(query);
4373                         appendPQExpBuffer(query,
4374                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4375                                                           fmtQualifiedId(fout,
4376                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4377                                                                                          tblinfo[i].dobj.name));
4378                         ExecuteSqlStatement(fout, query->data);
4379                 }
4380
4381                 /* Emit notice if join for owner failed */
4382                 if (strlen(tblinfo[i].rolname) == 0)
4383                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4384                                           tblinfo[i].dobj.name);
4385         }
4386
4387         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4388         {
4389                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4390         }
4391
4392         PQclear(res);
4393
4394         destroyPQExpBuffer(query);
4395
4396         return tblinfo;
4397 }
4398
4399 /*
4400  * getOwnedSeqs
4401  *        identify owned sequences and mark them as dumpable if owning table is
4402  *
4403  * We used to do this in getTables(), but it's better to do it after the
4404  * index used by findTableByOid() has been set up.
4405  */
4406 void
4407 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4408 {
4409         int                     i;
4410
4411         /*
4412          * Force sequences that are "owned" by table columns to be dumped whenever
4413          * their owning table is being dumped.
4414          */
4415         for (i = 0; i < numTables; i++)
4416         {
4417                 TableInfo  *seqinfo = &tblinfo[i];
4418                 TableInfo  *owning_tab;
4419
4420                 if (!OidIsValid(seqinfo->owning_tab))
4421                         continue;                       /* not an owned sequence */
4422                 if (seqinfo->dobj.dump)
4423                         continue;                       /* no need to search */
4424                 owning_tab = findTableByOid(seqinfo->owning_tab);
4425                 if (owning_tab && owning_tab->dobj.dump)
4426                 {
4427                         seqinfo->interesting = true;
4428                         seqinfo->dobj.dump = true;
4429                 }
4430         }
4431 }
4432
4433 /*
4434  * getInherits
4435  *        read all the inheritance information
4436  * from the system catalogs return them in the InhInfo* structure
4437  *
4438  * numInherits is set to the number of pairs read in
4439  */
4440 InhInfo *
4441 getInherits(Archive *fout, int *numInherits)
4442 {
4443         PGresult   *res;
4444         int                     ntups;
4445         int                     i;
4446         PQExpBuffer query = createPQExpBuffer();
4447         InhInfo    *inhinfo;
4448
4449         int                     i_inhrelid;
4450         int                     i_inhparent;
4451
4452         /* Make sure we are in proper schema */
4453         selectSourceSchema(fout, "pg_catalog");
4454
4455         /* find all the inheritance information */
4456
4457         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4458
4459         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4460
4461         ntups = PQntuples(res);
4462
4463         *numInherits = ntups;
4464
4465         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4466
4467         i_inhrelid = PQfnumber(res, "inhrelid");
4468         i_inhparent = PQfnumber(res, "inhparent");
4469
4470         for (i = 0; i < ntups; i++)
4471         {
4472                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4473                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4474         }
4475
4476         PQclear(res);
4477
4478         destroyPQExpBuffer(query);
4479
4480         return inhinfo;
4481 }
4482
4483 /*
4484  * getIndexes
4485  *        get information about every index on a dumpable table
4486  *
4487  * Note: index data is not returned directly to the caller, but it
4488  * does get entered into the DumpableObject tables.
4489  */
4490 void
4491 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4492 {
4493         int                     i,
4494                                 j;
4495         PQExpBuffer query = createPQExpBuffer();
4496         PGresult   *res;
4497         IndxInfo   *indxinfo;
4498         ConstraintInfo *constrinfo;
4499         int                     i_tableoid,
4500                                 i_oid,
4501                                 i_indexname,
4502                                 i_indexdef,
4503                                 i_indnkeys,
4504                                 i_indkey,
4505                                 i_indisclustered,
4506                                 i_contype,
4507                                 i_conname,
4508                                 i_condeferrable,
4509                                 i_condeferred,
4510                                 i_contableoid,
4511                                 i_conoid,
4512                                 i_condef,
4513                                 i_tablespace,
4514                                 i_options;
4515         int                     ntups;
4516
4517         for (i = 0; i < numTables; i++)
4518         {
4519                 TableInfo  *tbinfo = &tblinfo[i];
4520
4521                 /* Only plain tables have indexes */
4522                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4523                         continue;
4524
4525                 /* Ignore indexes of tables not to be dumped */
4526                 if (!tbinfo->dobj.dump)
4527                         continue;
4528
4529                 if (g_verbose)
4530                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4531                                           tbinfo->dobj.name);
4532
4533                 /* Make sure we are in proper schema so indexdef is right */
4534                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4535
4536                 /*
4537                  * The point of the messy-looking outer join is to find a constraint
4538                  * that is related by an internal dependency link to the index. If we
4539                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4540                  * assume an index won't have more than one internal dependency.
4541                  *
4542                  * As of 9.0 we don't need to look at pg_depend but can check for a
4543                  * match to pg_constraint.conindid.  The check on conrelid is
4544                  * redundant but useful because that column is indexed while conindid
4545                  * is not.
4546                  */
4547                 resetPQExpBuffer(query);
4548                 if (fout->remoteVersion >= 90000)
4549                 {
4550                         appendPQExpBuffer(query,
4551                                                           "SELECT t.tableoid, t.oid, "
4552                                                           "t.relname AS indexname, "
4553                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4554                                                           "t.relnatts AS indnkeys, "
4555                                                           "i.indkey, i.indisclustered, "
4556                                                           "c.contype, c.conname, "
4557                                                           "c.condeferrable, c.condeferred, "
4558                                                           "c.tableoid AS contableoid, "
4559                                                           "c.oid AS conoid, "
4560                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4561                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4562                                                         "array_to_string(t.reloptions, ', ') AS options "
4563                                                           "FROM pg_catalog.pg_index i "
4564                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4565                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4566                                                           "ON (i.indrelid = c.conrelid AND "
4567                                                           "i.indexrelid = c.conindid AND "
4568                                                           "c.contype IN ('p','u','x')) "
4569                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4570                                                           "ORDER BY indexname",
4571                                                           tbinfo->dobj.catId.oid);
4572                 }
4573                 else if (fout->remoteVersion >= 80200)
4574                 {
4575                         appendPQExpBuffer(query,
4576                                                           "SELECT t.tableoid, t.oid, "
4577                                                           "t.relname AS indexname, "
4578                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4579                                                           "t.relnatts AS indnkeys, "
4580                                                           "i.indkey, i.indisclustered, "
4581                                                           "c.contype, c.conname, "
4582                                                           "c.condeferrable, c.condeferred, "
4583                                                           "c.tableoid AS contableoid, "
4584                                                           "c.oid AS conoid, "
4585                                                           "null AS condef, "
4586                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4587                                                         "array_to_string(t.reloptions, ', ') AS options "
4588                                                           "FROM pg_catalog.pg_index i "
4589                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4590                                                           "LEFT JOIN pg_catalog.pg_depend d "
4591                                                           "ON (d.classid = t.tableoid "
4592                                                           "AND d.objid = t.oid "
4593                                                           "AND d.deptype = 'i') "
4594                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4595                                                           "ON (d.refclassid = c.tableoid "
4596                                                           "AND d.refobjid = c.oid) "
4597                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4598                                                           "ORDER BY indexname",
4599                                                           tbinfo->dobj.catId.oid);
4600                 }
4601                 else if (fout->remoteVersion >= 80000)
4602                 {
4603                         appendPQExpBuffer(query,
4604                                                           "SELECT t.tableoid, t.oid, "
4605                                                           "t.relname AS indexname, "
4606                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4607                                                           "t.relnatts AS indnkeys, "
4608                                                           "i.indkey, i.indisclustered, "
4609                                                           "c.contype, c.conname, "
4610                                                           "c.condeferrable, c.condeferred, "
4611                                                           "c.tableoid AS contableoid, "
4612                                                           "c.oid AS conoid, "
4613                                                           "null AS condef, "
4614                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4615                                                           "null AS options "
4616                                                           "FROM pg_catalog.pg_index i "
4617                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4618                                                           "LEFT JOIN pg_catalog.pg_depend d "
4619                                                           "ON (d.classid = t.tableoid "
4620                                                           "AND d.objid = t.oid "
4621                                                           "AND d.deptype = 'i') "
4622                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4623                                                           "ON (d.refclassid = c.tableoid "
4624                                                           "AND d.refobjid = c.oid) "
4625                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4626                                                           "ORDER BY indexname",
4627                                                           tbinfo->dobj.catId.oid);
4628                 }
4629                 else if (fout->remoteVersion >= 70300)
4630                 {
4631                         appendPQExpBuffer(query,
4632                                                           "SELECT t.tableoid, t.oid, "
4633                                                           "t.relname AS indexname, "
4634                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4635                                                           "t.relnatts AS indnkeys, "
4636                                                           "i.indkey, i.indisclustered, "
4637                                                           "c.contype, c.conname, "
4638                                                           "c.condeferrable, c.condeferred, "
4639                                                           "c.tableoid AS contableoid, "
4640                                                           "c.oid AS conoid, "
4641                                                           "null AS condef, "
4642                                                           "NULL AS tablespace, "
4643                                                           "null AS options "
4644                                                           "FROM pg_catalog.pg_index i "
4645                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4646                                                           "LEFT JOIN pg_catalog.pg_depend d "
4647                                                           "ON (d.classid = t.tableoid "
4648                                                           "AND d.objid = t.oid "
4649                                                           "AND d.deptype = 'i') "
4650                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4651                                                           "ON (d.refclassid = c.tableoid "
4652                                                           "AND d.refobjid = c.oid) "
4653                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4654                                                           "ORDER BY indexname",
4655                                                           tbinfo->dobj.catId.oid);
4656                 }
4657                 else if (fout->remoteVersion >= 70100)
4658                 {
4659                         appendPQExpBuffer(query,
4660                                                           "SELECT t.tableoid, t.oid, "
4661                                                           "t.relname AS indexname, "
4662                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4663                                                           "t.relnatts AS indnkeys, "
4664                                                           "i.indkey, false AS indisclustered, "
4665                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4666                                                           "ELSE '0'::char END AS contype, "
4667                                                           "t.relname AS conname, "
4668                                                           "false AS condeferrable, "
4669                                                           "false AS condeferred, "
4670                                                           "0::oid AS contableoid, "
4671                                                           "t.oid AS conoid, "
4672                                                           "null AS condef, "
4673                                                           "NULL AS tablespace, "
4674                                                           "null AS options "
4675                                                           "FROM pg_index i, pg_class t "
4676                                                           "WHERE t.oid = i.indexrelid "
4677                                                           "AND i.indrelid = '%u'::oid "
4678                                                           "ORDER BY indexname",
4679                                                           tbinfo->dobj.catId.oid);
4680                 }
4681                 else
4682                 {
4683                         appendPQExpBuffer(query,
4684                                                           "SELECT "
4685                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4686                                                           "t.oid, "
4687                                                           "t.relname AS indexname, "
4688                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4689                                                           "t.relnatts AS indnkeys, "
4690                                                           "i.indkey, false AS indisclustered, "
4691                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4692                                                           "ELSE '0'::char END AS contype, "
4693                                                           "t.relname AS conname, "
4694                                                           "false AS condeferrable, "
4695                                                           "false AS condeferred, "
4696                                                           "0::oid AS contableoid, "
4697                                                           "t.oid AS conoid, "
4698                                                           "null AS condef, "
4699                                                           "NULL AS tablespace, "
4700                                                           "null AS options "
4701                                                           "FROM pg_index i, pg_class t "
4702                                                           "WHERE t.oid = i.indexrelid "
4703                                                           "AND i.indrelid = '%u'::oid "
4704                                                           "ORDER BY indexname",
4705                                                           tbinfo->dobj.catId.oid);
4706                 }
4707
4708                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4709
4710                 ntups = PQntuples(res);
4711
4712                 i_tableoid = PQfnumber(res, "tableoid");
4713                 i_oid = PQfnumber(res, "oid");
4714                 i_indexname = PQfnumber(res, "indexname");
4715                 i_indexdef = PQfnumber(res, "indexdef");
4716                 i_indnkeys = PQfnumber(res, "indnkeys");
4717                 i_indkey = PQfnumber(res, "indkey");
4718                 i_indisclustered = PQfnumber(res, "indisclustered");
4719                 i_contype = PQfnumber(res, "contype");
4720                 i_conname = PQfnumber(res, "conname");
4721                 i_condeferrable = PQfnumber(res, "condeferrable");
4722                 i_condeferred = PQfnumber(res, "condeferred");
4723                 i_contableoid = PQfnumber(res, "contableoid");
4724                 i_conoid = PQfnumber(res, "conoid");
4725                 i_condef = PQfnumber(res, "condef");
4726                 i_tablespace = PQfnumber(res, "tablespace");
4727                 i_options = PQfnumber(res, "options");
4728
4729                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4730                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4731
4732                 for (j = 0; j < ntups; j++)
4733                 {
4734                         char            contype;
4735
4736                         indxinfo[j].dobj.objType = DO_INDEX;
4737                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4738                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4739                         AssignDumpId(&indxinfo[j].dobj);
4740                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4741                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4742                         indxinfo[j].indextable = tbinfo;
4743                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4744                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4745                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4746                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4747
4748                         /*
4749                          * In pre-7.4 releases, indkeys may contain more entries than
4750                          * indnkeys says (since indnkeys will be 1 for a functional
4751                          * index).      We don't actually care about this case since we don't
4752                          * examine indkeys except for indexes associated with PRIMARY and
4753                          * UNIQUE constraints, which are never functional indexes. But we
4754                          * have to allocate enough space to keep parseOidArray from
4755                          * complaining.
4756                          */
4757                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4758                         parseOidArray(PQgetvalue(res, j, i_indkey),
4759                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4760                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4761                         contype = *(PQgetvalue(res, j, i_contype));
4762
4763                         if (contype == 'p' || contype == 'u' || contype == 'x')
4764                         {
4765                                 /*
4766                                  * If we found a constraint matching the index, create an
4767                                  * entry for it.
4768                                  *
4769                                  * In a pre-7.3 database, we take this path iff the index was
4770                                  * marked indisprimary.
4771                                  */
4772                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4773                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4774                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4775                                 AssignDumpId(&constrinfo[j].dobj);
4776                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4777                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4778                                 constrinfo[j].contable = tbinfo;
4779                                 constrinfo[j].condomain = NULL;
4780                                 constrinfo[j].contype = contype;
4781                                 if (contype == 'x')
4782                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4783                                 else
4784                                         constrinfo[j].condef = NULL;
4785                                 constrinfo[j].confrelid = InvalidOid;
4786                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4787                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4788                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4789                                 constrinfo[j].conislocal = true;
4790                                 constrinfo[j].separate = true;
4791
4792                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4793
4794                                 /* If pre-7.3 DB, better make sure table comes first */
4795                                 addObjectDependency(&constrinfo[j].dobj,
4796                                                                         tbinfo->dobj.dumpId);
4797                         }
4798                         else
4799                         {
4800                                 /* Plain secondary index */
4801                                 indxinfo[j].indexconstraint = 0;
4802                         }
4803                 }
4804
4805                 PQclear(res);
4806         }
4807
4808         destroyPQExpBuffer(query);
4809 }
4810
4811 /*
4812  * getConstraints
4813  *
4814  * Get info about constraints on dumpable tables.
4815  *
4816  * Currently handles foreign keys only.
4817  * Unique and primary key constraints are handled with indexes,
4818  * while check constraints are processed in getTableAttrs().
4819  */
4820 void
4821 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4822 {
4823         int                     i,
4824                                 j;
4825         ConstraintInfo *constrinfo;
4826         PQExpBuffer query;
4827         PGresult   *res;
4828         int                     i_contableoid,
4829                                 i_conoid,
4830                                 i_conname,
4831                                 i_confrelid,
4832                                 i_condef;
4833         int                     ntups;
4834
4835         /* pg_constraint was created in 7.3, so nothing to do if older */
4836         if (fout->remoteVersion < 70300)
4837                 return;
4838
4839         query = createPQExpBuffer();
4840
4841         for (i = 0; i < numTables; i++)
4842         {
4843                 TableInfo  *tbinfo = &tblinfo[i];
4844
4845                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4846                         continue;
4847
4848                 if (g_verbose)
4849                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4850                                           tbinfo->dobj.name);
4851
4852                 /*
4853                  * select table schema to ensure constraint expr is qualified if
4854                  * needed
4855                  */
4856                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4857
4858                 resetPQExpBuffer(query);
4859                 appendPQExpBuffer(query,
4860                                                   "SELECT tableoid, oid, conname, confrelid, "
4861                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4862                                                   "FROM pg_catalog.pg_constraint "
4863                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4864                                                   "AND contype = 'f'",
4865                                                   tbinfo->dobj.catId.oid);
4866                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4867
4868                 ntups = PQntuples(res);
4869
4870                 i_contableoid = PQfnumber(res, "tableoid");
4871                 i_conoid = PQfnumber(res, "oid");
4872                 i_conname = PQfnumber(res, "conname");
4873                 i_confrelid = PQfnumber(res, "confrelid");
4874                 i_condef = PQfnumber(res, "condef");
4875
4876                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4877
4878                 for (j = 0; j < ntups; j++)
4879                 {
4880                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4881                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4882                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4883                         AssignDumpId(&constrinfo[j].dobj);
4884                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4885                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4886                         constrinfo[j].contable = tbinfo;
4887                         constrinfo[j].condomain = NULL;
4888                         constrinfo[j].contype = 'f';
4889                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4890                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4891                         constrinfo[j].conindex = 0;
4892                         constrinfo[j].condeferrable = false;
4893                         constrinfo[j].condeferred = false;
4894                         constrinfo[j].conislocal = true;
4895                         constrinfo[j].separate = true;
4896                 }
4897
4898                 PQclear(res);
4899         }
4900
4901         destroyPQExpBuffer(query);
4902 }
4903
4904 /*
4905  * getDomainConstraints
4906  *
4907  * Get info about constraints on a domain.
4908  */
4909 static void
4910 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4911 {
4912         int                     i;
4913         ConstraintInfo *constrinfo;
4914         PQExpBuffer query;
4915         PGresult   *res;
4916         int                     i_tableoid,
4917                                 i_oid,
4918                                 i_conname,
4919                                 i_consrc;
4920         int                     ntups;
4921
4922         /* pg_constraint was created in 7.3, so nothing to do if older */
4923         if (fout->remoteVersion < 70300)
4924                 return;
4925
4926         /*
4927          * select appropriate schema to ensure names in constraint are properly
4928          * qualified
4929          */
4930         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4931
4932         query = createPQExpBuffer();
4933
4934         if (fout->remoteVersion >= 90100)
4935                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4936                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4937                                                   "convalidated "
4938                                                   "FROM pg_catalog.pg_constraint "
4939                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4940                                                   "ORDER BY conname",
4941                                                   tyinfo->dobj.catId.oid);
4942
4943         else if (fout->remoteVersion >= 70400)
4944                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4945                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4946                                                   "true as convalidated "
4947                                                   "FROM pg_catalog.pg_constraint "
4948                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4949                                                   "ORDER BY conname",
4950                                                   tyinfo->dobj.catId.oid);
4951         else
4952                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4953                                                   "'CHECK (' || consrc || ')' AS consrc, "
4954                                                   "true as convalidated "
4955                                                   "FROM pg_catalog.pg_constraint "
4956                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4957                                                   "ORDER BY conname",
4958                                                   tyinfo->dobj.catId.oid);
4959
4960         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4961
4962         ntups = PQntuples(res);
4963
4964         i_tableoid = PQfnumber(res, "tableoid");
4965         i_oid = PQfnumber(res, "oid");
4966         i_conname = PQfnumber(res, "conname");
4967         i_consrc = PQfnumber(res, "consrc");
4968
4969         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4970
4971         tyinfo->nDomChecks = ntups;
4972         tyinfo->domChecks = constrinfo;
4973
4974         for (i = 0; i < ntups; i++)
4975         {
4976                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
4977
4978                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4979                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4980                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4981                 AssignDumpId(&constrinfo[i].dobj);
4982                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4983                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4984                 constrinfo[i].contable = NULL;
4985                 constrinfo[i].condomain = tyinfo;
4986                 constrinfo[i].contype = 'c';
4987                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4988                 constrinfo[i].confrelid = InvalidOid;
4989                 constrinfo[i].conindex = 0;
4990                 constrinfo[i].condeferrable = false;
4991                 constrinfo[i].condeferred = false;
4992                 constrinfo[i].conislocal = true;
4993
4994                 constrinfo[i].separate = !validated;
4995
4996                 /*
4997                  * Make the domain depend on the constraint, ensuring it won't be
4998                  * output till any constraint dependencies are OK.      If the constraint
4999                  * has not been validated, it's going to be dumped after the domain
5000                  * anyway, so this doesn't matter.
5001                  */
5002                 if (validated)
5003                         addObjectDependency(&tyinfo->dobj,
5004                                                                 constrinfo[i].dobj.dumpId);
5005         }
5006
5007         PQclear(res);
5008
5009         destroyPQExpBuffer(query);
5010 }
5011
5012 /*
5013  * getRules
5014  *        get basic information about every rule in the system
5015  *
5016  * numRules is set to the number of rules read in
5017  */
5018 RuleInfo *
5019 getRules(Archive *fout, int *numRules)
5020 {
5021         PGresult   *res;
5022         int                     ntups;
5023         int                     i;
5024         PQExpBuffer query = createPQExpBuffer();
5025         RuleInfo   *ruleinfo;
5026         int                     i_tableoid;
5027         int                     i_oid;
5028         int                     i_rulename;
5029         int                     i_ruletable;
5030         int                     i_ev_type;
5031         int                     i_is_instead;
5032         int                     i_ev_enabled;
5033
5034         /* Make sure we are in proper schema */
5035         selectSourceSchema(fout, "pg_catalog");
5036
5037         if (fout->remoteVersion >= 80300)
5038         {
5039                 appendPQExpBuffer(query, "SELECT "
5040                                                   "tableoid, oid, rulename, "
5041                                                   "ev_class AS ruletable, ev_type, is_instead, "
5042                                                   "ev_enabled "
5043                                                   "FROM pg_rewrite "
5044                                                   "ORDER BY oid");
5045         }
5046         else if (fout->remoteVersion >= 70100)
5047         {
5048                 appendPQExpBuffer(query, "SELECT "
5049                                                   "tableoid, oid, rulename, "
5050                                                   "ev_class AS ruletable, ev_type, is_instead, "
5051                                                   "'O'::char AS ev_enabled "
5052                                                   "FROM pg_rewrite "
5053                                                   "ORDER BY oid");
5054         }
5055         else
5056         {
5057                 appendPQExpBuffer(query, "SELECT "
5058                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5059                                                   "oid, rulename, "
5060                                                   "ev_class AS ruletable, ev_type, is_instead, "
5061                                                   "'O'::char AS ev_enabled "
5062                                                   "FROM pg_rewrite "
5063                                                   "ORDER BY oid");
5064         }
5065
5066         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5067
5068         ntups = PQntuples(res);
5069
5070         *numRules = ntups;
5071
5072         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5073
5074         i_tableoid = PQfnumber(res, "tableoid");
5075         i_oid = PQfnumber(res, "oid");
5076         i_rulename = PQfnumber(res, "rulename");
5077         i_ruletable = PQfnumber(res, "ruletable");
5078         i_ev_type = PQfnumber(res, "ev_type");
5079         i_is_instead = PQfnumber(res, "is_instead");
5080         i_ev_enabled = PQfnumber(res, "ev_enabled");
5081
5082         for (i = 0; i < ntups; i++)
5083         {
5084                 Oid                     ruletableoid;
5085
5086                 ruleinfo[i].dobj.objType = DO_RULE;
5087                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5088                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5089                 AssignDumpId(&ruleinfo[i].dobj);
5090                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5091                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5092                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5093                 if (ruleinfo[i].ruletable == NULL)
5094                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5095                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5096                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5097                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5098                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5099                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5100                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5101                 if (ruleinfo[i].ruletable)
5102                 {
5103                         /*
5104                          * If the table is a view, force its ON SELECT rule to be sorted
5105                          * before the view itself --- this ensures that any dependencies
5106                          * for the rule affect the table's positioning. Other rules are
5107                          * forced to appear after their table.
5108                          */
5109                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5110                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5111                         {
5112                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5113                                                                         ruleinfo[i].dobj.dumpId);
5114                                 /* We'll merge the rule into CREATE VIEW, if possible */
5115                                 ruleinfo[i].separate = false;
5116                         }
5117                         else
5118                         {
5119                                 addObjectDependency(&ruleinfo[i].dobj,
5120                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5121                                 ruleinfo[i].separate = true;
5122                         }
5123                 }
5124                 else
5125                         ruleinfo[i].separate = true;
5126
5127                 /*
5128                  * If we're forced to break a dependency loop by dumping a view as a
5129                  * table and separate _RETURN rule, we'll move the view's reloptions
5130                  * to the rule.  (This is necessary because tables and views have
5131                  * different valid reloptions, so we can't apply the options until the
5132                  * backend knows it's a view.)  Otherwise the rule's reloptions stay
5133                  * NULL.
5134                  */
5135                 ruleinfo[i].reloptions = NULL;
5136         }
5137
5138         PQclear(res);
5139
5140         destroyPQExpBuffer(query);
5141
5142         return ruleinfo;
5143 }
5144
5145 /*
5146  * getTriggers
5147  *        get information about every trigger on a dumpable table
5148  *
5149  * Note: trigger data is not returned directly to the caller, but it
5150  * does get entered into the DumpableObject tables.
5151  */
5152 void
5153 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5154 {
5155         int                     i,
5156                                 j;
5157         PQExpBuffer query = createPQExpBuffer();
5158         PGresult   *res;
5159         TriggerInfo *tginfo;
5160         int                     i_tableoid,
5161                                 i_oid,
5162                                 i_tgname,
5163                                 i_tgfname,
5164                                 i_tgtype,
5165                                 i_tgnargs,
5166                                 i_tgargs,
5167                                 i_tgisconstraint,
5168                                 i_tgconstrname,
5169                                 i_tgconstrrelid,
5170                                 i_tgconstrrelname,
5171                                 i_tgenabled,
5172                                 i_tgdeferrable,
5173                                 i_tginitdeferred,
5174                                 i_tgdef;
5175         int                     ntups;
5176
5177         for (i = 0; i < numTables; i++)
5178         {
5179                 TableInfo  *tbinfo = &tblinfo[i];
5180
5181                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5182                         continue;
5183
5184                 if (g_verbose)
5185                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5186                                           tbinfo->dobj.name);
5187
5188                 /*
5189                  * select table schema to ensure regproc name is qualified if needed
5190                  */
5191                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5192
5193                 resetPQExpBuffer(query);
5194                 if (fout->remoteVersion >= 90000)
5195                 {
5196                         /*
5197                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5198                          * could result in non-forward-compatible dumps of WHEN clauses
5199                          * due to under-parenthesization.
5200                          */
5201                         appendPQExpBuffer(query,
5202                                                           "SELECT tgname, "
5203                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5204                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5205                                                           "tgenabled, tableoid, oid "
5206                                                           "FROM pg_catalog.pg_trigger t "
5207                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5208                                                           "AND NOT tgisinternal",
5209                                                           tbinfo->dobj.catId.oid);
5210                 }
5211                 else if (fout->remoteVersion >= 80300)
5212                 {
5213                         /*
5214                          * We ignore triggers that are tied to a foreign-key constraint
5215                          */
5216                         appendPQExpBuffer(query,
5217                                                           "SELECT tgname, "
5218                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5219                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5220                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5221                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5222                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5223                                                           "FROM pg_catalog.pg_trigger t "
5224                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5225                                                           "AND tgconstraint = 0",
5226                                                           tbinfo->dobj.catId.oid);
5227                 }
5228                 else if (fout->remoteVersion >= 70300)
5229                 {
5230                         /*
5231                          * We ignore triggers that are tied to a foreign-key constraint,
5232                          * but in these versions we have to grovel through pg_constraint
5233                          * to find out
5234                          */
5235                         appendPQExpBuffer(query,
5236                                                           "SELECT tgname, "
5237                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5238                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5239                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5240                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5241                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5242                                                           "FROM pg_catalog.pg_trigger t "
5243                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5244                                                           "AND (NOT tgisconstraint "
5245                                                           " OR NOT EXISTS"
5246                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5247                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5248                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5249                                                           tbinfo->dobj.catId.oid);
5250                 }
5251                 else if (fout->remoteVersion >= 70100)
5252                 {
5253                         appendPQExpBuffer(query,
5254                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5255                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5256                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5257                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5258                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5259                                                           "             AS tgconstrrelname "
5260                                                           "FROM pg_trigger "
5261                                                           "WHERE tgrelid = '%u'::oid",
5262                                                           tbinfo->dobj.catId.oid);
5263                 }
5264                 else
5265                 {
5266                         appendPQExpBuffer(query,
5267                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5268                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5269                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5270                                                           "tgconstrrelid, tginitdeferred, "
5271                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5272                                                           "oid, "
5273                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5274                                                           "             AS tgconstrrelname "
5275                                                           "FROM pg_trigger "
5276                                                           "WHERE tgrelid = '%u'::oid",
5277                                                           tbinfo->dobj.catId.oid);
5278                 }
5279                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5280
5281                 ntups = PQntuples(res);
5282
5283                 i_tableoid = PQfnumber(res, "tableoid");
5284                 i_oid = PQfnumber(res, "oid");
5285                 i_tgname = PQfnumber(res, "tgname");
5286                 i_tgfname = PQfnumber(res, "tgfname");
5287                 i_tgtype = PQfnumber(res, "tgtype");
5288                 i_tgnargs = PQfnumber(res, "tgnargs");
5289                 i_tgargs = PQfnumber(res, "tgargs");
5290                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5291                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5292                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5293                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5294                 i_tgenabled = PQfnumber(res, "tgenabled");
5295                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5296                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5297                 i_tgdef = PQfnumber(res, "tgdef");
5298
5299                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5300
5301                 for (j = 0; j < ntups; j++)
5302                 {
5303                         tginfo[j].dobj.objType = DO_TRIGGER;
5304                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5305                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5306                         AssignDumpId(&tginfo[j].dobj);
5307                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5308                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5309                         tginfo[j].tgtable = tbinfo;
5310                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5311                         if (i_tgdef >= 0)
5312                         {
5313                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5314
5315                                 /* remaining fields are not valid if we have tgdef */
5316                                 tginfo[j].tgfname = NULL;
5317                                 tginfo[j].tgtype = 0;
5318                                 tginfo[j].tgnargs = 0;
5319                                 tginfo[j].tgargs = NULL;
5320                                 tginfo[j].tgisconstraint = false;
5321                                 tginfo[j].tgdeferrable = false;
5322                                 tginfo[j].tginitdeferred = false;
5323                                 tginfo[j].tgconstrname = NULL;
5324                                 tginfo[j].tgconstrrelid = InvalidOid;
5325                                 tginfo[j].tgconstrrelname = NULL;
5326                         }
5327                         else
5328                         {
5329                                 tginfo[j].tgdef = NULL;
5330
5331                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5332                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5333                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5334                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5335                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5336                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5337                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5338
5339                                 if (tginfo[j].tgisconstraint)
5340                                 {
5341                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5342                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5343                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5344                                         {
5345                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5346                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5347                                                                                   tginfo[j].dobj.name,
5348                                                                                   tbinfo->dobj.name,
5349                                                                                   tginfo[j].tgconstrrelid);
5350                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5351                                         }
5352                                         else
5353                                                 tginfo[j].tgconstrrelname = NULL;
5354                                 }
5355                                 else
5356                                 {
5357                                         tginfo[j].tgconstrname = NULL;
5358                                         tginfo[j].tgconstrrelid = InvalidOid;
5359                                         tginfo[j].tgconstrrelname = NULL;
5360                                 }
5361                         }
5362                 }
5363
5364                 PQclear(res);
5365         }
5366
5367         destroyPQExpBuffer(query);
5368 }
5369
5370 /*
5371  * getEventTriggers
5372  *        get information about event triggers
5373  */
5374 EventTriggerInfo *
5375 getEventTriggers(Archive *fout, int *numEventTriggers)
5376 {
5377         int                     i;
5378         PQExpBuffer query = createPQExpBuffer();
5379         PGresult   *res;
5380         EventTriggerInfo *evtinfo;
5381         int                     i_tableoid,
5382                                 i_oid,
5383                                 i_evtname,
5384                                 i_evtevent,
5385                                 i_evtowner,
5386                                 i_evttags,
5387                                 i_evtfname,
5388                                 i_evtenabled;
5389         int                     ntups;
5390
5391         /* Before 9.3, there are no event triggers */
5392         if (fout->remoteVersion < 90300)
5393         {
5394                 *numEventTriggers = 0;
5395                 return NULL;
5396         }
5397
5398         /* Make sure we are in proper schema */
5399         selectSourceSchema(fout, "pg_catalog");
5400
5401         appendPQExpBuffer(query,
5402                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5403                                           "evtevent, (%s evtowner) AS evtowner, "
5404                                           "array_to_string(array("
5405                                           "select quote_literal(x) "
5406                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
5407                                           "e.evtfoid::regproc as evtfname "
5408                                           "FROM pg_event_trigger e "
5409                                           "ORDER BY e.oid",
5410                                           username_subquery);
5411
5412         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5413
5414         ntups = PQntuples(res);
5415
5416         *numEventTriggers = ntups;
5417
5418         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5419
5420         i_tableoid = PQfnumber(res, "tableoid");
5421         i_oid = PQfnumber(res, "oid");
5422         i_evtname = PQfnumber(res, "evtname");
5423         i_evtevent = PQfnumber(res, "evtevent");
5424         i_evtowner = PQfnumber(res, "evtowner");
5425         i_evttags = PQfnumber(res, "evttags");
5426         i_evtfname = PQfnumber(res, "evtfname");
5427         i_evtenabled = PQfnumber(res, "evtenabled");
5428
5429         for (i = 0; i < ntups; i++)
5430         {
5431                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5432                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5433                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5434                 AssignDumpId(&evtinfo[i].dobj);
5435                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5436                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5437                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5438                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5439                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5440                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5441                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5442         }
5443
5444         PQclear(res);
5445
5446         destroyPQExpBuffer(query);
5447
5448         return evtinfo;
5449 }
5450
5451 /*
5452  * getProcLangs
5453  *        get basic information about every procedural language in the system
5454  *
5455  * numProcLangs is set to the number of langs read in
5456  *
5457  * NB: this must run after getFuncs() because we assume we can do
5458  * findFuncByOid().
5459  */
5460 ProcLangInfo *
5461 getProcLangs(Archive *fout, int *numProcLangs)
5462 {
5463         PGresult   *res;
5464         int                     ntups;
5465         int                     i;
5466         PQExpBuffer query = createPQExpBuffer();
5467         ProcLangInfo *planginfo;
5468         int                     i_tableoid;
5469         int                     i_oid;
5470         int                     i_lanname;
5471         int                     i_lanpltrusted;
5472         int                     i_lanplcallfoid;
5473         int                     i_laninline;
5474         int                     i_lanvalidator;
5475         int                     i_lanacl;
5476         int                     i_lanowner;
5477
5478         /* Make sure we are in proper schema */
5479         selectSourceSchema(fout, "pg_catalog");
5480
5481         if (fout->remoteVersion >= 90000)
5482         {
5483                 /* pg_language has a laninline column */
5484                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5485                                                   "lanname, lanpltrusted, lanplcallfoid, "
5486                                                   "laninline, lanvalidator,  lanacl, "
5487                                                   "(%s lanowner) AS lanowner "
5488                                                   "FROM pg_language "
5489                                                   "WHERE lanispl "
5490                                                   "ORDER BY oid",
5491                                                   username_subquery);
5492         }
5493         else if (fout->remoteVersion >= 80300)
5494         {
5495                 /* pg_language has a lanowner column */
5496                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5497                                                   "lanname, lanpltrusted, lanplcallfoid, "
5498                                                   "lanvalidator,  lanacl, "
5499                                                   "(%s lanowner) AS lanowner "
5500                                                   "FROM pg_language "
5501                                                   "WHERE lanispl "
5502                                                   "ORDER BY oid",
5503                                                   username_subquery);
5504         }
5505         else if (fout->remoteVersion >= 80100)
5506         {
5507                 /* Languages are owned by the bootstrap superuser, OID 10 */
5508                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5509                                                   "(%s '10') AS lanowner "
5510                                                   "FROM pg_language "
5511                                                   "WHERE lanispl "
5512                                                   "ORDER BY oid",
5513                                                   username_subquery);
5514         }
5515         else if (fout->remoteVersion >= 70400)
5516         {
5517                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5518                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5519                                                   "(%s '1') AS lanowner "
5520                                                   "FROM pg_language "
5521                                                   "WHERE lanispl "
5522                                                   "ORDER BY oid",
5523                                                   username_subquery);
5524         }
5525         else if (fout->remoteVersion >= 70100)
5526         {
5527                 /* No clear notion of an owner at all before 7.4 ... */
5528                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5529                                                   "WHERE lanispl "
5530                                                   "ORDER BY oid");
5531         }
5532         else
5533         {
5534                 appendPQExpBuffer(query, "SELECT "
5535                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5536                                                   "oid, * FROM pg_language "
5537                                                   "WHERE lanispl "
5538                                                   "ORDER BY oid");
5539         }
5540
5541         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5542
5543         ntups = PQntuples(res);
5544
5545         *numProcLangs = ntups;
5546
5547         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5548
5549         i_tableoid = PQfnumber(res, "tableoid");
5550         i_oid = PQfnumber(res, "oid");
5551         i_lanname = PQfnumber(res, "lanname");
5552         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5553         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5554         /* these may fail and return -1: */
5555         i_laninline = PQfnumber(res, "laninline");
5556         i_lanvalidator = PQfnumber(res, "lanvalidator");
5557         i_lanacl = PQfnumber(res, "lanacl");
5558         i_lanowner = PQfnumber(res, "lanowner");
5559
5560         for (i = 0; i < ntups; i++)
5561         {
5562                 planginfo[i].dobj.objType = DO_PROCLANG;
5563                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5564                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5565                 AssignDumpId(&planginfo[i].dobj);
5566
5567                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5568                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5569                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5570                 if (i_laninline >= 0)
5571                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5572                 else
5573                         planginfo[i].laninline = InvalidOid;
5574                 if (i_lanvalidator >= 0)
5575                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5576                 else
5577                         planginfo[i].lanvalidator = InvalidOid;
5578                 if (i_lanacl >= 0)
5579                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5580                 else
5581                         planginfo[i].lanacl = pg_strdup("{=U}");
5582                 if (i_lanowner >= 0)
5583                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5584                 else
5585                         planginfo[i].lanowner = pg_strdup("");
5586
5587                 if (fout->remoteVersion < 70300)
5588                 {
5589                         /*
5590                          * We need to make a dependency to ensure the function will be
5591                          * dumped first.  (In 7.3 and later the regular dependency
5592                          * mechanism will handle this for us.)
5593                          */
5594                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5595
5596                         if (funcInfo)
5597                                 addObjectDependency(&planginfo[i].dobj,
5598                                                                         funcInfo->dobj.dumpId);
5599                 }
5600         }
5601
5602         PQclear(res);
5603
5604         destroyPQExpBuffer(query);
5605
5606         return planginfo;
5607 }
5608
5609 /*
5610  * getCasts
5611  *        get basic information about every cast in the system
5612  *
5613  * numCasts is set to the number of casts read in
5614  */
5615 CastInfo *
5616 getCasts(Archive *fout, int *numCasts)
5617 {
5618         PGresult   *res;
5619         int                     ntups;
5620         int                     i;
5621         PQExpBuffer query = createPQExpBuffer();
5622         CastInfo   *castinfo;
5623         int                     i_tableoid;
5624         int                     i_oid;
5625         int                     i_castsource;
5626         int                     i_casttarget;
5627         int                     i_castfunc;
5628         int                     i_castcontext;
5629         int                     i_castmethod;
5630
5631         /* Make sure we are in proper schema */
5632         selectSourceSchema(fout, "pg_catalog");
5633
5634         if (fout->remoteVersion >= 80400)
5635         {
5636                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5637                                                   "castsource, casttarget, castfunc, castcontext, "
5638                                                   "castmethod "
5639                                                   "FROM pg_cast ORDER BY 3,4");
5640         }
5641         else if (fout->remoteVersion >= 70300)
5642         {
5643                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5644                                                   "castsource, casttarget, castfunc, castcontext, "
5645                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5646                                                   "FROM pg_cast ORDER BY 3,4");
5647         }
5648         else
5649         {
5650                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5651                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5652                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5653                                                   "'f' AS castmethod "
5654                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5655                                                   "WHERE p.pronargs = 1 AND "
5656                                                   "p.proargtypes[0] = t1.oid AND "
5657                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5658                                                   "ORDER BY 3,4");
5659         }
5660
5661         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5662
5663         ntups = PQntuples(res);
5664
5665         *numCasts = ntups;
5666
5667         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5668
5669         i_tableoid = PQfnumber(res, "tableoid");
5670         i_oid = PQfnumber(res, "oid");
5671         i_castsource = PQfnumber(res, "castsource");
5672         i_casttarget = PQfnumber(res, "casttarget");
5673         i_castfunc = PQfnumber(res, "castfunc");
5674         i_castcontext = PQfnumber(res, "castcontext");
5675         i_castmethod = PQfnumber(res, "castmethod");
5676
5677         for (i = 0; i < ntups; i++)
5678         {
5679                 PQExpBufferData namebuf;
5680                 TypeInfo   *sTypeInfo;
5681                 TypeInfo   *tTypeInfo;
5682
5683                 castinfo[i].dobj.objType = DO_CAST;
5684                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5685                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5686                 AssignDumpId(&castinfo[i].dobj);
5687                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5688                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5689                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5690                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5691                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5692
5693                 /*
5694                  * Try to name cast as concatenation of typnames.  This is only used
5695                  * for purposes of sorting.  If we fail to find either type, the name
5696                  * will be an empty string.
5697                  */
5698                 initPQExpBuffer(&namebuf);
5699                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5700                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5701                 if (sTypeInfo && tTypeInfo)
5702                         appendPQExpBuffer(&namebuf, "%s %s",
5703                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5704                 castinfo[i].dobj.name = namebuf.data;
5705
5706                 if (OidIsValid(castinfo[i].castfunc))
5707                 {
5708                         /*
5709                          * We need to make a dependency to ensure the function will be
5710                          * dumped first.  (In 7.3 and later the regular dependency
5711                          * mechanism will handle this for us.)
5712                          */
5713                         FuncInfo   *funcInfo;
5714
5715                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5716                         if (funcInfo)
5717                                 addObjectDependency(&castinfo[i].dobj,
5718                                                                         funcInfo->dobj.dumpId);
5719                 }
5720         }
5721
5722         PQclear(res);
5723
5724         destroyPQExpBuffer(query);
5725
5726         return castinfo;
5727 }
5728
5729 /*
5730  * getTableAttrs -
5731  *        for each interesting table, read info about its attributes
5732  *        (names, types, default values, CHECK constraints, etc)
5733  *
5734  * This is implemented in a very inefficient way right now, looping
5735  * through the tblinfo and doing a join per table to find the attrs and their
5736  * types.  However, because we want type names and so forth to be named
5737  * relative to the schema of each table, we couldn't do it in just one
5738  * query.  (Maybe one query per schema?)
5739  *
5740  *      modifies tblinfo
5741  */
5742 void
5743 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5744 {
5745         int                     i,
5746                                 j;
5747         PQExpBuffer q = createPQExpBuffer();
5748         int                     i_attnum;
5749         int                     i_attname;
5750         int                     i_atttypname;
5751         int                     i_atttypmod;
5752         int                     i_attstattarget;
5753         int                     i_attstorage;
5754         int                     i_typstorage;
5755         int                     i_attnotnull;
5756         int                     i_atthasdef;
5757         int                     i_attisdropped;
5758         int                     i_attlen;
5759         int                     i_attalign;
5760         int                     i_attislocal;
5761         int                     i_attoptions;
5762         int                     i_attcollation;
5763         int                     i_attfdwoptions;
5764         PGresult   *res;
5765         int                     ntups;
5766         bool            hasdefaults;
5767
5768         for (i = 0; i < numTables; i++)
5769         {
5770                 TableInfo  *tbinfo = &tblinfo[i];
5771
5772                 /* Don't bother to collect info for sequences */
5773                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5774                         continue;
5775
5776                 /* Don't bother with uninteresting tables, either */
5777                 if (!tbinfo->interesting)
5778                         continue;
5779
5780                 /*
5781                  * Make sure we are in proper schema for this table; this allows
5782                  * correct retrieval of formatted type names and default exprs
5783                  */
5784                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5785
5786                 /* find all the user attributes and their types */
5787
5788                 /*
5789                  * we must read the attribute names in attribute number order! because
5790                  * we will use the attnum to index into the attnames array later.  We
5791                  * actually ask to order by "attrelid, attnum" because (at least up to
5792                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5793                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5794                  */
5795                 if (g_verbose)
5796                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5797                                           tbinfo->dobj.name);
5798
5799                 resetPQExpBuffer(q);
5800
5801                 if (fout->remoteVersion >= 90200)
5802                 {
5803                         /*
5804                          * attfdwoptions is new in 9.2.
5805                          */
5806                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5807                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5808                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5809                                                           "a.attlen, a.attalign, a.attislocal, "
5810                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5811                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5812                                                           "CASE WHEN a.attcollation <> t.typcollation "
5813                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5814                                                           "pg_catalog.array_to_string(ARRAY("
5815                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5816                                                           "' ' || pg_catalog.quote_literal(option_value) "
5817                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5818                                                           "ORDER BY option_name"
5819                                                           "), E',\n    ') AS attfdwoptions "
5820                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5821                                                           "ON a.atttypid = t.oid "
5822                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5823                                                           "AND a.attnum > 0::pg_catalog.int2 "
5824                                                           "ORDER BY a.attrelid, a.attnum",
5825                                                           tbinfo->dobj.catId.oid);
5826                 }
5827                 else if (fout->remoteVersion >= 90100)
5828                 {
5829                         /*
5830                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5831                          * clauses for attributes whose collation is different from their
5832                          * type's default, we use a CASE here to suppress uninteresting
5833                          * attcollations cheaply.
5834                          */
5835                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5836                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5837                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5838                                                           "a.attlen, a.attalign, a.attislocal, "
5839                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5840                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5841                                                           "CASE WHEN a.attcollation <> t.typcollation "
5842                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5843                                                           "NULL AS attfdwoptions "
5844                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5845                                                           "ON a.atttypid = t.oid "
5846                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5847                                                           "AND a.attnum > 0::pg_catalog.int2 "
5848                                                           "ORDER BY a.attrelid, a.attnum",
5849                                                           tbinfo->dobj.catId.oid);
5850                 }
5851                 else if (fout->remoteVersion >= 90000)
5852                 {
5853                         /* attoptions is new in 9.0 */
5854                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5855                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5856                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5857                                                           "a.attlen, a.attalign, a.attislocal, "
5858                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5859                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5860                                                           "0 AS attcollation, "
5861                                                           "NULL AS attfdwoptions "
5862                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5863                                                           "ON a.atttypid = t.oid "
5864                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5865                                                           "AND a.attnum > 0::pg_catalog.int2 "
5866                                                           "ORDER BY a.attrelid, a.attnum",
5867                                                           tbinfo->dobj.catId.oid);
5868                 }
5869                 else if (fout->remoteVersion >= 70300)
5870                 {
5871                         /* need left join here to not fail on dropped columns ... */
5872                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5873                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5874                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5875                                                           "a.attlen, a.attalign, a.attislocal, "
5876                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5877                                                           "'' AS attoptions, 0 AS attcollation, "
5878                                                           "NULL AS attfdwoptions "
5879                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5880                                                           "ON a.atttypid = t.oid "
5881                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5882                                                           "AND a.attnum > 0::pg_catalog.int2 "
5883                                                           "ORDER BY a.attrelid, a.attnum",
5884                                                           tbinfo->dobj.catId.oid);
5885                 }
5886                 else if (fout->remoteVersion >= 70100)
5887                 {
5888                         /*
5889                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5890                          * we don't dump it because we can't tell whether it's been
5891                          * explicitly set or was just a default.
5892                          *
5893                          * attislocal doesn't exist before 7.3, either; in older databases
5894                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5895                          */
5896                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5897                                                           "-1 AS attstattarget, a.attstorage, "
5898                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5899                                                           "false AS attisdropped, a.attlen, "
5900                                                           "a.attalign, true AS attislocal, "
5901                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5902                                                           "'' AS attoptions, 0 AS attcollation, "
5903                                                           "NULL AS attfdwoptions "
5904                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5905                                                           "ON a.atttypid = t.oid "
5906                                                           "WHERE a.attrelid = '%u'::oid "
5907                                                           "AND a.attnum > 0::int2 "
5908                                                           "ORDER BY a.attrelid, a.attnum",
5909                                                           tbinfo->dobj.catId.oid);
5910                 }
5911                 else
5912                 {
5913                         /* format_type not available before 7.1 */
5914                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5915                                                           "-1 AS attstattarget, "
5916                                                           "attstorage, attstorage AS typstorage, "
5917                                                           "attnotnull, atthasdef, false AS attisdropped, "
5918                                                           "attlen, attalign, "
5919                                                           "true AS attislocal, "
5920                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5921                                                           "'' AS attoptions, 0 AS attcollation, "
5922                                                           "NULL AS attfdwoptions "
5923                                                           "FROM pg_attribute a "
5924                                                           "WHERE attrelid = '%u'::oid "
5925                                                           "AND attnum > 0::int2 "
5926                                                           "ORDER BY attrelid, attnum",
5927                                                           tbinfo->dobj.catId.oid);
5928                 }
5929
5930                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5931
5932                 ntups = PQntuples(res);
5933
5934                 i_attnum = PQfnumber(res, "attnum");
5935                 i_attname = PQfnumber(res, "attname");
5936                 i_atttypname = PQfnumber(res, "atttypname");
5937                 i_atttypmod = PQfnumber(res, "atttypmod");
5938                 i_attstattarget = PQfnumber(res, "attstattarget");
5939                 i_attstorage = PQfnumber(res, "attstorage");
5940                 i_typstorage = PQfnumber(res, "typstorage");
5941                 i_attnotnull = PQfnumber(res, "attnotnull");
5942                 i_atthasdef = PQfnumber(res, "atthasdef");
5943                 i_attisdropped = PQfnumber(res, "attisdropped");
5944                 i_attlen = PQfnumber(res, "attlen");
5945                 i_attalign = PQfnumber(res, "attalign");
5946                 i_attislocal = PQfnumber(res, "attislocal");
5947                 i_attoptions = PQfnumber(res, "attoptions");
5948                 i_attcollation = PQfnumber(res, "attcollation");
5949                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5950
5951                 tbinfo->numatts = ntups;
5952                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5953                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5954                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5955                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5956                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5957                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5958                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5959                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5960                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5961                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5962                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5963                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5964                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5965                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5966                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5967                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5968                 hasdefaults = false;
5969
5970                 for (j = 0; j < ntups; j++)
5971                 {
5972                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5973                                 exit_horribly(NULL,
5974                                                           "invalid column numbering in table \"%s\"\n",
5975                                                           tbinfo->dobj.name);
5976                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5977                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5978                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5979                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5980                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5981                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5982                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5983                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5984                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5985                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5986                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5987                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5988                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5989                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5990                         tbinfo->attrdefs[j] = NULL; /* fix below */
5991                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5992                                 hasdefaults = true;
5993                         /* these flags will be set in flagInhAttrs() */
5994                         tbinfo->inhNotNull[j] = false;
5995                 }
5996
5997                 PQclear(res);
5998
5999                 /*
6000                  * Get info about column defaults
6001                  */
6002                 if (hasdefaults)
6003                 {
6004                         AttrDefInfo *attrdefs;
6005                         int                     numDefaults;
6006
6007                         if (g_verbose)
6008                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6009                                                   tbinfo->dobj.name);
6010
6011                         resetPQExpBuffer(q);
6012                         if (fout->remoteVersion >= 70300)
6013                         {
6014                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6015                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6016                                                                   "FROM pg_catalog.pg_attrdef "
6017                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
6018                                                                   tbinfo->dobj.catId.oid);
6019                         }
6020                         else if (fout->remoteVersion >= 70200)
6021                         {
6022                                 /* 7.2 did not have OIDs in pg_attrdef */
6023                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6024                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
6025                                                                   "FROM pg_attrdef "
6026                                                                   "WHERE adrelid = '%u'::oid",
6027                                                                   tbinfo->dobj.catId.oid);
6028                         }
6029                         else if (fout->remoteVersion >= 70100)
6030                         {
6031                                 /* no pg_get_expr, so must rely on adsrc */
6032                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6033                                                                   "FROM pg_attrdef "
6034                                                                   "WHERE adrelid = '%u'::oid",
6035                                                                   tbinfo->dobj.catId.oid);
6036                         }
6037                         else
6038                         {
6039                                 /* no pg_get_expr, no tableoid either */
6040                                 appendPQExpBuffer(q, "SELECT "
6041                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6042                                                                   "oid, adnum, adsrc "
6043                                                                   "FROM pg_attrdef "
6044                                                                   "WHERE adrelid = '%u'::oid",
6045                                                                   tbinfo->dobj.catId.oid);
6046                         }
6047                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6048
6049                         numDefaults = PQntuples(res);
6050                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6051
6052                         for (j = 0; j < numDefaults; j++)
6053                         {
6054                                 int                     adnum;
6055
6056                                 adnum = atoi(PQgetvalue(res, j, 2));
6057
6058                                 if (adnum <= 0 || adnum > ntups)
6059                                         exit_horribly(NULL,
6060                                                                   "invalid adnum value %d for table \"%s\"\n",
6061                                                                   adnum, tbinfo->dobj.name);
6062
6063                                 /*
6064                                  * dropped columns shouldn't have defaults, but just in case,
6065                                  * ignore 'em
6066                                  */
6067                                 if (tbinfo->attisdropped[adnum - 1])
6068                                         continue;
6069
6070                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
6071                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6072                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6073                                 AssignDumpId(&attrdefs[j].dobj);
6074                                 attrdefs[j].adtable = tbinfo;
6075                                 attrdefs[j].adnum = adnum;
6076                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6077
6078                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6079                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6080
6081                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6082
6083                                 /*
6084                                  * Defaults on a VIEW must always be dumped as separate ALTER
6085                                  * TABLE commands.      Defaults on regular tables are dumped as
6086                                  * part of the CREATE TABLE if possible, which it won't be if
6087                                  * the column is not going to be emitted explicitly.
6088                                  */
6089                                 if (tbinfo->relkind == RELKIND_VIEW)
6090                                 {
6091                                         attrdefs[j].separate = true;
6092                                         /* needed in case pre-7.3 DB: */
6093                                         addObjectDependency(&attrdefs[j].dobj,
6094                                                                                 tbinfo->dobj.dumpId);
6095                                 }
6096                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6097                                 {
6098                                         /* column will be suppressed, print default separately */
6099                                         attrdefs[j].separate = true;
6100                                         /* needed in case pre-7.3 DB: */
6101                                         addObjectDependency(&attrdefs[j].dobj,
6102                                                                                 tbinfo->dobj.dumpId);
6103                                 }
6104                                 else
6105                                 {
6106                                         attrdefs[j].separate = false;
6107
6108                                         /*
6109                                          * Mark the default as needing to appear before the table,
6110                                          * so that any dependencies it has must be emitted before
6111                                          * the CREATE TABLE.  If this is not possible, we'll
6112                                          * change to "separate" mode while sorting dependencies.
6113                                          */
6114                                         addObjectDependency(&tbinfo->dobj,
6115                                                                                 attrdefs[j].dobj.dumpId);
6116                                 }
6117
6118                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6119                         }
6120                         PQclear(res);
6121                 }
6122
6123                 /*
6124                  * Get info about table CHECK constraints
6125                  */
6126                 if (tbinfo->ncheck > 0)
6127                 {
6128                         ConstraintInfo *constrs;
6129                         int                     numConstrs;
6130
6131                         if (g_verbose)
6132                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6133                                                   tbinfo->dobj.name);
6134
6135                         resetPQExpBuffer(q);
6136                         if (fout->remoteVersion >= 90200)
6137                         {
6138                                 /*
6139                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
6140                                  * but it wasn't ever false for check constraints until 9.2).
6141                                  */
6142                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6143                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6144                                                                   "conislocal, convalidated "
6145                                                                   "FROM pg_catalog.pg_constraint "
6146                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6147                                                                   "   AND contype = 'c' "
6148                                                                   "ORDER BY conname",
6149                                                                   tbinfo->dobj.catId.oid);
6150                         }
6151                         else if (fout->remoteVersion >= 80400)
6152                         {
6153                                 /* conislocal is new in 8.4 */
6154                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6155                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6156                                                                   "conislocal, true AS convalidated "
6157                                                                   "FROM pg_catalog.pg_constraint "
6158                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6159                                                                   "   AND contype = 'c' "
6160                                                                   "ORDER BY conname",
6161                                                                   tbinfo->dobj.catId.oid);
6162                         }
6163                         else if (fout->remoteVersion >= 70400)
6164                         {
6165                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6166                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6167                                                                   "true AS conislocal, true AS convalidated "
6168                                                                   "FROM pg_catalog.pg_constraint "
6169                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6170                                                                   "   AND contype = 'c' "
6171                                                                   "ORDER BY conname",
6172                                                                   tbinfo->dobj.catId.oid);
6173                         }
6174                         else if (fout->remoteVersion >= 70300)
6175                         {
6176                                 /* no pg_get_constraintdef, must use consrc */
6177                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6178                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6179                                                                   "true AS conislocal, true AS convalidated "
6180                                                                   "FROM pg_catalog.pg_constraint "
6181                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6182                                                                   "   AND contype = 'c' "
6183                                                                   "ORDER BY conname",
6184                                                                   tbinfo->dobj.catId.oid);
6185                         }
6186                         else if (fout->remoteVersion >= 70200)
6187                         {
6188                                 /* 7.2 did not have OIDs in pg_relcheck */
6189                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6190                                                                   "rcname AS conname, "
6191                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6192                                                                   "true AS conislocal, true AS convalidated "
6193                                                                   "FROM pg_relcheck "
6194                                                                   "WHERE rcrelid = '%u'::oid "
6195                                                                   "ORDER BY rcname",
6196                                                                   tbinfo->dobj.catId.oid);
6197                         }
6198                         else if (fout->remoteVersion >= 70100)
6199                         {
6200                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6201                                                                   "rcname AS conname, "
6202                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6203                                                                   "true AS conislocal, true AS convalidated "
6204                                                                   "FROM pg_relcheck "
6205                                                                   "WHERE rcrelid = '%u'::oid "
6206                                                                   "ORDER BY rcname",
6207                                                                   tbinfo->dobj.catId.oid);
6208                         }
6209                         else
6210                         {
6211                                 /* no tableoid in 7.0 */
6212                                 appendPQExpBuffer(q, "SELECT "
6213                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6214                                                                   "oid, rcname AS conname, "
6215                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6216                                                                   "true AS conislocal, true AS convalidated "
6217                                                                   "FROM pg_relcheck "
6218                                                                   "WHERE rcrelid = '%u'::oid "
6219                                                                   "ORDER BY rcname",
6220                                                                   tbinfo->dobj.catId.oid);
6221                         }
6222                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6223
6224                         numConstrs = PQntuples(res);
6225                         if (numConstrs != tbinfo->ncheck)
6226                         {
6227                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6228                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6229                                                                                  tbinfo->ncheck),
6230                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6231                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6232                                 exit_nicely(1);
6233                         }
6234
6235                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6236                         tbinfo->checkexprs = constrs;
6237
6238                         for (j = 0; j < numConstrs; j++)
6239                         {
6240                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6241
6242                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6243                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6244                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6245                                 AssignDumpId(&constrs[j].dobj);
6246                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6247                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6248                                 constrs[j].contable = tbinfo;
6249                                 constrs[j].condomain = NULL;
6250                                 constrs[j].contype = 'c';
6251                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6252                                 constrs[j].confrelid = InvalidOid;
6253                                 constrs[j].conindex = 0;
6254                                 constrs[j].condeferrable = false;
6255                                 constrs[j].condeferred = false;
6256                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6257
6258                                 /*
6259                                  * An unvalidated constraint needs to be dumped separately, so
6260                                  * that potentially-violating existing data is loaded before
6261                                  * the constraint.
6262                                  */
6263                                 constrs[j].separate = !validated;
6264
6265                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6266
6267                                 /*
6268                                  * Mark the constraint as needing to appear before the table
6269                                  * --- this is so that any other dependencies of the
6270                                  * constraint will be emitted before we try to create the
6271                                  * table.  If the constraint is to be dumped separately, it
6272                                  * will be dumped after data is loaded anyway, so don't do it.
6273                                  * (There's an automatic dependency in the opposite direction
6274                                  * anyway, so don't need to add one manually here.)
6275                                  */
6276                                 if (!constrs[j].separate)
6277                                         addObjectDependency(&tbinfo->dobj,
6278                                                                                 constrs[j].dobj.dumpId);
6279
6280                                 /*
6281                                  * If the constraint is inherited, this will be detected later
6282                                  * (in pre-8.4 databases).      We also detect later if the
6283                                  * constraint must be split out from the table definition.
6284                                  */
6285                         }
6286                         PQclear(res);
6287                 }
6288         }
6289
6290         destroyPQExpBuffer(q);
6291 }
6292
6293 /*
6294  * Test whether a column should be printed as part of table's CREATE TABLE.
6295  * Column number is zero-based.
6296  *
6297  * Normally this is always true, but it's false for dropped columns, as well
6298  * as those that were inherited without any local definition.  (If we print
6299  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6300  * However, in binary_upgrade mode, we must print all such columns anyway and
6301  * fix the attislocal/attisdropped state later, so as to keep control of the
6302  * physical column order.
6303  *
6304  * This function exists because there are scattered nonobvious places that
6305  * must be kept in sync with this decision.
6306  */
6307 bool
6308 shouldPrintColumn(TableInfo *tbinfo, int colno)
6309 {
6310         if (binary_upgrade)
6311                 return true;
6312         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6313 }
6314
6315
6316 /*
6317  * getTSParsers:
6318  *        read all text search parsers in the system catalogs and return them
6319  *        in the TSParserInfo* structure
6320  *
6321  *      numTSParsers is set to the number of parsers read in
6322  */
6323 TSParserInfo *
6324 getTSParsers(Archive *fout, int *numTSParsers)
6325 {
6326         PGresult   *res;
6327         int                     ntups;
6328         int                     i;
6329         PQExpBuffer query;
6330         TSParserInfo *prsinfo;
6331         int                     i_tableoid;
6332         int                     i_oid;
6333         int                     i_prsname;
6334         int                     i_prsnamespace;
6335         int                     i_prsstart;
6336         int                     i_prstoken;
6337         int                     i_prsend;
6338         int                     i_prsheadline;
6339         int                     i_prslextype;
6340
6341         /* Before 8.3, there is no built-in text search support */
6342         if (fout->remoteVersion < 80300)
6343         {
6344                 *numTSParsers = 0;
6345                 return NULL;
6346         }
6347
6348         query = createPQExpBuffer();
6349
6350         /*
6351          * find all text search objects, including builtin ones; we filter out
6352          * system-defined objects at dump-out time.
6353          */
6354
6355         /* Make sure we are in proper schema */
6356         selectSourceSchema(fout, "pg_catalog");
6357
6358         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6359                                           "prsstart::oid, prstoken::oid, "
6360                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6361                                           "FROM pg_ts_parser");
6362
6363         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6364
6365         ntups = PQntuples(res);
6366         *numTSParsers = ntups;
6367
6368         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6369
6370         i_tableoid = PQfnumber(res, "tableoid");
6371         i_oid = PQfnumber(res, "oid");
6372         i_prsname = PQfnumber(res, "prsname");
6373         i_prsnamespace = PQfnumber(res, "prsnamespace");
6374         i_prsstart = PQfnumber(res, "prsstart");
6375         i_prstoken = PQfnumber(res, "prstoken");
6376         i_prsend = PQfnumber(res, "prsend");
6377         i_prsheadline = PQfnumber(res, "prsheadline");
6378         i_prslextype = PQfnumber(res, "prslextype");
6379
6380         for (i = 0; i < ntups; i++)
6381         {
6382                 prsinfo[i].dobj.objType = DO_TSPARSER;
6383                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6384                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6385                 AssignDumpId(&prsinfo[i].dobj);
6386                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6387                 prsinfo[i].dobj.namespace =
6388                         findNamespace(fout,
6389                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6390                                                   prsinfo[i].dobj.catId.oid);
6391                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6392                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6393                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6394                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6395                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6396
6397                 /* Decide whether we want to dump it */
6398                 selectDumpableObject(&(prsinfo[i].dobj));
6399         }
6400
6401         PQclear(res);
6402
6403         destroyPQExpBuffer(query);
6404
6405         return prsinfo;
6406 }
6407
6408 /*
6409  * getTSDictionaries:
6410  *        read all text search dictionaries in the system catalogs and return them
6411  *        in the TSDictInfo* structure
6412  *
6413  *      numTSDicts is set to the number of dictionaries read in
6414  */
6415 TSDictInfo *
6416 getTSDictionaries(Archive *fout, int *numTSDicts)
6417 {
6418         PGresult   *res;
6419         int                     ntups;
6420         int                     i;
6421         PQExpBuffer query;
6422         TSDictInfo *dictinfo;
6423         int                     i_tableoid;
6424         int                     i_oid;
6425         int                     i_dictname;
6426         int                     i_dictnamespace;
6427         int                     i_rolname;
6428         int                     i_dicttemplate;
6429         int                     i_dictinitoption;
6430
6431         /* Before 8.3, there is no built-in text search support */
6432         if (fout->remoteVersion < 80300)
6433         {
6434                 *numTSDicts = 0;
6435                 return NULL;
6436         }
6437
6438         query = createPQExpBuffer();
6439
6440         /* Make sure we are in proper schema */
6441         selectSourceSchema(fout, "pg_catalog");
6442
6443         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6444                                           "dictnamespace, (%s dictowner) AS rolname, "
6445                                           "dicttemplate, dictinitoption "
6446                                           "FROM pg_ts_dict",
6447                                           username_subquery);
6448
6449         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6450
6451         ntups = PQntuples(res);
6452         *numTSDicts = ntups;
6453
6454         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6455
6456         i_tableoid = PQfnumber(res, "tableoid");
6457         i_oid = PQfnumber(res, "oid");
6458         i_dictname = PQfnumber(res, "dictname");
6459         i_dictnamespace = PQfnumber(res, "dictnamespace");
6460         i_rolname = PQfnumber(res, "rolname");
6461         i_dictinitoption = PQfnumber(res, "dictinitoption");
6462         i_dicttemplate = PQfnumber(res, "dicttemplate");
6463
6464         for (i = 0; i < ntups; i++)
6465         {
6466                 dictinfo[i].dobj.objType = DO_TSDICT;
6467                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6468                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6469                 AssignDumpId(&dictinfo[i].dobj);
6470                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6471                 dictinfo[i].dobj.namespace =
6472                         findNamespace(fout,
6473                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6474                                                   dictinfo[i].dobj.catId.oid);
6475                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6476                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6477                 if (PQgetisnull(res, i, i_dictinitoption))
6478                         dictinfo[i].dictinitoption = NULL;
6479                 else
6480                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6481
6482                 /* Decide whether we want to dump it */
6483                 selectDumpableObject(&(dictinfo[i].dobj));
6484         }
6485
6486         PQclear(res);
6487
6488         destroyPQExpBuffer(query);
6489
6490         return dictinfo;
6491 }
6492
6493 /*
6494  * getTSTemplates:
6495  *        read all text search templates in the system catalogs and return them
6496  *        in the TSTemplateInfo* structure
6497  *
6498  *      numTSTemplates is set to the number of templates read in
6499  */
6500 TSTemplateInfo *
6501 getTSTemplates(Archive *fout, int *numTSTemplates)
6502 {
6503         PGresult   *res;
6504         int                     ntups;
6505         int                     i;
6506         PQExpBuffer query;
6507         TSTemplateInfo *tmplinfo;
6508         int                     i_tableoid;
6509         int                     i_oid;
6510         int                     i_tmplname;
6511         int                     i_tmplnamespace;
6512         int                     i_tmplinit;
6513         int                     i_tmpllexize;
6514
6515         /* Before 8.3, there is no built-in text search support */
6516         if (fout->remoteVersion < 80300)
6517         {
6518                 *numTSTemplates = 0;
6519                 return NULL;
6520         }
6521
6522         query = createPQExpBuffer();
6523
6524         /* Make sure we are in proper schema */
6525         selectSourceSchema(fout, "pg_catalog");
6526
6527         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6528                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6529                                           "FROM pg_ts_template");
6530
6531         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6532
6533         ntups = PQntuples(res);
6534         *numTSTemplates = ntups;
6535
6536         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6537
6538         i_tableoid = PQfnumber(res, "tableoid");
6539         i_oid = PQfnumber(res, "oid");
6540         i_tmplname = PQfnumber(res, "tmplname");
6541         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6542         i_tmplinit = PQfnumber(res, "tmplinit");
6543         i_tmpllexize = PQfnumber(res, "tmpllexize");
6544
6545         for (i = 0; i < ntups; i++)
6546         {
6547                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6548                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6549                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6550                 AssignDumpId(&tmplinfo[i].dobj);
6551                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6552                 tmplinfo[i].dobj.namespace =
6553                         findNamespace(fout,
6554                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6555                                                   tmplinfo[i].dobj.catId.oid);
6556                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6557                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6558
6559                 /* Decide whether we want to dump it */
6560                 selectDumpableObject(&(tmplinfo[i].dobj));
6561         }
6562
6563         PQclear(res);
6564
6565         destroyPQExpBuffer(query);
6566
6567         return tmplinfo;
6568 }
6569
6570 /*
6571  * getTSConfigurations:
6572  *        read all text search configurations in the system catalogs and return
6573  *        them in the TSConfigInfo* structure
6574  *
6575  *      numTSConfigs is set to the number of configurations read in
6576  */
6577 TSConfigInfo *
6578 getTSConfigurations(Archive *fout, int *numTSConfigs)
6579 {
6580         PGresult   *res;
6581         int                     ntups;
6582         int                     i;
6583         PQExpBuffer query;
6584         TSConfigInfo *cfginfo;
6585         int                     i_tableoid;
6586         int                     i_oid;
6587         int                     i_cfgname;
6588         int                     i_cfgnamespace;
6589         int                     i_rolname;
6590         int                     i_cfgparser;
6591
6592         /* Before 8.3, there is no built-in text search support */
6593         if (fout->remoteVersion < 80300)
6594         {
6595                 *numTSConfigs = 0;
6596                 return NULL;
6597         }
6598
6599         query = createPQExpBuffer();
6600
6601         /* Make sure we are in proper schema */
6602         selectSourceSchema(fout, "pg_catalog");
6603
6604         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6605                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6606                                           "FROM pg_ts_config",
6607                                           username_subquery);
6608
6609         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6610
6611         ntups = PQntuples(res);
6612         *numTSConfigs = ntups;
6613
6614         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6615
6616         i_tableoid = PQfnumber(res, "tableoid");
6617         i_oid = PQfnumber(res, "oid");
6618         i_cfgname = PQfnumber(res, "cfgname");
6619         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6620         i_rolname = PQfnumber(res, "rolname");
6621         i_cfgparser = PQfnumber(res, "cfgparser");
6622
6623         for (i = 0; i < ntups; i++)
6624         {
6625                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6626                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6627                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6628                 AssignDumpId(&cfginfo[i].dobj);
6629                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6630                 cfginfo[i].dobj.namespace =
6631                         findNamespace(fout,
6632                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6633                                                   cfginfo[i].dobj.catId.oid);
6634                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6635                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6636
6637                 /* Decide whether we want to dump it */
6638                 selectDumpableObject(&(cfginfo[i].dobj));
6639         }
6640
6641         PQclear(res);
6642
6643         destroyPQExpBuffer(query);
6644
6645         return cfginfo;
6646 }
6647
6648 /*
6649  * getForeignDataWrappers:
6650  *        read all foreign-data wrappers in the system catalogs and return
6651  *        them in the FdwInfo* structure
6652  *
6653  *      numForeignDataWrappers is set to the number of fdws read in
6654  */
6655 FdwInfo *
6656 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6657 {
6658         PGresult   *res;
6659         int                     ntups;
6660         int                     i;
6661         PQExpBuffer query = createPQExpBuffer();
6662         FdwInfo    *fdwinfo;
6663         int                     i_tableoid;
6664         int                     i_oid;
6665         int                     i_fdwname;
6666         int                     i_rolname;
6667         int                     i_fdwhandler;
6668         int                     i_fdwvalidator;
6669         int                     i_fdwacl;
6670         int                     i_fdwoptions;
6671
6672         /* Before 8.4, there are no foreign-data wrappers */
6673         if (fout->remoteVersion < 80400)
6674         {
6675                 *numForeignDataWrappers = 0;
6676                 return NULL;
6677         }
6678
6679         /* Make sure we are in proper schema */
6680         selectSourceSchema(fout, "pg_catalog");
6681
6682         if (fout->remoteVersion >= 90100)
6683         {
6684                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6685                                                   "(%s fdwowner) AS rolname, "
6686                                                   "fdwhandler::pg_catalog.regproc, "
6687                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6688                                                   "array_to_string(ARRAY("
6689                                                   "SELECT quote_ident(option_name) || ' ' || "
6690                                                   "quote_literal(option_value) "
6691                                                   "FROM pg_options_to_table(fdwoptions) "
6692                                                   "ORDER BY option_name"
6693                                                   "), E',\n    ') AS fdwoptions "
6694                                                   "FROM pg_foreign_data_wrapper",
6695                                                   username_subquery);
6696         }
6697         else
6698         {
6699                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6700                                                   "(%s fdwowner) AS rolname, "
6701                                                   "'-' AS fdwhandler, "
6702                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6703                                                   "array_to_string(ARRAY("
6704                                                   "SELECT quote_ident(option_name) || ' ' || "
6705                                                   "quote_literal(option_value) "
6706                                                   "FROM pg_options_to_table(fdwoptions) "
6707                                                   "ORDER BY option_name"
6708                                                   "), E',\n    ') AS fdwoptions "
6709                                                   "FROM pg_foreign_data_wrapper",
6710                                                   username_subquery);
6711         }
6712
6713         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6714
6715         ntups = PQntuples(res);
6716         *numForeignDataWrappers = ntups;
6717
6718         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6719
6720         i_tableoid = PQfnumber(res, "tableoid");
6721         i_oid = PQfnumber(res, "oid");
6722         i_fdwname = PQfnumber(res, "fdwname");
6723         i_rolname = PQfnumber(res, "rolname");
6724         i_fdwhandler = PQfnumber(res, "fdwhandler");
6725         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6726         i_fdwacl = PQfnumber(res, "fdwacl");
6727         i_fdwoptions = PQfnumber(res, "fdwoptions");
6728
6729         for (i = 0; i < ntups; i++)
6730         {
6731                 fdwinfo[i].dobj.objType = DO_FDW;
6732                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6733                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6734                 AssignDumpId(&fdwinfo[i].dobj);
6735                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6736                 fdwinfo[i].dobj.namespace = NULL;
6737                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6738                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6739                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6740                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6741                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6742
6743                 /* Decide whether we want to dump it */
6744                 selectDumpableObject(&(fdwinfo[i].dobj));
6745         }
6746
6747         PQclear(res);
6748
6749         destroyPQExpBuffer(query);
6750
6751         return fdwinfo;
6752 }
6753
6754 /*
6755  * getForeignServers:
6756  *        read all foreign servers in the system catalogs and return
6757  *        them in the ForeignServerInfo * structure
6758  *
6759  *      numForeignServers is set to the number of servers read in
6760  */
6761 ForeignServerInfo *
6762 getForeignServers(Archive *fout, int *numForeignServers)
6763 {
6764         PGresult   *res;
6765         int                     ntups;
6766         int                     i;
6767         PQExpBuffer query = createPQExpBuffer();
6768         ForeignServerInfo *srvinfo;
6769         int                     i_tableoid;
6770         int                     i_oid;
6771         int                     i_srvname;
6772         int                     i_rolname;
6773         int                     i_srvfdw;
6774         int                     i_srvtype;
6775         int                     i_srvversion;
6776         int                     i_srvacl;
6777         int                     i_srvoptions;
6778
6779         /* Before 8.4, there are no foreign servers */
6780         if (fout->remoteVersion < 80400)
6781         {
6782                 *numForeignServers = 0;
6783                 return NULL;
6784         }
6785
6786         /* Make sure we are in proper schema */
6787         selectSourceSchema(fout, "pg_catalog");
6788
6789         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6790                                           "(%s srvowner) AS rolname, "
6791                                           "srvfdw, srvtype, srvversion, srvacl,"
6792                                           "array_to_string(ARRAY("
6793                                           "SELECT quote_ident(option_name) || ' ' || "
6794                                           "quote_literal(option_value) "
6795                                           "FROM pg_options_to_table(srvoptions) "
6796                                           "ORDER BY option_name"
6797                                           "), E',\n    ') AS srvoptions "
6798                                           "FROM pg_foreign_server",
6799                                           username_subquery);
6800
6801         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6802
6803         ntups = PQntuples(res);
6804         *numForeignServers = ntups;
6805
6806         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6807
6808         i_tableoid = PQfnumber(res, "tableoid");
6809         i_oid = PQfnumber(res, "oid");
6810         i_srvname = PQfnumber(res, "srvname");
6811         i_rolname = PQfnumber(res, "rolname");
6812         i_srvfdw = PQfnumber(res, "srvfdw");
6813         i_srvtype = PQfnumber(res, "srvtype");
6814         i_srvversion = PQfnumber(res, "srvversion");
6815         i_srvacl = PQfnumber(res, "srvacl");
6816         i_srvoptions = PQfnumber(res, "srvoptions");
6817
6818         for (i = 0; i < ntups; i++)
6819         {
6820                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6821                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6822                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6823                 AssignDumpId(&srvinfo[i].dobj);
6824                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6825                 srvinfo[i].dobj.namespace = NULL;
6826                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6827                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6828                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6829                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6830                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6831                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6832
6833                 /* Decide whether we want to dump it */
6834                 selectDumpableObject(&(srvinfo[i].dobj));
6835         }
6836
6837         PQclear(res);
6838
6839         destroyPQExpBuffer(query);
6840
6841         return srvinfo;
6842 }
6843
6844 /*
6845  * getDefaultACLs:
6846  *        read all default ACL information in the system catalogs and return
6847  *        them in the DefaultACLInfo structure
6848  *
6849  *      numDefaultACLs is set to the number of ACLs read in
6850  */
6851 DefaultACLInfo *
6852 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6853 {
6854         DefaultACLInfo *daclinfo;
6855         PQExpBuffer query;
6856         PGresult   *res;
6857         int                     i_oid;
6858         int                     i_tableoid;
6859         int                     i_defaclrole;
6860         int                     i_defaclnamespace;
6861         int                     i_defaclobjtype;
6862         int                     i_defaclacl;
6863         int                     i,
6864                                 ntups;
6865
6866         if (fout->remoteVersion < 90000)
6867         {
6868                 *numDefaultACLs = 0;
6869                 return NULL;
6870         }
6871
6872         query = createPQExpBuffer();
6873
6874         /* Make sure we are in proper schema */
6875         selectSourceSchema(fout, "pg_catalog");
6876
6877         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6878                                           "(%s defaclrole) AS defaclrole, "
6879                                           "defaclnamespace, "
6880                                           "defaclobjtype, "
6881                                           "defaclacl "
6882                                           "FROM pg_default_acl",
6883                                           username_subquery);
6884
6885         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6886
6887         ntups = PQntuples(res);
6888         *numDefaultACLs = ntups;
6889
6890         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6891
6892         i_oid = PQfnumber(res, "oid");
6893         i_tableoid = PQfnumber(res, "tableoid");
6894         i_defaclrole = PQfnumber(res, "defaclrole");
6895         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6896         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6897         i_defaclacl = PQfnumber(res, "defaclacl");
6898
6899         for (i = 0; i < ntups; i++)
6900         {
6901                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6902
6903                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6904                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6905                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6906                 AssignDumpId(&daclinfo[i].dobj);
6907                 /* cheesy ... is it worth coming up with a better object name? */
6908                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6909
6910                 if (nspid != InvalidOid)
6911                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6912                                                                                                  daclinfo[i].dobj.catId.oid);
6913                 else
6914                         daclinfo[i].dobj.namespace = NULL;
6915
6916                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6917                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6918                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6919
6920                 /* Decide whether we want to dump it */
6921                 selectDumpableDefaultACL(&(daclinfo[i]));
6922         }
6923
6924         PQclear(res);
6925
6926         destroyPQExpBuffer(query);
6927
6928         return daclinfo;
6929 }
6930
6931 /*
6932  * dumpComment --
6933  *
6934  * This routine is used to dump any comments associated with the
6935  * object handed to this routine. The routine takes a constant character
6936  * string for the target part of the comment-creation command, plus
6937  * the namespace and owner of the object (for labeling the ArchiveEntry),
6938  * plus catalog ID and subid which are the lookup key for pg_description,
6939  * plus the dump ID for the object (for setting a dependency).
6940  * If a matching pg_description entry is found, it is dumped.
6941  *
6942  * Note: although this routine takes a dumpId for dependency purposes,
6943  * that purpose is just to mark the dependency in the emitted dump file
6944  * for possible future use by pg_restore.  We do NOT use it for determining
6945  * ordering of the comment in the dump file, because this routine is called
6946  * after dependency sorting occurs.  This routine should be called just after
6947  * calling ArchiveEntry() for the specified object.
6948  */
6949 static void
6950 dumpComment(Archive *fout, const char *target,
6951                         const char *namespace, const char *owner,
6952                         CatalogId catalogId, int subid, DumpId dumpId)
6953 {
6954         CommentItem *comments;
6955         int                     ncomments;
6956
6957         /* Comments are schema not data ... except blob comments are data */
6958         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6959         {
6960                 if (dataOnly)
6961                         return;
6962         }
6963         else
6964         {
6965                 if (schemaOnly)
6966                         return;
6967         }
6968
6969         /* Search for comments associated with catalogId, using table */
6970         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6971                                                          &comments);
6972
6973         /* Is there one matching the subid? */
6974         while (ncomments > 0)
6975         {
6976                 if (comments->objsubid == subid)
6977                         break;
6978                 comments++;
6979                 ncomments--;
6980         }
6981
6982         /* If a comment exists, build COMMENT ON statement */
6983         if (ncomments > 0)
6984         {
6985                 PQExpBuffer query = createPQExpBuffer();
6986
6987                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6988                 appendStringLiteralAH(query, comments->descr, fout);
6989                 appendPQExpBuffer(query, ";\n");
6990
6991                 /*
6992                  * We mark comments as SECTION_NONE because they really belong in the
6993                  * same section as their parent, whether that is pre-data or
6994                  * post-data.
6995                  */
6996                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6997                                          target, namespace, NULL, owner,
6998                                          false, "COMMENT", SECTION_NONE,
6999                                          query->data, "", NULL,
7000                                          &(dumpId), 1,
7001                                          NULL, NULL);
7002
7003                 destroyPQExpBuffer(query);
7004         }
7005 }
7006
7007 /*
7008  * dumpTableComment --
7009  *
7010  * As above, but dump comments for both the specified table (or view)
7011  * and its columns.
7012  */
7013 static void
7014 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7015                                  const char *reltypename)
7016 {
7017         CommentItem *comments;
7018         int                     ncomments;
7019         PQExpBuffer query;
7020         PQExpBuffer target;
7021
7022         /* Comments are SCHEMA not data */
7023         if (dataOnly)
7024                 return;
7025
7026         /* Search for comments associated with relation, using table */
7027         ncomments = findComments(fout,
7028                                                          tbinfo->dobj.catId.tableoid,
7029                                                          tbinfo->dobj.catId.oid,
7030                                                          &comments);
7031
7032         /* If comments exist, build COMMENT ON statements */
7033         if (ncomments <= 0)
7034                 return;
7035
7036         query = createPQExpBuffer();
7037         target = createPQExpBuffer();
7038
7039         while (ncomments > 0)
7040         {
7041                 const char *descr = comments->descr;
7042                 int                     objsubid = comments->objsubid;
7043
7044                 if (objsubid == 0)
7045                 {
7046                         resetPQExpBuffer(target);
7047                         appendPQExpBuffer(target, "%s %s", reltypename,
7048                                                           fmtId(tbinfo->dobj.name));
7049
7050                         resetPQExpBuffer(query);
7051                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7052                         appendStringLiteralAH(query, descr, fout);
7053                         appendPQExpBuffer(query, ";\n");
7054
7055                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7056                                                  target->data,
7057                                                  tbinfo->dobj.namespace->dobj.name,
7058                                                  NULL, tbinfo->rolname,
7059                                                  false, "COMMENT", SECTION_NONE,
7060                                                  query->data, "", NULL,
7061                                                  &(tbinfo->dobj.dumpId), 1,
7062                                                  NULL, NULL);
7063                 }
7064                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7065                 {
7066                         resetPQExpBuffer(target);
7067                         appendPQExpBuffer(target, "COLUMN %s.",
7068                                                           fmtId(tbinfo->dobj.name));
7069                         appendPQExpBuffer(target, "%s",
7070                                                           fmtId(tbinfo->attnames[objsubid - 1]));
7071
7072                         resetPQExpBuffer(query);
7073                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7074                         appendStringLiteralAH(query, descr, fout);
7075                         appendPQExpBuffer(query, ";\n");
7076
7077                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7078                                                  target->data,
7079                                                  tbinfo->dobj.namespace->dobj.name,
7080                                                  NULL, tbinfo->rolname,
7081                                                  false, "COMMENT", SECTION_NONE,
7082                                                  query->data, "", NULL,
7083                                                  &(tbinfo->dobj.dumpId), 1,
7084                                                  NULL, NULL);
7085                 }
7086
7087                 comments++;
7088                 ncomments--;
7089         }
7090
7091         destroyPQExpBuffer(query);
7092         destroyPQExpBuffer(target);
7093 }
7094
7095 /*
7096  * findComments --
7097  *
7098  * Find the comment(s), if any, associated with the given object.  All the
7099  * objsubid values associated with the given classoid/objoid are found with
7100  * one search.
7101  */
7102 static int
7103 findComments(Archive *fout, Oid classoid, Oid objoid,
7104                          CommentItem **items)
7105 {
7106         /* static storage for table of comments */
7107         static CommentItem *comments = NULL;
7108         static int      ncomments = -1;
7109
7110         CommentItem *middle = NULL;
7111         CommentItem *low;
7112         CommentItem *high;
7113         int                     nmatch;
7114
7115         /* Get comments if we didn't already */
7116         if (ncomments < 0)
7117                 ncomments = collectComments(fout, &comments);
7118
7119         /*
7120          * Pre-7.2, pg_description does not contain classoid, so collectComments
7121          * just stores a zero.  If there's a collision on object OID, well, you
7122          * get duplicate comments.
7123          */
7124         if (fout->remoteVersion < 70200)
7125                 classoid = 0;
7126
7127         /*
7128          * Do binary search to find some item matching the object.
7129          */
7130         low = &comments[0];
7131         high = &comments[ncomments - 1];
7132         while (low <= high)
7133         {
7134                 middle = low + (high - low) / 2;
7135
7136                 if (classoid < middle->classoid)
7137                         high = middle - 1;
7138                 else if (classoid > middle->classoid)
7139                         low = middle + 1;
7140                 else if (objoid < middle->objoid)
7141                         high = middle - 1;
7142                 else if (objoid > middle->objoid)
7143                         low = middle + 1;
7144                 else
7145                         break;                          /* found a match */
7146         }
7147
7148         if (low > high)                         /* no matches */
7149         {
7150                 *items = NULL;
7151                 return 0;
7152         }
7153
7154         /*
7155          * Now determine how many items match the object.  The search loop
7156          * invariant still holds: only items between low and high inclusive could
7157          * match.
7158          */
7159         nmatch = 1;
7160         while (middle > low)
7161         {
7162                 if (classoid != middle[-1].classoid ||
7163                         objoid != middle[-1].objoid)
7164                         break;
7165                 middle--;
7166                 nmatch++;
7167         }
7168
7169         *items = middle;
7170
7171         middle += nmatch;
7172         while (middle <= high)
7173         {
7174                 if (classoid != middle->classoid ||
7175                         objoid != middle->objoid)
7176                         break;
7177                 middle++;
7178                 nmatch++;
7179         }
7180
7181         return nmatch;
7182 }
7183
7184 /*
7185  * collectComments --
7186  *
7187  * Construct a table of all comments available for database objects.
7188  * We used to do per-object queries for the comments, but it's much faster
7189  * to pull them all over at once, and on most databases the memory cost
7190  * isn't high.
7191  *
7192  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7193  */
7194 static int
7195 collectComments(Archive *fout, CommentItem **items)
7196 {
7197         PGresult   *res;
7198         PQExpBuffer query;
7199         int                     i_description;
7200         int                     i_classoid;
7201         int                     i_objoid;
7202         int                     i_objsubid;
7203         int                     ntups;
7204         int                     i;
7205         CommentItem *comments;
7206
7207         /*
7208          * Note we do NOT change source schema here; preserve the caller's
7209          * setting, instead.
7210          */
7211
7212         query = createPQExpBuffer();
7213
7214         if (fout->remoteVersion >= 70300)
7215         {
7216                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7217                                                   "FROM pg_catalog.pg_description "
7218                                                   "ORDER BY classoid, objoid, objsubid");
7219         }
7220         else if (fout->remoteVersion >= 70200)
7221         {
7222                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7223                                                   "FROM pg_description "
7224                                                   "ORDER BY classoid, objoid, objsubid");
7225         }
7226         else
7227         {
7228                 /* Note: this will fail to find attribute comments in pre-7.2... */
7229                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7230                                                   "FROM pg_description "
7231                                                   "ORDER BY objoid");
7232         }
7233
7234         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7235
7236         /* Construct lookup table containing OIDs in numeric form */
7237
7238         i_description = PQfnumber(res, "description");
7239         i_classoid = PQfnumber(res, "classoid");
7240         i_objoid = PQfnumber(res, "objoid");
7241         i_objsubid = PQfnumber(res, "objsubid");
7242
7243         ntups = PQntuples(res);
7244
7245         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7246
7247         for (i = 0; i < ntups; i++)
7248         {
7249                 comments[i].descr = PQgetvalue(res, i, i_description);
7250                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7251                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7252                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7253         }
7254
7255         /* Do NOT free the PGresult since we are keeping pointers into it */
7256         destroyPQExpBuffer(query);
7257
7258         *items = comments;
7259         return ntups;
7260 }
7261
7262 /*
7263  * dumpDumpableObject
7264  *
7265  * This routine and its subsidiaries are responsible for creating
7266  * ArchiveEntries (TOC objects) for each object to be dumped.
7267  */
7268 static void
7269 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7270 {
7271         switch (dobj->objType)
7272         {
7273                 case DO_NAMESPACE:
7274                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7275                         break;
7276                 case DO_EXTENSION:
7277                         dumpExtension(fout, (ExtensionInfo *) dobj);
7278                         break;
7279                 case DO_TYPE:
7280                         dumpType(fout, (TypeInfo *) dobj);
7281                         break;
7282                 case DO_SHELL_TYPE:
7283                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7284                         break;
7285                 case DO_FUNC:
7286                         dumpFunc(fout, (FuncInfo *) dobj);
7287                         break;
7288                 case DO_AGG:
7289                         dumpAgg(fout, (AggInfo *) dobj);
7290                         break;
7291                 case DO_OPERATOR:
7292                         dumpOpr(fout, (OprInfo *) dobj);
7293                         break;
7294                 case DO_OPCLASS:
7295                         dumpOpclass(fout, (OpclassInfo *) dobj);
7296                         break;
7297                 case DO_OPFAMILY:
7298                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7299                         break;
7300                 case DO_COLLATION:
7301                         dumpCollation(fout, (CollInfo *) dobj);
7302                         break;
7303                 case DO_CONVERSION:
7304                         dumpConversion(fout, (ConvInfo *) dobj);
7305                         break;
7306                 case DO_TABLE:
7307                         dumpTable(fout, (TableInfo *) dobj);
7308                         break;
7309                 case DO_ATTRDEF:
7310                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7311                         break;
7312                 case DO_INDEX:
7313                         dumpIndex(fout, (IndxInfo *) dobj);
7314                         break;
7315                 case DO_RULE:
7316                         dumpRule(fout, (RuleInfo *) dobj);
7317                         break;
7318                 case DO_TRIGGER:
7319                         dumpTrigger(fout, (TriggerInfo *) dobj);
7320                         break;
7321                 case DO_EVENT_TRIGGER:
7322                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7323                         break;
7324                 case DO_CONSTRAINT:
7325                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7326                         break;
7327                 case DO_FK_CONSTRAINT:
7328                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7329                         break;
7330                 case DO_PROCLANG:
7331                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7332                         break;
7333                 case DO_CAST:
7334                         dumpCast(fout, (CastInfo *) dobj);
7335                         break;
7336                 case DO_TABLE_DATA:
7337                         if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7338                                 dumpSequenceData(fout, (TableDataInfo *) dobj);
7339                         else
7340                                 dumpTableData(fout, (TableDataInfo *) dobj);
7341                         break;
7342                 case DO_DUMMY_TYPE:
7343                         /* table rowtypes and array types are never dumped separately */
7344                         break;
7345                 case DO_TSPARSER:
7346                         dumpTSParser(fout, (TSParserInfo *) dobj);
7347                         break;
7348                 case DO_TSDICT:
7349                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7350                         break;
7351                 case DO_TSTEMPLATE:
7352                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7353                         break;
7354                 case DO_TSCONFIG:
7355                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7356                         break;
7357                 case DO_FDW:
7358                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7359                         break;
7360                 case DO_FOREIGN_SERVER:
7361                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7362                         break;
7363                 case DO_DEFAULT_ACL:
7364                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7365                         break;
7366                 case DO_BLOB:
7367                         dumpBlob(fout, (BlobInfo *) dobj);
7368                         break;
7369                 case DO_BLOB_DATA:
7370                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7371                                                  dobj->name, NULL, NULL, "",
7372                                                  false, "BLOBS", SECTION_DATA,
7373                                                  "", "", NULL,
7374                                                  NULL, 0,
7375                                                  dumpBlobs, NULL);
7376                         break;
7377                 case DO_PRE_DATA_BOUNDARY:
7378                 case DO_POST_DATA_BOUNDARY:
7379                         /* never dumped, nothing to do */
7380                         break;
7381         }
7382 }
7383
7384 /*
7385  * dumpNamespace
7386  *        writes out to fout the queries to recreate a user-defined namespace
7387  */
7388 static void
7389 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7390 {
7391         PQExpBuffer q;
7392         PQExpBuffer delq;
7393         PQExpBuffer labelq;
7394         char       *qnspname;
7395
7396         /* Skip if not to be dumped */
7397         if (!nspinfo->dobj.dump || dataOnly)
7398                 return;
7399
7400         /* don't dump dummy namespace from pre-7.3 source */
7401         if (strlen(nspinfo->dobj.name) == 0)
7402                 return;
7403
7404         q = createPQExpBuffer();
7405         delq = createPQExpBuffer();
7406         labelq = createPQExpBuffer();
7407
7408         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7409
7410         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7411
7412         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7413
7414         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7415
7416         if (binary_upgrade)
7417                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7418
7419         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7420                                  nspinfo->dobj.name,
7421                                  NULL, NULL,
7422                                  nspinfo->rolname,
7423                                  false, "SCHEMA", SECTION_PRE_DATA,
7424                                  q->data, delq->data, NULL,
7425                                  NULL, 0,
7426                                  NULL, NULL);
7427
7428         /* Dump Schema Comments and Security Labels */
7429         dumpComment(fout, labelq->data,
7430                                 NULL, nspinfo->rolname,
7431                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7432         dumpSecLabel(fout, labelq->data,
7433                                  NULL, nspinfo->rolname,
7434                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7435
7436         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7437                         qnspname, NULL, nspinfo->dobj.name, NULL,
7438                         nspinfo->rolname, nspinfo->nspacl);
7439
7440         free(qnspname);
7441
7442         destroyPQExpBuffer(q);
7443         destroyPQExpBuffer(delq);
7444         destroyPQExpBuffer(labelq);
7445 }
7446
7447 /*
7448  * dumpExtension
7449  *        writes out to fout the queries to recreate an extension
7450  */
7451 static void
7452 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7453 {
7454         PQExpBuffer q;
7455         PQExpBuffer delq;
7456         PQExpBuffer labelq;
7457         char       *qextname;
7458
7459         /* Skip if not to be dumped */
7460         if (!extinfo->dobj.dump || dataOnly)
7461                 return;
7462
7463         q = createPQExpBuffer();
7464         delq = createPQExpBuffer();
7465         labelq = createPQExpBuffer();
7466
7467         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7468
7469         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7470
7471         if (!binary_upgrade)
7472         {
7473                 /*
7474                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7475                  * problem if the extension already exists in the target database;
7476                  * this is essential for installed-by-default extensions such as
7477                  * plpgsql.
7478                  *
7479                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7480                  * built-in extensions based on their OIDs; see
7481                  * selectDumpableExtension.
7482                  */
7483                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7484                                                   qextname, fmtId(extinfo->namespace));
7485         }
7486         else
7487         {
7488                 int                     i;
7489                 int                     n;
7490
7491                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7492
7493                 /*
7494                  *      We unconditionally create the extension, so we must drop it if it
7495                  *      exists.  This could happen if the user deleted 'plpgsql' and then
7496                  *      readded it, causing its oid to be greater than FirstNormalObjectId.
7497                  *      The FirstNormalObjectId test was kept to avoid repeatedly dropping
7498                  *      and recreating extensions like 'plpgsql'.
7499                  */
7500                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7501
7502                 appendPQExpBuffer(q,
7503                                                   "SELECT binary_upgrade.create_empty_extension(");
7504                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7505                 appendPQExpBuffer(q, ", ");
7506                 appendStringLiteralAH(q, extinfo->namespace, fout);
7507                 appendPQExpBuffer(q, ", ");
7508                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7509                 appendStringLiteralAH(q, extinfo->extversion, fout);
7510                 appendPQExpBuffer(q, ", ");
7511
7512                 /*
7513                  * Note that we're pushing extconfig (an OID array) back into
7514                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7515                  * preserved in binary upgrade.
7516                  */
7517                 if (strlen(extinfo->extconfig) > 2)
7518                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7519                 else
7520                         appendPQExpBuffer(q, "NULL");
7521                 appendPQExpBuffer(q, ", ");
7522                 if (strlen(extinfo->extcondition) > 2)
7523                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7524                 else
7525                         appendPQExpBuffer(q, "NULL");
7526                 appendPQExpBuffer(q, ", ");
7527                 appendPQExpBuffer(q, "ARRAY[");
7528                 n = 0;
7529                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7530                 {
7531                         DumpableObject *extobj;
7532
7533                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7534                         if (extobj && extobj->objType == DO_EXTENSION)
7535                         {
7536                                 if (n++ > 0)
7537                                         appendPQExpBuffer(q, ",");
7538                                 appendStringLiteralAH(q, extobj->name, fout);
7539                         }
7540                 }
7541                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7542                 appendPQExpBuffer(q, ");\n");
7543         }
7544
7545         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7546
7547         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7548                                  extinfo->dobj.name,
7549                                  NULL, NULL,
7550                                  "",
7551                                  false, "EXTENSION", SECTION_PRE_DATA,
7552                                  q->data, delq->data, NULL,
7553                                  NULL, 0,
7554                                  NULL, NULL);
7555
7556         /* Dump Extension Comments and Security Labels */
7557         dumpComment(fout, labelq->data,
7558                                 NULL, "",
7559                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7560         dumpSecLabel(fout, labelq->data,
7561                                  NULL, "",
7562                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7563
7564         free(qextname);
7565
7566         destroyPQExpBuffer(q);
7567         destroyPQExpBuffer(delq);
7568         destroyPQExpBuffer(labelq);
7569 }
7570
7571 /*
7572  * dumpType
7573  *        writes out to fout the queries to recreate a user-defined type
7574  */
7575 static void
7576 dumpType(Archive *fout, TypeInfo *tyinfo)
7577 {
7578         /* Skip if not to be dumped */
7579         if (!tyinfo->dobj.dump || dataOnly)
7580                 return;
7581
7582         /* Dump out in proper style */
7583         if (tyinfo->typtype == TYPTYPE_BASE)
7584                 dumpBaseType(fout, tyinfo);
7585         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7586                 dumpDomain(fout, tyinfo);
7587         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7588                 dumpCompositeType(fout, tyinfo);
7589         else if (tyinfo->typtype == TYPTYPE_ENUM)
7590                 dumpEnumType(fout, tyinfo);
7591         else if (tyinfo->typtype == TYPTYPE_RANGE)
7592                 dumpRangeType(fout, tyinfo);
7593         else
7594                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7595                                   tyinfo->dobj.name);
7596 }
7597
7598 /*
7599  * dumpEnumType
7600  *        writes out to fout the queries to recreate a user-defined enum type
7601  */
7602 static void
7603 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7604 {
7605         PQExpBuffer q = createPQExpBuffer();
7606         PQExpBuffer delq = createPQExpBuffer();
7607         PQExpBuffer labelq = createPQExpBuffer();
7608         PQExpBuffer query = createPQExpBuffer();
7609         PGresult   *res;
7610         int                     num,
7611                                 i;
7612         Oid                     enum_oid;
7613         char       *qtypname;
7614         char       *label;
7615
7616         /* Set proper schema search path */
7617         selectSourceSchema(fout, "pg_catalog");
7618
7619         if (fout->remoteVersion >= 90100)
7620                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7621                                                   "FROM pg_catalog.pg_enum "
7622                                                   "WHERE enumtypid = '%u'"
7623                                                   "ORDER BY enumsortorder",
7624                                                   tyinfo->dobj.catId.oid);
7625         else
7626                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7627                                                   "FROM pg_catalog.pg_enum "
7628                                                   "WHERE enumtypid = '%u'"
7629                                                   "ORDER BY oid",
7630                                                   tyinfo->dobj.catId.oid);
7631
7632         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7633
7634         num = PQntuples(res);
7635
7636         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7637
7638         /*
7639          * DROP must be fully qualified in case same name appears in pg_catalog.
7640          * CASCADE shouldn't be required here as for normal types since the I/O
7641          * functions are generic and do not get dropped.
7642          */
7643         appendPQExpBuffer(delq, "DROP TYPE %s.",
7644                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7645         appendPQExpBuffer(delq, "%s;\n",
7646                                           qtypname);
7647
7648         if (binary_upgrade)
7649                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7650                                                                                                  tyinfo->dobj.catId.oid);
7651
7652         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7653                                           qtypname);
7654
7655         if (!binary_upgrade)
7656         {
7657                 /* Labels with server-assigned oids */
7658                 for (i = 0; i < num; i++)
7659                 {
7660                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7661                         if (i > 0)
7662                                 appendPQExpBuffer(q, ",");
7663                         appendPQExpBuffer(q, "\n    ");
7664                         appendStringLiteralAH(q, label, fout);
7665                 }
7666         }
7667
7668         appendPQExpBuffer(q, "\n);\n");
7669
7670         if (binary_upgrade)
7671         {
7672                 /* Labels with dump-assigned (preserved) oids */
7673                 for (i = 0; i < num; i++)
7674                 {
7675                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7676                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7677
7678                         if (i == 0)
7679                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7680                         appendPQExpBuffer(q,
7681                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7682                                                           enum_oid);
7683                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7684                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7685                         appendPQExpBuffer(q, "%s ADD VALUE ",
7686                                                           qtypname);
7687                         appendStringLiteralAH(q, label, fout);
7688                         appendPQExpBuffer(q, ";\n\n");
7689                 }
7690         }
7691
7692         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7693
7694         if (binary_upgrade)
7695                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7696
7697         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7698                                  tyinfo->dobj.name,
7699                                  tyinfo->dobj.namespace->dobj.name,
7700                                  NULL,
7701                                  tyinfo->rolname, false,
7702                                  "TYPE", SECTION_PRE_DATA,
7703                                  q->data, delq->data, NULL,
7704                                  NULL, 0,
7705                                  NULL, NULL);
7706
7707         /* Dump Type Comments and Security Labels */
7708         dumpComment(fout, labelq->data,
7709                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7710                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7711         dumpSecLabel(fout, labelq->data,
7712                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7713                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7714
7715         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7716                         qtypname, NULL, tyinfo->dobj.name,
7717                         tyinfo->dobj.namespace->dobj.name,
7718                         tyinfo->rolname, tyinfo->typacl);
7719
7720         PQclear(res);
7721         destroyPQExpBuffer(q);
7722         destroyPQExpBuffer(delq);
7723         destroyPQExpBuffer(labelq);
7724         destroyPQExpBuffer(query);
7725 }
7726
7727 /*
7728  * dumpRangeType
7729  *        writes out to fout the queries to recreate a user-defined range type
7730  */
7731 static void
7732 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7733 {
7734         PQExpBuffer q = createPQExpBuffer();
7735         PQExpBuffer delq = createPQExpBuffer();
7736         PQExpBuffer labelq = createPQExpBuffer();
7737         PQExpBuffer query = createPQExpBuffer();
7738         PGresult   *res;
7739         Oid                     collationOid;
7740         char       *qtypname;
7741         char       *procname;
7742
7743         /*
7744          * select appropriate schema to ensure names in CREATE are properly
7745          * qualified
7746          */
7747         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7748
7749         appendPQExpBuffer(query,
7750                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7751                                           "opc.opcname AS opcname, "
7752                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7753                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7754                                           "opc.opcdefault, "
7755                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7756                                           "     ELSE rngcollation END AS collation, "
7757                                           "rngcanonical, rngsubdiff "
7758                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7759                                           "     pg_catalog.pg_opclass opc "
7760                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7761                                           "rngtypid = '%u'",
7762                                           tyinfo->dobj.catId.oid);
7763
7764         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7765
7766         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7767
7768         /*
7769          * DROP must be fully qualified in case same name appears in pg_catalog.
7770          * CASCADE shouldn't be required here as for normal types since the I/O
7771          * functions are generic and do not get dropped.
7772          */
7773         appendPQExpBuffer(delq, "DROP TYPE %s.",
7774                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7775         appendPQExpBuffer(delq, "%s;\n",
7776                                           qtypname);
7777
7778         if (binary_upgrade)
7779                 binary_upgrade_set_type_oids_by_type_oid(fout,
7780                                                                                                  q, tyinfo->dobj.catId.oid);
7781
7782         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7783                                           qtypname);
7784
7785         appendPQExpBuffer(q, "\n    subtype = %s",
7786                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7787
7788         /* print subtype_opclass only if not default for subtype */
7789         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7790         {
7791                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7792                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7793
7794                 /* always schema-qualify, don't try to be smart */
7795                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7796                                                   fmtId(nspname));
7797                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7798         }
7799
7800         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7801         if (OidIsValid(collationOid))
7802         {
7803                 CollInfo   *coll = findCollationByOid(collationOid);
7804
7805                 if (coll)
7806                 {
7807                         /* always schema-qualify, don't try to be smart */
7808                         appendPQExpBuffer(q, ",\n    collation = %s.",
7809                                                           fmtId(coll->dobj.namespace->dobj.name));
7810                         appendPQExpBuffer(q, "%s",
7811                                                           fmtId(coll->dobj.name));
7812                 }
7813         }
7814
7815         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7816         if (strcmp(procname, "-") != 0)
7817                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7818
7819         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7820         if (strcmp(procname, "-") != 0)
7821                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7822
7823         appendPQExpBuffer(q, "\n);\n");
7824
7825         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7826
7827         if (binary_upgrade)
7828                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7829
7830         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7831                                  tyinfo->dobj.name,
7832                                  tyinfo->dobj.namespace->dobj.name,
7833                                  NULL,
7834                                  tyinfo->rolname, false,
7835                                  "TYPE", SECTION_PRE_DATA,
7836                                  q->data, delq->data, NULL,
7837                                  NULL, 0,
7838                                  NULL, NULL);
7839
7840         /* Dump Type Comments and Security Labels */
7841         dumpComment(fout, labelq->data,
7842                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7843                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7844         dumpSecLabel(fout, labelq->data,
7845                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7846                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7847
7848         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7849                         qtypname, NULL, tyinfo->dobj.name,
7850                         tyinfo->dobj.namespace->dobj.name,
7851                         tyinfo->rolname, tyinfo->typacl);
7852
7853         PQclear(res);
7854         destroyPQExpBuffer(q);
7855         destroyPQExpBuffer(delq);
7856         destroyPQExpBuffer(labelq);
7857         destroyPQExpBuffer(query);
7858 }
7859
7860 /*
7861  * dumpBaseType
7862  *        writes out to fout the queries to recreate a user-defined base type
7863  */
7864 static void
7865 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7866 {
7867         PQExpBuffer q = createPQExpBuffer();
7868         PQExpBuffer delq = createPQExpBuffer();
7869         PQExpBuffer labelq = createPQExpBuffer();
7870         PQExpBuffer query = createPQExpBuffer();
7871         PGresult   *res;
7872         char       *qtypname;
7873         char       *typlen;
7874         char       *typinput;
7875         char       *typoutput;
7876         char       *typreceive;
7877         char       *typsend;
7878         char       *typmodin;
7879         char       *typmodout;
7880         char       *typanalyze;
7881         Oid                     typreceiveoid;
7882         Oid                     typsendoid;
7883         Oid                     typmodinoid;
7884         Oid                     typmodoutoid;
7885         Oid                     typanalyzeoid;
7886         char       *typcategory;
7887         char       *typispreferred;
7888         char       *typdelim;
7889         char       *typbyval;
7890         char       *typalign;
7891         char       *typstorage;
7892         char       *typcollatable;
7893         char       *typdefault;
7894         bool            typdefault_is_literal = false;
7895
7896         /* Set proper schema search path so regproc references list correctly */
7897         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7898
7899         /* Fetch type-specific details */
7900         if (fout->remoteVersion >= 90100)
7901         {
7902                 appendPQExpBuffer(query, "SELECT typlen, "
7903                                                   "typinput, typoutput, typreceive, typsend, "
7904                                                   "typmodin, typmodout, typanalyze, "
7905                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7906                                                   "typsend::pg_catalog.oid AS typsendoid, "
7907                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7908                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7909                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7910                                                   "typcategory, typispreferred, "
7911                                                   "typdelim, typbyval, typalign, typstorage, "
7912                                                   "(typcollation <> 0) AS typcollatable, "
7913                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7914                                                   "FROM pg_catalog.pg_type "
7915                                                   "WHERE oid = '%u'::pg_catalog.oid",
7916                                                   tyinfo->dobj.catId.oid);
7917         }
7918         else if (fout->remoteVersion >= 80400)
7919         {
7920                 appendPQExpBuffer(query, "SELECT typlen, "
7921                                                   "typinput, typoutput, typreceive, typsend, "
7922                                                   "typmodin, typmodout, typanalyze, "
7923                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7924                                                   "typsend::pg_catalog.oid AS typsendoid, "
7925                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7926                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7927                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7928                                                   "typcategory, typispreferred, "
7929                                                   "typdelim, typbyval, typalign, typstorage, "
7930                                                   "false AS typcollatable, "
7931                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7932                                                   "FROM pg_catalog.pg_type "
7933                                                   "WHERE oid = '%u'::pg_catalog.oid",
7934                                                   tyinfo->dobj.catId.oid);
7935         }
7936         else if (fout->remoteVersion >= 80300)
7937         {
7938                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7939                 appendPQExpBuffer(query, "SELECT typlen, "
7940                                                   "typinput, typoutput, typreceive, typsend, "
7941                                                   "typmodin, typmodout, typanalyze, "
7942                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7943                                                   "typsend::pg_catalog.oid AS typsendoid, "
7944                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7945                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7946                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7947                                                   "'U' AS typcategory, false AS typispreferred, "
7948                                                   "typdelim, typbyval, typalign, typstorage, "
7949                                                   "false AS typcollatable, "
7950                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7951                                                   "FROM pg_catalog.pg_type "
7952                                                   "WHERE oid = '%u'::pg_catalog.oid",
7953                                                   tyinfo->dobj.catId.oid);
7954         }
7955         else if (fout->remoteVersion >= 80000)
7956         {
7957                 appendPQExpBuffer(query, "SELECT typlen, "
7958                                                   "typinput, typoutput, typreceive, typsend, "
7959                                                   "'-' AS typmodin, '-' AS typmodout, "
7960                                                   "typanalyze, "
7961                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7962                                                   "typsend::pg_catalog.oid AS typsendoid, "
7963                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7964                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7965                                                   "'U' AS typcategory, false AS typispreferred, "
7966                                                   "typdelim, typbyval, typalign, typstorage, "
7967                                                   "false AS typcollatable, "
7968                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7969                                                   "FROM pg_catalog.pg_type "
7970                                                   "WHERE oid = '%u'::pg_catalog.oid",
7971                                                   tyinfo->dobj.catId.oid);
7972         }
7973         else if (fout->remoteVersion >= 70400)
7974         {
7975                 appendPQExpBuffer(query, "SELECT typlen, "
7976                                                   "typinput, typoutput, typreceive, typsend, "
7977                                                   "'-' AS typmodin, '-' AS typmodout, "
7978                                                   "'-' AS typanalyze, "
7979                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7980                                                   "typsend::pg_catalog.oid AS typsendoid, "
7981                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7982                                                   "0 AS typanalyzeoid, "
7983                                                   "'U' AS typcategory, false AS typispreferred, "
7984                                                   "typdelim, typbyval, typalign, typstorage, "
7985                                                   "false AS typcollatable, "
7986                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7987                                                   "FROM pg_catalog.pg_type "
7988                                                   "WHERE oid = '%u'::pg_catalog.oid",
7989                                                   tyinfo->dobj.catId.oid);
7990         }
7991         else if (fout->remoteVersion >= 70300)
7992         {
7993                 appendPQExpBuffer(query, "SELECT typlen, "
7994                                                   "typinput, typoutput, "
7995                                                   "'-' AS typreceive, '-' AS typsend, "
7996                                                   "'-' AS typmodin, '-' AS typmodout, "
7997                                                   "'-' AS typanalyze, "
7998                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7999                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8000                                                   "0 AS typanalyzeoid, "
8001                                                   "'U' AS typcategory, false AS typispreferred, "
8002                                                   "typdelim, typbyval, typalign, typstorage, "
8003                                                   "false AS typcollatable, "
8004                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8005                                                   "FROM pg_catalog.pg_type "
8006                                                   "WHERE oid = '%u'::pg_catalog.oid",
8007                                                   tyinfo->dobj.catId.oid);
8008         }
8009         else if (fout->remoteVersion >= 70200)
8010         {
8011                 /*
8012                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
8013                  * ignore them because they are not right.
8014                  */
8015                 appendPQExpBuffer(query, "SELECT typlen, "
8016                                                   "typinput, typoutput, "
8017                                                   "'-' AS typreceive, '-' AS typsend, "
8018                                                   "'-' AS typmodin, '-' AS typmodout, "
8019                                                   "'-' AS typanalyze, "
8020                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8021                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8022                                                   "0 AS typanalyzeoid, "
8023                                                   "'U' AS typcategory, false AS typispreferred, "
8024                                                   "typdelim, typbyval, typalign, typstorage, "
8025                                                   "false AS typcollatable, "
8026                                                   "NULL AS typdefaultbin, typdefault "
8027                                                   "FROM pg_type "
8028                                                   "WHERE oid = '%u'::oid",
8029                                                   tyinfo->dobj.catId.oid);
8030         }
8031         else if (fout->remoteVersion >= 70100)
8032         {
8033                 /*
8034                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
8035                  * representation.
8036                  */
8037                 appendPQExpBuffer(query, "SELECT typlen, "
8038                                                   "typinput, typoutput, "
8039                                                   "'-' AS typreceive, '-' AS typsend, "
8040                                                   "'-' AS typmodin, '-' AS typmodout, "
8041                                                   "'-' AS typanalyze, "
8042                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8043                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8044                                                   "0 AS typanalyzeoid, "
8045                                                   "'U' AS typcategory, false AS typispreferred, "
8046                                                   "typdelim, typbyval, typalign, typstorage, "
8047                                                   "false AS typcollatable, "
8048                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8049                                                   "FROM pg_type "
8050                                                   "WHERE oid = '%u'::oid",
8051                                                   tyinfo->dobj.catId.oid);
8052         }
8053         else
8054         {
8055                 appendPQExpBuffer(query, "SELECT typlen, "
8056                                                   "typinput, typoutput, "
8057                                                   "'-' AS typreceive, '-' AS typsend, "
8058                                                   "'-' AS typmodin, '-' AS typmodout, "
8059                                                   "'-' AS typanalyze, "
8060                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8061                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8062                                                   "0 AS typanalyzeoid, "
8063                                                   "'U' AS typcategory, false AS typispreferred, "
8064                                                   "typdelim, typbyval, typalign, "
8065                                                   "'p'::char AS typstorage, "
8066                                                   "false AS typcollatable, "
8067                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8068                                                   "FROM pg_type "
8069                                                   "WHERE oid = '%u'::oid",
8070                                                   tyinfo->dobj.catId.oid);
8071         }
8072
8073         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8074
8075         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8076         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8077         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8078         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8079         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8080         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8081         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8082         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8083         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8084         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8085         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8086         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8087         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8088         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8089         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8090         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8091         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8092         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8093         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8094         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8095         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8096                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8097         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8098         {
8099                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8100                 typdefault_is_literal = true;   /* it needs quotes */
8101         }
8102         else
8103                 typdefault = NULL;
8104
8105         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8106
8107         /*
8108          * DROP must be fully qualified in case same name appears in pg_catalog.
8109          * The reason we include CASCADE is that the circular dependency between
8110          * the type and its I/O functions makes it impossible to drop the type any
8111          * other way.
8112          */
8113         appendPQExpBuffer(delq, "DROP TYPE %s.",
8114                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8115         appendPQExpBuffer(delq, "%s CASCADE;\n",
8116                                           qtypname);
8117
8118         /* We might already have a shell type, but setting pg_type_oid is harmless */
8119         if (binary_upgrade)
8120                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8121                                                                                                  tyinfo->dobj.catId.oid);
8122
8123         appendPQExpBuffer(q,
8124                                           "CREATE TYPE %s (\n"
8125                                           "    INTERNALLENGTH = %s",
8126                                           qtypname,
8127                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8128
8129         if (fout->remoteVersion >= 70300)
8130         {
8131                 /* regproc result is correctly quoted as of 7.3 */
8132                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
8133                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
8134                 if (OidIsValid(typreceiveoid))
8135                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
8136                 if (OidIsValid(typsendoid))
8137                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
8138                 if (OidIsValid(typmodinoid))
8139                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
8140                 if (OidIsValid(typmodoutoid))
8141                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
8142                 if (OidIsValid(typanalyzeoid))
8143                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
8144         }
8145         else
8146         {
8147                 /* regproc delivers an unquoted name before 7.3 */
8148                 /* cannot combine these because fmtId uses static result area */
8149                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
8150                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
8151                 /* receive/send/typmodin/typmodout/analyze need not be printed */
8152         }
8153
8154         if (strcmp(typcollatable, "t") == 0)
8155                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
8156
8157         if (typdefault != NULL)
8158         {
8159                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
8160                 if (typdefault_is_literal)
8161                         appendStringLiteralAH(q, typdefault, fout);
8162                 else
8163                         appendPQExpBufferStr(q, typdefault);
8164         }
8165
8166         if (OidIsValid(tyinfo->typelem))
8167         {
8168                 char       *elemType;
8169
8170                 /* reselect schema in case changed by function dump */
8171                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8172                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8173                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8174                 free(elemType);
8175         }
8176
8177         if (strcmp(typcategory, "U") != 0)
8178         {
8179                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8180                 appendStringLiteralAH(q, typcategory, fout);
8181         }
8182
8183         if (strcmp(typispreferred, "t") == 0)
8184                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8185
8186         if (typdelim && strcmp(typdelim, ",") != 0)
8187         {
8188                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8189                 appendStringLiteralAH(q, typdelim, fout);
8190         }
8191
8192         if (strcmp(typalign, "c") == 0)
8193                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8194         else if (strcmp(typalign, "s") == 0)
8195                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8196         else if (strcmp(typalign, "i") == 0)
8197                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8198         else if (strcmp(typalign, "d") == 0)
8199                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8200
8201         if (strcmp(typstorage, "p") == 0)
8202                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8203         else if (strcmp(typstorage, "e") == 0)
8204                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8205         else if (strcmp(typstorage, "x") == 0)
8206                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8207         else if (strcmp(typstorage, "m") == 0)
8208                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8209
8210         if (strcmp(typbyval, "t") == 0)
8211                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8212
8213         appendPQExpBuffer(q, "\n);\n");
8214
8215         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8216
8217         if (binary_upgrade)
8218                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8219
8220         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8221                                  tyinfo->dobj.name,
8222                                  tyinfo->dobj.namespace->dobj.name,
8223                                  NULL,
8224                                  tyinfo->rolname, false,
8225                                  "TYPE", SECTION_PRE_DATA,
8226                                  q->data, delq->data, NULL,
8227                                  NULL, 0,
8228                                  NULL, NULL);
8229
8230         /* Dump Type Comments and Security Labels */
8231         dumpComment(fout, labelq->data,
8232                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8233                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8234         dumpSecLabel(fout, labelq->data,
8235                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8236                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8237
8238         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8239                         qtypname, NULL, tyinfo->dobj.name,
8240                         tyinfo->dobj.namespace->dobj.name,
8241                         tyinfo->rolname, tyinfo->typacl);
8242
8243         PQclear(res);
8244         destroyPQExpBuffer(q);
8245         destroyPQExpBuffer(delq);
8246         destroyPQExpBuffer(labelq);
8247         destroyPQExpBuffer(query);
8248 }
8249
8250 /*
8251  * dumpDomain
8252  *        writes out to fout the queries to recreate a user-defined domain
8253  */
8254 static void
8255 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8256 {
8257         PQExpBuffer q = createPQExpBuffer();
8258         PQExpBuffer delq = createPQExpBuffer();
8259         PQExpBuffer labelq = createPQExpBuffer();
8260         PQExpBuffer query = createPQExpBuffer();
8261         PGresult   *res;
8262         int                     i;
8263         char       *qtypname;
8264         char       *typnotnull;
8265         char       *typdefn;
8266         char       *typdefault;
8267         Oid                     typcollation;
8268         bool            typdefault_is_literal = false;
8269
8270         /* Set proper schema search path so type references list correctly */
8271         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8272
8273         /* Fetch domain specific details */
8274         if (fout->remoteVersion >= 90100)
8275         {
8276                 /* typcollation is new in 9.1 */
8277                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8278                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8279                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8280                                                   "t.typdefault, "
8281                                                   "CASE WHEN t.typcollation <> u.typcollation "
8282                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8283                                                   "FROM pg_catalog.pg_type t "
8284                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8285                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8286                                                   tyinfo->dobj.catId.oid);
8287         }
8288         else
8289         {
8290                 /* We assume here that remoteVersion must be at least 70300 */
8291                 appendPQExpBuffer(query, "SELECT typnotnull, "
8292                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8293                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8294                                                   "typdefault, 0 AS typcollation "
8295                                                   "FROM pg_catalog.pg_type "
8296                                                   "WHERE oid = '%u'::pg_catalog.oid",
8297                                                   tyinfo->dobj.catId.oid);
8298         }
8299
8300         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8301
8302         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8303         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8304         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8305                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8306         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8307         {
8308                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8309                 typdefault_is_literal = true;   /* it needs quotes */
8310         }
8311         else
8312                 typdefault = NULL;
8313         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8314
8315         if (binary_upgrade)
8316                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8317                                                                                                  tyinfo->dobj.catId.oid);
8318
8319         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8320
8321         appendPQExpBuffer(q,
8322                                           "CREATE DOMAIN %s AS %s",
8323                                           qtypname,
8324                                           typdefn);
8325
8326         /* Print collation only if different from base type's collation */
8327         if (OidIsValid(typcollation))
8328         {
8329                 CollInfo   *coll;
8330
8331                 coll = findCollationByOid(typcollation);
8332                 if (coll)
8333                 {
8334                         /* always schema-qualify, don't try to be smart */
8335                         appendPQExpBuffer(q, " COLLATE %s.",
8336                                                           fmtId(coll->dobj.namespace->dobj.name));
8337                         appendPQExpBuffer(q, "%s",
8338                                                           fmtId(coll->dobj.name));
8339                 }
8340         }
8341
8342         if (typnotnull[0] == 't')
8343                 appendPQExpBuffer(q, " NOT NULL");
8344
8345         if (typdefault != NULL)
8346         {
8347                 appendPQExpBuffer(q, " DEFAULT ");
8348                 if (typdefault_is_literal)
8349                         appendStringLiteralAH(q, typdefault, fout);
8350                 else
8351                         appendPQExpBufferStr(q, typdefault);
8352         }
8353
8354         PQclear(res);
8355
8356         /*
8357          * Add any CHECK constraints for the domain
8358          */
8359         for (i = 0; i < tyinfo->nDomChecks; i++)
8360         {
8361                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8362
8363                 if (!domcheck->separate)
8364                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8365                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8366         }
8367
8368         appendPQExpBuffer(q, ";\n");
8369
8370         /*
8371          * DROP must be fully qualified in case same name appears in pg_catalog
8372          */
8373         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8374                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8375         appendPQExpBuffer(delq, "%s;\n",
8376                                           qtypname);
8377
8378         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8379
8380         if (binary_upgrade)
8381                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8382
8383         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8384                                  tyinfo->dobj.name,
8385                                  tyinfo->dobj.namespace->dobj.name,
8386                                  NULL,
8387                                  tyinfo->rolname, false,
8388                                  "DOMAIN", SECTION_PRE_DATA,
8389                                  q->data, delq->data, NULL,
8390                                  NULL, 0,
8391                                  NULL, NULL);
8392
8393         /* Dump Domain Comments and Security Labels */
8394         dumpComment(fout, labelq->data,
8395                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8396                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8397         dumpSecLabel(fout, labelq->data,
8398                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8399                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8400
8401         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8402                         qtypname, NULL, tyinfo->dobj.name,
8403                         tyinfo->dobj.namespace->dobj.name,
8404                         tyinfo->rolname, tyinfo->typacl);
8405
8406         destroyPQExpBuffer(q);
8407         destroyPQExpBuffer(delq);
8408         destroyPQExpBuffer(labelq);
8409         destroyPQExpBuffer(query);
8410 }
8411
8412 /*
8413  * dumpCompositeType
8414  *        writes out to fout the queries to recreate a user-defined stand-alone
8415  *        composite type
8416  */
8417 static void
8418 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8419 {
8420         PQExpBuffer q = createPQExpBuffer();
8421         PQExpBuffer dropped = createPQExpBuffer();
8422         PQExpBuffer delq = createPQExpBuffer();
8423         PQExpBuffer labelq = createPQExpBuffer();
8424         PQExpBuffer query = createPQExpBuffer();
8425         PGresult   *res;
8426         char       *qtypname;
8427         int                     ntups;
8428         int                     i_attname;
8429         int                     i_atttypdefn;
8430         int                     i_attlen;
8431         int                     i_attalign;
8432         int                     i_attisdropped;
8433         int                     i_attcollation;
8434         int                     i_typrelid;
8435         int                     i;
8436         int                     actual_atts;
8437
8438         /* Set proper schema search path so type references list correctly */
8439         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8440
8441         /* Fetch type specific details */
8442         if (fout->remoteVersion >= 90100)
8443         {
8444                 /*
8445                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8446                  * clauses for attributes whose collation is different from their
8447                  * type's default, we use a CASE here to suppress uninteresting
8448                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8449                  * collation does not matter for those.
8450                  */
8451                 appendPQExpBuffer(query, "SELECT a.attname, "
8452                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8453                                                   "a.attlen, a.attalign, a.attisdropped, "
8454                                                   "CASE WHEN a.attcollation <> at.typcollation "
8455                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8456                                                   "ct.typrelid "
8457                                                   "FROM pg_catalog.pg_type ct "
8458                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8459                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8460                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8461                                                   "ORDER BY a.attnum ",
8462                                                   tyinfo->dobj.catId.oid);
8463         }
8464         else
8465         {
8466                 /*
8467                  * We assume here that remoteVersion must be at least 70300.  Since
8468                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8469                  * always be false.
8470                  */
8471                 appendPQExpBuffer(query, "SELECT a.attname, "
8472                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8473                                                   "a.attlen, a.attalign, a.attisdropped, "
8474                                                   "0 AS attcollation, "
8475                                                   "ct.typrelid "
8476                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8477                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8478                                                   "AND a.attrelid = ct.typrelid "
8479                                                   "ORDER BY a.attnum ",
8480                                                   tyinfo->dobj.catId.oid);
8481         }
8482
8483         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8484
8485         ntups = PQntuples(res);
8486
8487         i_attname = PQfnumber(res, "attname");
8488         i_atttypdefn = PQfnumber(res, "atttypdefn");
8489         i_attlen = PQfnumber(res, "attlen");
8490         i_attalign = PQfnumber(res, "attalign");
8491         i_attisdropped = PQfnumber(res, "attisdropped");
8492         i_attcollation = PQfnumber(res, "attcollation");
8493         i_typrelid = PQfnumber(res, "typrelid");
8494
8495         if (binary_upgrade)
8496         {
8497                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8498
8499                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8500                                                                                                  tyinfo->dobj.catId.oid);
8501                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8502         }
8503
8504         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8505
8506         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8507                                           qtypname);
8508
8509         actual_atts = 0;
8510         for (i = 0; i < ntups; i++)
8511         {
8512                 char       *attname;
8513                 char       *atttypdefn;
8514                 char       *attlen;
8515                 char       *attalign;
8516                 bool            attisdropped;
8517                 Oid                     attcollation;
8518
8519                 attname = PQgetvalue(res, i, i_attname);
8520                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8521                 attlen = PQgetvalue(res, i, i_attlen);
8522                 attalign = PQgetvalue(res, i, i_attalign);
8523                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8524                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8525
8526                 if (attisdropped && !binary_upgrade)
8527                         continue;
8528
8529                 /* Format properly if not first attr */
8530                 if (actual_atts++ > 0)
8531                         appendPQExpBuffer(q, ",");
8532                 appendPQExpBuffer(q, "\n\t");
8533
8534                 if (!attisdropped)
8535                 {
8536                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8537
8538                         /* Add collation if not default for the column type */
8539                         if (OidIsValid(attcollation))
8540                         {
8541                                 CollInfo   *coll;
8542
8543                                 coll = findCollationByOid(attcollation);
8544                                 if (coll)
8545                                 {
8546                                         /* always schema-qualify, don't try to be smart */
8547                                         appendPQExpBuffer(q, " COLLATE %s.",
8548                                                                           fmtId(coll->dobj.namespace->dobj.name));
8549                                         appendPQExpBuffer(q, "%s",
8550                                                                           fmtId(coll->dobj.name));
8551                                 }
8552                         }
8553                 }
8554                 else
8555                 {
8556                         /*
8557                          * This is a dropped attribute and we're in binary_upgrade mode.
8558                          * Insert a placeholder for it in the CREATE TYPE command, and set
8559                          * length and alignment with direct UPDATE to the catalogs
8560                          * afterwards. See similar code in dumpTableSchema().
8561                          */
8562                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8563
8564                         /* stash separately for insertion after the CREATE TYPE */
8565                         appendPQExpBuffer(dropped,
8566                                           "\n-- For binary upgrade, recreate dropped column.\n");
8567                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8568                                                           "SET attlen = %s, "
8569                                                           "attalign = '%s', attbyval = false\n"
8570                                                           "WHERE attname = ", attlen, attalign);
8571                         appendStringLiteralAH(dropped, attname, fout);
8572                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8573                         appendStringLiteralAH(dropped, qtypname, fout);
8574                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8575
8576                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8577                                                           qtypname);
8578                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8579                                                           fmtId(attname));
8580                 }
8581         }
8582         appendPQExpBuffer(q, "\n);\n");
8583         appendPQExpBufferStr(q, dropped->data);
8584
8585         /*
8586          * DROP must be fully qualified in case same name appears in pg_catalog
8587          */
8588         appendPQExpBuffer(delq, "DROP TYPE %s.",
8589                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8590         appendPQExpBuffer(delq, "%s;\n",
8591                                           qtypname);
8592
8593         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8594
8595         if (binary_upgrade)
8596                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8597
8598         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8599                                  tyinfo->dobj.name,
8600                                  tyinfo->dobj.namespace->dobj.name,
8601                                  NULL,
8602                                  tyinfo->rolname, false,
8603                                  "TYPE", SECTION_PRE_DATA,
8604                                  q->data, delq->data, NULL,
8605                                  NULL, 0,
8606                                  NULL, NULL);
8607
8608
8609         /* Dump Type Comments and Security Labels */
8610         dumpComment(fout, labelq->data,
8611                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8612                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8613         dumpSecLabel(fout, labelq->data,
8614                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8615                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8616
8617         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8618                         qtypname, NULL, tyinfo->dobj.name,
8619                         tyinfo->dobj.namespace->dobj.name,
8620                         tyinfo->rolname, tyinfo->typacl);
8621
8622         PQclear(res);
8623         destroyPQExpBuffer(q);
8624         destroyPQExpBuffer(dropped);
8625         destroyPQExpBuffer(delq);
8626         destroyPQExpBuffer(labelq);
8627         destroyPQExpBuffer(query);
8628
8629         /* Dump any per-column comments */
8630         dumpCompositeTypeColComments(fout, tyinfo);
8631 }
8632
8633 /*
8634  * dumpCompositeTypeColComments
8635  *        writes out to fout the queries to recreate comments on the columns of
8636  *        a user-defined stand-alone composite type
8637  */
8638 static void
8639 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8640 {
8641         CommentItem *comments;
8642         int                     ncomments;
8643         PGresult   *res;
8644         PQExpBuffer query;
8645         PQExpBuffer target;
8646         Oid                     pgClassOid;
8647         int                     i;
8648         int                     ntups;
8649         int                     i_attname;
8650         int                     i_attnum;
8651
8652         query = createPQExpBuffer();
8653
8654         /* We assume here that remoteVersion must be at least 70300 */
8655         appendPQExpBuffer(query,
8656                                           "SELECT c.tableoid, a.attname, a.attnum "
8657                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8658                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8659                                           "  AND NOT a.attisdropped "
8660                                           "ORDER BY a.attnum ",
8661                                           tyinfo->typrelid);
8662
8663         /* Fetch column attnames */
8664         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8665
8666         ntups = PQntuples(res);
8667         if (ntups < 1)
8668         {
8669                 PQclear(res);
8670                 destroyPQExpBuffer(query);
8671                 return;
8672         }
8673
8674         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8675
8676         /* Search for comments associated with type's pg_class OID */
8677         ncomments = findComments(fout,
8678                                                          pgClassOid,
8679                                                          tyinfo->typrelid,
8680                                                          &comments);
8681
8682         /* If no comments exist, we're done */
8683         if (ncomments <= 0)
8684         {
8685                 PQclear(res);
8686                 destroyPQExpBuffer(query);
8687                 return;
8688         }
8689
8690         /* Build COMMENT ON statements */
8691         target = createPQExpBuffer();
8692
8693         i_attnum = PQfnumber(res, "attnum");
8694         i_attname = PQfnumber(res, "attname");
8695         while (ncomments > 0)
8696         {
8697                 const char *attname;
8698
8699                 attname = NULL;
8700                 for (i = 0; i < ntups; i++)
8701                 {
8702                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8703                         {
8704                                 attname = PQgetvalue(res, i, i_attname);
8705                                 break;
8706                         }
8707                 }
8708                 if (attname)                    /* just in case we don't find it */
8709                 {
8710                         const char *descr = comments->descr;
8711
8712                         resetPQExpBuffer(target);
8713                         appendPQExpBuffer(target, "COLUMN %s.",
8714                                                           fmtId(tyinfo->dobj.name));
8715                         appendPQExpBuffer(target, "%s",
8716                                                           fmtId(attname));
8717
8718                         resetPQExpBuffer(query);
8719                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8720                         appendStringLiteralAH(query, descr, fout);
8721                         appendPQExpBuffer(query, ";\n");
8722
8723                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8724                                                  target->data,
8725                                                  tyinfo->dobj.namespace->dobj.name,
8726                                                  NULL, tyinfo->rolname,
8727                                                  false, "COMMENT", SECTION_NONE,
8728                                                  query->data, "", NULL,
8729                                                  &(tyinfo->dobj.dumpId), 1,
8730                                                  NULL, NULL);
8731                 }
8732
8733                 comments++;
8734                 ncomments--;
8735         }
8736
8737         PQclear(res);
8738         destroyPQExpBuffer(query);
8739         destroyPQExpBuffer(target);
8740 }
8741
8742 /*
8743  * dumpShellType
8744  *        writes out to fout the queries to create a shell type
8745  *
8746  * We dump a shell definition in advance of the I/O functions for the type.
8747  */
8748 static void
8749 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8750 {
8751         PQExpBuffer q;
8752
8753         /* Skip if not to be dumped */
8754         if (!stinfo->dobj.dump || dataOnly)
8755                 return;
8756
8757         q = createPQExpBuffer();
8758
8759         /*
8760          * Note the lack of a DROP command for the shell type; any required DROP
8761          * is driven off the base type entry, instead.  This interacts with
8762          * _printTocEntry()'s use of the presence of a DROP command to decide
8763          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8764          * the shell type's owner immediately on creation; that should happen only
8765          * after it's filled in, otherwise the backend complains.
8766          */
8767
8768         if (binary_upgrade)
8769                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8770                                                                                    stinfo->baseType->dobj.catId.oid);
8771
8772         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8773                                           fmtId(stinfo->dobj.name));
8774
8775         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8776                                  stinfo->dobj.name,
8777                                  stinfo->dobj.namespace->dobj.name,
8778                                  NULL,
8779                                  stinfo->baseType->rolname, false,
8780                                  "SHELL TYPE", SECTION_PRE_DATA,
8781                                  q->data, "", NULL,
8782                                  NULL, 0,
8783                                  NULL, NULL);
8784
8785         destroyPQExpBuffer(q);
8786 }
8787
8788 /*
8789  * Determine whether we want to dump definitions for procedural languages.
8790  * Since the languages themselves don't have schemas, we can't rely on
8791  * the normal schema-based selection mechanism.  We choose to dump them
8792  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8793  * the dump flag of the PL's call handler function, but in 8.1 this will
8794  * probably always be false since call handlers are created in pg_catalog.)
8795  *
8796  * For some backwards compatibility with the older behavior, we forcibly
8797  * dump a PL if its handler function (and validator if any) are in a
8798  * dumpable namespace.  That case is not checked here.
8799  *
8800  * Also, if the PL belongs to an extension, we do not use this heuristic.
8801  * That case isn't checked here either.
8802  */
8803 static bool
8804 shouldDumpProcLangs(void)
8805 {
8806         if (!include_everything)
8807                 return false;
8808         /* And they're schema not data */
8809         if (dataOnly)
8810                 return false;
8811         return true;
8812 }
8813
8814 /*
8815  * dumpProcLang
8816  *                writes out to fout the queries to recreate a user-defined
8817  *                procedural language
8818  */
8819 static void
8820 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8821 {
8822         PQExpBuffer defqry;
8823         PQExpBuffer delqry;
8824         PQExpBuffer labelq;
8825         bool            useParams;
8826         char       *qlanname;
8827         char       *lanschema;
8828         FuncInfo   *funcInfo;
8829         FuncInfo   *inlineInfo = NULL;
8830         FuncInfo   *validatorInfo = NULL;
8831
8832         /* Skip if not to be dumped */
8833         if (!plang->dobj.dump || dataOnly)
8834                 return;
8835
8836         /*
8837          * Try to find the support function(s).  It is not an error if we don't
8838          * find them --- if the functions are in the pg_catalog schema, as is
8839          * standard in 8.1 and up, then we won't have loaded them. (In this case
8840          * we will emit a parameterless CREATE LANGUAGE command, which will
8841          * require PL template knowledge in the backend to reload.)
8842          */
8843
8844         funcInfo = findFuncByOid(plang->lanplcallfoid);
8845         if (funcInfo != NULL && !funcInfo->dobj.dump)
8846                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8847
8848         if (OidIsValid(plang->laninline))
8849         {
8850                 inlineInfo = findFuncByOid(plang->laninline);
8851                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8852                         inlineInfo = NULL;
8853         }
8854
8855         if (OidIsValid(plang->lanvalidator))
8856         {
8857                 validatorInfo = findFuncByOid(plang->lanvalidator);
8858                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8859                         validatorInfo = NULL;
8860         }
8861
8862         /*
8863          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8864          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8865          * dump it.
8866          *
8867          * However, for a language that belongs to an extension, we must not use
8868          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8869          * told to (via dobj.dump).  Generally the support functions will belong
8870          * to the same extension and so have the same dump flags ... if they
8871          * don't, this might not work terribly nicely.
8872          */
8873         useParams = (funcInfo != NULL &&
8874                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8875                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8876
8877         if (!plang->dobj.ext_member)
8878         {
8879                 if (!useParams && !shouldDumpProcLangs())
8880                         return;
8881         }
8882
8883         defqry = createPQExpBuffer();
8884         delqry = createPQExpBuffer();
8885         labelq = createPQExpBuffer();
8886
8887         qlanname = pg_strdup(fmtId(plang->dobj.name));
8888
8889         /*
8890          * If dumping a HANDLER clause, treat the language as being in the handler
8891          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8892          * it doesn't really have a schema.
8893          */
8894         if (useParams)
8895                 lanschema = funcInfo->dobj.namespace->dobj.name;
8896         else
8897                 lanschema = NULL;
8898
8899         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8900                                           qlanname);
8901
8902         if (useParams)
8903         {
8904                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8905                                                   plang->lanpltrusted ? "TRUSTED " : "",
8906                                                   qlanname);
8907                 appendPQExpBuffer(defqry, " HANDLER %s",
8908                                                   fmtId(funcInfo->dobj.name));
8909                 if (OidIsValid(plang->laninline))
8910                 {
8911                         appendPQExpBuffer(defqry, " INLINE ");
8912                         /* Cope with possibility that inline is in different schema */
8913                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8914                                 appendPQExpBuffer(defqry, "%s.",
8915                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8916                         appendPQExpBuffer(defqry, "%s",
8917                                                           fmtId(inlineInfo->dobj.name));
8918                 }
8919                 if (OidIsValid(plang->lanvalidator))
8920                 {
8921                         appendPQExpBuffer(defqry, " VALIDATOR ");
8922                         /* Cope with possibility that validator is in different schema */
8923                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8924                                 appendPQExpBuffer(defqry, "%s.",
8925                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8926                         appendPQExpBuffer(defqry, "%s",
8927                                                           fmtId(validatorInfo->dobj.name));
8928                 }
8929         }
8930         else
8931         {
8932                 /*
8933                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8934                  * command will not fail if the language is preinstalled in the target
8935                  * database.  We restrict the use of REPLACE to this case so as to
8936                  * eliminate the risk of replacing a language with incompatible
8937                  * parameter settings: this command will only succeed at all if there
8938                  * is a pg_pltemplate entry, and if there is one, the existing entry
8939                  * must match it too.
8940                  */
8941                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8942                                                   qlanname);
8943         }
8944         appendPQExpBuffer(defqry, ";\n");
8945
8946         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8947
8948         if (binary_upgrade)
8949                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8950
8951         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8952                                  plang->dobj.name,
8953                                  lanschema, NULL, plang->lanowner,
8954                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8955                                  defqry->data, delqry->data, NULL,
8956                                  NULL, 0,
8957                                  NULL, NULL);
8958
8959         /* Dump Proc Lang Comments and Security Labels */
8960         dumpComment(fout, labelq->data,
8961                                 NULL, "",
8962                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8963         dumpSecLabel(fout, labelq->data,
8964                                  NULL, "",
8965                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8966
8967         if (plang->lanpltrusted)
8968                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8969                                 qlanname, NULL, plang->dobj.name,
8970                                 lanschema,
8971                                 plang->lanowner, plang->lanacl);
8972
8973         free(qlanname);
8974
8975         destroyPQExpBuffer(defqry);
8976         destroyPQExpBuffer(delqry);
8977         destroyPQExpBuffer(labelq);
8978 }
8979
8980 /*
8981  * format_function_arguments: generate function name and argument list
8982  *
8983  * This is used when we can rely on pg_get_function_arguments to format
8984  * the argument list.
8985  */
8986 static char *
8987 format_function_arguments(FuncInfo *finfo, char *funcargs)
8988 {
8989         PQExpBufferData fn;
8990
8991         initPQExpBuffer(&fn);
8992         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8993         return fn.data;
8994 }
8995
8996 /*
8997  * format_function_arguments_old: generate function name and argument list
8998  *
8999  * The argument type names are qualified if needed.  The function name
9000  * is never qualified.
9001  *
9002  * This is used only with pre-8.4 servers, so we aren't expecting to see
9003  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9004  *
9005  * Any or all of allargtypes, argmodes, argnames may be NULL.
9006  */
9007 static char *
9008 format_function_arguments_old(Archive *fout,
9009                                                           FuncInfo *finfo, int nallargs,
9010                                                           char **allargtypes,
9011                                                           char **argmodes,
9012                                                           char **argnames)
9013 {
9014         PQExpBufferData fn;
9015         int                     j;
9016
9017         initPQExpBuffer(&fn);
9018         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9019         for (j = 0; j < nallargs; j++)
9020         {
9021                 Oid                     typid;
9022                 char       *typname;
9023                 const char *argmode;
9024                 const char *argname;
9025
9026                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9027                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9028
9029                 if (argmodes)
9030                 {
9031                         switch (argmodes[j][0])
9032                         {
9033                                 case PROARGMODE_IN:
9034                                         argmode = "";
9035                                         break;
9036                                 case PROARGMODE_OUT:
9037                                         argmode = "OUT ";
9038                                         break;
9039                                 case PROARGMODE_INOUT:
9040                                         argmode = "INOUT ";
9041                                         break;
9042                                 default:
9043                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9044                                         argmode = "";
9045                                         break;
9046                         }
9047                 }
9048                 else
9049                         argmode = "";
9050
9051                 argname = argnames ? argnames[j] : (char *) NULL;
9052                 if (argname && argname[0] == '\0')
9053                         argname = NULL;
9054
9055                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9056                                                   (j > 0) ? ", " : "",
9057                                                   argmode,
9058                                                   argname ? fmtId(argname) : "",
9059                                                   argname ? " " : "",
9060                                                   typname);
9061                 free(typname);
9062         }
9063         appendPQExpBuffer(&fn, ")");
9064         return fn.data;
9065 }
9066
9067 /*
9068  * format_function_signature: generate function name and argument list
9069  *
9070  * This is like format_function_arguments_old except that only a minimal
9071  * list of input argument types is generated; this is sufficient to
9072  * reference the function, but not to define it.
9073  *
9074  * If honor_quotes is false then the function name is never quoted.
9075  * This is appropriate for use in TOC tags, but not in SQL commands.
9076  */
9077 static char *
9078 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9079 {
9080         PQExpBufferData fn;
9081         int                     j;
9082
9083         initPQExpBuffer(&fn);
9084         if (honor_quotes)
9085                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9086         else
9087                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9088         for (j = 0; j < finfo->nargs; j++)
9089         {
9090                 char       *typname;
9091
9092                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9093                                                                            zeroAsOpaque);
9094
9095                 appendPQExpBuffer(&fn, "%s%s",
9096                                                   (j > 0) ? ", " : "",
9097                                                   typname);
9098                 free(typname);
9099         }
9100         appendPQExpBuffer(&fn, ")");
9101         return fn.data;
9102 }
9103
9104
9105 /*
9106  * dumpFunc:
9107  *        dump out one function
9108  */
9109 static void
9110 dumpFunc(Archive *fout, FuncInfo *finfo)
9111 {
9112         PQExpBuffer query;
9113         PQExpBuffer q;
9114         PQExpBuffer delqry;
9115         PQExpBuffer labelq;
9116         PQExpBuffer asPart;
9117         PGresult   *res;
9118         char       *funcsig;            /* identity signature */
9119         char       *funcfullsig;        /* full signature */
9120         char       *funcsig_tag;
9121         char       *proretset;
9122         char       *prosrc;
9123         char       *probin;
9124         char       *funcargs;
9125         char       *funciargs;
9126         char       *funcresult;
9127         char       *proallargtypes;
9128         char       *proargmodes;
9129         char       *proargnames;
9130         char       *proiswindow;
9131         char       *provolatile;
9132         char       *proisstrict;
9133         char       *prosecdef;
9134         char       *proleakproof;
9135         char       *proconfig;
9136         char       *procost;
9137         char       *prorows;
9138         char       *lanname;
9139         char       *rettypename;
9140         int                     nallargs;
9141         char      **allargtypes = NULL;
9142         char      **argmodes = NULL;
9143         char      **argnames = NULL;
9144         char      **configitems = NULL;
9145         int                     nconfigitems = 0;
9146         int                     i;
9147
9148         /* Skip if not to be dumped */
9149         if (!finfo->dobj.dump || dataOnly)
9150                 return;
9151
9152         query = createPQExpBuffer();
9153         q = createPQExpBuffer();
9154         delqry = createPQExpBuffer();
9155         labelq = createPQExpBuffer();
9156         asPart = createPQExpBuffer();
9157
9158         /* Set proper schema search path so type references list correctly */
9159         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9160
9161         /* Fetch function-specific details */
9162         if (fout->remoteVersion >= 90200)
9163         {
9164                 /*
9165                  * proleakproof was added at v9.2
9166                  */
9167                 appendPQExpBuffer(query,
9168                                                   "SELECT proretset, prosrc, probin, "
9169                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9170                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9171                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9172                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9173                                                   "proleakproof, proconfig, procost, prorows, "
9174                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9175                                                   "FROM pg_catalog.pg_proc "
9176                                                   "WHERE oid = '%u'::pg_catalog.oid",
9177                                                   finfo->dobj.catId.oid);
9178         }
9179         else if (fout->remoteVersion >= 80400)
9180         {
9181                 /*
9182                  * In 8.4 and up we rely on pg_get_function_arguments and
9183                  * pg_get_function_result instead of examining proallargtypes etc.
9184                  */
9185                 appendPQExpBuffer(query,
9186                                                   "SELECT proretset, prosrc, probin, "
9187                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9188                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9189                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9190                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9191                                                   "false AS proleakproof, "
9192                                                   " proconfig, procost, prorows, "
9193                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9194                                                   "FROM pg_catalog.pg_proc "
9195                                                   "WHERE oid = '%u'::pg_catalog.oid",
9196                                                   finfo->dobj.catId.oid);
9197         }
9198         else if (fout->remoteVersion >= 80300)
9199         {
9200                 appendPQExpBuffer(query,
9201                                                   "SELECT proretset, prosrc, probin, "
9202                                                   "proallargtypes, proargmodes, proargnames, "
9203                                                   "false AS proiswindow, "
9204                                                   "provolatile, proisstrict, prosecdef, "
9205                                                   "false AS proleakproof, "
9206                                                   "proconfig, procost, prorows, "
9207                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9208                                                   "FROM pg_catalog.pg_proc "
9209                                                   "WHERE oid = '%u'::pg_catalog.oid",
9210                                                   finfo->dobj.catId.oid);
9211         }
9212         else if (fout->remoteVersion >= 80100)
9213         {
9214                 appendPQExpBuffer(query,
9215                                                   "SELECT proretset, prosrc, probin, "
9216                                                   "proallargtypes, proargmodes, proargnames, "
9217                                                   "false AS proiswindow, "
9218                                                   "provolatile, proisstrict, prosecdef, "
9219                                                   "false AS proleakproof, "
9220                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9221                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9222                                                   "FROM pg_catalog.pg_proc "
9223                                                   "WHERE oid = '%u'::pg_catalog.oid",
9224                                                   finfo->dobj.catId.oid);
9225         }
9226         else if (fout->remoteVersion >= 80000)
9227         {
9228                 appendPQExpBuffer(query,
9229                                                   "SELECT proretset, prosrc, probin, "
9230                                                   "null AS proallargtypes, "
9231                                                   "null AS proargmodes, "
9232                                                   "proargnames, "
9233                                                   "false AS proiswindow, "
9234                                                   "provolatile, proisstrict, prosecdef, "
9235                                                   "false AS proleakproof, "
9236                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9237                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9238                                                   "FROM pg_catalog.pg_proc "
9239                                                   "WHERE oid = '%u'::pg_catalog.oid",
9240                                                   finfo->dobj.catId.oid);
9241         }
9242         else if (fout->remoteVersion >= 70300)
9243         {
9244                 appendPQExpBuffer(query,
9245                                                   "SELECT proretset, prosrc, probin, "
9246                                                   "null AS proallargtypes, "
9247                                                   "null AS proargmodes, "
9248                                                   "null AS proargnames, "
9249                                                   "false AS proiswindow, "
9250                                                   "provolatile, proisstrict, prosecdef, "
9251                                                   "false AS proleakproof, "
9252                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9253                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9254                                                   "FROM pg_catalog.pg_proc "
9255                                                   "WHERE oid = '%u'::pg_catalog.oid",
9256                                                   finfo->dobj.catId.oid);
9257         }
9258         else if (fout->remoteVersion >= 70100)
9259         {
9260                 appendPQExpBuffer(query,
9261                                                   "SELECT proretset, prosrc, probin, "
9262                                                   "null AS proallargtypes, "
9263                                                   "null AS proargmodes, "
9264                                                   "null AS proargnames, "
9265                                                   "false AS proiswindow, "
9266                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9267                                                   "proisstrict, "
9268                                                   "false AS prosecdef, "
9269                                                   "false AS proleakproof, "
9270                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9271                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9272                                                   "FROM pg_proc "
9273                                                   "WHERE oid = '%u'::oid",
9274                                                   finfo->dobj.catId.oid);
9275         }
9276         else
9277         {
9278                 appendPQExpBuffer(query,
9279                                                   "SELECT proretset, prosrc, probin, "
9280                                                   "null AS proallargtypes, "
9281                                                   "null AS proargmodes, "
9282                                                   "null AS proargnames, "
9283                                                   "false AS proiswindow, "
9284                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9285                                                   "false AS proisstrict, "
9286                                                   "false AS prosecdef, "
9287                                                   "false AS proleakproof, "
9288                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9289                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9290                                                   "FROM pg_proc "
9291                                                   "WHERE oid = '%u'::oid",
9292                                                   finfo->dobj.catId.oid);
9293         }
9294
9295         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9296
9297         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9298         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9299         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9300         if (fout->remoteVersion >= 80400)
9301         {
9302                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9303                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9304                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9305                 proallargtypes = proargmodes = proargnames = NULL;
9306         }
9307         else
9308         {
9309                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9310                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9311                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9312                 funcargs = funciargs = funcresult = NULL;
9313         }
9314         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9315         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9316         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9317         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9318         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9319         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9320         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9321         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9322         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9323
9324         /*
9325          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9326          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9327          * versions would set it to "-".  There are no known cases in which prosrc
9328          * is unused, so the tests below for "-" are probably useless.
9329          */
9330         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9331         {
9332                 appendPQExpBuffer(asPart, "AS ");
9333                 appendStringLiteralAH(asPart, probin, fout);
9334                 if (strcmp(prosrc, "-") != 0)
9335                 {
9336                         appendPQExpBuffer(asPart, ", ");
9337
9338                         /*
9339                          * where we have bin, use dollar quoting if allowed and src
9340                          * contains quote or backslash; else use regular quoting.
9341                          */
9342                         if (disable_dollar_quoting ||
9343                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9344                                 appendStringLiteralAH(asPart, prosrc, fout);
9345                         else
9346                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9347                 }
9348         }
9349         else
9350         {
9351                 if (strcmp(prosrc, "-") != 0)
9352                 {
9353                         appendPQExpBuffer(asPart, "AS ");
9354                         /* with no bin, dollar quote src unconditionally if allowed */
9355                         if (disable_dollar_quoting)
9356                                 appendStringLiteralAH(asPart, prosrc, fout);
9357                         else
9358                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9359                 }
9360         }
9361
9362         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9363
9364         if (proallargtypes && *proallargtypes)
9365         {
9366                 int                     nitems = 0;
9367
9368                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9369                         nitems < finfo->nargs)
9370                 {
9371                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9372                         if (allargtypes)
9373                                 free(allargtypes);
9374                         allargtypes = NULL;
9375                 }
9376                 else
9377                         nallargs = nitems;
9378         }
9379
9380         if (proargmodes && *proargmodes)
9381         {
9382                 int                     nitems = 0;
9383
9384                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9385                         nitems != nallargs)
9386                 {
9387                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9388                         if (argmodes)
9389                                 free(argmodes);
9390                         argmodes = NULL;
9391                 }
9392         }
9393
9394         if (proargnames && *proargnames)
9395         {
9396                 int                     nitems = 0;
9397
9398                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9399                         nitems != nallargs)
9400                 {
9401                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9402                         if (argnames)
9403                                 free(argnames);
9404                         argnames = NULL;
9405                 }
9406         }
9407
9408         if (proconfig && *proconfig)
9409         {
9410                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9411                 {
9412                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9413                         if (configitems)
9414                                 free(configitems);
9415                         configitems = NULL;
9416                         nconfigitems = 0;
9417                 }
9418         }
9419
9420         if (funcargs)
9421         {
9422                 /* 8.4 or later; we rely on server-side code for most of the work */
9423                 funcfullsig = format_function_arguments(finfo, funcargs);
9424                 funcsig = format_function_arguments(finfo, funciargs);
9425         }
9426         else
9427         {
9428                 /* pre-8.4, do it ourselves */
9429                 funcsig = format_function_arguments_old(fout,
9430                                                                                                 finfo, nallargs, allargtypes,
9431                                                                                                 argmodes, argnames);
9432                 funcfullsig = funcsig;
9433         }
9434
9435         funcsig_tag = format_function_signature(fout, finfo, false);
9436
9437         /*
9438          * DROP must be fully qualified in case same name appears in pg_catalog
9439          */
9440         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9441                                           fmtId(finfo->dobj.namespace->dobj.name),
9442                                           funcsig);
9443
9444         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9445         if (funcresult)
9446                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9447         else
9448         {
9449                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9450                                                                                    zeroAsOpaque);
9451                 appendPQExpBuffer(q, "RETURNS %s%s",
9452                                                   (proretset[0] == 't') ? "SETOF " : "",
9453                                                   rettypename);
9454                 free(rettypename);
9455         }
9456
9457         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9458
9459         if (proiswindow[0] == 't')
9460                 appendPQExpBuffer(q, " WINDOW");
9461
9462         if (provolatile[0] != PROVOLATILE_VOLATILE)
9463         {
9464                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9465                         appendPQExpBuffer(q, " IMMUTABLE");
9466                 else if (provolatile[0] == PROVOLATILE_STABLE)
9467                         appendPQExpBuffer(q, " STABLE");
9468                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9469                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9470                                                   finfo->dobj.name);
9471         }
9472
9473         if (proisstrict[0] == 't')
9474                 appendPQExpBuffer(q, " STRICT");
9475
9476         if (prosecdef[0] == 't')
9477                 appendPQExpBuffer(q, " SECURITY DEFINER");
9478
9479         if (proleakproof[0] == 't')
9480                 appendPQExpBuffer(q, " LEAKPROOF");
9481
9482         /*
9483          * COST and ROWS are emitted only if present and not default, so as not to
9484          * break backwards-compatibility of the dump without need.      Keep this code
9485          * in sync with the defaults in functioncmds.c.
9486          */
9487         if (strcmp(procost, "0") != 0)
9488         {
9489                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9490                 {
9491                         /* default cost is 1 */
9492                         if (strcmp(procost, "1") != 0)
9493                                 appendPQExpBuffer(q, " COST %s", procost);
9494                 }
9495                 else
9496                 {
9497                         /* default cost is 100 */
9498                         if (strcmp(procost, "100") != 0)
9499                                 appendPQExpBuffer(q, " COST %s", procost);
9500                 }
9501         }
9502         if (proretset[0] == 't' &&
9503                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9504                 appendPQExpBuffer(q, " ROWS %s", prorows);
9505
9506         for (i = 0; i < nconfigitems; i++)
9507         {
9508                 /* we feel free to scribble on configitems[] here */
9509                 char       *configitem = configitems[i];
9510                 char       *pos;
9511
9512                 pos = strchr(configitem, '=');
9513                 if (pos == NULL)
9514                         continue;
9515                 *pos++ = '\0';
9516                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9517
9518                 /*
9519                  * Some GUC variable names are 'LIST' type and hence must not be
9520                  * quoted.
9521                  */
9522                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9523                         || pg_strcasecmp(configitem, "search_path") == 0)
9524                         appendPQExpBuffer(q, "%s", pos);
9525                 else
9526                         appendStringLiteralAH(q, pos, fout);
9527         }
9528
9529         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9530
9531         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9532
9533         if (binary_upgrade)
9534                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9535
9536         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9537                                  funcsig_tag,
9538                                  finfo->dobj.namespace->dobj.name,
9539                                  NULL,
9540                                  finfo->rolname, false,
9541                                  "FUNCTION", SECTION_PRE_DATA,
9542                                  q->data, delqry->data, NULL,
9543                                  NULL, 0,
9544                                  NULL, NULL);
9545
9546         /* Dump Function Comments and Security Labels */
9547         dumpComment(fout, labelq->data,
9548                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9549                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9550         dumpSecLabel(fout, labelq->data,
9551                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9552                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9553
9554         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9555                         funcsig, NULL, funcsig_tag,
9556                         finfo->dobj.namespace->dobj.name,
9557                         finfo->rolname, finfo->proacl);
9558
9559         PQclear(res);
9560
9561         destroyPQExpBuffer(query);
9562         destroyPQExpBuffer(q);
9563         destroyPQExpBuffer(delqry);
9564         destroyPQExpBuffer(labelq);
9565         destroyPQExpBuffer(asPart);
9566         free(funcsig);
9567         free(funcsig_tag);
9568         if (allargtypes)
9569                 free(allargtypes);
9570         if (argmodes)
9571                 free(argmodes);
9572         if (argnames)
9573                 free(argnames);
9574         if (configitems)
9575                 free(configitems);
9576 }
9577
9578
9579 /*
9580  * Dump a user-defined cast
9581  */
9582 static void
9583 dumpCast(Archive *fout, CastInfo *cast)
9584 {
9585         PQExpBuffer defqry;
9586         PQExpBuffer delqry;
9587         PQExpBuffer labelq;
9588         FuncInfo   *funcInfo = NULL;
9589
9590         /* Skip if not to be dumped */
9591         if (!cast->dobj.dump || dataOnly)
9592                 return;
9593
9594         /* Cannot dump if we don't have the cast function's info */
9595         if (OidIsValid(cast->castfunc))
9596         {
9597                 funcInfo = findFuncByOid(cast->castfunc);
9598                 if (funcInfo == NULL)
9599                         return;
9600         }
9601
9602         /*
9603          * As per discussion we dump casts if one or more of the underlying
9604          * objects (the conversion function and the two data types) are not
9605          * builtin AND if all of the non-builtin objects are included in the dump.
9606          * Builtin meaning, the namespace name does not start with "pg_".
9607          *
9608          * However, for a cast that belongs to an extension, we must not use this
9609          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9610          */
9611         if (!cast->dobj.ext_member)
9612         {
9613                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9614                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9615
9616                 if (sourceInfo == NULL || targetInfo == NULL)
9617                         return;
9618
9619                 /*
9620                  * Skip this cast if all objects are from pg_
9621                  */
9622                 if ((funcInfo == NULL ||
9623                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9624                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9625                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9626                         return;
9627
9628                 /*
9629                  * Skip cast if function isn't from pg_ and is not to be dumped.
9630                  */
9631                 if (funcInfo &&
9632                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9633                         !funcInfo->dobj.dump)
9634                         return;
9635
9636                 /*
9637                  * Same for the source type
9638                  */
9639                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9640                         !sourceInfo->dobj.dump)
9641                         return;
9642
9643                 /*
9644                  * and the target type.
9645                  */
9646                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9647                         !targetInfo->dobj.dump)
9648                         return;
9649         }
9650
9651         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9652         selectSourceSchema(fout, "pg_catalog");
9653
9654         defqry = createPQExpBuffer();
9655         delqry = createPQExpBuffer();
9656         labelq = createPQExpBuffer();
9657
9658         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9659                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9660                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9661
9662         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9663                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9664                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9665
9666         switch (cast->castmethod)
9667         {
9668                 case COERCION_METHOD_BINARY:
9669                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9670                         break;
9671                 case COERCION_METHOD_INOUT:
9672                         appendPQExpBuffer(defqry, "WITH INOUT");
9673                         break;
9674                 case COERCION_METHOD_FUNCTION:
9675                         if (funcInfo)
9676                         {
9677                                 char       *fsig = format_function_signature(fout, funcInfo, true);
9678
9679                                 /*
9680                                  * Always qualify the function name, in case it is not in
9681                                  * pg_catalog schema (format_function_signature won't qualify
9682                                  * it).
9683                                  */
9684                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9685                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9686                                 free(fsig);
9687                         }
9688                         else
9689                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9690                         break;
9691                 default:
9692                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9693         }
9694
9695         if (cast->castcontext == 'a')
9696                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9697         else if (cast->castcontext == 'i')
9698                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9699         appendPQExpBuffer(defqry, ";\n");
9700
9701         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9702                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9703                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9704
9705         if (binary_upgrade)
9706                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9707
9708         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9709                                  labelq->data,
9710                                  "pg_catalog", NULL, "",
9711                                  false, "CAST", SECTION_PRE_DATA,
9712                                  defqry->data, delqry->data, NULL,
9713                                  NULL, 0,
9714                                  NULL, NULL);
9715
9716         /* Dump Cast Comments */
9717         dumpComment(fout, labelq->data,
9718                                 NULL, "",
9719                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9720
9721         destroyPQExpBuffer(defqry);
9722         destroyPQExpBuffer(delqry);
9723         destroyPQExpBuffer(labelq);
9724 }
9725
9726 /*
9727  * dumpOpr
9728  *        write out a single operator definition
9729  */
9730 static void
9731 dumpOpr(Archive *fout, OprInfo *oprinfo)
9732 {
9733         PQExpBuffer query;
9734         PQExpBuffer q;
9735         PQExpBuffer delq;
9736         PQExpBuffer labelq;
9737         PQExpBuffer oprid;
9738         PQExpBuffer details;
9739         const char *name;
9740         PGresult   *res;
9741         int                     i_oprkind;
9742         int                     i_oprcode;
9743         int                     i_oprleft;
9744         int                     i_oprright;
9745         int                     i_oprcom;
9746         int                     i_oprnegate;
9747         int                     i_oprrest;
9748         int                     i_oprjoin;
9749         int                     i_oprcanmerge;
9750         int                     i_oprcanhash;
9751         char       *oprkind;
9752         char       *oprcode;
9753         char       *oprleft;
9754         char       *oprright;
9755         char       *oprcom;
9756         char       *oprnegate;
9757         char       *oprrest;
9758         char       *oprjoin;
9759         char       *oprcanmerge;
9760         char       *oprcanhash;
9761
9762         /* Skip if not to be dumped */
9763         if (!oprinfo->dobj.dump || dataOnly)
9764                 return;
9765
9766         /*
9767          * some operators are invalid because they were the result of user
9768          * defining operators before commutators exist
9769          */
9770         if (!OidIsValid(oprinfo->oprcode))
9771                 return;
9772
9773         query = createPQExpBuffer();
9774         q = createPQExpBuffer();
9775         delq = createPQExpBuffer();
9776         labelq = createPQExpBuffer();
9777         oprid = createPQExpBuffer();
9778         details = createPQExpBuffer();
9779
9780         /* Make sure we are in proper schema so regoperator works correctly */
9781         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9782
9783         if (fout->remoteVersion >= 80300)
9784         {
9785                 appendPQExpBuffer(query, "SELECT oprkind, "
9786                                                   "oprcode::pg_catalog.regprocedure, "
9787                                                   "oprleft::pg_catalog.regtype, "
9788                                                   "oprright::pg_catalog.regtype, "
9789                                                   "oprcom::pg_catalog.regoperator, "
9790                                                   "oprnegate::pg_catalog.regoperator, "
9791                                                   "oprrest::pg_catalog.regprocedure, "
9792                                                   "oprjoin::pg_catalog.regprocedure, "
9793                                                   "oprcanmerge, oprcanhash "
9794                                                   "FROM pg_catalog.pg_operator "
9795                                                   "WHERE oid = '%u'::pg_catalog.oid",
9796                                                   oprinfo->dobj.catId.oid);
9797         }
9798         else if (fout->remoteVersion >= 70300)
9799         {
9800                 appendPQExpBuffer(query, "SELECT oprkind, "
9801                                                   "oprcode::pg_catalog.regprocedure, "
9802                                                   "oprleft::pg_catalog.regtype, "
9803                                                   "oprright::pg_catalog.regtype, "
9804                                                   "oprcom::pg_catalog.regoperator, "
9805                                                   "oprnegate::pg_catalog.regoperator, "
9806                                                   "oprrest::pg_catalog.regprocedure, "
9807                                                   "oprjoin::pg_catalog.regprocedure, "
9808                                                   "(oprlsortop != 0) AS oprcanmerge, "
9809                                                   "oprcanhash "
9810                                                   "FROM pg_catalog.pg_operator "
9811                                                   "WHERE oid = '%u'::pg_catalog.oid",
9812                                                   oprinfo->dobj.catId.oid);
9813         }
9814         else if (fout->remoteVersion >= 70100)
9815         {
9816                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9817                                                   "CASE WHEN oprleft = 0 THEN '-' "
9818                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9819                                                   "CASE WHEN oprright = 0 THEN '-' "
9820                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9821                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9822                                                   "(oprlsortop != 0) AS oprcanmerge, "
9823                                                   "oprcanhash "
9824                                                   "FROM pg_operator "
9825                                                   "WHERE oid = '%u'::oid",
9826                                                   oprinfo->dobj.catId.oid);
9827         }
9828         else
9829         {
9830                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9831                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9832                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9833                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9834                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9835                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9836                                                   "(oprlsortop != 0) AS oprcanmerge, "
9837                                                   "oprcanhash "
9838                                                   "FROM pg_operator "
9839                                                   "WHERE oid = '%u'::oid",
9840                                                   oprinfo->dobj.catId.oid);
9841         }
9842
9843         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9844
9845         i_oprkind = PQfnumber(res, "oprkind");
9846         i_oprcode = PQfnumber(res, "oprcode");
9847         i_oprleft = PQfnumber(res, "oprleft");
9848         i_oprright = PQfnumber(res, "oprright");
9849         i_oprcom = PQfnumber(res, "oprcom");
9850         i_oprnegate = PQfnumber(res, "oprnegate");
9851         i_oprrest = PQfnumber(res, "oprrest");
9852         i_oprjoin = PQfnumber(res, "oprjoin");
9853         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9854         i_oprcanhash = PQfnumber(res, "oprcanhash");
9855
9856         oprkind = PQgetvalue(res, 0, i_oprkind);
9857         oprcode = PQgetvalue(res, 0, i_oprcode);
9858         oprleft = PQgetvalue(res, 0, i_oprleft);
9859         oprright = PQgetvalue(res, 0, i_oprright);
9860         oprcom = PQgetvalue(res, 0, i_oprcom);
9861         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9862         oprrest = PQgetvalue(res, 0, i_oprrest);
9863         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9864         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9865         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9866
9867         appendPQExpBuffer(details, "    PROCEDURE = %s",
9868                                           convertRegProcReference(fout, oprcode));
9869
9870         appendPQExpBuffer(oprid, "%s (",
9871                                           oprinfo->dobj.name);
9872
9873         /*
9874          * right unary means there's a left arg and left unary means there's a
9875          * right arg
9876          */
9877         if (strcmp(oprkind, "r") == 0 ||
9878                 strcmp(oprkind, "b") == 0)
9879         {
9880                 if (fout->remoteVersion >= 70100)
9881                         name = oprleft;
9882                 else
9883                         name = fmtId(oprleft);
9884                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9885                 appendPQExpBuffer(oprid, "%s", name);
9886         }
9887         else
9888                 appendPQExpBuffer(oprid, "NONE");
9889
9890         if (strcmp(oprkind, "l") == 0 ||
9891                 strcmp(oprkind, "b") == 0)
9892         {
9893                 if (fout->remoteVersion >= 70100)
9894                         name = oprright;
9895                 else
9896                         name = fmtId(oprright);
9897                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9898                 appendPQExpBuffer(oprid, ", %s)", name);
9899         }
9900         else
9901                 appendPQExpBuffer(oprid, ", NONE)");
9902
9903         name = convertOperatorReference(fout, oprcom);
9904         if (name)
9905                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9906
9907         name = convertOperatorReference(fout, oprnegate);
9908         if (name)
9909                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9910
9911         if (strcmp(oprcanmerge, "t") == 0)
9912                 appendPQExpBuffer(details, ",\n    MERGES");
9913
9914         if (strcmp(oprcanhash, "t") == 0)
9915                 appendPQExpBuffer(details, ",\n    HASHES");
9916
9917         name = convertRegProcReference(fout, oprrest);
9918         if (name)
9919                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9920
9921         name = convertRegProcReference(fout, oprjoin);
9922         if (name)
9923                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9924
9925         /*
9926          * DROP must be fully qualified in case same name appears in pg_catalog
9927          */
9928         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9929                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9930                                           oprid->data);
9931
9932         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9933                                           oprinfo->dobj.name, details->data);
9934
9935         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9936
9937         if (binary_upgrade)
9938                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9939
9940         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9941                                  oprinfo->dobj.name,
9942                                  oprinfo->dobj.namespace->dobj.name,
9943                                  NULL,
9944                                  oprinfo->rolname,
9945                                  false, "OPERATOR", SECTION_PRE_DATA,
9946                                  q->data, delq->data, NULL,
9947                                  NULL, 0,
9948                                  NULL, NULL);
9949
9950         /* Dump Operator Comments */
9951         dumpComment(fout, labelq->data,
9952                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9953                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9954
9955         PQclear(res);
9956
9957         destroyPQExpBuffer(query);
9958         destroyPQExpBuffer(q);
9959         destroyPQExpBuffer(delq);
9960         destroyPQExpBuffer(labelq);
9961         destroyPQExpBuffer(oprid);
9962         destroyPQExpBuffer(details);
9963 }
9964
9965 /*
9966  * Convert a function reference obtained from pg_operator
9967  *
9968  * Returns what to print, or NULL if function references is InvalidOid
9969  *
9970  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9971  * argument-types part.  In prior versions, the input is a REGPROC display.
9972  */
9973 static const char *
9974 convertRegProcReference(Archive *fout, const char *proc)
9975 {
9976         /* In all cases "-" means a null reference */
9977         if (strcmp(proc, "-") == 0)
9978                 return NULL;
9979
9980         if (fout->remoteVersion >= 70300)
9981         {
9982                 char       *name;
9983                 char       *paren;
9984                 bool            inquote;
9985
9986                 name = pg_strdup(proc);
9987                 /* find non-double-quoted left paren */
9988                 inquote = false;
9989                 for (paren = name; *paren; paren++)
9990                 {
9991                         if (*paren == '(' && !inquote)
9992                         {
9993                                 *paren = '\0';
9994                                 break;
9995                         }
9996                         if (*paren == '"')
9997                                 inquote = !inquote;
9998                 }
9999                 return name;
10000         }
10001
10002         /* REGPROC before 7.3 does not quote its result */
10003         return fmtId(proc);
10004 }
10005
10006 /*
10007  * Convert an operator cross-reference obtained from pg_operator
10008  *
10009  * Returns what to print, or NULL to print nothing
10010  *
10011  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10012  * argument-types part, and add OPERATOR() decoration if the name is
10013  * schema-qualified.  In older versions, the input is just a numeric OID,
10014  * which we search our operator list for.
10015  */
10016 static const char *
10017 convertOperatorReference(Archive *fout, const char *opr)
10018 {
10019         OprInfo    *oprInfo;
10020
10021         /* In all cases "0" means a null reference */
10022         if (strcmp(opr, "0") == 0)
10023                 return NULL;
10024
10025         if (fout->remoteVersion >= 70300)
10026         {
10027                 char       *name;
10028                 char       *oname;
10029                 char       *ptr;
10030                 bool            inquote;
10031                 bool            sawdot;
10032
10033                 name = pg_strdup(opr);
10034                 /* find non-double-quoted left paren, and check for non-quoted dot */
10035                 inquote = false;
10036                 sawdot = false;
10037                 for (ptr = name; *ptr; ptr++)
10038                 {
10039                         if (*ptr == '"')
10040                                 inquote = !inquote;
10041                         else if (*ptr == '.' && !inquote)
10042                                 sawdot = true;
10043                         else if (*ptr == '(' && !inquote)
10044                         {
10045                                 *ptr = '\0';
10046                                 break;
10047                         }
10048                 }
10049                 /* If not schema-qualified, don't need to add OPERATOR() */
10050                 if (!sawdot)
10051                         return name;
10052                 oname = pg_malloc(strlen(name) + 11);
10053                 sprintf(oname, "OPERATOR(%s)", name);
10054                 free(name);
10055                 return oname;
10056         }
10057
10058         oprInfo = findOprByOid(atooid(opr));
10059         if (oprInfo == NULL)
10060         {
10061                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10062                                   opr);
10063                 return NULL;
10064         }
10065         return oprInfo->dobj.name;
10066 }
10067
10068 /*
10069  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10070  *
10071  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10072  * argument lists of these functions are predetermined.  Note that the
10073  * caller should ensure we are in the proper schema, because the results
10074  * are search path dependent!
10075  */
10076 static const char *
10077 convertTSFunction(Archive *fout, Oid funcOid)
10078 {
10079         char       *result;
10080         char            query[128];
10081         PGresult   *res;
10082
10083         snprintf(query, sizeof(query),
10084                          "SELECT '%u'::pg_catalog.regproc", funcOid);
10085         res = ExecuteSqlQueryForSingleRow(fout, query);
10086
10087         result = pg_strdup(PQgetvalue(res, 0, 0));
10088
10089         PQclear(res);
10090
10091         return result;
10092 }
10093
10094
10095 /*
10096  * dumpOpclass
10097  *        write out a single operator class definition
10098  */
10099 static void
10100 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10101 {
10102         PQExpBuffer query;
10103         PQExpBuffer q;
10104         PQExpBuffer delq;
10105         PQExpBuffer labelq;
10106         PGresult   *res;
10107         int                     ntups;
10108         int                     i_opcintype;
10109         int                     i_opckeytype;
10110         int                     i_opcdefault;
10111         int                     i_opcfamily;
10112         int                     i_opcfamilyname;
10113         int                     i_opcfamilynsp;
10114         int                     i_amname;
10115         int                     i_amopstrategy;
10116         int                     i_amopreqcheck;
10117         int                     i_amopopr;
10118         int                     i_sortfamily;
10119         int                     i_sortfamilynsp;
10120         int                     i_amprocnum;
10121         int                     i_amproc;
10122         int                     i_amproclefttype;
10123         int                     i_amprocrighttype;
10124         char       *opcintype;
10125         char       *opckeytype;
10126         char       *opcdefault;
10127         char       *opcfamily;
10128         char       *opcfamilyname;
10129         char       *opcfamilynsp;
10130         char       *amname;
10131         char       *amopstrategy;
10132         char       *amopreqcheck;
10133         char       *amopopr;
10134         char       *sortfamily;
10135         char       *sortfamilynsp;
10136         char       *amprocnum;
10137         char       *amproc;
10138         char       *amproclefttype;
10139         char       *amprocrighttype;
10140         bool            needComma;
10141         int                     i;
10142
10143         /* Skip if not to be dumped */
10144         if (!opcinfo->dobj.dump || dataOnly)
10145                 return;
10146
10147         /*
10148          * XXX currently we do not implement dumping of operator classes from
10149          * pre-7.3 databases.  This could be done but it seems not worth the
10150          * trouble.
10151          */
10152         if (fout->remoteVersion < 70300)
10153                 return;
10154
10155         query = createPQExpBuffer();
10156         q = createPQExpBuffer();
10157         delq = createPQExpBuffer();
10158         labelq = createPQExpBuffer();
10159
10160         /* Make sure we are in proper schema so regoperator works correctly */
10161         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10162
10163         /* Get additional fields from the pg_opclass row */
10164         if (fout->remoteVersion >= 80300)
10165         {
10166                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10167                                                   "opckeytype::pg_catalog.regtype, "
10168                                                   "opcdefault, opcfamily, "
10169                                                   "opfname AS opcfamilyname, "
10170                                                   "nspname AS opcfamilynsp, "
10171                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10172                                                   "FROM pg_catalog.pg_opclass c "
10173                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10174                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10175                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
10176                                                   opcinfo->dobj.catId.oid);
10177         }
10178         else
10179         {
10180                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10181                                                   "opckeytype::pg_catalog.regtype, "
10182                                                   "opcdefault, NULL AS opcfamily, "
10183                                                   "NULL AS opcfamilyname, "
10184                                                   "NULL AS opcfamilynsp, "
10185                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10186                                                   "FROM pg_catalog.pg_opclass "
10187                                                   "WHERE oid = '%u'::pg_catalog.oid",
10188                                                   opcinfo->dobj.catId.oid);
10189         }
10190
10191         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10192
10193         i_opcintype = PQfnumber(res, "opcintype");
10194         i_opckeytype = PQfnumber(res, "opckeytype");
10195         i_opcdefault = PQfnumber(res, "opcdefault");
10196         i_opcfamily = PQfnumber(res, "opcfamily");
10197         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10198         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10199         i_amname = PQfnumber(res, "amname");
10200
10201         opcintype = PQgetvalue(res, 0, i_opcintype);
10202         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10203         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10204         /* opcfamily will still be needed after we PQclear res */
10205         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10206         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10207         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10208         /* amname will still be needed after we PQclear res */
10209         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10210
10211         /*
10212          * DROP must be fully qualified in case same name appears in pg_catalog
10213          */
10214         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10215                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10216         appendPQExpBuffer(delq, ".%s",
10217                                           fmtId(opcinfo->dobj.name));
10218         appendPQExpBuffer(delq, " USING %s;\n",
10219                                           fmtId(amname));
10220
10221         /* Build the fixed portion of the CREATE command */
10222         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10223                                           fmtId(opcinfo->dobj.name));
10224         if (strcmp(opcdefault, "t") == 0)
10225                 appendPQExpBuffer(q, "DEFAULT ");
10226         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10227                                           opcintype,
10228                                           fmtId(amname));
10229         if (strlen(opcfamilyname) > 0 &&
10230                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10231                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10232         {
10233                 appendPQExpBuffer(q, " FAMILY ");
10234                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10235                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10236                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10237         }
10238         appendPQExpBuffer(q, " AS\n    ");
10239
10240         needComma = false;
10241
10242         if (strcmp(opckeytype, "-") != 0)
10243         {
10244                 appendPQExpBuffer(q, "STORAGE %s",
10245                                                   opckeytype);
10246                 needComma = true;
10247         }
10248
10249         PQclear(res);
10250
10251         /*
10252          * Now fetch and print the OPERATOR entries (pg_amop rows).
10253          *
10254          * Print only those opfamily members that are tied to the opclass by
10255          * pg_depend entries.
10256          *
10257          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10258          * older server's opclass in which it is used.  This is to avoid
10259          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10260          * older server and then reload into that old version.  This can go away
10261          * once 8.3 is so old as to not be of interest to anyone.
10262          */
10263         resetPQExpBuffer(query);
10264
10265         if (fout->remoteVersion >= 90100)
10266         {
10267                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10268                                                   "amopopr::pg_catalog.regoperator, "
10269                                                   "opfname AS sortfamily, "
10270                                                   "nspname AS sortfamilynsp "
10271                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10272                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10273                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10274                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10275                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10276                                                   "AND refobjid = '%u'::pg_catalog.oid "
10277                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10278                                                   "ORDER BY amopstrategy",
10279                                                   opcinfo->dobj.catId.oid,
10280                                                   opcfamily);
10281         }
10282         else if (fout->remoteVersion >= 80400)
10283         {
10284                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10285                                                   "amopopr::pg_catalog.regoperator, "
10286                                                   "NULL AS sortfamily, "
10287                                                   "NULL AS sortfamilynsp "
10288                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10289                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10290                                                   "AND refobjid = '%u'::pg_catalog.oid "
10291                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10292                                                   "AND objid = ao.oid "
10293                                                   "ORDER BY amopstrategy",
10294                                                   opcinfo->dobj.catId.oid);
10295         }
10296         else if (fout->remoteVersion >= 80300)
10297         {
10298                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10299                                                   "amopopr::pg_catalog.regoperator, "
10300                                                   "NULL AS sortfamily, "
10301                                                   "NULL AS sortfamilynsp "
10302                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10303                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10304                                                   "AND refobjid = '%u'::pg_catalog.oid "
10305                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10306                                                   "AND objid = ao.oid "
10307                                                   "ORDER BY amopstrategy",
10308                                                   opcinfo->dobj.catId.oid);
10309         }
10310         else
10311         {
10312                 /*
10313                  * Here, we print all entries since there are no opfamilies and hence
10314                  * no loose operators to worry about.
10315                  */
10316                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10317                                                   "amopopr::pg_catalog.regoperator, "
10318                                                   "NULL AS sortfamily, "
10319                                                   "NULL AS sortfamilynsp "
10320                                                   "FROM pg_catalog.pg_amop "
10321                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10322                                                   "ORDER BY amopstrategy",
10323                                                   opcinfo->dobj.catId.oid);
10324         }
10325
10326         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10327
10328         ntups = PQntuples(res);
10329
10330         i_amopstrategy = PQfnumber(res, "amopstrategy");
10331         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10332         i_amopopr = PQfnumber(res, "amopopr");
10333         i_sortfamily = PQfnumber(res, "sortfamily");
10334         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10335
10336         for (i = 0; i < ntups; i++)
10337         {
10338                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10339                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10340                 amopopr = PQgetvalue(res, i, i_amopopr);
10341                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10342                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10343
10344                 if (needComma)
10345                         appendPQExpBuffer(q, " ,\n    ");
10346
10347                 appendPQExpBuffer(q, "OPERATOR %s %s",
10348                                                   amopstrategy, amopopr);
10349
10350                 if (strlen(sortfamily) > 0)
10351                 {
10352                         appendPQExpBuffer(q, " FOR ORDER BY ");
10353                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10354                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10355                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10356                 }
10357
10358                 if (strcmp(amopreqcheck, "t") == 0)
10359                         appendPQExpBuffer(q, " RECHECK");
10360
10361                 needComma = true;
10362         }
10363
10364         PQclear(res);
10365
10366         /*
10367          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10368          *
10369          * Print only those opfamily members that are tied to the opclass by
10370          * pg_depend entries.
10371          *
10372          * We print the amproclefttype/amprocrighttype even though in most cases
10373          * the backend could deduce the right values, because of the corner case
10374          * of a btree sort support function for a cross-type comparison.  That's
10375          * only allowed in 9.2 and later, but for simplicity print them in all
10376          * versions that have the columns.
10377          */
10378         resetPQExpBuffer(query);
10379
10380         if (fout->remoteVersion >= 80300)
10381         {
10382                 appendPQExpBuffer(query, "SELECT amprocnum, "
10383                                                   "amproc::pg_catalog.regprocedure, "
10384                                                   "amproclefttype::pg_catalog.regtype, "
10385                                                   "amprocrighttype::pg_catalog.regtype "
10386                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10387                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10388                                                   "AND refobjid = '%u'::pg_catalog.oid "
10389                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10390                                                   "AND objid = ap.oid "
10391                                                   "ORDER BY amprocnum",
10392                                                   opcinfo->dobj.catId.oid);
10393         }
10394         else
10395         {
10396                 appendPQExpBuffer(query, "SELECT amprocnum, "
10397                                                   "amproc::pg_catalog.regprocedure, "
10398                                                   "'' AS amproclefttype, "
10399                                                   "'' AS amprocrighttype "
10400                                                   "FROM pg_catalog.pg_amproc "
10401                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10402                                                   "ORDER BY amprocnum",
10403                                                   opcinfo->dobj.catId.oid);
10404         }
10405
10406         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10407
10408         ntups = PQntuples(res);
10409
10410         i_amprocnum = PQfnumber(res, "amprocnum");
10411         i_amproc = PQfnumber(res, "amproc");
10412         i_amproclefttype = PQfnumber(res, "amproclefttype");
10413         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10414
10415         for (i = 0; i < ntups; i++)
10416         {
10417                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10418                 amproc = PQgetvalue(res, i, i_amproc);
10419                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10420                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10421
10422                 if (needComma)
10423                         appendPQExpBuffer(q, " ,\n    ");
10424
10425                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10426
10427                 if (*amproclefttype && *amprocrighttype)
10428                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10429
10430                 appendPQExpBuffer(q, " %s", amproc);
10431
10432                 needComma = true;
10433         }
10434
10435         PQclear(res);
10436
10437         appendPQExpBuffer(q, ";\n");
10438
10439         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10440                                           fmtId(opcinfo->dobj.name));
10441         appendPQExpBuffer(labelq, " USING %s",
10442                                           fmtId(amname));
10443
10444         if (binary_upgrade)
10445                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10446
10447         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10448                                  opcinfo->dobj.name,
10449                                  opcinfo->dobj.namespace->dobj.name,
10450                                  NULL,
10451                                  opcinfo->rolname,
10452                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10453                                  q->data, delq->data, NULL,
10454                                  NULL, 0,
10455                                  NULL, NULL);
10456
10457         /* Dump Operator Class Comments */
10458         dumpComment(fout, labelq->data,
10459                                 NULL, opcinfo->rolname,
10460                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10461
10462         free(amname);
10463         destroyPQExpBuffer(query);
10464         destroyPQExpBuffer(q);
10465         destroyPQExpBuffer(delq);
10466         destroyPQExpBuffer(labelq);
10467 }
10468
10469 /*
10470  * dumpOpfamily
10471  *        write out a single operator family definition
10472  *
10473  * Note: this also dumps any "loose" operator members that aren't bound to a
10474  * specific opclass within the opfamily.
10475  */
10476 static void
10477 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10478 {
10479         PQExpBuffer query;
10480         PQExpBuffer q;
10481         PQExpBuffer delq;
10482         PQExpBuffer labelq;
10483         PGresult   *res;
10484         PGresult   *res_ops;
10485         PGresult   *res_procs;
10486         int                     ntups;
10487         int                     i_amname;
10488         int                     i_amopstrategy;
10489         int                     i_amopreqcheck;
10490         int                     i_amopopr;
10491         int                     i_sortfamily;
10492         int                     i_sortfamilynsp;
10493         int                     i_amprocnum;
10494         int                     i_amproc;
10495         int                     i_amproclefttype;
10496         int                     i_amprocrighttype;
10497         char       *amname;
10498         char       *amopstrategy;
10499         char       *amopreqcheck;
10500         char       *amopopr;
10501         char       *sortfamily;
10502         char       *sortfamilynsp;
10503         char       *amprocnum;
10504         char       *amproc;
10505         char       *amproclefttype;
10506         char       *amprocrighttype;
10507         bool            needComma;
10508         int                     i;
10509
10510         /* Skip if not to be dumped */
10511         if (!opfinfo->dobj.dump || dataOnly)
10512                 return;
10513
10514         /*
10515          * We want to dump the opfamily only if (1) it contains "loose" operators
10516          * or functions, or (2) it contains an opclass with a different name or
10517          * owner.  Otherwise it's sufficient to let it be created during creation
10518          * of the contained opclass, and not dumping it improves portability of
10519          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10520          * that first.
10521          */
10522
10523         query = createPQExpBuffer();
10524         q = createPQExpBuffer();
10525         delq = createPQExpBuffer();
10526         labelq = createPQExpBuffer();
10527
10528         /* Make sure we are in proper schema so regoperator works correctly */
10529         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10530
10531         /*
10532          * Fetch only those opfamily members that are tied directly to the
10533          * opfamily by pg_depend entries.
10534          *
10535          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10536          * older server's opclass in which it is used.  This is to avoid
10537          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10538          * older server and then reload into that old version.  This can go away
10539          * once 8.3 is so old as to not be of interest to anyone.
10540          */
10541         if (fout->remoteVersion >= 90100)
10542         {
10543                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10544                                                   "amopopr::pg_catalog.regoperator, "
10545                                                   "opfname AS sortfamily, "
10546                                                   "nspname AS sortfamilynsp "
10547                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10548                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10549                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10550                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10551                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10552                                                   "AND refobjid = '%u'::pg_catalog.oid "
10553                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10554                                                   "ORDER BY amopstrategy",
10555                                                   opfinfo->dobj.catId.oid,
10556                                                   opfinfo->dobj.catId.oid);
10557         }
10558         else if (fout->remoteVersion >= 80400)
10559         {
10560                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10561                                                   "amopopr::pg_catalog.regoperator, "
10562                                                   "NULL AS sortfamily, "
10563                                                   "NULL AS sortfamilynsp "
10564                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10565                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10566                                                   "AND refobjid = '%u'::pg_catalog.oid "
10567                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10568                                                   "AND objid = ao.oid "
10569                                                   "ORDER BY amopstrategy",
10570                                                   opfinfo->dobj.catId.oid);
10571         }
10572         else
10573         {
10574                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10575                                                   "amopopr::pg_catalog.regoperator, "
10576                                                   "NULL AS sortfamily, "
10577                                                   "NULL AS sortfamilynsp "
10578                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10579                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10580                                                   "AND refobjid = '%u'::pg_catalog.oid "
10581                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10582                                                   "AND objid = ao.oid "
10583                                                   "ORDER BY amopstrategy",
10584                                                   opfinfo->dobj.catId.oid);
10585         }
10586
10587         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10588
10589         resetPQExpBuffer(query);
10590
10591         appendPQExpBuffer(query, "SELECT amprocnum, "
10592                                           "amproc::pg_catalog.regprocedure, "
10593                                           "amproclefttype::pg_catalog.regtype, "
10594                                           "amprocrighttype::pg_catalog.regtype "
10595                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10596                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10597                                           "AND refobjid = '%u'::pg_catalog.oid "
10598                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10599                                           "AND objid = ap.oid "
10600                                           "ORDER BY amprocnum",
10601                                           opfinfo->dobj.catId.oid);
10602
10603         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10604
10605         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10606         {
10607                 /* No loose members, so check contained opclasses */
10608                 resetPQExpBuffer(query);
10609
10610                 appendPQExpBuffer(query, "SELECT 1 "
10611                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10612                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10613                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10614                                                   "AND refobjid = f.oid "
10615                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10616                                                   "AND objid = c.oid "
10617                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10618                                                   "LIMIT 1",
10619                                                   opfinfo->dobj.catId.oid);
10620
10621                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10622
10623                 if (PQntuples(res) == 0)
10624                 {
10625                         /* no need to dump it, so bail out */
10626                         PQclear(res);
10627                         PQclear(res_ops);
10628                         PQclear(res_procs);
10629                         destroyPQExpBuffer(query);
10630                         destroyPQExpBuffer(q);
10631                         destroyPQExpBuffer(delq);
10632                         destroyPQExpBuffer(labelq);
10633                         return;
10634                 }
10635
10636                 PQclear(res);
10637         }
10638
10639         /* Get additional fields from the pg_opfamily row */
10640         resetPQExpBuffer(query);
10641
10642         appendPQExpBuffer(query, "SELECT "
10643          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10644                                           "FROM pg_catalog.pg_opfamily "
10645                                           "WHERE oid = '%u'::pg_catalog.oid",
10646                                           opfinfo->dobj.catId.oid);
10647
10648         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10649
10650         i_amname = PQfnumber(res, "amname");
10651
10652         /* amname will still be needed after we PQclear res */
10653         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10654
10655         /*
10656          * DROP must be fully qualified in case same name appears in pg_catalog
10657          */
10658         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10659                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10660         appendPQExpBuffer(delq, ".%s",
10661                                           fmtId(opfinfo->dobj.name));
10662         appendPQExpBuffer(delq, " USING %s;\n",
10663                                           fmtId(amname));
10664
10665         /* Build the fixed portion of the CREATE command */
10666         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10667                                           fmtId(opfinfo->dobj.name));
10668         appendPQExpBuffer(q, " USING %s;\n",
10669                                           fmtId(amname));
10670
10671         PQclear(res);
10672
10673         /* Do we need an ALTER to add loose members? */
10674         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10675         {
10676                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10677                                                   fmtId(opfinfo->dobj.name));
10678                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10679                                                   fmtId(amname));
10680
10681                 needComma = false;
10682
10683                 /*
10684                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10685                  */
10686                 ntups = PQntuples(res_ops);
10687
10688                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10689                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10690                 i_amopopr = PQfnumber(res_ops, "amopopr");
10691                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10692                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10693
10694                 for (i = 0; i < ntups; i++)
10695                 {
10696                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10697                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10698                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10699                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10700                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10701
10702                         if (needComma)
10703                                 appendPQExpBuffer(q, " ,\n    ");
10704
10705                         appendPQExpBuffer(q, "OPERATOR %s %s",
10706                                                           amopstrategy, amopopr);
10707
10708                         if (strlen(sortfamily) > 0)
10709                         {
10710                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10711                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10712                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10713                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10714                         }
10715
10716                         if (strcmp(amopreqcheck, "t") == 0)
10717                                 appendPQExpBuffer(q, " RECHECK");
10718
10719                         needComma = true;
10720                 }
10721
10722                 /*
10723                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10724                  */
10725                 ntups = PQntuples(res_procs);
10726
10727                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10728                 i_amproc = PQfnumber(res_procs, "amproc");
10729                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10730                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10731
10732                 for (i = 0; i < ntups; i++)
10733                 {
10734                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10735                         amproc = PQgetvalue(res_procs, i, i_amproc);
10736                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10737                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10738
10739                         if (needComma)
10740                                 appendPQExpBuffer(q, " ,\n    ");
10741
10742                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10743                                                           amprocnum, amproclefttype, amprocrighttype,
10744                                                           amproc);
10745
10746                         needComma = true;
10747                 }
10748
10749                 appendPQExpBuffer(q, ";\n");
10750         }
10751
10752         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10753                                           fmtId(opfinfo->dobj.name));
10754         appendPQExpBuffer(labelq, " USING %s",
10755                                           fmtId(amname));
10756
10757         if (binary_upgrade)
10758                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10759
10760         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10761                                  opfinfo->dobj.name,
10762                                  opfinfo->dobj.namespace->dobj.name,
10763                                  NULL,
10764                                  opfinfo->rolname,
10765                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10766                                  q->data, delq->data, NULL,
10767                                  NULL, 0,
10768                                  NULL, NULL);
10769
10770         /* Dump Operator Family Comments */
10771         dumpComment(fout, labelq->data,
10772                                 NULL, opfinfo->rolname,
10773                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10774
10775         free(amname);
10776         PQclear(res_ops);
10777         PQclear(res_procs);
10778         destroyPQExpBuffer(query);
10779         destroyPQExpBuffer(q);
10780         destroyPQExpBuffer(delq);
10781         destroyPQExpBuffer(labelq);
10782 }
10783
10784 /*
10785  * dumpCollation
10786  *        write out a single collation definition
10787  */
10788 static void
10789 dumpCollation(Archive *fout, CollInfo *collinfo)
10790 {
10791         PQExpBuffer query;
10792         PQExpBuffer q;
10793         PQExpBuffer delq;
10794         PQExpBuffer labelq;
10795         PGresult   *res;
10796         int                     i_collcollate;
10797         int                     i_collctype;
10798         const char *collcollate;
10799         const char *collctype;
10800
10801         /* Skip if not to be dumped */
10802         if (!collinfo->dobj.dump || dataOnly)
10803                 return;
10804
10805         query = createPQExpBuffer();
10806         q = createPQExpBuffer();
10807         delq = createPQExpBuffer();
10808         labelq = createPQExpBuffer();
10809
10810         /* Make sure we are in proper schema */
10811         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10812
10813         /* Get conversion-specific details */
10814         appendPQExpBuffer(query, "SELECT "
10815                                           "collcollate, "
10816                                           "collctype "
10817                                           "FROM pg_catalog.pg_collation c "
10818                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10819                                           collinfo->dobj.catId.oid);
10820
10821         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10822
10823         i_collcollate = PQfnumber(res, "collcollate");
10824         i_collctype = PQfnumber(res, "collctype");
10825
10826         collcollate = PQgetvalue(res, 0, i_collcollate);
10827         collctype = PQgetvalue(res, 0, i_collctype);
10828
10829         /*
10830          * DROP must be fully qualified in case same name appears in pg_catalog
10831          */
10832         appendPQExpBuffer(delq, "DROP COLLATION %s",
10833                                           fmtId(collinfo->dobj.namespace->dobj.name));
10834         appendPQExpBuffer(delq, ".%s;\n",
10835                                           fmtId(collinfo->dobj.name));
10836
10837         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10838                                           fmtId(collinfo->dobj.name));
10839         appendStringLiteralAH(q, collcollate, fout);
10840         appendPQExpBuffer(q, ", lc_ctype = ");
10841         appendStringLiteralAH(q, collctype, fout);
10842         appendPQExpBuffer(q, ");\n");
10843
10844         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10845
10846         if (binary_upgrade)
10847                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10848
10849         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10850                                  collinfo->dobj.name,
10851                                  collinfo->dobj.namespace->dobj.name,
10852                                  NULL,
10853                                  collinfo->rolname,
10854                                  false, "COLLATION", SECTION_PRE_DATA,
10855                                  q->data, delq->data, NULL,
10856                                  NULL, 0,
10857                                  NULL, NULL);
10858
10859         /* Dump Collation Comments */
10860         dumpComment(fout, labelq->data,
10861                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10862                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10863
10864         PQclear(res);
10865
10866         destroyPQExpBuffer(query);
10867         destroyPQExpBuffer(q);
10868         destroyPQExpBuffer(delq);
10869         destroyPQExpBuffer(labelq);
10870 }
10871
10872 /*
10873  * dumpConversion
10874  *        write out a single conversion definition
10875  */
10876 static void
10877 dumpConversion(Archive *fout, ConvInfo *convinfo)
10878 {
10879         PQExpBuffer query;
10880         PQExpBuffer q;
10881         PQExpBuffer delq;
10882         PQExpBuffer labelq;
10883         PGresult   *res;
10884         int                     i_conforencoding;
10885         int                     i_contoencoding;
10886         int                     i_conproc;
10887         int                     i_condefault;
10888         const char *conforencoding;
10889         const char *contoencoding;
10890         const char *conproc;
10891         bool            condefault;
10892
10893         /* Skip if not to be dumped */
10894         if (!convinfo->dobj.dump || dataOnly)
10895                 return;
10896
10897         query = createPQExpBuffer();
10898         q = createPQExpBuffer();
10899         delq = createPQExpBuffer();
10900         labelq = createPQExpBuffer();
10901
10902         /* Make sure we are in proper schema */
10903         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10904
10905         /* Get conversion-specific details */
10906         appendPQExpBuffer(query, "SELECT "
10907                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10908                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10909                                           "conproc, condefault "
10910                                           "FROM pg_catalog.pg_conversion c "
10911                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10912                                           convinfo->dobj.catId.oid);
10913
10914         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10915
10916         i_conforencoding = PQfnumber(res, "conforencoding");
10917         i_contoencoding = PQfnumber(res, "contoencoding");
10918         i_conproc = PQfnumber(res, "conproc");
10919         i_condefault = PQfnumber(res, "condefault");
10920
10921         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10922         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10923         conproc = PQgetvalue(res, 0, i_conproc);
10924         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10925
10926         /*
10927          * DROP must be fully qualified in case same name appears in pg_catalog
10928          */
10929         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10930                                           fmtId(convinfo->dobj.namespace->dobj.name));
10931         appendPQExpBuffer(delq, ".%s;\n",
10932                                           fmtId(convinfo->dobj.name));
10933
10934         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10935                                           (condefault) ? "DEFAULT " : "",
10936                                           fmtId(convinfo->dobj.name));
10937         appendStringLiteralAH(q, conforencoding, fout);
10938         appendPQExpBuffer(q, " TO ");
10939         appendStringLiteralAH(q, contoencoding, fout);
10940         /* regproc is automatically quoted in 7.3 and above */
10941         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10942
10943         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10944
10945         if (binary_upgrade)
10946                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10947
10948         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10949                                  convinfo->dobj.name,
10950                                  convinfo->dobj.namespace->dobj.name,
10951                                  NULL,
10952                                  convinfo->rolname,
10953                                  false, "CONVERSION", SECTION_PRE_DATA,
10954                                  q->data, delq->data, NULL,
10955                                  NULL, 0,
10956                                  NULL, NULL);
10957
10958         /* Dump Conversion Comments */
10959         dumpComment(fout, labelq->data,
10960                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10961                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10962
10963         PQclear(res);
10964
10965         destroyPQExpBuffer(query);
10966         destroyPQExpBuffer(q);
10967         destroyPQExpBuffer(delq);
10968         destroyPQExpBuffer(labelq);
10969 }
10970
10971 /*
10972  * format_aggregate_signature: generate aggregate name and argument list
10973  *
10974  * The argument type names are qualified if needed.  The aggregate name
10975  * is never qualified.
10976  */
10977 static char *
10978 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10979 {
10980         PQExpBufferData buf;
10981         int                     j;
10982
10983         initPQExpBuffer(&buf);
10984         if (honor_quotes)
10985                 appendPQExpBuffer(&buf, "%s",
10986                                                   fmtId(agginfo->aggfn.dobj.name));
10987         else
10988                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10989
10990         if (agginfo->aggfn.nargs == 0)
10991                 appendPQExpBuffer(&buf, "(*)");
10992         else
10993         {
10994                 appendPQExpBuffer(&buf, "(");
10995                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10996                 {
10997                         char       *typname;
10998
10999                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11000                                                                                    zeroAsOpaque);
11001
11002                         appendPQExpBuffer(&buf, "%s%s",
11003                                                           (j > 0) ? ", " : "",
11004                                                           typname);
11005                         free(typname);
11006                 }
11007                 appendPQExpBuffer(&buf, ")");
11008         }
11009         return buf.data;
11010 }
11011
11012 /*
11013  * dumpAgg
11014  *        write out a single aggregate definition
11015  */
11016 static void
11017 dumpAgg(Archive *fout, AggInfo *agginfo)
11018 {
11019         PQExpBuffer query;
11020         PQExpBuffer q;
11021         PQExpBuffer delq;
11022         PQExpBuffer labelq;
11023         PQExpBuffer details;
11024         char       *aggsig;
11025         char       *aggsig_tag;
11026         PGresult   *res;
11027         int                     i_aggtransfn;
11028         int                     i_aggfinalfn;
11029         int                     i_aggsortop;
11030         int                     i_aggtranstype;
11031         int                     i_agginitval;
11032         int                     i_convertok;
11033         const char *aggtransfn;
11034         const char *aggfinalfn;
11035         const char *aggsortop;
11036         const char *aggtranstype;
11037         const char *agginitval;
11038         bool            convertok;
11039
11040         /* Skip if not to be dumped */
11041         if (!agginfo->aggfn.dobj.dump || dataOnly)
11042                 return;
11043
11044         query = createPQExpBuffer();
11045         q = createPQExpBuffer();
11046         delq = createPQExpBuffer();
11047         labelq = createPQExpBuffer();
11048         details = createPQExpBuffer();
11049
11050         /* Make sure we are in proper schema */
11051         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11052
11053         /* Get aggregate-specific details */
11054         if (fout->remoteVersion >= 80100)
11055         {
11056                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11057                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11058                                                   "aggsortop::pg_catalog.regoperator, "
11059                                                   "agginitval, "
11060                                                   "'t'::boolean AS convertok "
11061                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11062                                                   "WHERE a.aggfnoid = p.oid "
11063                                                   "AND p.oid = '%u'::pg_catalog.oid",
11064                                                   agginfo->aggfn.dobj.catId.oid);
11065         }
11066         else if (fout->remoteVersion >= 70300)
11067         {
11068                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11069                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11070                                                   "0 AS aggsortop, "
11071                                                   "agginitval, "
11072                                                   "'t'::boolean AS convertok "
11073                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11074                                                   "WHERE a.aggfnoid = p.oid "
11075                                                   "AND p.oid = '%u'::pg_catalog.oid",
11076                                                   agginfo->aggfn.dobj.catId.oid);
11077         }
11078         else if (fout->remoteVersion >= 70100)
11079         {
11080                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11081                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
11082                                                   "0 AS aggsortop, "
11083                                                   "agginitval, "
11084                                                   "'t'::boolean AS convertok "
11085                                                   "FROM pg_aggregate "
11086                                                   "WHERE oid = '%u'::oid",
11087                                                   agginfo->aggfn.dobj.catId.oid);
11088         }
11089         else
11090         {
11091                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11092                                                   "aggfinalfn, "
11093                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11094                                                   "0 AS aggsortop, "
11095                                                   "agginitval1 AS agginitval, "
11096                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11097                                                   "FROM pg_aggregate "
11098                                                   "WHERE oid = '%u'::oid",
11099                                                   agginfo->aggfn.dobj.catId.oid);
11100         }
11101
11102         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11103
11104         i_aggtransfn = PQfnumber(res, "aggtransfn");
11105         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11106         i_aggsortop = PQfnumber(res, "aggsortop");
11107         i_aggtranstype = PQfnumber(res, "aggtranstype");
11108         i_agginitval = PQfnumber(res, "agginitval");
11109         i_convertok = PQfnumber(res, "convertok");
11110
11111         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11112         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11113         aggsortop = PQgetvalue(res, 0, i_aggsortop);
11114         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11115         agginitval = PQgetvalue(res, 0, i_agginitval);
11116         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11117
11118         aggsig = format_aggregate_signature(agginfo, fout, true);
11119         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11120
11121         if (!convertok)
11122         {
11123                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11124                                   aggsig);
11125                 return;
11126         }
11127
11128         if (fout->remoteVersion >= 70300)
11129         {
11130                 /* If using 7.3's regproc or regtype, data is already quoted */
11131                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11132                                                   aggtransfn,
11133                                                   aggtranstype);
11134         }
11135         else if (fout->remoteVersion >= 70100)
11136         {
11137                 /* format_type quotes, regproc does not */
11138                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11139                                                   fmtId(aggtransfn),
11140                                                   aggtranstype);
11141         }
11142         else
11143         {
11144                 /* need quotes all around */
11145                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
11146                                                   fmtId(aggtransfn));
11147                 appendPQExpBuffer(details, "    STYPE = %s",
11148                                                   fmtId(aggtranstype));
11149         }
11150
11151         if (!PQgetisnull(res, 0, i_agginitval))
11152         {
11153                 appendPQExpBuffer(details, ",\n    INITCOND = ");
11154                 appendStringLiteralAH(details, agginitval, fout);
11155         }
11156
11157         if (strcmp(aggfinalfn, "-") != 0)
11158         {
11159                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
11160                                                   aggfinalfn);
11161         }
11162
11163         aggsortop = convertOperatorReference(fout, aggsortop);
11164         if (aggsortop)
11165         {
11166                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
11167                                                   aggsortop);
11168         }
11169
11170         /*
11171          * DROP must be fully qualified in case same name appears in pg_catalog
11172          */
11173         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11174                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11175                                           aggsig);
11176
11177         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11178                                           aggsig, details->data);
11179
11180         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11181
11182         if (binary_upgrade)
11183                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11184
11185         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11186                                  aggsig_tag,
11187                                  agginfo->aggfn.dobj.namespace->dobj.name,
11188                                  NULL,
11189                                  agginfo->aggfn.rolname,
11190                                  false, "AGGREGATE", SECTION_PRE_DATA,
11191                                  q->data, delq->data, NULL,
11192                                  NULL, 0,
11193                                  NULL, NULL);
11194
11195         /* Dump Aggregate Comments */
11196         dumpComment(fout, labelq->data,
11197                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11198                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11199         dumpSecLabel(fout, labelq->data,
11200                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11201                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11202
11203         /*
11204          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11205          * command look like a function's GRANT; in particular this affects the
11206          * syntax for zero-argument aggregates.
11207          */
11208         free(aggsig);
11209         free(aggsig_tag);
11210
11211         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11212         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11213
11214         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11215                         "FUNCTION",
11216                         aggsig, NULL, aggsig_tag,
11217                         agginfo->aggfn.dobj.namespace->dobj.name,
11218                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11219
11220         free(aggsig);
11221         free(aggsig_tag);
11222
11223         PQclear(res);
11224
11225         destroyPQExpBuffer(query);
11226         destroyPQExpBuffer(q);
11227         destroyPQExpBuffer(delq);
11228         destroyPQExpBuffer(labelq);
11229         destroyPQExpBuffer(details);
11230 }
11231
11232 /*
11233  * dumpTSParser
11234  *        write out a single text search parser
11235  */
11236 static void
11237 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11238 {
11239         PQExpBuffer q;
11240         PQExpBuffer delq;
11241         PQExpBuffer labelq;
11242
11243         /* Skip if not to be dumped */
11244         if (!prsinfo->dobj.dump || dataOnly)
11245                 return;
11246
11247         q = createPQExpBuffer();
11248         delq = createPQExpBuffer();
11249         labelq = createPQExpBuffer();
11250
11251         /* Make sure we are in proper schema */
11252         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11253
11254         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11255                                           fmtId(prsinfo->dobj.name));
11256
11257         appendPQExpBuffer(q, "    START = %s,\n",
11258                                           convertTSFunction(fout, prsinfo->prsstart));
11259         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11260                                           convertTSFunction(fout, prsinfo->prstoken));
11261         appendPQExpBuffer(q, "    END = %s,\n",
11262                                           convertTSFunction(fout, prsinfo->prsend));
11263         if (prsinfo->prsheadline != InvalidOid)
11264                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11265                                                   convertTSFunction(fout, prsinfo->prsheadline));
11266         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11267                                           convertTSFunction(fout, prsinfo->prslextype));
11268
11269         /*
11270          * DROP must be fully qualified in case same name appears in pg_catalog
11271          */
11272         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11273                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11274         appendPQExpBuffer(delq, ".%s;\n",
11275                                           fmtId(prsinfo->dobj.name));
11276
11277         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11278                                           fmtId(prsinfo->dobj.name));
11279
11280         if (binary_upgrade)
11281                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11282
11283         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11284                                  prsinfo->dobj.name,
11285                                  prsinfo->dobj.namespace->dobj.name,
11286                                  NULL,
11287                                  "",
11288                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11289                                  q->data, delq->data, NULL,
11290                                  NULL, 0,
11291                                  NULL, NULL);
11292
11293         /* Dump Parser Comments */
11294         dumpComment(fout, labelq->data,
11295                                 NULL, "",
11296                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11297
11298         destroyPQExpBuffer(q);
11299         destroyPQExpBuffer(delq);
11300         destroyPQExpBuffer(labelq);
11301 }
11302
11303 /*
11304  * dumpTSDictionary
11305  *        write out a single text search dictionary
11306  */
11307 static void
11308 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11309 {
11310         PQExpBuffer q;
11311         PQExpBuffer delq;
11312         PQExpBuffer labelq;
11313         PQExpBuffer query;
11314         PGresult   *res;
11315         char       *nspname;
11316         char       *tmplname;
11317
11318         /* Skip if not to be dumped */
11319         if (!dictinfo->dobj.dump || dataOnly)
11320                 return;
11321
11322         q = createPQExpBuffer();
11323         delq = createPQExpBuffer();
11324         labelq = createPQExpBuffer();
11325         query = createPQExpBuffer();
11326
11327         /* Fetch name and namespace of the dictionary's template */
11328         selectSourceSchema(fout, "pg_catalog");
11329         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11330                                           "FROM pg_ts_template p, pg_namespace n "
11331                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11332                                           dictinfo->dicttemplate);
11333         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11334         nspname = PQgetvalue(res, 0, 0);
11335         tmplname = PQgetvalue(res, 0, 1);
11336
11337         /* Make sure we are in proper schema */
11338         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11339
11340         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11341                                           fmtId(dictinfo->dobj.name));
11342
11343         appendPQExpBuffer(q, "    TEMPLATE = ");
11344         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11345                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11346         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11347
11348         PQclear(res);
11349
11350         /* the dictinitoption can be dumped straight into the command */
11351         if (dictinfo->dictinitoption)
11352                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11353
11354         appendPQExpBuffer(q, " );\n");
11355
11356         /*
11357          * DROP must be fully qualified in case same name appears in pg_catalog
11358          */
11359         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11360                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11361         appendPQExpBuffer(delq, ".%s;\n",
11362                                           fmtId(dictinfo->dobj.name));
11363
11364         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11365                                           fmtId(dictinfo->dobj.name));
11366
11367         if (binary_upgrade)
11368                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11369
11370         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11371                                  dictinfo->dobj.name,
11372                                  dictinfo->dobj.namespace->dobj.name,
11373                                  NULL,
11374                                  dictinfo->rolname,
11375                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11376                                  q->data, delq->data, NULL,
11377                                  NULL, 0,
11378                                  NULL, NULL);
11379
11380         /* Dump Dictionary Comments */
11381         dumpComment(fout, labelq->data,
11382                                 NULL, dictinfo->rolname,
11383                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11384
11385         destroyPQExpBuffer(q);
11386         destroyPQExpBuffer(delq);
11387         destroyPQExpBuffer(labelq);
11388         destroyPQExpBuffer(query);
11389 }
11390
11391 /*
11392  * dumpTSTemplate
11393  *        write out a single text search template
11394  */
11395 static void
11396 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11397 {
11398         PQExpBuffer q;
11399         PQExpBuffer delq;
11400         PQExpBuffer labelq;
11401
11402         /* Skip if not to be dumped */
11403         if (!tmplinfo->dobj.dump || dataOnly)
11404                 return;
11405
11406         q = createPQExpBuffer();
11407         delq = createPQExpBuffer();
11408         labelq = createPQExpBuffer();
11409
11410         /* Make sure we are in proper schema */
11411         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11412
11413         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11414                                           fmtId(tmplinfo->dobj.name));
11415
11416         if (tmplinfo->tmplinit != InvalidOid)
11417                 appendPQExpBuffer(q, "    INIT = %s,\n",
11418                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11419         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11420                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11421
11422         /*
11423          * DROP must be fully qualified in case same name appears in pg_catalog
11424          */
11425         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11426                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11427         appendPQExpBuffer(delq, ".%s;\n",
11428                                           fmtId(tmplinfo->dobj.name));
11429
11430         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11431                                           fmtId(tmplinfo->dobj.name));
11432
11433         if (binary_upgrade)
11434                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11435
11436         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11437                                  tmplinfo->dobj.name,
11438                                  tmplinfo->dobj.namespace->dobj.name,
11439                                  NULL,
11440                                  "",
11441                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11442                                  q->data, delq->data, NULL,
11443                                  NULL, 0,
11444                                  NULL, NULL);
11445
11446         /* Dump Template Comments */
11447         dumpComment(fout, labelq->data,
11448                                 NULL, "",
11449                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11450
11451         destroyPQExpBuffer(q);
11452         destroyPQExpBuffer(delq);
11453         destroyPQExpBuffer(labelq);
11454 }
11455
11456 /*
11457  * dumpTSConfig
11458  *        write out a single text search configuration
11459  */
11460 static void
11461 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11462 {
11463         PQExpBuffer q;
11464         PQExpBuffer delq;
11465         PQExpBuffer labelq;
11466         PQExpBuffer query;
11467         PGresult   *res;
11468         char       *nspname;
11469         char       *prsname;
11470         int                     ntups,
11471                                 i;
11472         int                     i_tokenname;
11473         int                     i_dictname;
11474
11475         /* Skip if not to be dumped */
11476         if (!cfginfo->dobj.dump || dataOnly)
11477                 return;
11478
11479         q = createPQExpBuffer();
11480         delq = createPQExpBuffer();
11481         labelq = createPQExpBuffer();
11482         query = createPQExpBuffer();
11483
11484         /* Fetch name and namespace of the config's parser */
11485         selectSourceSchema(fout, "pg_catalog");
11486         appendPQExpBuffer(query, "SELECT nspname, prsname "
11487                                           "FROM pg_ts_parser p, pg_namespace n "
11488                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11489                                           cfginfo->cfgparser);
11490         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11491         nspname = PQgetvalue(res, 0, 0);
11492         prsname = PQgetvalue(res, 0, 1);
11493
11494         /* Make sure we are in proper schema */
11495         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11496
11497         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11498                                           fmtId(cfginfo->dobj.name));
11499
11500         appendPQExpBuffer(q, "    PARSER = ");
11501         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11502                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11503         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11504
11505         PQclear(res);
11506
11507         resetPQExpBuffer(query);
11508         appendPQExpBuffer(query,
11509                                           "SELECT \n"
11510                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11511                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11512                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11513                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11514                                           "WHERE m.mapcfg = '%u' \n"
11515                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11516                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11517
11518         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11519         ntups = PQntuples(res);
11520
11521         i_tokenname = PQfnumber(res, "tokenname");
11522         i_dictname = PQfnumber(res, "dictname");
11523
11524         for (i = 0; i < ntups; i++)
11525         {
11526                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11527                 char       *dictname = PQgetvalue(res, i, i_dictname);
11528
11529                 if (i == 0 ||
11530                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11531                 {
11532                         /* starting a new token type, so start a new command */
11533                         if (i > 0)
11534                                 appendPQExpBuffer(q, ";\n");
11535                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11536                                                           fmtId(cfginfo->dobj.name));
11537                         /* tokenname needs quoting, dictname does NOT */
11538                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11539                                                           fmtId(tokenname), dictname);
11540                 }
11541                 else
11542                         appendPQExpBuffer(q, ", %s", dictname);
11543         }
11544
11545         if (ntups > 0)
11546                 appendPQExpBuffer(q, ";\n");
11547
11548         PQclear(res);
11549
11550         /*
11551          * DROP must be fully qualified in case same name appears in pg_catalog
11552          */
11553         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11554                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11555         appendPQExpBuffer(delq, ".%s;\n",
11556                                           fmtId(cfginfo->dobj.name));
11557
11558         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11559                                           fmtId(cfginfo->dobj.name));
11560
11561         if (binary_upgrade)
11562                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11563
11564         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11565                                  cfginfo->dobj.name,
11566                                  cfginfo->dobj.namespace->dobj.name,
11567                                  NULL,
11568                                  cfginfo->rolname,
11569                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11570                                  q->data, delq->data, NULL,
11571                                  NULL, 0,
11572                                  NULL, NULL);
11573
11574         /* Dump Configuration Comments */
11575         dumpComment(fout, labelq->data,
11576                                 NULL, cfginfo->rolname,
11577                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11578
11579         destroyPQExpBuffer(q);
11580         destroyPQExpBuffer(delq);
11581         destroyPQExpBuffer(labelq);
11582         destroyPQExpBuffer(query);
11583 }
11584
11585 /*
11586  * dumpForeignDataWrapper
11587  *        write out a single foreign-data wrapper definition
11588  */
11589 static void
11590 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11591 {
11592         PQExpBuffer q;
11593         PQExpBuffer delq;
11594         PQExpBuffer labelq;
11595         char       *qfdwname;
11596
11597         /* Skip if not to be dumped */
11598         if (!fdwinfo->dobj.dump || dataOnly)
11599                 return;
11600
11601         /*
11602          * FDWs that belong to an extension are dumped based on their "dump"
11603          * field. Otherwise omit them if we are only dumping some specific object.
11604          */
11605         if (!fdwinfo->dobj.ext_member)
11606                 if (!include_everything)
11607                         return;
11608
11609         q = createPQExpBuffer();
11610         delq = createPQExpBuffer();
11611         labelq = createPQExpBuffer();
11612
11613         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11614
11615         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11616                                           qfdwname);
11617
11618         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11619                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11620
11621         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11622                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11623
11624         if (strlen(fdwinfo->fdwoptions) > 0)
11625                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11626
11627         appendPQExpBuffer(q, ";\n");
11628
11629         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11630                                           qfdwname);
11631
11632         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11633                                           qfdwname);
11634
11635         if (binary_upgrade)
11636                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11637
11638         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11639                                  fdwinfo->dobj.name,
11640                                  NULL,
11641                                  NULL,
11642                                  fdwinfo->rolname,
11643                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11644                                  q->data, delq->data, NULL,
11645                                  NULL, 0,
11646                                  NULL, NULL);
11647
11648         /* Handle the ACL */
11649         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11650                         "FOREIGN DATA WRAPPER",
11651                         qfdwname, NULL, fdwinfo->dobj.name,
11652                         NULL, fdwinfo->rolname,
11653                         fdwinfo->fdwacl);
11654
11655         /* Dump Foreign Data Wrapper Comments */
11656         dumpComment(fout, labelq->data,
11657                                 NULL, fdwinfo->rolname,
11658                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11659
11660         free(qfdwname);
11661
11662         destroyPQExpBuffer(q);
11663         destroyPQExpBuffer(delq);
11664         destroyPQExpBuffer(labelq);
11665 }
11666
11667 /*
11668  * dumpForeignServer
11669  *        write out a foreign server definition
11670  */
11671 static void
11672 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11673 {
11674         PQExpBuffer q;
11675         PQExpBuffer delq;
11676         PQExpBuffer labelq;
11677         PQExpBuffer query;
11678         PGresult   *res;
11679         char       *qsrvname;
11680         char       *fdwname;
11681
11682         /* Skip if not to be dumped */
11683         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11684                 return;
11685
11686         q = createPQExpBuffer();
11687         delq = createPQExpBuffer();
11688         labelq = createPQExpBuffer();
11689         query = createPQExpBuffer();
11690
11691         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11692
11693         /* look up the foreign-data wrapper */
11694         selectSourceSchema(fout, "pg_catalog");
11695         appendPQExpBuffer(query, "SELECT fdwname "
11696                                           "FROM pg_foreign_data_wrapper w "
11697                                           "WHERE w.oid = '%u'",
11698                                           srvinfo->srvfdw);
11699         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11700         fdwname = PQgetvalue(res, 0, 0);
11701
11702         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11703         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11704         {
11705                 appendPQExpBuffer(q, " TYPE ");
11706                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11707         }
11708         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11709         {
11710                 appendPQExpBuffer(q, " VERSION ");
11711                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11712         }
11713
11714         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11715         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11716
11717         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11718                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11719
11720         appendPQExpBuffer(q, ";\n");
11721
11722         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11723                                           qsrvname);
11724
11725         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11726
11727         if (binary_upgrade)
11728                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11729
11730         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11731                                  srvinfo->dobj.name,
11732                                  NULL,
11733                                  NULL,
11734                                  srvinfo->rolname,
11735                                  false, "SERVER", SECTION_PRE_DATA,
11736                                  q->data, delq->data, NULL,
11737                                  NULL, 0,
11738                                  NULL, NULL);
11739
11740         /* Handle the ACL */
11741         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11742                         "FOREIGN SERVER",
11743                         qsrvname, NULL, srvinfo->dobj.name,
11744                         NULL, srvinfo->rolname,
11745                         srvinfo->srvacl);
11746
11747         /* Dump user mappings */
11748         dumpUserMappings(fout,
11749                                          srvinfo->dobj.name, NULL,
11750                                          srvinfo->rolname,
11751                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11752
11753         /* Dump Foreign Server Comments */
11754         dumpComment(fout, labelq->data,
11755                                 NULL, srvinfo->rolname,
11756                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11757
11758         free(qsrvname);
11759
11760         destroyPQExpBuffer(q);
11761         destroyPQExpBuffer(delq);
11762         destroyPQExpBuffer(labelq);
11763 }
11764
11765 /*
11766  * dumpUserMappings
11767  *
11768  * This routine is used to dump any user mappings associated with the
11769  * server handed to this routine. Should be called after ArchiveEntry()
11770  * for the server.
11771  */
11772 static void
11773 dumpUserMappings(Archive *fout,
11774                                  const char *servername, const char *namespace,
11775                                  const char *owner,
11776                                  CatalogId catalogId, DumpId dumpId)
11777 {
11778         PQExpBuffer q;
11779         PQExpBuffer delq;
11780         PQExpBuffer query;
11781         PQExpBuffer tag;
11782         PGresult   *res;
11783         int                     ntups;
11784         int                     i_usename;
11785         int                     i_umoptions;
11786         int                     i;
11787
11788         q = createPQExpBuffer();
11789         tag = createPQExpBuffer();
11790         delq = createPQExpBuffer();
11791         query = createPQExpBuffer();
11792
11793         /*
11794          * We read from the publicly accessible view pg_user_mappings, so as not
11795          * to fail if run by a non-superuser.  Note that the view will show
11796          * umoptions as null if the user hasn't got privileges for the associated
11797          * server; this means that pg_dump will dump such a mapping, but with no
11798          * OPTIONS clause.      A possible alternative is to skip such mappings
11799          * altogether, but it's not clear that that's an improvement.
11800          */
11801         selectSourceSchema(fout, "pg_catalog");
11802
11803         appendPQExpBuffer(query,
11804                                           "SELECT usename, "
11805                                           "array_to_string(ARRAY("
11806                                           "SELECT quote_ident(option_name) || ' ' || "
11807                                           "quote_literal(option_value) "
11808                                           "FROM pg_options_to_table(umoptions) "
11809                                           "ORDER BY option_name"
11810                                           "), E',\n    ') AS umoptions "
11811                                           "FROM pg_user_mappings "
11812                                           "WHERE srvid = '%u' "
11813                                           "ORDER BY usename",
11814                                           catalogId.oid);
11815
11816         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11817
11818         ntups = PQntuples(res);
11819         i_usename = PQfnumber(res, "usename");
11820         i_umoptions = PQfnumber(res, "umoptions");
11821
11822         for (i = 0; i < ntups; i++)
11823         {
11824                 char       *usename;
11825                 char       *umoptions;
11826
11827                 usename = PQgetvalue(res, i, i_usename);
11828                 umoptions = PQgetvalue(res, i, i_umoptions);
11829
11830                 resetPQExpBuffer(q);
11831                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11832                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11833
11834                 if (umoptions && strlen(umoptions) > 0)
11835                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11836
11837                 appendPQExpBuffer(q, ";\n");
11838
11839                 resetPQExpBuffer(delq);
11840                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11841                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11842
11843                 resetPQExpBuffer(tag);
11844                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11845                                                   usename, servername);
11846
11847                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11848                                          tag->data,
11849                                          namespace,
11850                                          NULL,
11851                                          owner, false,
11852                                          "USER MAPPING", SECTION_PRE_DATA,
11853                                          q->data, delq->data, NULL,
11854                                          &dumpId, 1,
11855                                          NULL, NULL);
11856         }
11857
11858         PQclear(res);
11859
11860         destroyPQExpBuffer(query);
11861         destroyPQExpBuffer(delq);
11862         destroyPQExpBuffer(q);
11863 }
11864
11865 /*
11866  * Write out default privileges information
11867  */
11868 static void
11869 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11870 {
11871         PQExpBuffer q;
11872         PQExpBuffer tag;
11873         const char *type;
11874
11875         /* Skip if not to be dumped */
11876         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11877                 return;
11878
11879         q = createPQExpBuffer();
11880         tag = createPQExpBuffer();
11881
11882         switch (daclinfo->defaclobjtype)
11883         {
11884                 case DEFACLOBJ_RELATION:
11885                         type = "TABLES";
11886                         break;
11887                 case DEFACLOBJ_SEQUENCE:
11888                         type = "SEQUENCES";
11889                         break;
11890                 case DEFACLOBJ_FUNCTION:
11891                         type = "FUNCTIONS";
11892                         break;
11893                 case DEFACLOBJ_TYPE:
11894                         type = "TYPES";
11895                         break;
11896                 default:
11897                         /* shouldn't get here */
11898                         exit_horribly(NULL,
11899                                                   "unrecognized object type in default privileges: %d\n",
11900                                                   (int) daclinfo->defaclobjtype);
11901                         type = "";                      /* keep compiler quiet */
11902         }
11903
11904         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11905
11906         /* build the actual command(s) for this tuple */
11907         if (!buildDefaultACLCommands(type,
11908                                                                  daclinfo->dobj.namespace != NULL ?
11909                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11910                                                                  daclinfo->defaclacl,
11911                                                                  daclinfo->defaclrole,
11912                                                                  fout->remoteVersion,
11913                                                                  q))
11914                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11915                                           daclinfo->defaclacl);
11916
11917         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11918                                  tag->data,
11919            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11920                                  NULL,
11921                                  daclinfo->defaclrole,
11922                                  false, "DEFAULT ACL", SECTION_POST_DATA,
11923                                  q->data, "", NULL,
11924                                  NULL, 0,
11925                                  NULL, NULL);
11926
11927         destroyPQExpBuffer(tag);
11928         destroyPQExpBuffer(q);
11929 }
11930
11931 /*----------
11932  * Write out grant/revoke information
11933  *
11934  * 'objCatId' is the catalog ID of the underlying object.
11935  * 'objDumpId' is the dump ID of the underlying object.
11936  * 'type' must be one of
11937  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11938  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11939  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11940  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11941  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11942  * 'nspname' is the namespace the object is in (NULL if none).
11943  * 'owner' is the owner, NULL if there is no owner (for languages).
11944  * 'acls' is the string read out of the fooacl system catalog field;
11945  *              it will be parsed here.
11946  *----------
11947  */
11948 static void
11949 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11950                 const char *type, const char *name, const char *subname,
11951                 const char *tag, const char *nspname, const char *owner,
11952                 const char *acls)
11953 {
11954         PQExpBuffer sql;
11955
11956         /* Do nothing if ACL dump is not enabled */
11957         if (aclsSkip)
11958                 return;
11959
11960         /* --data-only skips ACLs *except* BLOB ACLs */
11961         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11962                 return;
11963
11964         sql = createPQExpBuffer();
11965
11966         if (!buildACLCommands(name, subname, type, acls, owner,
11967                                                   "", fout->remoteVersion, sql))
11968                 exit_horribly(NULL,
11969                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11970                                           acls, name, type);
11971
11972         if (sql->len > 0)
11973                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11974                                          tag, nspname,
11975                                          NULL,
11976                                          owner ? owner : "",
11977                                          false, "ACL", SECTION_NONE,
11978                                          sql->data, "", NULL,
11979                                          &(objDumpId), 1,
11980                                          NULL, NULL);
11981
11982         destroyPQExpBuffer(sql);
11983 }
11984
11985 /*
11986  * dumpSecLabel
11987  *
11988  * This routine is used to dump any security labels associated with the
11989  * object handed to this routine. The routine takes a constant character
11990  * string for the target part of the security-label command, plus
11991  * the namespace and owner of the object (for labeling the ArchiveEntry),
11992  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11993  * plus the dump ID for the object (for setting a dependency).
11994  * If a matching pg_seclabel entry is found, it is dumped.
11995  *
11996  * Note: although this routine takes a dumpId for dependency purposes,
11997  * that purpose is just to mark the dependency in the emitted dump file
11998  * for possible future use by pg_restore.  We do NOT use it for determining
11999  * ordering of the label in the dump file, because this routine is called
12000  * after dependency sorting occurs.  This routine should be called just after
12001  * calling ArchiveEntry() for the specified object.
12002  */
12003 static void
12004 dumpSecLabel(Archive *fout, const char *target,
12005                          const char *namespace, const char *owner,
12006                          CatalogId catalogId, int subid, DumpId dumpId)
12007 {
12008         SecLabelItem *labels;
12009         int                     nlabels;
12010         int                     i;
12011         PQExpBuffer query;
12012
12013         /* do nothing, if --no-security-labels is supplied */
12014         if (no_security_labels)
12015                 return;
12016
12017         /* Comments are schema not data ... except blob comments are data */
12018         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12019         {
12020                 if (dataOnly)
12021                         return;
12022         }
12023         else
12024         {
12025                 if (schemaOnly)
12026                         return;
12027         }
12028
12029         /* Search for security labels associated with catalogId, using table */
12030         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12031
12032         query = createPQExpBuffer();
12033
12034         for (i = 0; i < nlabels; i++)
12035         {
12036                 /*
12037                  * Ignore label entries for which the subid doesn't match.
12038                  */
12039                 if (labels[i].objsubid != subid)
12040                         continue;
12041
12042                 appendPQExpBuffer(query,
12043                                                   "SECURITY LABEL FOR %s ON %s IS ",
12044                                                   fmtId(labels[i].provider), target);
12045                 appendStringLiteralAH(query, labels[i].label, fout);
12046                 appendPQExpBuffer(query, ";\n");
12047         }
12048
12049         if (query->len > 0)
12050         {
12051                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12052                                          target, namespace, NULL, owner,
12053                                          false, "SECURITY LABEL", SECTION_NONE,
12054                                          query->data, "", NULL,
12055                                          &(dumpId), 1,
12056                                          NULL, NULL);
12057         }
12058         destroyPQExpBuffer(query);
12059 }
12060
12061 /*
12062  * dumpTableSecLabel
12063  *
12064  * As above, but dump security label for both the specified table (or view)
12065  * and its columns.
12066  */
12067 static void
12068 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12069 {
12070         SecLabelItem *labels;
12071         int                     nlabels;
12072         int                     i;
12073         PQExpBuffer query;
12074         PQExpBuffer target;
12075
12076         /* do nothing, if --no-security-labels is supplied */
12077         if (no_security_labels)
12078                 return;
12079
12080         /* SecLabel are SCHEMA not data */
12081         if (dataOnly)
12082                 return;
12083
12084         /* Search for comments associated with relation, using table */
12085         nlabels = findSecLabels(fout,
12086                                                         tbinfo->dobj.catId.tableoid,
12087                                                         tbinfo->dobj.catId.oid,
12088                                                         &labels);
12089
12090         /* If security labels exist, build SECURITY LABEL statements */
12091         if (nlabels <= 0)
12092                 return;
12093
12094         query = createPQExpBuffer();
12095         target = createPQExpBuffer();
12096
12097         for (i = 0; i < nlabels; i++)
12098         {
12099                 const char *colname;
12100                 const char *provider = labels[i].provider;
12101                 const char *label = labels[i].label;
12102                 int                     objsubid = labels[i].objsubid;
12103
12104                 resetPQExpBuffer(target);
12105                 if (objsubid == 0)
12106                 {
12107                         appendPQExpBuffer(target, "%s %s", reltypename,
12108                                                           fmtId(tbinfo->dobj.name));
12109                 }
12110                 else
12111                 {
12112                         colname = getAttrName(objsubid, tbinfo);
12113                         /* first fmtId result must be consumed before calling it again */
12114                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12115                         appendPQExpBuffer(target, ".%s", fmtId(colname));
12116                 }
12117                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12118                                                   fmtId(provider), target->data);
12119                 appendStringLiteralAH(query, label, fout);
12120                 appendPQExpBuffer(query, ";\n");
12121         }
12122         if (query->len > 0)
12123         {
12124                 resetPQExpBuffer(target);
12125                 appendPQExpBuffer(target, "%s %s", reltypename,
12126                                                   fmtId(tbinfo->dobj.name));
12127                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12128                                          target->data,
12129                                          tbinfo->dobj.namespace->dobj.name,
12130                                          NULL, tbinfo->rolname,
12131                                          false, "SECURITY LABEL", SECTION_NONE,
12132                                          query->data, "", NULL,
12133                                          &(tbinfo->dobj.dumpId), 1,
12134                                          NULL, NULL);
12135         }
12136         destroyPQExpBuffer(query);
12137         destroyPQExpBuffer(target);
12138 }
12139
12140 /*
12141  * findSecLabels
12142  *
12143  * Find the security label(s), if any, associated with the given object.
12144  * All the objsubid values associated with the given classoid/objoid are
12145  * found with one search.
12146  */
12147 static int
12148 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12149 {
12150         /* static storage for table of security labels */
12151         static SecLabelItem *labels = NULL;
12152         static int      nlabels = -1;
12153
12154         SecLabelItem *middle = NULL;
12155         SecLabelItem *low;
12156         SecLabelItem *high;
12157         int                     nmatch;
12158
12159         /* Get security labels if we didn't already */
12160         if (nlabels < 0)
12161                 nlabels = collectSecLabels(fout, &labels);
12162
12163         if (nlabels <= 0)                       /* no labels, so no match is possible */
12164         {
12165                 *items = NULL;
12166                 return 0;
12167         }
12168
12169         /*
12170          * Do binary search to find some item matching the object.
12171          */
12172         low = &labels[0];
12173         high = &labels[nlabels - 1];
12174         while (low <= high)
12175         {
12176                 middle = low + (high - low) / 2;
12177
12178                 if (classoid < middle->classoid)
12179                         high = middle - 1;
12180                 else if (classoid > middle->classoid)
12181                         low = middle + 1;
12182                 else if (objoid < middle->objoid)
12183                         high = middle - 1;
12184                 else if (objoid > middle->objoid)
12185                         low = middle + 1;
12186                 else
12187                         break;                          /* found a match */
12188         }
12189
12190         if (low > high)                         /* no matches */
12191         {
12192                 *items = NULL;
12193                 return 0;
12194         }
12195
12196         /*
12197          * Now determine how many items match the object.  The search loop
12198          * invariant still holds: only items between low and high inclusive could
12199          * match.
12200          */
12201         nmatch = 1;
12202         while (middle > low)
12203         {
12204                 if (classoid != middle[-1].classoid ||
12205                         objoid != middle[-1].objoid)
12206                         break;
12207                 middle--;
12208                 nmatch++;
12209         }
12210
12211         *items = middle;
12212
12213         middle += nmatch;
12214         while (middle <= high)
12215         {
12216                 if (classoid != middle->classoid ||
12217                         objoid != middle->objoid)
12218                         break;
12219                 middle++;
12220                 nmatch++;
12221         }
12222
12223         return nmatch;
12224 }
12225
12226 /*
12227  * collectSecLabels
12228  *
12229  * Construct a table of all security labels available for database objects.
12230  * It's much faster to pull them all at once.
12231  *
12232  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12233  */
12234 static int
12235 collectSecLabels(Archive *fout, SecLabelItem **items)
12236 {
12237         PGresult   *res;
12238         PQExpBuffer query;
12239         int                     i_label;
12240         int                     i_provider;
12241         int                     i_classoid;
12242         int                     i_objoid;
12243         int                     i_objsubid;
12244         int                     ntups;
12245         int                     i;
12246         SecLabelItem *labels;
12247
12248         query = createPQExpBuffer();
12249
12250         appendPQExpBuffer(query,
12251                                           "SELECT label, provider, classoid, objoid, objsubid "
12252                                           "FROM pg_catalog.pg_seclabel "
12253                                           "ORDER BY classoid, objoid, objsubid");
12254
12255         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12256
12257         /* Construct lookup table containing OIDs in numeric form */
12258         i_label = PQfnumber(res, "label");
12259         i_provider = PQfnumber(res, "provider");
12260         i_classoid = PQfnumber(res, "classoid");
12261         i_objoid = PQfnumber(res, "objoid");
12262         i_objsubid = PQfnumber(res, "objsubid");
12263
12264         ntups = PQntuples(res);
12265
12266         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12267
12268         for (i = 0; i < ntups; i++)
12269         {
12270                 labels[i].label = PQgetvalue(res, i, i_label);
12271                 labels[i].provider = PQgetvalue(res, i, i_provider);
12272                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12273                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12274                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12275         }
12276
12277         /* Do NOT free the PGresult since we are keeping pointers into it */
12278         destroyPQExpBuffer(query);
12279
12280         *items = labels;
12281         return ntups;
12282 }
12283
12284 /*
12285  * dumpTable
12286  *        write out to fout the declarations (not data) of a user-defined table
12287  */
12288 static void
12289 dumpTable(Archive *fout, TableInfo *tbinfo)
12290 {
12291         if (tbinfo->dobj.dump && !dataOnly)
12292         {
12293                 char       *namecopy;
12294
12295                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12296                         dumpSequence(fout, tbinfo);
12297                 else
12298                         dumpTableSchema(fout, tbinfo);
12299
12300                 /* Handle the ACL here */
12301                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12302                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12303                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12304                                 "TABLE",
12305                                 namecopy, NULL, tbinfo->dobj.name,
12306                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12307                                 tbinfo->relacl);
12308
12309                 /*
12310                  * Handle column ACLs, if any.  Note: we pull these with a separate
12311                  * query rather than trying to fetch them during getTableAttrs, so
12312                  * that we won't miss ACLs on system columns.
12313                  */
12314                 if (fout->remoteVersion >= 80400)
12315                 {
12316                         PQExpBuffer query = createPQExpBuffer();
12317                         PGresult   *res;
12318                         int                     i;
12319
12320                         appendPQExpBuffer(query,
12321                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12322                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12323                                                           "ORDER BY attnum",
12324                                                           tbinfo->dobj.catId.oid);
12325                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12326
12327                         for (i = 0; i < PQntuples(res); i++)
12328                         {
12329                                 char       *attname = PQgetvalue(res, i, 0);
12330                                 char       *attacl = PQgetvalue(res, i, 1);
12331                                 char       *attnamecopy;
12332                                 char       *acltag;
12333
12334                                 attnamecopy = pg_strdup(fmtId(attname));
12335                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12336                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12337                                 /* Column's GRANT type is always TABLE */
12338                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12339                                                 namecopy, attnamecopy, acltag,
12340                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12341                                                 attacl);
12342                                 free(attnamecopy);
12343                                 free(acltag);
12344                         }
12345                         PQclear(res);
12346                         destroyPQExpBuffer(query);
12347                 }
12348
12349                 free(namecopy);
12350         }
12351 }
12352
12353 /*
12354  * dumpTableSchema
12355  *        write the declaration (not data) of one user-defined table or view
12356  */
12357 static void
12358 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12359 {
12360         PQExpBuffer query = createPQExpBuffer();
12361         PQExpBuffer q = createPQExpBuffer();
12362         PQExpBuffer delq = createPQExpBuffer();
12363         PQExpBuffer labelq = createPQExpBuffer();
12364         PGresult   *res;
12365         int                     numParents;
12366         TableInfo **parents;
12367         int                     actual_atts;    /* number of attrs in this CREATE statement */
12368         const char *reltypename;
12369         char       *storage;
12370         char       *srvname;
12371         char       *ftoptions;
12372         int                     j,
12373                                 k;
12374
12375         /* Make sure we are in proper schema */
12376         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12377
12378         if (binary_upgrade)
12379                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12380                                                                                                 tbinfo->dobj.catId.oid);
12381
12382         /* Is it a table or a view? */
12383         if (tbinfo->relkind == RELKIND_VIEW)
12384         {
12385                 char       *viewdef;
12386
12387                 reltypename = "VIEW";
12388
12389                 /* Fetch the view definition */
12390                 if (fout->remoteVersion >= 70300)
12391                 {
12392                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12393                         appendPQExpBuffer(query,
12394                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12395                                                           tbinfo->dobj.catId.oid);
12396                 }
12397                 else
12398                 {
12399                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12400                                                           "FROM pg_views WHERE viewname = ");
12401                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12402                         appendPQExpBuffer(query, ";");
12403                 }
12404
12405                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12406
12407                 if (PQntuples(res) != 1)
12408                 {
12409                         if (PQntuples(res) < 1)
12410                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12411                                                           tbinfo->dobj.name);
12412                         else
12413                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12414                                                           tbinfo->dobj.name);
12415                 }
12416
12417                 viewdef = PQgetvalue(res, 0, 0);
12418
12419                 if (strlen(viewdef) == 0)
12420                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12421                                                   tbinfo->dobj.name);
12422
12423                 /*
12424                  * DROP must be fully qualified in case same name appears in
12425                  * pg_catalog
12426                  */
12427                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12428                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12429                 appendPQExpBuffer(delq, "%s;\n",
12430                                                   fmtId(tbinfo->dobj.name));
12431
12432                 if (binary_upgrade)
12433                         binary_upgrade_set_pg_class_oids(fout, q,
12434                                                                                          tbinfo->dobj.catId.oid, false);
12435
12436                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12437                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12438                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12439                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12440
12441                 appendPQExpBuffer(labelq, "VIEW %s",
12442                                                   fmtId(tbinfo->dobj.name));
12443
12444                 PQclear(res);
12445         }
12446         else
12447         {
12448                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12449                 {
12450                         int                     i_srvname;
12451                         int                     i_ftoptions;
12452
12453                         reltypename = "FOREIGN TABLE";
12454
12455                         /* retrieve name of foreign server and generic options */
12456                         appendPQExpBuffer(query,
12457                                                           "SELECT fs.srvname, "
12458                                                           "pg_catalog.array_to_string(ARRAY("
12459                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12460                                                           "' ' || pg_catalog.quote_literal(option_value) "
12461                                                         "FROM pg_catalog.pg_options_to_table(ftoptions) "
12462                                                           "ORDER BY option_name"
12463                                                           "), E',\n    ') AS ftoptions "
12464                                                           "FROM pg_catalog.pg_foreign_table ft "
12465                                                           "JOIN pg_catalog.pg_foreign_server fs "
12466                                                           "ON (fs.oid = ft.ftserver) "
12467                                                           "WHERE ft.ftrelid = '%u'",
12468                                                           tbinfo->dobj.catId.oid);
12469                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12470                         i_srvname = PQfnumber(res, "srvname");
12471                         i_ftoptions = PQfnumber(res, "ftoptions");
12472                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12473                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12474                         PQclear(res);
12475                 }
12476                 else
12477                 {
12478                         reltypename = "TABLE";
12479                         srvname = NULL;
12480                         ftoptions = NULL;
12481                 }
12482                 numParents = tbinfo->numParents;
12483                 parents = tbinfo->parents;
12484
12485                 /*
12486                  * DROP must be fully qualified in case same name appears in
12487                  * pg_catalog
12488                  */
12489                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12490                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12491                 appendPQExpBuffer(delq, "%s;\n",
12492                                                   fmtId(tbinfo->dobj.name));
12493
12494                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12495                                                   fmtId(tbinfo->dobj.name));
12496
12497                 if (binary_upgrade)
12498                         binary_upgrade_set_pg_class_oids(fout, q,
12499                                                                                          tbinfo->dobj.catId.oid, false);
12500
12501                 appendPQExpBuffer(q, "CREATE %s%s %s",
12502                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12503                                                   "UNLOGGED " : "",
12504                                                   reltypename,
12505                                                   fmtId(tbinfo->dobj.name));
12506
12507                 /*
12508                  * Attach to type, if reloftype; except in case of a binary upgrade,
12509                  * we dump the table normally and attach it to the type afterward.
12510                  */
12511                 if (tbinfo->reloftype && !binary_upgrade)
12512                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12513
12514                 /* Dump the attributes */
12515                 actual_atts = 0;
12516                 for (j = 0; j < tbinfo->numatts; j++)
12517                 {
12518                         /*
12519                          * Normally, dump if it's locally defined in this table, and not
12520                          * dropped.  But for binary upgrade, we'll dump all the columns,
12521                          * and then fix up the dropped and nonlocal cases below.
12522                          */
12523                         if (shouldPrintColumn(tbinfo, j))
12524                         {
12525                                 /*
12526                                  * Default value --- suppress if to be printed separately.
12527                                  */
12528                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12529                                                                                    !tbinfo->attrdefs[j]->separate);
12530
12531                                 /*
12532                                  * Not Null constraint --- suppress if inherited, except in
12533                                  * binary-upgrade case where that won't work.
12534                                  */
12535                                 bool            has_notnull = (tbinfo->notnull[j] &&
12536                                                                                    (!tbinfo->inhNotNull[j] ||
12537                                                                                         binary_upgrade));
12538
12539                                 /* Skip column if fully defined by reloftype */
12540                                 if (tbinfo->reloftype &&
12541                                         !has_default && !has_notnull && !binary_upgrade)
12542                                         continue;
12543
12544                                 /* Format properly if not first attr */
12545                                 if (actual_atts == 0)
12546                                         appendPQExpBuffer(q, " (");
12547                                 else
12548                                         appendPQExpBuffer(q, ",");
12549                                 appendPQExpBuffer(q, "\n    ");
12550                                 actual_atts++;
12551
12552                                 /* Attribute name */
12553                                 appendPQExpBuffer(q, "%s ",
12554                                                                   fmtId(tbinfo->attnames[j]));
12555
12556                                 if (tbinfo->attisdropped[j])
12557                                 {
12558                                         /*
12559                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12560                                          * so we will not have gotten a valid type name; insert
12561                                          * INTEGER as a stopgap.  We'll clean things up later.
12562                                          */
12563                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12564                                         /* Skip all the rest, too */
12565                                         continue;
12566                                 }
12567
12568                                 /* Attribute type */
12569                                 if (tbinfo->reloftype && !binary_upgrade)
12570                                 {
12571                                         appendPQExpBuffer(q, "WITH OPTIONS");
12572                                 }
12573                                 else if (fout->remoteVersion >= 70100)
12574                                 {
12575                                         appendPQExpBuffer(q, "%s",
12576                                                                           tbinfo->atttypnames[j]);
12577                                 }
12578                                 else
12579                                 {
12580                                         /* If no format_type, fake it */
12581                                         appendPQExpBuffer(q, "%s",
12582                                                                           myFormatType(tbinfo->atttypnames[j],
12583                                                                                                    tbinfo->atttypmod[j]));
12584                                 }
12585
12586                                 /* Add collation if not default for the type */
12587                                 if (OidIsValid(tbinfo->attcollation[j]))
12588                                 {
12589                                         CollInfo   *coll;
12590
12591                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12592                                         if (coll)
12593                                         {
12594                                                 /* always schema-qualify, don't try to be smart */
12595                                                 appendPQExpBuffer(q, " COLLATE %s.",
12596                                                                          fmtId(coll->dobj.namespace->dobj.name));
12597                                                 appendPQExpBuffer(q, "%s",
12598                                                                                   fmtId(coll->dobj.name));
12599                                         }
12600                                 }
12601
12602                                 if (has_default)
12603                                         appendPQExpBuffer(q, " DEFAULT %s",
12604                                                                           tbinfo->attrdefs[j]->adef_expr);
12605
12606                                 if (has_notnull)
12607                                         appendPQExpBuffer(q, " NOT NULL");
12608                         }
12609                 }
12610
12611                 /*
12612                  * Add non-inherited CHECK constraints, if any.
12613                  */
12614                 for (j = 0; j < tbinfo->ncheck; j++)
12615                 {
12616                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12617
12618                         if (constr->separate || !constr->conislocal)
12619                                 continue;
12620
12621                         if (actual_atts == 0)
12622                                 appendPQExpBuffer(q, " (\n    ");
12623                         else
12624                                 appendPQExpBuffer(q, ",\n    ");
12625
12626                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12627                                                           fmtId(constr->dobj.name));
12628                         appendPQExpBuffer(q, "%s", constr->condef);
12629
12630                         actual_atts++;
12631                 }
12632
12633                 if (actual_atts)
12634                         appendPQExpBuffer(q, "\n)");
12635                 else if (!(tbinfo->reloftype && !binary_upgrade))
12636                 {
12637                         /*
12638                          * We must have a parenthesized attribute list, even though empty,
12639                          * when not using the OF TYPE syntax.
12640                          */
12641                         appendPQExpBuffer(q, " (\n)");
12642                 }
12643
12644                 if (numParents > 0 && !binary_upgrade)
12645                 {
12646                         appendPQExpBuffer(q, "\nINHERITS (");
12647                         for (k = 0; k < numParents; k++)
12648                         {
12649                                 TableInfo  *parentRel = parents[k];
12650
12651                                 if (k > 0)
12652                                         appendPQExpBuffer(q, ", ");
12653                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12654                                         appendPQExpBuffer(q, "%s.",
12655                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12656                                 appendPQExpBuffer(q, "%s",
12657                                                                   fmtId(parentRel->dobj.name));
12658                         }
12659                         appendPQExpBuffer(q, ")");
12660                 }
12661
12662                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12663                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12664
12665                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12666                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12667                 {
12668                         bool            addcomma = false;
12669
12670                         appendPQExpBuffer(q, "\nWITH (");
12671                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12672                         {
12673                                 addcomma = true;
12674                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12675                         }
12676                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12677                         {
12678                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12679                                                                   tbinfo->toast_reloptions);
12680                         }
12681                         appendPQExpBuffer(q, ")");
12682                 }
12683
12684                 /* Dump generic options if any */
12685                 if (ftoptions && ftoptions[0])
12686                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12687
12688                 appendPQExpBuffer(q, ";\n");
12689
12690                 /*
12691                  * To create binary-compatible heap files, we have to ensure the same
12692                  * physical column order, including dropped columns, as in the
12693                  * original.  Therefore, we create dropped columns above and drop them
12694                  * here, also updating their attlen/attalign values so that the
12695                  * dropped column can be skipped properly.      (We do not bother with
12696                  * restoring the original attbyval setting.)  Also, inheritance
12697                  * relationships are set up by doing ALTER INHERIT rather than using
12698                  * an INHERITS clause --- the latter would possibly mess up the column
12699                  * order.  That also means we have to take care about setting
12700                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12701                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12702                  */
12703                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12704                 {
12705                         for (j = 0; j < tbinfo->numatts; j++)
12706                         {
12707                                 if (tbinfo->attisdropped[j])
12708                                 {
12709                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12710                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12711                                                                           "SET attlen = %d, "
12712                                                                           "attalign = '%c', attbyval = false\n"
12713                                                                           "WHERE attname = ",
12714                                                                           tbinfo->attlen[j],
12715                                                                           tbinfo->attalign[j]);
12716                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12717                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12718                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12719                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12720
12721                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12722                                                                           fmtId(tbinfo->dobj.name));
12723                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12724                                                                           fmtId(tbinfo->attnames[j]));
12725                                 }
12726                                 else if (!tbinfo->attislocal[j])
12727                                 {
12728                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12729                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12730                                                                           "SET attislocal = false\n"
12731                                                                           "WHERE attname = ");
12732                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12733                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12734                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12735                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12736                                 }
12737                         }
12738
12739                         for (k = 0; k < tbinfo->ncheck; k++)
12740                         {
12741                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12742
12743                                 if (constr->separate || constr->conislocal)
12744                                         continue;
12745
12746                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12747                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12748                                                                   fmtId(tbinfo->dobj.name));
12749                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12750                                                                   fmtId(constr->dobj.name));
12751                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12752                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12753                                                                   "SET conislocal = false\n"
12754                                                                   "WHERE contype = 'c' AND conname = ");
12755                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12756                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12757                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12758                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12759                         }
12760
12761                         if (numParents > 0)
12762                         {
12763                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12764                                 for (k = 0; k < numParents; k++)
12765                                 {
12766                                         TableInfo  *parentRel = parents[k];
12767
12768                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12769                                                                           fmtId(tbinfo->dobj.name));
12770                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12771                                                 appendPQExpBuffer(q, "%s.",
12772                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12773                                         appendPQExpBuffer(q, "%s;\n",
12774                                                                           fmtId(parentRel->dobj.name));
12775                                 }
12776                         }
12777
12778                         if (tbinfo->reloftype)
12779                         {
12780                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12781                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12782                                                                   fmtId(tbinfo->dobj.name),
12783                                                                   tbinfo->reloftype);
12784                         }
12785
12786                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12787                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12788                                                           "SET relfrozenxid = '%u'\n"
12789                                                           "WHERE oid = ",
12790                                                           tbinfo->frozenxid);
12791                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12792                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12793
12794                         if (tbinfo->toast_oid)
12795                         {
12796                                 /* We preserve the toast oids, so we can use it during restore */
12797                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12798                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12799                                                                   "SET relfrozenxid = '%u'\n"
12800                                                                   "WHERE oid = '%u';\n",
12801                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12802                         }
12803                 }
12804
12805                 /*
12806                  * Dump additional per-column properties that we can't handle in the
12807                  * main CREATE TABLE command.
12808                  */
12809                 for (j = 0; j < tbinfo->numatts; j++)
12810                 {
12811                         /* None of this applies to dropped columns */
12812                         if (tbinfo->attisdropped[j])
12813                                 continue;
12814
12815                         /*
12816                          * If we didn't dump the column definition explicitly above, and
12817                          * it is NOT NULL and did not inherit that property from a parent,
12818                          * we have to mark it separately.
12819                          */
12820                         if (!shouldPrintColumn(tbinfo, j) &&
12821                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12822                         {
12823                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12824                                                                   fmtId(tbinfo->dobj.name));
12825                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12826                                                                   fmtId(tbinfo->attnames[j]));
12827                         }
12828
12829                         /*
12830                          * Dump per-column statistics information. We only issue an ALTER
12831                          * TABLE statement if the attstattarget entry for this column is
12832                          * non-negative (i.e. it's not the default value)
12833                          */
12834                         if (tbinfo->attstattarget[j] >= 0)
12835                         {
12836                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12837                                                                   fmtId(tbinfo->dobj.name));
12838                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12839                                                                   fmtId(tbinfo->attnames[j]));
12840                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12841                                                                   tbinfo->attstattarget[j]);
12842                         }
12843
12844                         /*
12845                          * Dump per-column storage information.  The statement is only
12846                          * dumped if the storage has been changed from the type's default.
12847                          */
12848                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12849                         {
12850                                 switch (tbinfo->attstorage[j])
12851                                 {
12852                                         case 'p':
12853                                                 storage = "PLAIN";
12854                                                 break;
12855                                         case 'e':
12856                                                 storage = "EXTERNAL";
12857                                                 break;
12858                                         case 'm':
12859                                                 storage = "MAIN";
12860                                                 break;
12861                                         case 'x':
12862                                                 storage = "EXTENDED";
12863                                                 break;
12864                                         default:
12865                                                 storage = NULL;
12866                                 }
12867
12868                                 /*
12869                                  * Only dump the statement if it's a storage type we recognize
12870                                  */
12871                                 if (storage != NULL)
12872                                 {
12873                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12874                                                                           fmtId(tbinfo->dobj.name));
12875                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12876                                                                           fmtId(tbinfo->attnames[j]));
12877                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12878                                                                           storage);
12879                                 }
12880                         }
12881
12882                         /*
12883                          * Dump per-column attributes.
12884                          */
12885                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12886                         {
12887                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12888                                                                   fmtId(tbinfo->dobj.name));
12889                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12890                                                                   fmtId(tbinfo->attnames[j]));
12891                                 appendPQExpBuffer(q, "SET (%s);\n",
12892                                                                   tbinfo->attoptions[j]);
12893                         }
12894
12895                         /*
12896                          * Dump per-column fdw options.
12897                          */
12898                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12899                                 tbinfo->attfdwoptions[j] &&
12900                                 tbinfo->attfdwoptions[j][0] != '\0')
12901                         {
12902                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12903                                                                   fmtId(tbinfo->dobj.name));
12904                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12905                                                                   fmtId(tbinfo->attnames[j]));
12906                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12907                                                                   tbinfo->attfdwoptions[j]);
12908                         }
12909                 }
12910         }
12911
12912         if (binary_upgrade)
12913                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12914
12915         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12916                                  tbinfo->dobj.name,
12917                                  tbinfo->dobj.namespace->dobj.name,
12918                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12919                                  tbinfo->rolname,
12920                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12921                                  reltypename, SECTION_PRE_DATA,
12922                                  q->data, delq->data, NULL,
12923                                  NULL, 0,
12924                                  NULL, NULL);
12925
12926
12927         /* Dump Table Comments */
12928         dumpTableComment(fout, tbinfo, reltypename);
12929
12930         /* Dump Table Security Labels */
12931         dumpTableSecLabel(fout, tbinfo, reltypename);
12932
12933         /* Dump comments on inlined table constraints */
12934         for (j = 0; j < tbinfo->ncheck; j++)
12935         {
12936                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12937
12938                 if (constr->separate || !constr->conislocal)
12939                         continue;
12940
12941                 dumpTableConstraintComment(fout, constr);
12942         }
12943
12944         destroyPQExpBuffer(query);
12945         destroyPQExpBuffer(q);
12946         destroyPQExpBuffer(delq);
12947         destroyPQExpBuffer(labelq);
12948 }
12949
12950 /*
12951  * dumpAttrDef --- dump an attribute's default-value declaration
12952  */
12953 static void
12954 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12955 {
12956         TableInfo  *tbinfo = adinfo->adtable;
12957         int                     adnum = adinfo->adnum;
12958         PQExpBuffer q;
12959         PQExpBuffer delq;
12960
12961         /* Skip if table definition not to be dumped */
12962         if (!tbinfo->dobj.dump || dataOnly)
12963                 return;
12964
12965         /* Skip if not "separate"; it was dumped in the table's definition */
12966         if (!adinfo->separate)
12967                 return;
12968
12969         q = createPQExpBuffer();
12970         delq = createPQExpBuffer();
12971
12972         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12973                                           fmtId(tbinfo->dobj.name));
12974         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12975                                           fmtId(tbinfo->attnames[adnum - 1]),
12976                                           adinfo->adef_expr);
12977
12978         /*
12979          * DROP must be fully qualified in case same name appears in pg_catalog
12980          */
12981         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12982                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12983         appendPQExpBuffer(delq, "%s ",
12984                                           fmtId(tbinfo->dobj.name));
12985         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12986                                           fmtId(tbinfo->attnames[adnum - 1]));
12987
12988         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12989                                  tbinfo->attnames[adnum - 1],
12990                                  tbinfo->dobj.namespace->dobj.name,
12991                                  NULL,
12992                                  tbinfo->rolname,
12993                                  false, "DEFAULT", SECTION_PRE_DATA,
12994                                  q->data, delq->data, NULL,
12995                                  NULL, 0,
12996                                  NULL, NULL);
12997
12998         destroyPQExpBuffer(q);
12999         destroyPQExpBuffer(delq);
13000 }
13001
13002 /*
13003  * getAttrName: extract the correct name for an attribute
13004  *
13005  * The array tblInfo->attnames[] only provides names of user attributes;
13006  * if a system attribute number is supplied, we have to fake it.
13007  * We also do a little bit of bounds checking for safety's sake.
13008  */
13009 static const char *
13010 getAttrName(int attrnum, TableInfo *tblInfo)
13011 {
13012         if (attrnum > 0 && attrnum <= tblInfo->numatts)
13013                 return tblInfo->attnames[attrnum - 1];
13014         switch (attrnum)
13015         {
13016                 case SelfItemPointerAttributeNumber:
13017                         return "ctid";
13018                 case ObjectIdAttributeNumber:
13019                         return "oid";
13020                 case MinTransactionIdAttributeNumber:
13021                         return "xmin";
13022                 case MinCommandIdAttributeNumber:
13023                         return "cmin";
13024                 case MaxTransactionIdAttributeNumber:
13025                         return "xmax";
13026                 case MaxCommandIdAttributeNumber:
13027                         return "cmax";
13028                 case TableOidAttributeNumber:
13029                         return "tableoid";
13030         }
13031         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13032                                   attrnum, tblInfo->dobj.name);
13033         return NULL;                            /* keep compiler quiet */
13034 }
13035
13036 /*
13037  * dumpIndex
13038  *        write out to fout a user-defined index
13039  */
13040 static void
13041 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13042 {
13043         TableInfo  *tbinfo = indxinfo->indextable;
13044         PQExpBuffer q;
13045         PQExpBuffer delq;
13046         PQExpBuffer labelq;
13047
13048         if (dataOnly)
13049                 return;
13050
13051         q = createPQExpBuffer();
13052         delq = createPQExpBuffer();
13053         labelq = createPQExpBuffer();
13054
13055         appendPQExpBuffer(labelq, "INDEX %s",
13056                                           fmtId(indxinfo->dobj.name));
13057
13058         /*
13059          * If there's an associated constraint, don't dump the index per se, but
13060          * do dump any comment for it.  (This is safe because dependency ordering
13061          * will have ensured the constraint is emitted first.)
13062          */
13063         if (indxinfo->indexconstraint == 0)
13064         {
13065                 if (binary_upgrade)
13066                         binary_upgrade_set_pg_class_oids(fout, q,
13067                                                                                          indxinfo->dobj.catId.oid, true);
13068
13069                 /* Plain secondary index */
13070                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13071
13072                 /* If the index is clustered, we need to record that. */
13073                 if (indxinfo->indisclustered)
13074                 {
13075                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13076                                                           fmtId(tbinfo->dobj.name));
13077                         appendPQExpBuffer(q, " ON %s;\n",
13078                                                           fmtId(indxinfo->dobj.name));
13079                 }
13080
13081                 /*
13082                  * DROP must be fully qualified in case same name appears in
13083                  * pg_catalog
13084                  */
13085                 appendPQExpBuffer(delq, "DROP INDEX %s.",
13086                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13087                 appendPQExpBuffer(delq, "%s;\n",
13088                                                   fmtId(indxinfo->dobj.name));
13089
13090                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13091                                          indxinfo->dobj.name,
13092                                          tbinfo->dobj.namespace->dobj.name,
13093                                          indxinfo->tablespace,
13094                                          tbinfo->rolname, false,
13095                                          "INDEX", SECTION_POST_DATA,
13096                                          q->data, delq->data, NULL,
13097                                          NULL, 0,
13098                                          NULL, NULL);
13099         }
13100
13101         /* Dump Index Comments */
13102         dumpComment(fout, labelq->data,
13103                                 tbinfo->dobj.namespace->dobj.name,
13104                                 tbinfo->rolname,
13105                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13106
13107         destroyPQExpBuffer(q);
13108         destroyPQExpBuffer(delq);
13109         destroyPQExpBuffer(labelq);
13110 }
13111
13112 /*
13113  * dumpConstraint
13114  *        write out to fout a user-defined constraint
13115  */
13116 static void
13117 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13118 {
13119         TableInfo  *tbinfo = coninfo->contable;
13120         PQExpBuffer q;
13121         PQExpBuffer delq;
13122
13123         /* Skip if not to be dumped */
13124         if (!coninfo->dobj.dump || dataOnly)
13125                 return;
13126
13127         q = createPQExpBuffer();
13128         delq = createPQExpBuffer();
13129
13130         if (coninfo->contype == 'p' ||
13131                 coninfo->contype == 'u' ||
13132                 coninfo->contype == 'x')
13133         {
13134                 /* Index-related constraint */
13135                 IndxInfo   *indxinfo;
13136                 int                     k;
13137
13138                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13139
13140                 if (indxinfo == NULL)
13141                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13142                                                   coninfo->dobj.name);
13143
13144                 if (binary_upgrade)
13145                         binary_upgrade_set_pg_class_oids(fout, q,
13146                                                                                          indxinfo->dobj.catId.oid, true);
13147
13148                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13149                                                   fmtId(tbinfo->dobj.name));
13150                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
13151                                                   fmtId(coninfo->dobj.name));
13152
13153                 if (coninfo->condef)
13154                 {
13155                         /* pg_get_constraintdef should have provided everything */
13156                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13157                 }
13158                 else
13159                 {
13160                         appendPQExpBuffer(q, "%s (",
13161                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13162                         for (k = 0; k < indxinfo->indnkeys; k++)
13163                         {
13164                                 int                     indkey = (int) indxinfo->indkeys[k];
13165                                 const char *attname;
13166
13167                                 if (indkey == InvalidAttrNumber)
13168                                         break;
13169                                 attname = getAttrName(indkey, tbinfo);
13170
13171                                 appendPQExpBuffer(q, "%s%s",
13172                                                                   (k == 0) ? "" : ", ",
13173                                                                   fmtId(attname));
13174                         }
13175
13176                         appendPQExpBuffer(q, ")");
13177
13178                         if (indxinfo->options && strlen(indxinfo->options) > 0)
13179                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13180
13181                         if (coninfo->condeferrable)
13182                         {
13183                                 appendPQExpBuffer(q, " DEFERRABLE");
13184                                 if (coninfo->condeferred)
13185                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
13186                         }
13187
13188                         appendPQExpBuffer(q, ";\n");
13189                 }
13190
13191                 /* If the index is clustered, we need to record that. */
13192                 if (indxinfo->indisclustered)
13193                 {
13194                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13195                                                           fmtId(tbinfo->dobj.name));
13196                         appendPQExpBuffer(q, " ON %s;\n",
13197                                                           fmtId(indxinfo->dobj.name));
13198                 }
13199
13200                 /*
13201                  * DROP must be fully qualified in case same name appears in
13202                  * pg_catalog
13203                  */
13204                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13205                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13206                 appendPQExpBuffer(delq, "%s ",
13207                                                   fmtId(tbinfo->dobj.name));
13208                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13209                                                   fmtId(coninfo->dobj.name));
13210
13211                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13212                                          coninfo->dobj.name,
13213                                          tbinfo->dobj.namespace->dobj.name,
13214                                          indxinfo->tablespace,
13215                                          tbinfo->rolname, false,
13216                                          "CONSTRAINT", SECTION_POST_DATA,
13217                                          q->data, delq->data, NULL,
13218                                          NULL, 0,
13219                                          NULL, NULL);
13220         }
13221         else if (coninfo->contype == 'f')
13222         {
13223                 /*
13224                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13225                  * current table data is not processed
13226                  */
13227                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13228                                                   fmtId(tbinfo->dobj.name));
13229                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13230                                                   fmtId(coninfo->dobj.name),
13231                                                   coninfo->condef);
13232
13233                 /*
13234                  * DROP must be fully qualified in case same name appears in
13235                  * pg_catalog
13236                  */
13237                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13238                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13239                 appendPQExpBuffer(delq, "%s ",
13240                                                   fmtId(tbinfo->dobj.name));
13241                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13242                                                   fmtId(coninfo->dobj.name));
13243
13244                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13245                                          coninfo->dobj.name,
13246                                          tbinfo->dobj.namespace->dobj.name,
13247                                          NULL,
13248                                          tbinfo->rolname, false,
13249                                          "FK CONSTRAINT", SECTION_POST_DATA,
13250                                          q->data, delq->data, NULL,
13251                                          NULL, 0,
13252                                          NULL, NULL);
13253         }
13254         else if (coninfo->contype == 'c' && tbinfo)
13255         {
13256                 /* CHECK constraint on a table */
13257
13258                 /* Ignore if not to be dumped separately */
13259                 if (coninfo->separate)
13260                 {
13261                         /* not ONLY since we want it to propagate to children */
13262                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13263                                                           fmtId(tbinfo->dobj.name));
13264                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13265                                                           fmtId(coninfo->dobj.name),
13266                                                           coninfo->condef);
13267
13268                         /*
13269                          * DROP must be fully qualified in case same name appears in
13270                          * pg_catalog
13271                          */
13272                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13273                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13274                         appendPQExpBuffer(delq, "%s ",
13275                                                           fmtId(tbinfo->dobj.name));
13276                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13277                                                           fmtId(coninfo->dobj.name));
13278
13279                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13280                                                  coninfo->dobj.name,
13281                                                  tbinfo->dobj.namespace->dobj.name,
13282                                                  NULL,
13283                                                  tbinfo->rolname, false,
13284                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13285                                                  q->data, delq->data, NULL,
13286                                                  NULL, 0,
13287                                                  NULL, NULL);
13288                 }
13289         }
13290         else if (coninfo->contype == 'c' && tbinfo == NULL)
13291         {
13292                 /* CHECK constraint on a domain */
13293                 TypeInfo   *tyinfo = coninfo->condomain;
13294
13295                 /* Ignore if not to be dumped separately */
13296                 if (coninfo->separate)
13297                 {
13298                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13299                                                           fmtId(tyinfo->dobj.name));
13300                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13301                                                           fmtId(coninfo->dobj.name),
13302                                                           coninfo->condef);
13303
13304                         /*
13305                          * DROP must be fully qualified in case same name appears in
13306                          * pg_catalog
13307                          */
13308                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13309                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13310                         appendPQExpBuffer(delq, "%s ",
13311                                                           fmtId(tyinfo->dobj.name));
13312                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13313                                                           fmtId(coninfo->dobj.name));
13314
13315                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13316                                                  coninfo->dobj.name,
13317                                                  tyinfo->dobj.namespace->dobj.name,
13318                                                  NULL,
13319                                                  tyinfo->rolname, false,
13320                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13321                                                  q->data, delq->data, NULL,
13322                                                  NULL, 0,
13323                                                  NULL, NULL);
13324                 }
13325         }
13326         else
13327         {
13328                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13329                                           coninfo->contype);
13330         }
13331
13332         /* Dump Constraint Comments --- only works for table constraints */
13333         if (tbinfo && coninfo->separate)
13334                 dumpTableConstraintComment(fout, coninfo);
13335
13336         destroyPQExpBuffer(q);
13337         destroyPQExpBuffer(delq);
13338 }
13339
13340 /*
13341  * dumpTableConstraintComment --- dump a constraint's comment if any
13342  *
13343  * This is split out because we need the function in two different places
13344  * depending on whether the constraint is dumped as part of CREATE TABLE
13345  * or as a separate ALTER command.
13346  */
13347 static void
13348 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13349 {
13350         TableInfo  *tbinfo = coninfo->contable;
13351         PQExpBuffer labelq = createPQExpBuffer();
13352
13353         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13354                                           fmtId(coninfo->dobj.name));
13355         appendPQExpBuffer(labelq, "ON %s",
13356                                           fmtId(tbinfo->dobj.name));
13357         dumpComment(fout, labelq->data,
13358                                 tbinfo->dobj.namespace->dobj.name,
13359                                 tbinfo->rolname,
13360                                 coninfo->dobj.catId, 0,
13361                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13362
13363         destroyPQExpBuffer(labelq);
13364 }
13365
13366 /*
13367  * findLastBuiltInOid -
13368  * find the last built in oid
13369  *
13370  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13371  * pg_database entry for the current database
13372  */
13373 static Oid
13374 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13375 {
13376         PGresult   *res;
13377         Oid                     last_oid;
13378         PQExpBuffer query = createPQExpBuffer();
13379
13380         resetPQExpBuffer(query);
13381         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13382         appendStringLiteralAH(query, dbname, fout);
13383
13384         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13385         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13386         PQclear(res);
13387         destroyPQExpBuffer(query);
13388         return last_oid;
13389 }
13390
13391 /*
13392  * findLastBuiltInOid -
13393  * find the last built in oid
13394  *
13395  * For 7.0, we do this by assuming that the last thing that initdb does is to
13396  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13397  * initdb won't be changing anymore, it'll do.
13398  */
13399 static Oid
13400 findLastBuiltinOid_V70(Archive *fout)
13401 {
13402         PGresult   *res;
13403         int                     last_oid;
13404
13405         res = ExecuteSqlQueryForSingleRow(fout,
13406                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13407         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13408         PQclear(res);
13409         return last_oid;
13410 }
13411
13412 /*
13413  * dumpSequence
13414  *        write the declaration (not data) of one user-defined sequence
13415  */
13416 static void
13417 dumpSequence(Archive *fout, TableInfo *tbinfo)
13418 {
13419         PGresult   *res;
13420         char       *startv,
13421                            *incby,
13422                            *maxv = NULL,
13423                            *minv = NULL,
13424                            *cache;
13425         char            bufm[100],
13426                                 bufx[100];
13427         bool            cycled;
13428         PQExpBuffer query = createPQExpBuffer();
13429         PQExpBuffer delqry = createPQExpBuffer();
13430         PQExpBuffer labelq = createPQExpBuffer();
13431
13432         /* Make sure we are in proper schema */
13433         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13434
13435         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13436         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13437
13438         if (fout->remoteVersion >= 80400)
13439         {
13440                 appendPQExpBuffer(query,
13441                                                   "SELECT sequence_name, "
13442                                                   "start_value, increment_by, "
13443                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13444                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13445                                                   "     ELSE max_value "
13446                                                   "END AS max_value, "
13447                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13448                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13449                                                   "     ELSE min_value "
13450                                                   "END AS min_value, "
13451                                                   "cache_value, is_cycled FROM %s",
13452                                                   bufx, bufm,
13453                                                   fmtId(tbinfo->dobj.name));
13454         }
13455         else
13456         {
13457                 appendPQExpBuffer(query,
13458                                                   "SELECT sequence_name, "
13459                                                   "0 AS start_value, increment_by, "
13460                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13461                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13462                                                   "     ELSE max_value "
13463                                                   "END AS max_value, "
13464                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13465                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13466                                                   "     ELSE min_value "
13467                                                   "END AS min_value, "
13468                                                   "cache_value, is_cycled FROM %s",
13469                                                   bufx, bufm,
13470                                                   fmtId(tbinfo->dobj.name));
13471         }
13472
13473         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13474
13475         if (PQntuples(res) != 1)
13476         {
13477                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13478                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13479                                                                  PQntuples(res)),
13480                                   tbinfo->dobj.name, PQntuples(res));
13481                 exit_nicely(1);
13482         }
13483
13484         /* Disable this check: it fails if sequence has been renamed */
13485 #ifdef NOT_USED
13486         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13487         {
13488                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13489                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13490                 exit_nicely(1);
13491         }
13492 #endif
13493
13494         startv = PQgetvalue(res, 0, 1);
13495         incby = PQgetvalue(res, 0, 2);
13496         if (!PQgetisnull(res, 0, 3))
13497                 maxv = PQgetvalue(res, 0, 3);
13498         if (!PQgetisnull(res, 0, 4))
13499                 minv = PQgetvalue(res, 0, 4);
13500         cache = PQgetvalue(res, 0, 5);
13501         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13502
13503         /*
13504          * DROP must be fully qualified in case same name appears in pg_catalog
13505          */
13506         appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13507                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13508         appendPQExpBuffer(delqry, "%s;\n",
13509                                           fmtId(tbinfo->dobj.name));
13510
13511         resetPQExpBuffer(query);
13512
13513         if (binary_upgrade)
13514         {
13515                 binary_upgrade_set_pg_class_oids(fout, query,
13516                                                                                  tbinfo->dobj.catId.oid, false);
13517                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13518                                                                                                 tbinfo->dobj.catId.oid);
13519         }
13520
13521         appendPQExpBuffer(query,
13522                                           "CREATE SEQUENCE %s\n",
13523                                           fmtId(tbinfo->dobj.name));
13524
13525         if (fout->remoteVersion >= 80400)
13526                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
13527
13528         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13529
13530         if (minv)
13531                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13532         else
13533                 appendPQExpBuffer(query, "    NO MINVALUE\n");
13534
13535         if (maxv)
13536                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13537         else
13538                 appendPQExpBuffer(query, "    NO MAXVALUE\n");
13539
13540         appendPQExpBuffer(query,
13541                                           "    CACHE %s%s",
13542                                           cache, (cycled ? "\n    CYCLE" : ""));
13543
13544         appendPQExpBuffer(query, ";\n");
13545
13546         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13547
13548         /* binary_upgrade:      no need to clear TOAST table oid */
13549
13550         if (binary_upgrade)
13551                 binary_upgrade_extension_member(query, &tbinfo->dobj,
13552                                                                                 labelq->data);
13553
13554         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13555                                  tbinfo->dobj.name,
13556                                  tbinfo->dobj.namespace->dobj.name,
13557                                  NULL,
13558                                  tbinfo->rolname,
13559                                  false, "SEQUENCE", SECTION_PRE_DATA,
13560                                  query->data, delqry->data, NULL,
13561                                  NULL, 0,
13562                                  NULL, NULL);
13563
13564         /*
13565          * If the sequence is owned by a table column, emit the ALTER for it as a
13566          * separate TOC entry immediately following the sequence's own entry.
13567          * It's OK to do this rather than using full sorting logic, because the
13568          * dependency that tells us it's owned will have forced the table to be
13569          * created first.  We can't just include the ALTER in the TOC entry
13570          * because it will fail if we haven't reassigned the sequence owner to
13571          * match the table's owner.
13572          *
13573          * We need not schema-qualify the table reference because both sequence
13574          * and table must be in the same schema.
13575          */
13576         if (OidIsValid(tbinfo->owning_tab))
13577         {
13578                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13579
13580                 if (owning_tab && owning_tab->dobj.dump)
13581                 {
13582                         resetPQExpBuffer(query);
13583                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13584                                                           fmtId(tbinfo->dobj.name));
13585                         appendPQExpBuffer(query, " OWNED BY %s",
13586                                                           fmtId(owning_tab->dobj.name));
13587                         appendPQExpBuffer(query, ".%s;\n",
13588                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13589
13590                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
13591                                                  tbinfo->dobj.name,
13592                                                  tbinfo->dobj.namespace->dobj.name,
13593                                                  NULL,
13594                                                  tbinfo->rolname,
13595                                                  false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13596                                                  query->data, "", NULL,
13597                                                  &(tbinfo->dobj.dumpId), 1,
13598                                                  NULL, NULL);
13599                 }
13600         }
13601
13602         /* Dump Sequence Comments and Security Labels */
13603         dumpComment(fout, labelq->data,
13604                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13605                                 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13606         dumpSecLabel(fout, labelq->data,
13607                                  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13608                                  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13609
13610         PQclear(res);
13611
13612         destroyPQExpBuffer(query);
13613         destroyPQExpBuffer(delqry);
13614         destroyPQExpBuffer(labelq);
13615 }
13616
13617 /*
13618  * dumpSequenceData
13619  *        write the data of one user-defined sequence
13620  */
13621 static void
13622 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
13623 {
13624         TableInfo  *tbinfo = tdinfo->tdtable;
13625         PGresult   *res;
13626         char       *last;
13627         bool            called;
13628         PQExpBuffer query = createPQExpBuffer();
13629
13630         /* Make sure we are in proper schema */
13631         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13632
13633         appendPQExpBuffer(query,
13634                                           "SELECT last_value, is_called FROM %s",
13635                                           fmtId(tbinfo->dobj.name));
13636
13637         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13638
13639         if (PQntuples(res) != 1)
13640         {
13641                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13642                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13643                                                                  PQntuples(res)),
13644                                   tbinfo->dobj.name, PQntuples(res));
13645                 exit_nicely(1);
13646         }
13647
13648         last = PQgetvalue(res, 0, 0);
13649         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
13650
13651         resetPQExpBuffer(query);
13652         appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13653         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13654         appendPQExpBuffer(query, ", %s, %s);\n",
13655                                           last, (called ? "true" : "false"));
13656
13657         ArchiveEntry(fout, nilCatalogId, createDumpId(),
13658                                  tbinfo->dobj.name,
13659                                  tbinfo->dobj.namespace->dobj.name,
13660                                  NULL,
13661                                  tbinfo->rolname,
13662                                  false, "SEQUENCE SET", SECTION_DATA,
13663                                  query->data, "", NULL,
13664                                  &(tbinfo->dobj.dumpId), 1,
13665                                  NULL, NULL);
13666
13667         PQclear(res);
13668
13669         destroyPQExpBuffer(query);
13670 }
13671
13672 static void
13673 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13674 {
13675         TableInfo  *tbinfo = tginfo->tgtable;
13676         PQExpBuffer query;
13677         PQExpBuffer delqry;
13678         PQExpBuffer labelq;
13679         char       *tgargs;
13680         size_t          lentgargs;
13681         const char *p;
13682         int                     findx;
13683
13684         if (dataOnly)
13685                 return;
13686
13687         query = createPQExpBuffer();
13688         delqry = createPQExpBuffer();
13689         labelq = createPQExpBuffer();
13690
13691         /*
13692          * DROP must be fully qualified in case same name appears in pg_catalog
13693          */
13694         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13695                                           fmtId(tginfo->dobj.name));
13696         appendPQExpBuffer(delqry, "ON %s.",
13697                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13698         appendPQExpBuffer(delqry, "%s;\n",
13699                                           fmtId(tbinfo->dobj.name));
13700
13701         if (tginfo->tgdef)
13702         {
13703                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13704         }
13705         else
13706         {
13707                 if (tginfo->tgisconstraint)
13708                 {
13709                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13710                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13711                 }
13712                 else
13713                 {
13714                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13715                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13716                 }
13717                 appendPQExpBuffer(query, "\n    ");
13718
13719                 /* Trigger type */
13720                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13721                         appendPQExpBuffer(query, "BEFORE");
13722                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13723                         appendPQExpBuffer(query, "AFTER");
13724                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13725                         appendPQExpBuffer(query, "INSTEAD OF");
13726                 else
13727                 {
13728                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13729                         exit_nicely(1);
13730                 }
13731
13732                 findx = 0;
13733                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13734                 {
13735                         appendPQExpBuffer(query, " INSERT");
13736                         findx++;
13737                 }
13738                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13739                 {
13740                         if (findx > 0)
13741                                 appendPQExpBuffer(query, " OR DELETE");
13742                         else
13743                                 appendPQExpBuffer(query, " DELETE");
13744                         findx++;
13745                 }
13746                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13747                 {
13748                         if (findx > 0)
13749                                 appendPQExpBuffer(query, " OR UPDATE");
13750                         else
13751                                 appendPQExpBuffer(query, " UPDATE");
13752                         findx++;
13753                 }
13754                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13755                 {
13756                         if (findx > 0)
13757                                 appendPQExpBuffer(query, " OR TRUNCATE");
13758                         else
13759                                 appendPQExpBuffer(query, " TRUNCATE");
13760                         findx++;
13761                 }
13762                 appendPQExpBuffer(query, " ON %s\n",
13763                                                   fmtId(tbinfo->dobj.name));
13764
13765                 if (tginfo->tgisconstraint)
13766                 {
13767                         if (OidIsValid(tginfo->tgconstrrelid))
13768                         {
13769                                 /* If we are using regclass, name is already quoted */
13770                                 if (fout->remoteVersion >= 70300)
13771                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13772                                                                           tginfo->tgconstrrelname);
13773                                 else
13774                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13775                                                                           fmtId(tginfo->tgconstrrelname));
13776                         }
13777                         if (!tginfo->tgdeferrable)
13778                                 appendPQExpBuffer(query, "NOT ");
13779                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13780                         if (tginfo->tginitdeferred)
13781                                 appendPQExpBuffer(query, "DEFERRED\n");
13782                         else
13783                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13784                 }
13785
13786                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13787                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13788                 else
13789                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13790
13791                 /* In 7.3, result of regproc is already quoted */
13792                 if (fout->remoteVersion >= 70300)
13793                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13794                                                           tginfo->tgfname);
13795                 else
13796                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13797                                                           fmtId(tginfo->tgfname));
13798
13799                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13800                                                                                   &lentgargs);
13801                 p = tgargs;
13802                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13803                 {
13804                         /* find the embedded null that terminates this trigger argument */
13805                         size_t          tlen = strlen(p);
13806
13807                         if (p + tlen >= tgargs + lentgargs)
13808                         {
13809                                 /* hm, not found before end of bytea value... */
13810                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13811                                                   tginfo->tgargs,
13812                                                   tginfo->dobj.name,
13813                                                   tbinfo->dobj.name);
13814                                 exit_nicely(1);
13815                         }
13816
13817                         if (findx > 0)
13818                                 appendPQExpBuffer(query, ", ");
13819                         appendStringLiteralAH(query, p, fout);
13820                         p += tlen + 1;
13821                 }
13822                 free(tgargs);
13823                 appendPQExpBuffer(query, ");\n");
13824         }
13825
13826         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13827         {
13828                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13829                                                   fmtId(tbinfo->dobj.name));
13830                 switch (tginfo->tgenabled)
13831                 {
13832                         case 'D':
13833                         case 'f':
13834                                 appendPQExpBuffer(query, "DISABLE");
13835                                 break;
13836                         case 'A':
13837                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13838                                 break;
13839                         case 'R':
13840                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13841                                 break;
13842                         default:
13843                                 appendPQExpBuffer(query, "ENABLE");
13844                                 break;
13845                 }
13846                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13847                                                   fmtId(tginfo->dobj.name));
13848         }
13849
13850         appendPQExpBuffer(labelq, "TRIGGER %s ",
13851                                           fmtId(tginfo->dobj.name));
13852         appendPQExpBuffer(labelq, "ON %s",
13853                                           fmtId(tbinfo->dobj.name));
13854
13855         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13856                                  tginfo->dobj.name,
13857                                  tbinfo->dobj.namespace->dobj.name,
13858                                  NULL,
13859                                  tbinfo->rolname, false,
13860                                  "TRIGGER", SECTION_POST_DATA,
13861                                  query->data, delqry->data, NULL,
13862                                  NULL, 0,
13863                                  NULL, NULL);
13864
13865         dumpComment(fout, labelq->data,
13866                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13867                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13868
13869         destroyPQExpBuffer(query);
13870         destroyPQExpBuffer(delqry);
13871         destroyPQExpBuffer(labelq);
13872 }
13873
13874 static void
13875 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
13876 {
13877         PQExpBuffer query;
13878         PQExpBuffer labelq;
13879
13880         query = createPQExpBuffer();
13881         labelq = createPQExpBuffer();
13882
13883         appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
13884         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
13885         appendPQExpBuffer(query, " ON ");
13886         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
13887         appendPQExpBufferStr(query, " ");
13888
13889         if (strcmp("", evtinfo->evttags) != 0)
13890         {
13891                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
13892                 appendPQExpBufferStr(query, evtinfo->evttags);
13893                 appendPQExpBufferStr(query, ") ");
13894         }
13895
13896         appendPQExpBuffer(query, "\n   EXECUTE PROCEDURE ");
13897         appendPQExpBufferStr(query, evtinfo->evtfname);
13898         appendPQExpBuffer(query, "();\n");
13899
13900         if (evtinfo->evtenabled != 'O')
13901         {
13902                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
13903                                                   fmtId(evtinfo->dobj.name));
13904                 switch (evtinfo->evtenabled)
13905                 {
13906                         case 'D':
13907                                 appendPQExpBuffer(query, "DISABLE");
13908                                 break;
13909                         case 'A':
13910                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13911                                 break;
13912                         case 'R':
13913                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13914                                 break;
13915                         default:
13916                                 appendPQExpBuffer(query, "ENABLE");
13917                                 break;
13918                 }
13919                 appendPQExpBuffer(query, ";\n");
13920         }
13921         appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
13922                                           fmtId(evtinfo->dobj.name));
13923
13924         ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
13925                                  evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
13926                                  "EVENT TRIGGER", SECTION_POST_DATA,
13927                                  query->data, "", NULL, NULL, 0, NULL, NULL);
13928
13929         dumpComment(fout, labelq->data,
13930                                 NULL, NULL,
13931                                 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
13932
13933         destroyPQExpBuffer(query);
13934         destroyPQExpBuffer(labelq);
13935 }
13936
13937 /*
13938  * dumpRule
13939  *              Dump a rule
13940  */
13941 static void
13942 dumpRule(Archive *fout, RuleInfo *rinfo)
13943 {
13944         TableInfo  *tbinfo = rinfo->ruletable;
13945         PQExpBuffer query;
13946         PQExpBuffer cmd;
13947         PQExpBuffer delcmd;
13948         PQExpBuffer labelq;
13949         PGresult   *res;
13950
13951         /* Skip if not to be dumped */
13952         if (!rinfo->dobj.dump || dataOnly)
13953                 return;
13954
13955         /*
13956          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13957          * we do not want to dump it as a separate object.
13958          */
13959         if (!rinfo->separate)
13960                 return;
13961
13962         /*
13963          * Make sure we are in proper schema.
13964          */
13965         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13966
13967         query = createPQExpBuffer();
13968         cmd = createPQExpBuffer();
13969         delcmd = createPQExpBuffer();
13970         labelq = createPQExpBuffer();
13971
13972         if (fout->remoteVersion >= 70300)
13973         {
13974                 appendPQExpBuffer(query,
13975                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13976                                                   rinfo->dobj.catId.oid);
13977         }
13978         else
13979         {
13980                 /* Rule name was unique before 7.3 ... */
13981                 appendPQExpBuffer(query,
13982                                                   "SELECT pg_get_ruledef('%s') AS definition",
13983                                                   rinfo->dobj.name);
13984         }
13985
13986         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13987
13988         if (PQntuples(res) != 1)
13989         {
13990                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13991                                   rinfo->dobj.name, tbinfo->dobj.name);
13992                 exit_nicely(1);
13993         }
13994
13995         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13996
13997         /*
13998          * Add the command to alter the rules replication firing semantics if it
13999          * differs from the default.
14000          */
14001         if (rinfo->ev_enabled != 'O')
14002         {
14003                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14004                 switch (rinfo->ev_enabled)
14005                 {
14006                         case 'A':
14007                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14008                                                                   fmtId(rinfo->dobj.name));
14009                                 break;
14010                         case 'R':
14011                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14012                                                                   fmtId(rinfo->dobj.name));
14013                                 break;
14014                         case 'D':
14015                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14016                                                                   fmtId(rinfo->dobj.name));
14017                                 break;
14018                 }
14019         }
14020
14021         /*
14022          * Apply view's reloptions when its ON SELECT rule is separate.
14023          */
14024         if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14025         {
14026                 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14027                                                   fmtId(tbinfo->dobj.name),
14028                                                   rinfo->reloptions);
14029         }
14030
14031         /*
14032          * DROP must be fully qualified in case same name appears in pg_catalog
14033          */
14034         appendPQExpBuffer(delcmd, "DROP RULE %s ",
14035                                           fmtId(rinfo->dobj.name));
14036         appendPQExpBuffer(delcmd, "ON %s.",
14037                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14038         appendPQExpBuffer(delcmd, "%s;\n",
14039                                           fmtId(tbinfo->dobj.name));
14040
14041         appendPQExpBuffer(labelq, "RULE %s",
14042                                           fmtId(rinfo->dobj.name));
14043         appendPQExpBuffer(labelq, " ON %s",
14044                                           fmtId(tbinfo->dobj.name));
14045
14046         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14047                                  rinfo->dobj.name,
14048                                  tbinfo->dobj.namespace->dobj.name,
14049                                  NULL,
14050                                  tbinfo->rolname, false,
14051                                  "RULE", SECTION_POST_DATA,
14052                                  cmd->data, delcmd->data, NULL,
14053                                  NULL, 0,
14054                                  NULL, NULL);
14055
14056         /* Dump rule comments */
14057         dumpComment(fout, labelq->data,
14058                                 tbinfo->dobj.namespace->dobj.name,
14059                                 tbinfo->rolname,
14060                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14061
14062         PQclear(res);
14063
14064         destroyPQExpBuffer(query);
14065         destroyPQExpBuffer(cmd);
14066         destroyPQExpBuffer(delcmd);
14067         destroyPQExpBuffer(labelq);
14068 }
14069
14070 /*
14071  * getExtensionMembership --- obtain extension membership data
14072  */
14073 void
14074 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14075                                            int numExtensions)
14076 {
14077         PQExpBuffer query;
14078         PGresult   *res;
14079         int                     ntups,
14080                                 i;
14081         int                     i_classid,
14082                                 i_objid,
14083                                 i_refclassid,
14084                                 i_refobjid;
14085         DumpableObject *dobj,
14086                            *refdobj;
14087
14088         /* Nothing to do if no extensions */
14089         if (numExtensions == 0)
14090                 return;
14091
14092         /* Make sure we are in proper schema */
14093         selectSourceSchema(fout, "pg_catalog");
14094
14095         query = createPQExpBuffer();
14096
14097         /* refclassid constraint is redundant but may speed the search */
14098         appendPQExpBuffer(query, "SELECT "
14099                                           "classid, objid, refclassid, refobjid "
14100                                           "FROM pg_depend "
14101                                           "WHERE refclassid = 'pg_extension'::regclass "
14102                                           "AND deptype = 'e' "
14103                                           "ORDER BY 3,4");
14104
14105         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14106
14107         ntups = PQntuples(res);
14108
14109         i_classid = PQfnumber(res, "classid");
14110         i_objid = PQfnumber(res, "objid");
14111         i_refclassid = PQfnumber(res, "refclassid");
14112         i_refobjid = PQfnumber(res, "refobjid");
14113
14114         /*
14115          * Since we ordered the SELECT by referenced ID, we can expect that
14116          * multiple entries for the same extension will appear together; this
14117          * saves on searches.
14118          */
14119         refdobj = NULL;
14120
14121         for (i = 0; i < ntups; i++)
14122         {
14123                 CatalogId       objId;
14124                 CatalogId       refobjId;
14125
14126                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14127                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14128                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14129                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14130
14131                 if (refdobj == NULL ||
14132                         refdobj->catId.tableoid != refobjId.tableoid ||
14133                         refdobj->catId.oid != refobjId.oid)
14134                         refdobj = findObjectByCatalogId(refobjId);
14135
14136                 /*
14137                  * Failure to find objects mentioned in pg_depend is not unexpected,
14138                  * since for example we don't collect info about TOAST tables.
14139                  */
14140                 if (refdobj == NULL)
14141                 {
14142 #ifdef NOT_USED
14143                         fprintf(stderr, "no referenced object %u %u\n",
14144                                         refobjId.tableoid, refobjId.oid);
14145 #endif
14146                         continue;
14147                 }
14148
14149                 dobj = findObjectByCatalogId(objId);
14150
14151                 if (dobj == NULL)
14152                 {
14153 #ifdef NOT_USED
14154                         fprintf(stderr, "no referencing object %u %u\n",
14155                                         objId.tableoid, objId.oid);
14156 #endif
14157                         continue;
14158                 }
14159
14160                 /* Record dependency so that getDependencies needn't repeat this */
14161                 addObjectDependency(dobj, refdobj->dumpId);
14162
14163                 dobj->ext_member = true;
14164
14165                 /*
14166                  * Normally, mark the member object as not to be dumped.  But in
14167                  * binary upgrades, we still dump the members individually, since the
14168                  * idea is to exactly reproduce the database contents rather than
14169                  * replace the extension contents with something different.
14170                  */
14171                 if (!binary_upgrade)
14172                         dobj->dump = false;
14173                 else
14174                         dobj->dump = refdobj->dump;
14175         }
14176
14177         PQclear(res);
14178
14179         /*
14180          * Now identify extension configuration tables and create TableDataInfo
14181          * objects for them, ensuring their data will be dumped even though the
14182          * tables themselves won't be.
14183          *
14184          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14185          * user data in a configuration table is treated like schema data. This
14186          * seems appropriate since system data in a config table would get
14187          * reloaded by CREATE EXTENSION.
14188          */
14189         for (i = 0; i < numExtensions; i++)
14190         {
14191                 ExtensionInfo *curext = &(extinfo[i]);
14192                 char       *extconfig = curext->extconfig;
14193                 char       *extcondition = curext->extcondition;
14194                 char      **extconfigarray = NULL;
14195                 char      **extconditionarray = NULL;
14196                 int                     nconfigitems;
14197                 int                     nconditionitems;
14198
14199                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14200                 if (!curext->dobj.dump)
14201                         continue;
14202
14203                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14204                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14205                         nconfigitems == nconditionitems)
14206                 {
14207                         int                     j;
14208
14209                         for (j = 0; j < nconfigitems; j++)
14210                         {
14211                                 TableInfo  *configtbl;
14212
14213                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
14214                                 if (configtbl == NULL)
14215                                         continue;
14216
14217                                 /*
14218                                  * Note: config tables are dumped without OIDs regardless of
14219                                  * the --oids setting.  This is because row filtering
14220                                  * conditions aren't compatible with dumping OIDs.
14221                                  */
14222                                 makeTableDataInfo(configtbl, false);
14223                                 if (configtbl->dataObj != NULL)
14224                                 {
14225                                         if (strlen(extconditionarray[j]) > 0)
14226                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14227                                 }
14228                         }
14229                 }
14230                 if (extconfigarray)
14231                         free(extconfigarray);
14232                 if (extconditionarray)
14233                         free(extconditionarray);
14234         }
14235
14236         destroyPQExpBuffer(query);
14237 }
14238
14239 /*
14240  * getDependencies --- obtain available dependency data
14241  */
14242 static void
14243 getDependencies(Archive *fout)
14244 {
14245         PQExpBuffer query;
14246         PGresult   *res;
14247         int                     ntups,
14248                                 i;
14249         int                     i_classid,
14250                                 i_objid,
14251                                 i_refclassid,
14252                                 i_refobjid,
14253                                 i_deptype;
14254         DumpableObject *dobj,
14255                            *refdobj;
14256
14257         /* No dependency info available before 7.3 */
14258         if (fout->remoteVersion < 70300)
14259                 return;
14260
14261         if (g_verbose)
14262                 write_msg(NULL, "reading dependency data\n");
14263
14264         /* Make sure we are in proper schema */
14265         selectSourceSchema(fout, "pg_catalog");
14266
14267         query = createPQExpBuffer();
14268
14269         /*
14270          * PIN dependencies aren't interesting, and EXTENSION dependencies were
14271          * already processed by getExtensionMembership.
14272          */
14273         appendPQExpBuffer(query, "SELECT "
14274                                           "classid, objid, refclassid, refobjid, deptype "
14275                                           "FROM pg_depend "
14276                                           "WHERE deptype != 'p' AND deptype != 'e' "
14277                                           "ORDER BY 1,2");
14278
14279         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14280
14281         ntups = PQntuples(res);
14282
14283         i_classid = PQfnumber(res, "classid");
14284         i_objid = PQfnumber(res, "objid");
14285         i_refclassid = PQfnumber(res, "refclassid");
14286         i_refobjid = PQfnumber(res, "refobjid");
14287         i_deptype = PQfnumber(res, "deptype");
14288
14289         /*
14290          * Since we ordered the SELECT by referencing ID, we can expect that
14291          * multiple entries for the same object will appear together; this saves
14292          * on searches.
14293          */
14294         dobj = NULL;
14295
14296         for (i = 0; i < ntups; i++)
14297         {
14298                 CatalogId       objId;
14299                 CatalogId       refobjId;
14300                 char            deptype;
14301
14302                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14303                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14304                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14305                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14306                 deptype = *(PQgetvalue(res, i, i_deptype));
14307
14308                 if (dobj == NULL ||
14309                         dobj->catId.tableoid != objId.tableoid ||
14310                         dobj->catId.oid != objId.oid)
14311                         dobj = findObjectByCatalogId(objId);
14312
14313                 /*
14314                  * Failure to find objects mentioned in pg_depend is not unexpected,
14315                  * since for example we don't collect info about TOAST tables.
14316                  */
14317                 if (dobj == NULL)
14318                 {
14319 #ifdef NOT_USED
14320                         fprintf(stderr, "no referencing object %u %u\n",
14321                                         objId.tableoid, objId.oid);
14322 #endif
14323                         continue;
14324                 }
14325
14326                 refdobj = findObjectByCatalogId(refobjId);
14327
14328                 if (refdobj == NULL)
14329                 {
14330 #ifdef NOT_USED
14331                         fprintf(stderr, "no referenced object %u %u\n",
14332                                         refobjId.tableoid, refobjId.oid);
14333 #endif
14334                         continue;
14335                 }
14336
14337                 /*
14338                  * Ordinarily, table rowtypes have implicit dependencies on their
14339                  * tables.      However, for a composite type the implicit dependency goes
14340                  * the other way in pg_depend; which is the right thing for DROP but
14341                  * it doesn't produce the dependency ordering we need. So in that one
14342                  * case, we reverse the direction of the dependency.
14343                  */
14344                 if (deptype == 'i' &&
14345                         dobj->objType == DO_TABLE &&
14346                         refdobj->objType == DO_TYPE)
14347                         addObjectDependency(refdobj, dobj->dumpId);
14348                 else
14349                         /* normal case */
14350                         addObjectDependency(dobj, refdobj->dumpId);
14351         }
14352
14353         PQclear(res);
14354
14355         destroyPQExpBuffer(query);
14356 }
14357
14358
14359 /*
14360  * createBoundaryObjects - create dummy DumpableObjects to represent
14361  * dump section boundaries.
14362  */
14363 static DumpableObject *
14364 createBoundaryObjects(void)
14365 {
14366         DumpableObject *dobjs;
14367
14368         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14369
14370         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14371         dobjs[0].catId = nilCatalogId;
14372         AssignDumpId(dobjs + 0);
14373         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14374
14375         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14376         dobjs[1].catId = nilCatalogId;
14377         AssignDumpId(dobjs + 1);
14378         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14379
14380         return dobjs;
14381 }
14382
14383 /*
14384  * addBoundaryDependencies - add dependencies as needed to enforce the dump
14385  * section boundaries.
14386  */
14387 static void
14388 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14389                                                 DumpableObject *boundaryObjs)
14390 {
14391         DumpableObject *preDataBound = boundaryObjs + 0;
14392         DumpableObject *postDataBound = boundaryObjs + 1;
14393         int                     i;
14394
14395         for (i = 0; i < numObjs; i++)
14396         {
14397                 DumpableObject *dobj = dobjs[i];
14398
14399                 /*
14400                  * The classification of object types here must match the SECTION_xxx
14401                  * values assigned during subsequent ArchiveEntry calls!
14402                  */
14403                 switch (dobj->objType)
14404                 {
14405                         case DO_NAMESPACE:
14406                         case DO_EXTENSION:
14407                         case DO_TYPE:
14408                         case DO_SHELL_TYPE:
14409                         case DO_FUNC:
14410                         case DO_AGG:
14411                         case DO_OPERATOR:
14412                         case DO_OPCLASS:
14413                         case DO_OPFAMILY:
14414                         case DO_COLLATION:
14415                         case DO_CONVERSION:
14416                         case DO_TABLE:
14417                         case DO_ATTRDEF:
14418                         case DO_PROCLANG:
14419                         case DO_CAST:
14420                         case DO_DUMMY_TYPE:
14421                         case DO_TSPARSER:
14422                         case DO_TSDICT:
14423                         case DO_TSTEMPLATE:
14424                         case DO_TSCONFIG:
14425                         case DO_FDW:
14426                         case DO_FOREIGN_SERVER:
14427                         case DO_BLOB:
14428                                 /* Pre-data objects: must come before the pre-data boundary */
14429                                 addObjectDependency(preDataBound, dobj->dumpId);
14430                                 break;
14431                         case DO_TABLE_DATA:
14432                         case DO_BLOB_DATA:
14433                                 /* Data objects: must come between the boundaries */
14434                                 addObjectDependency(dobj, preDataBound->dumpId);
14435                                 addObjectDependency(postDataBound, dobj->dumpId);
14436                                 break;
14437                         case DO_INDEX:
14438                         case DO_TRIGGER:
14439                         case DO_EVENT_TRIGGER:
14440                         case DO_DEFAULT_ACL:
14441                                 /* Post-data objects: must come after the post-data boundary */
14442                                 addObjectDependency(dobj, postDataBound->dumpId);
14443                                 break;
14444                         case DO_RULE:
14445                                 /* Rules are post-data, but only if dumped separately */
14446                                 if (((RuleInfo *) dobj)->separate)
14447                                         addObjectDependency(dobj, postDataBound->dumpId);
14448                                 break;
14449                         case DO_CONSTRAINT:
14450                         case DO_FK_CONSTRAINT:
14451                                 /* Constraints are post-data, but only if dumped separately */
14452                                 if (((ConstraintInfo *) dobj)->separate)
14453                                         addObjectDependency(dobj, postDataBound->dumpId);
14454                                 break;
14455                         case DO_PRE_DATA_BOUNDARY:
14456                                 /* nothing to do */
14457                                 break;
14458                         case DO_POST_DATA_BOUNDARY:
14459                                 /* must come after the pre-data boundary */
14460                                 addObjectDependency(dobj, preDataBound->dumpId);
14461                                 break;
14462                 }
14463         }
14464 }
14465
14466
14467 /*
14468  * BuildArchiveDependencies - create dependency data for archive TOC entries
14469  *
14470  * The raw dependency data obtained by getDependencies() is not terribly
14471  * useful in an archive dump, because in many cases there are dependency
14472  * chains linking through objects that don't appear explicitly in the dump.
14473  * For example, a view will depend on its _RETURN rule while the _RETURN rule
14474  * will depend on other objects --- but the rule will not appear as a separate
14475  * object in the dump.  We need to adjust the view's dependencies to include
14476  * whatever the rule depends on that is included in the dump.
14477  *
14478  * Just to make things more complicated, there are also "special" dependencies
14479  * such as the dependency of a TABLE DATA item on its TABLE, which we must
14480  * not rearrange because pg_restore knows that TABLE DATA only depends on
14481  * its table.  In these cases we must leave the dependencies strictly as-is
14482  * even if they refer to not-to-be-dumped objects.
14483  *
14484  * To handle this, the convention is that "special" dependencies are created
14485  * during ArchiveEntry calls, and an archive TOC item that has any such
14486  * entries will not be touched here.  Otherwise, we recursively search the
14487  * DumpableObject data structures to build the correct dependencies for each
14488  * archive TOC item.
14489  */
14490 static void
14491 BuildArchiveDependencies(Archive *fout)
14492 {
14493         ArchiveHandle *AH = (ArchiveHandle *) fout;
14494         TocEntry   *te;
14495
14496         /* Scan all TOC entries in the archive */
14497         for (te = AH->toc->next; te != AH->toc; te = te->next)
14498         {
14499                 DumpableObject *dobj;
14500                 DumpId     *dependencies;
14501                 int                     nDeps;
14502                 int                     allocDeps;
14503
14504                 /* No need to process entries that will not be dumped */
14505                 if (te->reqs == 0)
14506                         continue;
14507                 /* Ignore entries that already have "special" dependencies */
14508                 if (te->nDeps > 0)
14509                         continue;
14510                 /* Otherwise, look up the item's original DumpableObject, if any */
14511                 dobj = findObjectByDumpId(te->dumpId);
14512                 if (dobj == NULL)
14513                         continue;
14514                 /* No work if it has no dependencies */
14515                 if (dobj->nDeps <= 0)
14516                         continue;
14517                 /* Set up work array */
14518                 allocDeps = 64;
14519                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14520                 nDeps = 0;
14521                 /* Recursively find all dumpable dependencies */
14522                 findDumpableDependencies(AH, dobj,
14523                                                                  &dependencies, &nDeps, &allocDeps);
14524                 /* And save 'em ... */
14525                 if (nDeps > 0)
14526                 {
14527                         dependencies = (DumpId *) pg_realloc(dependencies,
14528                                                                                                  nDeps * sizeof(DumpId));
14529                         te->dependencies = dependencies;
14530                         te->nDeps = nDeps;
14531                 }
14532                 else
14533                         free(dependencies);
14534         }
14535 }
14536
14537 /* Recursive search subroutine for BuildArchiveDependencies */
14538 static void
14539 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14540                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
14541 {
14542         int                     i;
14543
14544         /*
14545          * Ignore section boundary objects: if we search through them, we'll
14546          * report lots of bogus dependencies.
14547          */
14548         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14549                 dobj->objType == DO_POST_DATA_BOUNDARY)
14550                 return;
14551
14552         for (i = 0; i < dobj->nDeps; i++)
14553         {
14554                 DumpId          depid = dobj->dependencies[i];
14555
14556                 if (TocIDRequired(AH, depid) != 0)
14557                 {
14558                         /* Object will be dumped, so just reference it as a dependency */
14559                         if (*nDeps >= *allocDeps)
14560                         {
14561                                 *allocDeps *= 2;
14562                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
14563                                                                                           *allocDeps * sizeof(DumpId));
14564                         }
14565                         (*dependencies)[*nDeps] = depid;
14566                         (*nDeps)++;
14567                 }
14568                 else
14569                 {
14570                         /*
14571                          * Object will not be dumped, so recursively consider its deps.
14572                          * We rely on the assumption that sortDumpableObjects already
14573                          * broke any dependency loops, else we might recurse infinitely.
14574                          */
14575                         DumpableObject *otherdobj = findObjectByDumpId(depid);
14576
14577                         if (otherdobj)
14578                                 findDumpableDependencies(AH, otherdobj,
14579                                                                                  dependencies, nDeps, allocDeps);
14580                 }
14581         }
14582 }
14583
14584
14585 /*
14586  * selectSourceSchema - make the specified schema the active search path
14587  * in the source database.
14588  *
14589  * NB: pg_catalog is explicitly searched after the specified schema;
14590  * so user names are only qualified if they are cross-schema references,
14591  * and system names are only qualified if they conflict with a user name
14592  * in the current schema.
14593  *
14594  * Whenever the selected schema is not pg_catalog, be careful to qualify
14595  * references to system catalogs and types in our emitted commands!
14596  */
14597 static void
14598 selectSourceSchema(Archive *fout, const char *schemaName)
14599 {
14600         static char *curSchemaName = NULL;
14601         PQExpBuffer query;
14602
14603         /* Not relevant if fetching from pre-7.3 DB */
14604         if (fout->remoteVersion < 70300)
14605                 return;
14606         /* Ignore null schema names */
14607         if (schemaName == NULL || *schemaName == '\0')
14608                 return;
14609         /* Optimize away repeated selection of same schema */
14610         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14611                 return;
14612
14613         query = createPQExpBuffer();
14614         appendPQExpBuffer(query, "SET search_path = %s",
14615                                           fmtId(schemaName));
14616         if (strcmp(schemaName, "pg_catalog") != 0)
14617                 appendPQExpBuffer(query, ", pg_catalog");
14618
14619         ExecuteSqlStatement(fout, query->data);
14620
14621         destroyPQExpBuffer(query);
14622         if (curSchemaName)
14623                 free(curSchemaName);
14624         curSchemaName = pg_strdup(schemaName);
14625 }
14626
14627 /*
14628  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14629  * given type name.
14630  *
14631  * NB: in 7.3 and up the result may depend on the currently-selected
14632  * schema; this is why we don't try to cache the names.
14633  */
14634 static char *
14635 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14636 {
14637         char       *result;
14638         PQExpBuffer query;
14639         PGresult   *res;
14640
14641         if (oid == 0)
14642         {
14643                 if ((opts & zeroAsOpaque) != 0)
14644                         return pg_strdup(g_opaque_type);
14645                 else if ((opts & zeroAsAny) != 0)
14646                         return pg_strdup("'any'");
14647                 else if ((opts & zeroAsStar) != 0)
14648                         return pg_strdup("*");
14649                 else if ((opts & zeroAsNone) != 0)
14650                         return pg_strdup("NONE");
14651         }
14652
14653         query = createPQExpBuffer();
14654         if (fout->remoteVersion >= 70300)
14655         {
14656                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14657                                                   oid);
14658         }
14659         else if (fout->remoteVersion >= 70100)
14660         {
14661                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14662                                                   oid);
14663         }
14664         else
14665         {
14666                 appendPQExpBuffer(query, "SELECT typname "
14667                                                   "FROM pg_type "
14668                                                   "WHERE oid = '%u'::oid",
14669                                                   oid);
14670         }
14671
14672         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14673
14674         if (fout->remoteVersion >= 70100)
14675         {
14676                 /* already quoted */
14677                 result = pg_strdup(PQgetvalue(res, 0, 0));
14678         }
14679         else
14680         {
14681                 /* may need to quote it */
14682                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14683         }
14684
14685         PQclear(res);
14686         destroyPQExpBuffer(query);
14687
14688         return result;
14689 }
14690
14691 /*
14692  * myFormatType --- local implementation of format_type for use with 7.0.
14693  */
14694 static char *
14695 myFormatType(const char *typname, int32 typmod)
14696 {
14697         char       *result;
14698         bool            isarray = false;
14699         PQExpBuffer buf = createPQExpBuffer();
14700
14701         /* Handle array types */
14702         if (typname[0] == '_')
14703         {
14704                 isarray = true;
14705                 typname++;
14706         }
14707
14708         /* Show lengths on bpchar and varchar */
14709         if (strcmp(typname, "bpchar") == 0)
14710         {
14711                 int                     len = (typmod - VARHDRSZ);
14712
14713                 appendPQExpBuffer(buf, "character");
14714                 if (len > 1)
14715                         appendPQExpBuffer(buf, "(%d)",
14716                                                           typmod - VARHDRSZ);
14717         }
14718         else if (strcmp(typname, "varchar") == 0)
14719         {
14720                 appendPQExpBuffer(buf, "character varying");
14721                 if (typmod != -1)
14722                         appendPQExpBuffer(buf, "(%d)",
14723                                                           typmod - VARHDRSZ);
14724         }
14725         else if (strcmp(typname, "numeric") == 0)
14726         {
14727                 appendPQExpBuffer(buf, "numeric");
14728                 if (typmod != -1)
14729                 {
14730                         int32           tmp_typmod;
14731                         int                     precision;
14732                         int                     scale;
14733
14734                         tmp_typmod = typmod - VARHDRSZ;
14735                         precision = (tmp_typmod >> 16) & 0xffff;
14736                         scale = tmp_typmod & 0xffff;
14737                         appendPQExpBuffer(buf, "(%d,%d)",
14738                                                           precision, scale);
14739                 }
14740         }
14741
14742         /*
14743          * char is an internal single-byte data type; Let's make sure we force it
14744          * through with quotes. - thomas 1998-12-13
14745          */
14746         else if (strcmp(typname, "char") == 0)
14747                 appendPQExpBuffer(buf, "\"char\"");
14748         else
14749                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14750
14751         /* Append array qualifier for array types */
14752         if (isarray)
14753                 appendPQExpBuffer(buf, "[]");
14754
14755         result = pg_strdup(buf->data);
14756         destroyPQExpBuffer(buf);
14757
14758         return result;
14759 }
14760
14761 /*
14762  * fmtQualifiedId - convert a qualified name to the proper format for
14763  * the source database.
14764  *
14765  * Like fmtId, use the result before calling again.
14766  */
14767 static const char *
14768 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14769 {
14770         static PQExpBuffer id_return = NULL;
14771
14772         if (id_return)                          /* first time through? */
14773                 resetPQExpBuffer(id_return);
14774         else
14775                 id_return = createPQExpBuffer();
14776
14777         /* Suppress schema name if fetching from pre-7.3 DB */
14778         if (fout->remoteVersion >= 70300 && schema && *schema)
14779         {
14780                 appendPQExpBuffer(id_return, "%s.",
14781                                                   fmtId(schema));
14782         }
14783         appendPQExpBuffer(id_return, "%s",
14784                                           fmtId(id));
14785
14786         return id_return->data;
14787 }
14788
14789 /*
14790  * Return a column list clause for the given relation.
14791  *
14792  * Special case: if there are no undropped columns in the relation, return
14793  * "", not an invalid "()" column list.
14794  */
14795 static const char *
14796 fmtCopyColumnList(const TableInfo *ti)
14797 {
14798         static PQExpBuffer q = NULL;
14799         int                     numatts = ti->numatts;
14800         char      **attnames = ti->attnames;
14801         bool       *attisdropped = ti->attisdropped;
14802         bool            needComma;
14803         int                     i;
14804
14805         if (q)                                          /* first time through? */
14806                 resetPQExpBuffer(q);
14807         else
14808                 q = createPQExpBuffer();
14809
14810         appendPQExpBuffer(q, "(");
14811         needComma = false;
14812         for (i = 0; i < numatts; i++)
14813         {
14814                 if (attisdropped[i])
14815                         continue;
14816                 if (needComma)
14817                         appendPQExpBuffer(q, ", ");
14818                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14819                 needComma = true;
14820         }
14821
14822         if (!needComma)
14823                 return "";                              /* no undropped columns */
14824
14825         appendPQExpBuffer(q, ")");
14826         return q->data;
14827 }
14828
14829 /*
14830  * Execute an SQL query and verify that we got exactly one row back.
14831  */
14832 static PGresult *
14833 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14834 {
14835         PGresult   *res;
14836         int                     ntups;
14837
14838         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14839
14840         /* Expecting a single result only */
14841         ntups = PQntuples(res);
14842         if (ntups != 1)
14843                 exit_horribly(NULL,
14844                                           ngettext("query returned %d row instead of one: %s\n",
14845                                                            "query returned %d rows instead of one: %s\n",
14846                                                            ntups),
14847                                           ntups, query);
14848
14849         return res;
14850 }