]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
e6c85ac0aedf11aa6f292e2823006144f78a64ca
[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-2013, 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 "dumputils.h"
63
64 extern char *optarg;
65 extern int      optind,
66                         opterr;
67
68
69 typedef struct
70 {
71         const char *descr;                      /* comment for an object */
72         Oid                     classoid;               /* object class (catalog OID) */
73         Oid                     objoid;                 /* object OID */
74         int                     objsubid;               /* subobject (table column #) */
75 } CommentItem;
76
77 typedef struct
78 {
79         const char *provider;           /* label provider of this security label */
80         const char *label;                      /* security label for an object */
81         Oid                     classoid;               /* object class (catalog OID) */
82         Oid                     objoid;                 /* object OID */
83         int                     objsubid;               /* subobject (table column #) */
84 } SecLabelItem;
85
86 /* global decls */
87 bool            g_verbose;                      /* User wants verbose narration of our
88                                                                  * activities. */
89
90 /* various user-settable parameters */
91 bool            schemaOnly;
92 bool            dataOnly;
93 int                     dumpSections;           /* bitmask of chosen sections */
94 bool            aclsSkip;
95 const char *lockWaitTimeout;
96
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
99
100 /* obsolete as of 7.3: */
101 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
102
103 /*
104  * Object inclusion/exclusion lists
105  *
106  * The string lists record the patterns given by command-line switches,
107  * which we then convert to lists of OIDs of matching objects.
108  */
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
113
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
120
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
123
124 char            g_opaque_type[10];      /* name for the opaque type */
125
126 /* placeholders for the delimiters for comments */
127 char            g_comment_start[10];
128 char            g_comment_end[10];
129
130 static const CatalogId nilCatalogId = {0, 0};
131
132 /* flags for various command-line long options */
133 static int      binary_upgrade = 0;
134 static int      disable_dollar_quoting = 0;
135 static int      dump_inserts = 0;
136 static int      column_inserts = 0;
137 static int      no_security_labels = 0;
138 static int      no_unlogged_table_data = 0;
139 static int      serializable_deferrable = 0;
140
141
142 static void help(const char *progname);
143 static void setup_connection(Archive *AH, const char *dumpencoding,
144                                  char *use_role);
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(Archive *fout,
147                                                         SimpleStringList *patterns,
148                                                         SimpleOidList *oids);
149 static void expand_table_name_patterns(Archive *fout,
150                                                    SimpleStringList *patterns,
151                                                    SimpleOidList *oids);
152 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
153 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
154 static void refreshMatViewData(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 buildMatViewRefreshDependencies(Archive *fout);
228 static void getTableDataFKConstraints(void);
229 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
230 static char *format_function_arguments_old(Archive *fout,
231                                                           FuncInfo *finfo, int nallargs,
232                                                           char **allargtypes,
233                                                           char **argmodes,
234                                                           char **argnames);
235 static char *format_function_signature(Archive *fout,
236                                                   FuncInfo *finfo, bool honor_quotes);
237 static const char *convertRegProcReference(Archive *fout,
238                                                 const char *proc);
239 static const char *convertOperatorReference(Archive *fout, const char *opr);
240 static const char *convertTSFunction(Archive *fout, Oid funcOid);
241 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
242 static Oid      findLastBuiltinOid_V70(Archive *fout);
243 static void selectSourceSchema(Archive *fout, const char *schemaName);
244 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
245 static char *myFormatType(const char *typname, int32 typmod);
246 static const char *fmtQualifiedId(Archive *fout,
247                            const char *schema, const char *id);
248 static void getBlobs(Archive *fout);
249 static void dumpBlob(Archive *fout, BlobInfo *binfo);
250 static int      dumpBlobs(Archive *fout, void *arg);
251 static void dumpDatabase(Archive *AH);
252 static void dumpEncoding(Archive *AH);
253 static void dumpStdStrings(Archive *AH);
254 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
255                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
256 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
257                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
258 static void binary_upgrade_set_pg_class_oids(Archive *fout,
259                                                                  PQExpBuffer upgrade_buffer,
260                                                                  Oid pg_class_oid, bool is_index);
261 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
262                                                                 DumpableObject *dobj,
263                                                                 const char *objlabel);
264 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
265 static const char *fmtCopyColumnList(const TableInfo *ti);
266 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
267
268
269 int
270 main(int argc, char **argv)
271 {
272         int                     c;
273         const char *filename = NULL;
274         const char *format = "p";
275         const char *dbname = NULL;
276         const char *pghost = NULL;
277         const char *pgport = NULL;
278         const char *username = NULL;
279         const char *dumpencoding = NULL;
280         bool            oids = false;
281         TableInfo  *tblinfo;
282         int                     numTables;
283         DumpableObject **dobjs;
284         int                     numObjs;
285         DumpableObject *boundaryObjs;
286         int                     i;
287         enum trivalue prompt_password = TRI_DEFAULT;
288         int                     compressLevel = -1;
289         int                     plainText = 0;
290         int                     outputClean = 0;
291         int                     outputCreateDB = 0;
292         bool            outputBlobs = false;
293         int                     outputNoOwner = 0;
294         char       *outputSuperuser = NULL;
295         char       *use_role = NULL;
296         int                     my_version;
297         int                     optindex;
298         RestoreOptions *ropt;
299         ArchiveFormat archiveFormat = archUnknown;
300         ArchiveMode archiveMode;
301         Archive    *fout;                       /* the script file */
302
303         static int      disable_triggers = 0;
304         static int      outputNoTablespaces = 0;
305         static int      use_setsessauth = 0;
306
307         static struct option long_options[] = {
308                 {"data-only", no_argument, NULL, 'a'},
309                 {"blobs", no_argument, NULL, 'b'},
310                 {"clean", no_argument, NULL, 'c'},
311                 {"create", no_argument, NULL, 'C'},
312                 {"dbname", required_argument, NULL, 'd'},
313                 {"file", required_argument, NULL, 'f'},
314                 {"format", required_argument, NULL, 'F'},
315                 {"host", required_argument, NULL, 'h'},
316                 {"ignore-version", no_argument, NULL, 'i'},
317                 {"no-reconnect", no_argument, NULL, 'R'},
318                 {"oids", no_argument, NULL, 'o'},
319                 {"no-owner", no_argument, NULL, 'O'},
320                 {"port", required_argument, NULL, 'p'},
321                 {"schema", required_argument, NULL, 'n'},
322                 {"exclude-schema", required_argument, NULL, 'N'},
323                 {"schema-only", no_argument, NULL, 's'},
324                 {"superuser", required_argument, NULL, 'S'},
325                 {"table", required_argument, NULL, 't'},
326                 {"exclude-table", required_argument, NULL, 'T'},
327                 {"no-password", no_argument, NULL, 'w'},
328                 {"password", no_argument, NULL, 'W'},
329                 {"username", required_argument, NULL, 'U'},
330                 {"verbose", no_argument, NULL, 'v'},
331                 {"no-privileges", no_argument, NULL, 'x'},
332                 {"no-acl", no_argument, NULL, 'x'},
333                 {"compress", required_argument, NULL, 'Z'},
334                 {"encoding", required_argument, NULL, 'E'},
335                 {"help", no_argument, NULL, '?'},
336                 {"version", no_argument, NULL, 'V'},
337
338                 /*
339                  * the following options don't have an equivalent short option letter
340                  */
341                 {"attribute-inserts", no_argument, &column_inserts, 1},
342                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
343                 {"column-inserts", no_argument, &column_inserts, 1},
344                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
345                 {"disable-triggers", no_argument, &disable_triggers, 1},
346                 {"exclude-table-data", required_argument, NULL, 4},
347                 {"inserts", no_argument, &dump_inserts, 1},
348                 {"lock-wait-timeout", required_argument, NULL, 2},
349                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
350                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
351                 {"role", required_argument, NULL, 3},
352                 {"section", required_argument, NULL, 5},
353                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
354                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
355                 {"no-security-labels", no_argument, &no_security_labels, 1},
356                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
357
358                 {NULL, 0, NULL, 0}
359         };
360
361         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
362
363         g_verbose = false;
364
365         strcpy(g_comment_start, "-- ");
366         g_comment_end[0] = '\0';
367         strcpy(g_opaque_type, "opaque");
368
369         dataOnly = schemaOnly = false;
370         dumpSections = DUMP_UNSECTIONED;
371         lockWaitTimeout = NULL;
372
373         progname = get_progname(argv[0]);
374
375         /* Set default options based on progname */
376         if (strcmp(progname, "pg_backup") == 0)
377                 format = "c";
378
379         if (argc > 1)
380         {
381                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
382                 {
383                         help(progname);
384                         exit_nicely(0);
385                 }
386                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
387                 {
388                         puts("pg_dump (PostgreSQL) " PG_VERSION);
389                         exit_nicely(0);
390                 }
391         }
392
393         while ((c = getopt_long(argc, argv, "abcCd:E:f:F:h:iK:n:N:oOp:RsS:t:T:U:vwWxZ:",
394                                                         long_options, &optindex)) != -1)
395         {
396                 switch (c)
397                 {
398                         case 'a':                       /* Dump data only */
399                                 dataOnly = true;
400                                 break;
401
402                         case 'b':                       /* Dump blobs */
403                                 outputBlobs = true;
404                                 break;
405
406                         case 'c':                       /* clean (i.e., drop) schema prior to create */
407                                 outputClean = 1;
408                                 break;
409
410                         case 'C':                       /* Create DB */
411                                 outputCreateDB = 1;
412                                 break;
413
414                         case 'd':                       /* database name */
415                                 dbname = pg_strdup(optarg);
416                                 break;
417
418                         case 'E':                       /* Dump encoding */
419                                 dumpencoding = pg_strdup(optarg);
420                                 break;
421
422                         case 'f':
423                                 filename = pg_strdup(optarg);
424                                 break;
425
426                         case 'F':
427                                 format = pg_strdup(optarg);
428                                 break;
429
430                         case 'h':                       /* server host */
431                                 pghost = pg_strdup(optarg);
432                                 break;
433
434                         case 'i':
435                                 /* ignored, deprecated option */
436                                 break;
437
438                         case 'n':                       /* include schema(s) */
439                                 simple_string_list_append(&schema_include_patterns, optarg);
440                                 include_everything = false;
441                                 break;
442
443                         case 'N':                       /* exclude schema(s) */
444                                 simple_string_list_append(&schema_exclude_patterns, optarg);
445                                 break;
446
447                         case 'o':                       /* Dump oids */
448                                 oids = true;
449                                 break;
450
451                         case 'O':                       /* Don't reconnect to match owner */
452                                 outputNoOwner = 1;
453                                 break;
454
455                         case 'p':                       /* server port */
456                                 pgport = pg_strdup(optarg);
457                                 break;
458
459                         case 'R':
460                                 /* no-op, still accepted for backwards compatibility */
461                                 break;
462
463                         case 's':                       /* dump schema only */
464                                 schemaOnly = true;
465                                 break;
466
467                         case 'S':                       /* Username for superuser in plain text output */
468                                 outputSuperuser = pg_strdup(optarg);
469                                 break;
470
471                         case 't':                       /* include table(s) */
472                                 simple_string_list_append(&table_include_patterns, optarg);
473                                 include_everything = false;
474                                 break;
475
476                         case 'T':                       /* exclude table(s) */
477                                 simple_string_list_append(&table_exclude_patterns, optarg);
478                                 break;
479
480                         case 'U':
481                                 username = pg_strdup(optarg);
482                                 break;
483
484                         case 'v':                       /* verbose */
485                                 g_verbose = true;
486                                 break;
487
488                         case 'w':
489                                 prompt_password = TRI_NO;
490                                 break;
491
492                         case 'W':
493                                 prompt_password = TRI_YES;
494                                 break;
495
496                         case 'x':                       /* skip ACL dump */
497                                 aclsSkip = true;
498                                 break;
499
500                         case 'Z':                       /* Compression Level */
501                                 compressLevel = atoi(optarg);
502                                 break;
503
504                         case 0:
505                                 /* This covers the long options. */
506                                 break;
507
508                         case 2:                         /* lock-wait-timeout */
509                                 lockWaitTimeout = pg_strdup(optarg);
510                                 break;
511
512                         case 3:                         /* SET ROLE */
513                                 use_role = pg_strdup(optarg);
514                                 break;
515
516                         case 4:                         /* exclude table(s) data */
517                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
518                                 break;
519
520                         case 5:                         /* section */
521                                 set_dump_section(optarg, &dumpSections);
522                                 break;
523
524                         default:
525                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
526                                 exit_nicely(1);
527                 }
528         }
529
530         /*
531          * Non-option argument specifies database name as long as it wasn't
532          * already specified with -d / --dbname
533          */
534         if (optind < argc && dbname == NULL)
535                 dbname = argv[optind++];
536
537         /* Complain if any arguments remain */
538         if (optind < argc)
539         {
540                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
541                                 progname, argv[optind]);
542                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
543                                 progname);
544                 exit_nicely(1);
545         }
546
547         /* --column-inserts implies --inserts */
548         if (column_inserts)
549                 dump_inserts = 1;
550
551         if (dataOnly && schemaOnly)
552                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
553
554         if (dataOnly && outputClean)
555                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
556
557         if (dump_inserts && oids)
558         {
559                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
560                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
561                 exit_nicely(1);
562         }
563
564         /* Identify archive format to emit */
565         archiveFormat = parseArchiveFormat(format, &archiveMode);
566
567         /* archiveFormat specific setup */
568         if (archiveFormat == archNull)
569                 plainText = 1;
570
571         /* Custom and directory formats are compressed by default, others not */
572         if (compressLevel == -1)
573         {
574                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
575                         compressLevel = Z_DEFAULT_COMPRESSION;
576                 else
577                         compressLevel = 0;
578         }
579
580         /* Open the output file */
581         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
582
583         /* Register the cleanup hook */
584         on_exit_close_archive(fout);
585
586         if (fout == NULL)
587                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
588
589         /* Let the archiver know how noisy to be */
590         fout->verbose = g_verbose;
591
592         my_version = parse_version(PG_VERSION);
593         if (my_version < 0)
594                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
595
596         /*
597          * We allow the server to be back to 7.0, and up to any minor release of
598          * our own major version.  (See also version check in pg_dumpall.c.)
599          */
600         fout->minRemoteVersion = 70000;
601         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
602
603         /*
604          * Open the database using the Archiver, so it knows about it. Errors mean
605          * death.
606          */
607         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
608         setup_connection(fout, dumpencoding, use_role);
609
610         /*
611          * Disable security label support if server version < v9.1.x (prevents
612          * access to nonexistent pg_seclabel catalog)
613          */
614         if (fout->remoteVersion < 90100)
615                 no_security_labels = 1;
616
617         /*
618          * When running against 9.0 or later, check if we are in recovery mode,
619          * which means we are on a hot standby.
620          */
621         if (fout->remoteVersion >= 90000)
622         {
623                 PGresult *res = ExecuteSqlQueryForSingleRow(fout, "SELECT pg_catalog.pg_is_in_recovery()");
624                 if (strcmp(PQgetvalue(res, 0, 0), "t") == 0)
625                 {
626                         /*
627                          * On hot standby slaves, never try to dump unlogged table data,
628                          * since it will just throw an error.
629                          */
630                         no_unlogged_table_data = true;
631                 }
632                 PQclear(res);
633         }
634
635         /*
636          * Start transaction-snapshot mode transaction to dump consistent data.
637          */
638         ExecuteSqlStatement(fout, "BEGIN");
639         if (fout->remoteVersion >= 90100)
640         {
641                 if (serializable_deferrable)
642                         ExecuteSqlStatement(fout,
643                                                                 "SET TRANSACTION ISOLATION LEVEL "
644                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
645                 else
646                         ExecuteSqlStatement(fout,
647                                                                 "SET TRANSACTION ISOLATION LEVEL "
648                                                                 "REPEATABLE READ, READ ONLY");
649         }
650         else if (fout->remoteVersion >= 70400)
651         {
652                 /* note: comma was not accepted in SET TRANSACTION before 8.0 */
653                 ExecuteSqlStatement(fout,
654                                                         "SET TRANSACTION ISOLATION LEVEL "
655                                                         "SERIALIZABLE READ ONLY");
656         }
657         else
658                 ExecuteSqlStatement(fout,
659                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
660
661         /* Select the appropriate subquery to convert user IDs to names */
662         if (fout->remoteVersion >= 80100)
663                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
664         else if (fout->remoteVersion >= 70300)
665                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
666         else
667                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
668
669         /* Find the last built-in OID, if needed */
670         if (fout->remoteVersion < 70300)
671         {
672                 if (fout->remoteVersion >= 70100)
673                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
674                                                                                                   PQdb(GetConnection(fout)));
675                 else
676                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
677                 if (g_verbose)
678                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
679         }
680
681         /* Expand schema selection patterns into OID lists */
682         if (schema_include_patterns.head != NULL)
683         {
684                 expand_schema_name_patterns(fout, &schema_include_patterns,
685                                                                         &schema_include_oids);
686                 if (schema_include_oids.head == NULL)
687                         exit_horribly(NULL, "No matching schemas were found\n");
688         }
689         expand_schema_name_patterns(fout, &schema_exclude_patterns,
690                                                                 &schema_exclude_oids);
691         /* non-matching exclusion patterns aren't an error */
692
693         /* Expand table selection patterns into OID lists */
694         if (table_include_patterns.head != NULL)
695         {
696                 expand_table_name_patterns(fout, &table_include_patterns,
697                                                                    &table_include_oids);
698                 if (table_include_oids.head == NULL)
699                         exit_horribly(NULL, "No matching tables were found\n");
700         }
701         expand_table_name_patterns(fout, &table_exclude_patterns,
702                                                            &table_exclude_oids);
703
704         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
705                                                            &tabledata_exclude_oids);
706
707         /* non-matching exclusion patterns aren't an error */
708
709         /*
710          * Dumping blobs is now default unless we saw an inclusion switch or -s
711          * ... but even if we did see one of these, -b turns it back on.
712          */
713         if (include_everything && !schemaOnly)
714                 outputBlobs = true;
715
716         /*
717          * Now scan the database and create DumpableObject structs for all the
718          * objects we intend to dump.
719          */
720         tblinfo = getSchemaData(fout, &numTables);
721
722         if (fout->remoteVersion < 80400)
723                 guessConstraintInheritance(tblinfo, numTables);
724
725         if (!schemaOnly)
726         {
727                 getTableData(tblinfo, numTables, oids);
728                 buildMatViewRefreshDependencies(fout);
729                 if (dataOnly)
730                         getTableDataFKConstraints();
731         }
732
733         if (outputBlobs)
734                 getBlobs(fout);
735
736         /*
737          * Collect dependency data to assist in ordering the objects.
738          */
739         getDependencies(fout);
740
741         /* Lastly, create dummy objects to represent the section boundaries */
742         boundaryObjs = createBoundaryObjects();
743
744         /* Get pointers to all the known DumpableObjects */
745         getDumpableObjects(&dobjs, &numObjs);
746
747         /*
748          * Add dummy dependencies to enforce the dump section ordering.
749          */
750         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
751
752         /*
753          * Sort the objects into a safe dump order (no forward references).
754          *
755          * In 7.3 or later, we can rely on dependency information to help us
756          * determine a safe order, so the initial sort is mostly for cosmetic
757          * purposes: we sort by name to ensure that logically identical schemas
758          * will dump identically.  Before 7.3 we don't have dependencies and we
759          * use OID ordering as an (unreliable) guide to creation order.
760          */
761         if (fout->remoteVersion >= 70300)
762                 sortDumpableObjectsByTypeName(dobjs, numObjs);
763         else
764                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
765
766         sortDumpableObjects(dobjs, numObjs,
767                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
768
769         /*
770          * Create archive TOC entries for all the objects to be dumped, in a safe
771          * order.
772          */
773
774         /* First the special ENCODING and STDSTRINGS entries. */
775         dumpEncoding(fout);
776         dumpStdStrings(fout);
777
778         /* The database item is always next, unless we don't want it at all */
779         if (include_everything && !dataOnly)
780                 dumpDatabase(fout);
781
782         /* Now the rearrangeable objects. */
783         for (i = 0; i < numObjs; i++)
784                 dumpDumpableObject(fout, dobjs[i]);
785
786         /*
787          * Set up options info to ensure we dump what we want.
788          */
789         ropt = NewRestoreOptions();
790         ropt->filename = filename;
791         ropt->dropSchema = outputClean;
792         ropt->dataOnly = dataOnly;
793         ropt->schemaOnly = schemaOnly;
794         ropt->dumpSections = dumpSections;
795         ropt->aclsSkip = aclsSkip;
796         ropt->superuser = outputSuperuser;
797         ropt->createDB = outputCreateDB;
798         ropt->noOwner = outputNoOwner;
799         ropt->noTablespace = outputNoTablespaces;
800         ropt->disable_triggers = disable_triggers;
801         ropt->use_setsessauth = use_setsessauth;
802
803         if (compressLevel == -1)
804                 ropt->compression = 0;
805         else
806                 ropt->compression = compressLevel;
807
808         ropt->suppressDumpWarnings = true;      /* We've already shown them */
809
810         SetArchiveRestoreOptions(fout, ropt);
811
812         /*
813          * The archive's TOC entries are now marked as to which ones will
814          * actually be output, so we can set up their dependency lists properly.
815          * This isn't necessary for plain-text output, though.
816          */
817         if (!plainText)
818                 BuildArchiveDependencies(fout);
819
820         /*
821          * And finally we can do the actual output.
822          *
823          * Note: for non-plain-text output formats, the output file is written
824          * inside CloseArchive().  This is, um, bizarre; but not worth changing
825          * right now.
826          */
827         if (plainText)
828                 RestoreArchive(fout);
829
830         CloseArchive(fout);
831
832         exit_nicely(0);
833 }
834
835
836 static void
837 help(const char *progname)
838 {
839         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
840         printf(_("Usage:\n"));
841         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
842
843         printf(_("\nGeneral options:\n"));
844         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
845         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
846                          "                               plain text (default))\n"));
847         printf(_("  -v, --verbose                verbose mode\n"));
848         printf(_("  -V, --version                output version information, then exit\n"));
849         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
850         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
851         printf(_("  -?, --help                   show this help, then exit\n"));
852
853         printf(_("\nOptions controlling the output content:\n"));
854         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
855         printf(_("  -b, --blobs                  include large objects in dump\n"));
856         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
857         printf(_("  -C, --create                 include commands to create database in dump\n"));
858         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
859         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
860         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
861         printf(_("  -o, --oids                   include OIDs in dump\n"));
862         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
863                          "                               plain-text format\n"));
864         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
865         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
866         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
867         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
868         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
869         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
870         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
871         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
872         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
873         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
874         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
875         printf(_("  --no-security-labels         do not dump security label assignments\n"));
876         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
877         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
878         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
879         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
880         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
881         printf(_("  --use-set-session-authorization\n"
882                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
883                          "                               ALTER OWNER commands to set ownership\n"));
884
885         printf(_("\nConnection options:\n"));
886         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
887         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
888         printf(_("  -p, --port=PORT          database server port number\n"));
889         printf(_("  -U, --username=NAME      connect as specified database user\n"));
890         printf(_("  -w, --no-password        never prompt for password\n"));
891         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
892         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
893
894         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
895                          "variable value is used.\n\n"));
896         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
897 }
898
899 static void
900 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
901 {
902         PGconn     *conn = GetConnection(AH);
903         const char *std_strings;
904
905         /* Set the client encoding if requested */
906         if (dumpencoding)
907         {
908                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
909                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
910                                                   dumpencoding);
911         }
912
913         /*
914          * Get the active encoding and the standard_conforming_strings setting, so
915          * we know how to escape strings.
916          */
917         AH->encoding = PQclientEncoding(conn);
918
919         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
920         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
921
922         /* Set the role if requested */
923         if (use_role && AH->remoteVersion >= 80100)
924         {
925                 PQExpBuffer query = createPQExpBuffer();
926
927                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
928                 ExecuteSqlStatement(AH, query->data);
929                 destroyPQExpBuffer(query);
930         }
931
932         /* Set the datestyle to ISO to ensure the dump's portability */
933         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
934
935         /* Likewise, avoid using sql_standard intervalstyle */
936         if (AH->remoteVersion >= 80400)
937                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
938
939         /*
940          * If supported, set extra_float_digits so that we can dump float data
941          * exactly (given correctly implemented float I/O code, anyway)
942          */
943         if (AH->remoteVersion >= 90000)
944                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
945         else if (AH->remoteVersion >= 70400)
946                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
947
948         /*
949          * If synchronized scanning is supported, disable it, to prevent
950          * unpredictable changes in row ordering across a dump and reload.
951          */
952         if (AH->remoteVersion >= 80300)
953                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
954
955         /*
956          * Disable timeouts if supported.
957          */
958         if (AH->remoteVersion >= 70300)
959                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
960
961         /*
962          * Quote all identifiers, if requested.
963          */
964         if (quote_all_identifiers && AH->remoteVersion >= 90100)
965                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
966 }
967
968 static ArchiveFormat
969 parseArchiveFormat(const char *format, ArchiveMode *mode)
970 {
971         ArchiveFormat archiveFormat;
972
973         *mode = archModeWrite;
974
975         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
976         {
977                 /* This is used by pg_dumpall, and is not documented */
978                 archiveFormat = archNull;
979                 *mode = archModeAppend;
980         }
981         else if (pg_strcasecmp(format, "c") == 0)
982                 archiveFormat = archCustom;
983         else if (pg_strcasecmp(format, "custom") == 0)
984                 archiveFormat = archCustom;
985         else if (pg_strcasecmp(format, "d") == 0)
986                 archiveFormat = archDirectory;
987         else if (pg_strcasecmp(format, "directory") == 0)
988                 archiveFormat = archDirectory;
989         else if (pg_strcasecmp(format, "p") == 0)
990                 archiveFormat = archNull;
991         else if (pg_strcasecmp(format, "plain") == 0)
992                 archiveFormat = archNull;
993         else if (pg_strcasecmp(format, "t") == 0)
994                 archiveFormat = archTar;
995         else if (pg_strcasecmp(format, "tar") == 0)
996                 archiveFormat = archTar;
997         else
998                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
999         return archiveFormat;
1000 }
1001
1002 /*
1003  * Find the OIDs of all schemas matching the given list of patterns,
1004  * and append them to the given OID list.
1005  */
1006 static void
1007 expand_schema_name_patterns(Archive *fout,
1008                                                         SimpleStringList *patterns,
1009                                                         SimpleOidList *oids)
1010 {
1011         PQExpBuffer query;
1012         PGresult   *res;
1013         SimpleStringListCell *cell;
1014         int                     i;
1015
1016         if (patterns->head == NULL)
1017                 return;                                 /* nothing to do */
1018
1019         if (fout->remoteVersion < 70300)
1020                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1021
1022         query = createPQExpBuffer();
1023
1024         /*
1025          * We use UNION ALL rather than UNION; this might sometimes result in
1026          * duplicate entries in the OID list, but we don't care.
1027          */
1028
1029         for (cell = patterns->head; cell; cell = cell->next)
1030         {
1031                 if (cell != patterns->head)
1032                         appendPQExpBuffer(query, "UNION ALL\n");
1033                 appendPQExpBuffer(query,
1034                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1035                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1036                                                           false, NULL, "n.nspname", NULL, NULL);
1037         }
1038
1039         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1040
1041         for (i = 0; i < PQntuples(res); i++)
1042         {
1043                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1044         }
1045
1046         PQclear(res);
1047         destroyPQExpBuffer(query);
1048 }
1049
1050 /*
1051  * Find the OIDs of all tables matching the given list of patterns,
1052  * and append them to the given OID list.
1053  */
1054 static void
1055 expand_table_name_patterns(Archive *fout,
1056                                                    SimpleStringList *patterns, SimpleOidList *oids)
1057 {
1058         PQExpBuffer query;
1059         PGresult   *res;
1060         SimpleStringListCell *cell;
1061         int                     i;
1062
1063         if (patterns->head == NULL)
1064                 return;                                 /* nothing to do */
1065
1066         query = createPQExpBuffer();
1067
1068         /*
1069          * We use UNION ALL rather than UNION; this might sometimes result in
1070          * duplicate entries in the OID list, but we don't care.
1071          */
1072
1073         for (cell = patterns->head; cell; cell = cell->next)
1074         {
1075                 if (cell != patterns->head)
1076                         appendPQExpBuffer(query, "UNION ALL\n");
1077                 appendPQExpBuffer(query,
1078                                                   "SELECT c.oid"
1079                                                   "\nFROM pg_catalog.pg_class c"
1080                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1081                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c')\n",
1082                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1083                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
1084                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1085                                                           false, "n.nspname", "c.relname", NULL,
1086                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1087         }
1088
1089         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1090
1091         for (i = 0; i < PQntuples(res); i++)
1092         {
1093                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1094         }
1095
1096         PQclear(res);
1097         destroyPQExpBuffer(query);
1098 }
1099
1100 /*
1101  * selectDumpableNamespace: policy-setting subroutine
1102  *              Mark a namespace as to be dumped or not
1103  */
1104 static void
1105 selectDumpableNamespace(NamespaceInfo *nsinfo)
1106 {
1107         /*
1108          * If specific tables are being dumped, do not dump any complete
1109          * namespaces. If specific namespaces are being dumped, dump just those
1110          * namespaces. Otherwise, dump all non-system namespaces.
1111          */
1112         if (table_include_oids.head != NULL)
1113                 nsinfo->dobj.dump = false;
1114         else if (schema_include_oids.head != NULL)
1115                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1116                                                                                                    nsinfo->dobj.catId.oid);
1117         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1118                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1119                 nsinfo->dobj.dump = false;
1120         else
1121                 nsinfo->dobj.dump = true;
1122
1123         /*
1124          * In any case, a namespace can be excluded by an exclusion switch
1125          */
1126         if (nsinfo->dobj.dump &&
1127                 simple_oid_list_member(&schema_exclude_oids,
1128                                                            nsinfo->dobj.catId.oid))
1129                 nsinfo->dobj.dump = false;
1130 }
1131
1132 /*
1133  * selectDumpableTable: policy-setting subroutine
1134  *              Mark a table as to be dumped or not
1135  */
1136 static void
1137 selectDumpableTable(TableInfo *tbinfo)
1138 {
1139         /*
1140          * If specific tables are being dumped, dump just those tables; else, dump
1141          * according to the parent namespace's dump flag.
1142          */
1143         if (table_include_oids.head != NULL)
1144                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1145                                                                                                    tbinfo->dobj.catId.oid);
1146         else
1147                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1148
1149         /*
1150          * In any case, a table can be excluded by an exclusion switch
1151          */
1152         if (tbinfo->dobj.dump &&
1153                 simple_oid_list_member(&table_exclude_oids,
1154                                                            tbinfo->dobj.catId.oid))
1155                 tbinfo->dobj.dump = false;
1156 }
1157
1158 /*
1159  * selectDumpableType: policy-setting subroutine
1160  *              Mark a type as to be dumped or not
1161  *
1162  * If it's a table's rowtype or an autogenerated array type, we also apply a
1163  * special type code to facilitate sorting into the desired order.      (We don't
1164  * want to consider those to be ordinary types because that would bring tables
1165  * up into the datatype part of the dump order.)  We still set the object's
1166  * dump flag; that's not going to cause the dummy type to be dumped, but we
1167  * need it so that casts involving such types will be dumped correctly -- see
1168  * dumpCast.  This means the flag should be set the same as for the underlying
1169  * object (the table or base type).
1170  */
1171 static void
1172 selectDumpableType(TypeInfo *tyinfo)
1173 {
1174         /* skip complex types, except for standalone composite types */
1175         if (OidIsValid(tyinfo->typrelid) &&
1176                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1177         {
1178                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1179
1180                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1181                 if (tytable != NULL)
1182                         tyinfo->dobj.dump = tytable->dobj.dump;
1183                 else
1184                         tyinfo->dobj.dump = false;
1185                 return;
1186         }
1187
1188         /* skip auto-generated array types */
1189         if (tyinfo->isArray)
1190         {
1191                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1192
1193                 /*
1194                  * Fall through to set the dump flag; we assume that the subsequent
1195                  * rules will do the same thing as they would for the array's base
1196                  * type.  (We cannot reliably look up the base type here, since
1197                  * getTypes may not have processed it yet.)
1198                  */
1199         }
1200
1201         /* dump only types in dumpable namespaces */
1202         if (!tyinfo->dobj.namespace->dobj.dump)
1203                 tyinfo->dobj.dump = false;
1204
1205         /* skip undefined placeholder types */
1206         else if (!tyinfo->isDefined)
1207                 tyinfo->dobj.dump = false;
1208
1209         else
1210                 tyinfo->dobj.dump = true;
1211 }
1212
1213 /*
1214  * selectDumpableDefaultACL: policy-setting subroutine
1215  *              Mark a default ACL as to be dumped or not
1216  *
1217  * For per-schema default ACLs, dump if the schema is to be dumped.
1218  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1219  * and aclsSkip are checked separately.
1220  */
1221 static void
1222 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1223 {
1224         if (dinfo->dobj.namespace)
1225                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1226         else
1227                 dinfo->dobj.dump = include_everything;
1228 }
1229
1230 /*
1231  * selectDumpableExtension: policy-setting subroutine
1232  *              Mark an extension as to be dumped or not
1233  *
1234  * Normally, we dump all extensions, or none of them if include_everything
1235  * is false (i.e., a --schema or --table switch was given).  However, in
1236  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1237  * assume those will already be installed in the target database.  We identify
1238  * such extensions by their having OIDs in the range reserved for initdb.
1239  */
1240 static void
1241 selectDumpableExtension(ExtensionInfo *extinfo)
1242 {
1243         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1244                 extinfo->dobj.dump = false;
1245         else
1246                 extinfo->dobj.dump = include_everything;
1247 }
1248
1249 /*
1250  * selectDumpableObject: policy-setting subroutine
1251  *              Mark a generic dumpable object as to be dumped or not
1252  *
1253  * Use this only for object types without a special-case routine above.
1254  */
1255 static void
1256 selectDumpableObject(DumpableObject *dobj)
1257 {
1258         /*
1259          * Default policy is to dump if parent namespace is dumpable, or always
1260          * for non-namespace-associated items.
1261          */
1262         if (dobj->namespace)
1263                 dobj->dump = dobj->namespace->dobj.dump;
1264         else
1265                 dobj->dump = true;
1266 }
1267
1268 /*
1269  *      Dump a table's contents for loading using the COPY command
1270  *      - this routine is called by the Archiver when it wants the table
1271  *        to be dumped.
1272  */
1273
1274 static int
1275 dumpTableData_copy(Archive *fout, void *dcontext)
1276 {
1277         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1278         TableInfo  *tbinfo = tdinfo->tdtable;
1279         const char *classname = tbinfo->dobj.name;
1280         const bool      hasoids = tbinfo->hasoids;
1281         const bool      oids = tdinfo->oids;
1282         PQExpBuffer q = createPQExpBuffer();
1283         PGconn     *conn = GetConnection(fout);
1284         PGresult   *res;
1285         int                     ret;
1286         char       *copybuf;
1287         const char *column_list;
1288
1289         if (g_verbose)
1290                 write_msg(NULL, "dumping contents of table %s\n", classname);
1291
1292         /*
1293          * Make sure we are in proper schema.  We will qualify the table name
1294          * below anyway (in case its name conflicts with a pg_catalog table); but
1295          * this ensures reproducible results in case the table contains regproc,
1296          * regclass, etc columns.
1297          */
1298         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1299
1300         /*
1301          * If possible, specify the column list explicitly so that we have no
1302          * possibility of retrieving data in the wrong column order.  (The default
1303          * column ordering of COPY will not be what we want in certain corner
1304          * cases involving ADD COLUMN and inheritance.)
1305          */
1306         if (fout->remoteVersion >= 70300)
1307                 column_list = fmtCopyColumnList(tbinfo);
1308         else
1309                 column_list = "";               /* can't select columns in COPY */
1310
1311         if (oids && hasoids)
1312         {
1313                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1314                                                   fmtQualifiedId(fout,
1315                                                                                  tbinfo->dobj.namespace->dobj.name,
1316                                                                                  classname),
1317                                                   column_list);
1318         }
1319         else if (tdinfo->filtercond)
1320         {
1321                 /* Note: this syntax is only supported in 8.2 and up */
1322                 appendPQExpBufferStr(q, "COPY (SELECT ");
1323                 /* klugery to get rid of parens in column list */
1324                 if (strlen(column_list) > 2)
1325                 {
1326                         appendPQExpBufferStr(q, column_list + 1);
1327                         q->data[q->len - 1] = ' ';
1328                 }
1329                 else
1330                         appendPQExpBufferStr(q, "* ");
1331                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1332                                                   fmtQualifiedId(fout,
1333                                                                                  tbinfo->dobj.namespace->dobj.name,
1334                                                                                  classname),
1335                                                   tdinfo->filtercond);
1336         }
1337         else
1338         {
1339                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1340                                                   fmtQualifiedId(fout,
1341                                                                                  tbinfo->dobj.namespace->dobj.name,
1342                                                                                  classname),
1343                                                   column_list);
1344         }
1345         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1346         PQclear(res);
1347
1348         for (;;)
1349         {
1350                 ret = PQgetCopyData(conn, &copybuf, 0);
1351
1352                 if (ret < 0)
1353                         break;                          /* done or error */
1354
1355                 if (copybuf)
1356                 {
1357                         WriteData(fout, copybuf, ret);
1358                         PQfreemem(copybuf);
1359                 }
1360
1361                 /* ----------
1362                  * THROTTLE:
1363                  *
1364                  * There was considerable discussion in late July, 2000 regarding
1365                  * slowing down pg_dump when backing up large tables. Users with both
1366                  * slow & fast (multi-processor) machines experienced performance
1367                  * degradation when doing a backup.
1368                  *
1369                  * Initial attempts based on sleeping for a number of ms for each ms
1370                  * of work were deemed too complex, then a simple 'sleep in each loop'
1371                  * implementation was suggested. The latter failed because the loop
1372                  * was too tight. Finally, the following was implemented:
1373                  *
1374                  * If throttle is non-zero, then
1375                  *              See how long since the last sleep.
1376                  *              Work out how long to sleep (based on ratio).
1377                  *              If sleep is more than 100ms, then
1378                  *                      sleep
1379                  *                      reset timer
1380                  *              EndIf
1381                  * EndIf
1382                  *
1383                  * where the throttle value was the number of ms to sleep per ms of
1384                  * work. The calculation was done in each loop.
1385                  *
1386                  * Most of the hard work is done in the backend, and this solution
1387                  * still did not work particularly well: on slow machines, the ratio
1388                  * was 50:1, and on medium paced machines, 1:1, and on fast
1389                  * multi-processor machines, it had little or no effect, for reasons
1390                  * that were unclear.
1391                  *
1392                  * Further discussion ensued, and the proposal was dropped.
1393                  *
1394                  * For those people who want this feature, it can be implemented using
1395                  * gettimeofday in each loop, calculating the time since last sleep,
1396                  * multiplying that by the sleep ratio, then if the result is more
1397                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1398                  * function to sleep for a subsecond period ie.
1399                  *
1400                  * select(0, NULL, NULL, NULL, &tvi);
1401                  *
1402                  * This will return after the interval specified in the structure tvi.
1403                  * Finally, call gettimeofday again to save the 'last sleep time'.
1404                  * ----------
1405                  */
1406         }
1407         archprintf(fout, "\\.\n\n\n");
1408
1409         if (ret == -2)
1410         {
1411                 /* copy data transfer failed */
1412                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1413                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1414                 write_msg(NULL, "The command was: %s\n", q->data);
1415                 exit_nicely(1);
1416         }
1417
1418         /* Check command status and return to normal libpq state */
1419         res = PQgetResult(conn);
1420         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1421         {
1422                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1423                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1424                 write_msg(NULL, "The command was: %s\n", q->data);
1425                 exit_nicely(1);
1426         }
1427         PQclear(res);
1428
1429         destroyPQExpBuffer(q);
1430         return 1;
1431 }
1432
1433 /*
1434  * Dump table data using INSERT commands.
1435  *
1436  * Caution: when we restore from an archive file direct to database, the
1437  * INSERT commands emitted by this function have to be parsed by
1438  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1439  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1440  */
1441 static int
1442 dumpTableData_insert(Archive *fout, void *dcontext)
1443 {
1444         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1445         TableInfo  *tbinfo = tdinfo->tdtable;
1446         const char *classname = tbinfo->dobj.name;
1447         PQExpBuffer q = createPQExpBuffer();
1448         PGresult   *res;
1449         int                     tuple;
1450         int                     nfields;
1451         int                     field;
1452
1453         /*
1454          * Make sure we are in proper schema.  We will qualify the table name
1455          * below anyway (in case its name conflicts with a pg_catalog table); but
1456          * this ensures reproducible results in case the table contains regproc,
1457          * regclass, etc columns.
1458          */
1459         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1460
1461         if (fout->remoteVersion >= 70100)
1462         {
1463                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1464                                                   "SELECT * FROM ONLY %s",
1465                                                   fmtQualifiedId(fout,
1466                                                                                  tbinfo->dobj.namespace->dobj.name,
1467                                                                                  classname));
1468         }
1469         else
1470         {
1471                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1472                                                   "SELECT * FROM %s",
1473                                                   fmtQualifiedId(fout,
1474                                                                                  tbinfo->dobj.namespace->dobj.name,
1475                                                                                  classname));
1476         }
1477         if (tdinfo->filtercond)
1478                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1479
1480         ExecuteSqlStatement(fout, q->data);
1481
1482         while (1)
1483         {
1484                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1485                                                           PGRES_TUPLES_OK);
1486                 nfields = PQnfields(res);
1487                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1488                 {
1489                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1490                         if (nfields == 0)
1491                         {
1492                                 /* corner case for zero-column table */
1493                                 archprintf(fout, "DEFAULT VALUES;\n");
1494                                 continue;
1495                         }
1496                         if (column_inserts)
1497                         {
1498                                 resetPQExpBuffer(q);
1499                                 appendPQExpBuffer(q, "(");
1500                                 for (field = 0; field < nfields; field++)
1501                                 {
1502                                         if (field > 0)
1503                                                 appendPQExpBuffer(q, ", ");
1504                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1505                                 }
1506                                 appendPQExpBuffer(q, ") ");
1507                                 archputs(q->data, fout);
1508                         }
1509                         archprintf(fout, "VALUES (");
1510                         for (field = 0; field < nfields; field++)
1511                         {
1512                                 if (field > 0)
1513                                         archprintf(fout, ", ");
1514                                 if (PQgetisnull(res, tuple, field))
1515                                 {
1516                                         archprintf(fout, "NULL");
1517                                         continue;
1518                                 }
1519
1520                                 /* XXX This code is partially duplicated in ruleutils.c */
1521                                 switch (PQftype(res, field))
1522                                 {
1523                                         case INT2OID:
1524                                         case INT4OID:
1525                                         case INT8OID:
1526                                         case OIDOID:
1527                                         case FLOAT4OID:
1528                                         case FLOAT8OID:
1529                                         case NUMERICOID:
1530                                                 {
1531                                                         /*
1532                                                          * These types are printed without quotes unless
1533                                                          * they contain values that aren't accepted by the
1534                                                          * scanner unquoted (e.g., 'NaN').      Note that
1535                                                          * strtod() and friends might accept NaN, so we
1536                                                          * can't use that to test.
1537                                                          *
1538                                                          * In reality we only need to defend against
1539                                                          * infinity and NaN, so we need not get too crazy
1540                                                          * about pattern matching here.
1541                                                          */
1542                                                         const char *s = PQgetvalue(res, tuple, field);
1543
1544                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1545                                                                 archprintf(fout, "%s", s);
1546                                                         else
1547                                                                 archprintf(fout, "'%s'", s);
1548                                                 }
1549                                                 break;
1550
1551                                         case BITOID:
1552                                         case VARBITOID:
1553                                                 archprintf(fout, "B'%s'",
1554                                                                    PQgetvalue(res, tuple, field));
1555                                                 break;
1556
1557                                         case BOOLOID:
1558                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1559                                                         archprintf(fout, "true");
1560                                                 else
1561                                                         archprintf(fout, "false");
1562                                                 break;
1563
1564                                         default:
1565                                                 /* All other types are printed as string literals. */
1566                                                 resetPQExpBuffer(q);
1567                                                 appendStringLiteralAH(q,
1568                                                                                           PQgetvalue(res, tuple, field),
1569                                                                                           fout);
1570                                                 archputs(q->data, fout);
1571                                                 break;
1572                                 }
1573                         }
1574                         archprintf(fout, ");\n");
1575                 }
1576
1577                 if (PQntuples(res) <= 0)
1578                 {
1579                         PQclear(res);
1580                         break;
1581                 }
1582                 PQclear(res);
1583         }
1584
1585         archprintf(fout, "\n\n");
1586
1587         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1588
1589         destroyPQExpBuffer(q);
1590         return 1;
1591 }
1592
1593
1594 /*
1595  * dumpTableData -
1596  *        dump the contents of a single table
1597  *
1598  * Actually, this just makes an ArchiveEntry for the table contents.
1599  */
1600 static void
1601 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1602 {
1603         TableInfo  *tbinfo = tdinfo->tdtable;
1604         PQExpBuffer copyBuf = createPQExpBuffer();
1605         DataDumperPtr dumpFn;
1606         char       *copyStmt;
1607
1608         if (!dump_inserts)
1609         {
1610                 /* Dump/restore using COPY */
1611                 dumpFn = dumpTableData_copy;
1612                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1613                 appendPQExpBuffer(copyBuf, "COPY %s ",
1614                                                   fmtId(tbinfo->dobj.name));
1615                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1616                                                   fmtCopyColumnList(tbinfo),
1617                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1618                 copyStmt = copyBuf->data;
1619         }
1620         else
1621         {
1622                 /* Restore using INSERT */
1623                 dumpFn = dumpTableData_insert;
1624                 copyStmt = NULL;
1625         }
1626
1627         /*
1628          * Note: although the TableDataInfo is a full DumpableObject, we treat its
1629          * dependency on its table as "special" and pass it to ArchiveEntry now.
1630          * See comments for BuildArchiveDependencies.
1631          */
1632         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1633                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1634                                  NULL, tbinfo->rolname,
1635                                  false, "TABLE DATA", SECTION_DATA,
1636                                  "", "", copyStmt,
1637                                  &(tbinfo->dobj.dumpId), 1,
1638                                  dumpFn, tdinfo);
1639
1640         destroyPQExpBuffer(copyBuf);
1641 }
1642
1643 /*
1644  * refreshMatViewData -
1645  *        load or refresh the contents of a single materialized view
1646  *
1647  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
1648  * statement.
1649  */
1650 static void
1651 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
1652 {
1653         TableInfo  *tbinfo = tdinfo->tdtable;
1654         PQExpBuffer q;
1655
1656         /* If the materialized view is not flagged as scannable, skip this. */
1657         if (!tbinfo->isscannable)
1658                 return;
1659
1660         q = createPQExpBuffer();
1661
1662         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
1663                                           fmtId(tbinfo->dobj.name));
1664
1665         ArchiveEntry(fout,
1666                                  tdinfo->dobj.catId,                                    /* catalog ID */
1667                                  tdinfo->dobj.dumpId,                                   /* dump ID */
1668                                  tbinfo->dobj.name,                                             /* Name */
1669                                  tbinfo->dobj.namespace->dobj.name,     /* Namespace */
1670                                  NULL,                                                                  /* Tablespace */
1671                                  tbinfo->rolname,                                               /* Owner */
1672                                  false,                                                                 /* with oids */
1673                                  "MATERIALIZED VIEW DATA",                              /* Desc */
1674                                  SECTION_POST_DATA,                                             /* Section */
1675                                  q->data,                                                               /* Create */
1676                                  "",                                                                    /* Del */
1677                                  NULL,                                                                  /* Copy */
1678                                  tdinfo->dobj.dependencies,                             /* Deps */
1679                                  tdinfo->dobj.nDeps,                                    /* # Deps */
1680                                  NULL,                                                                  /* Dumper */
1681                                  NULL);                                                                 /* Dumper Arg */
1682
1683         destroyPQExpBuffer(q);
1684 }
1685
1686 /*
1687  * getTableData -
1688  *        set up dumpable objects representing the contents of tables
1689  */
1690 static void
1691 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1692 {
1693         int                     i;
1694
1695         for (i = 0; i < numTables; i++)
1696         {
1697                 if (tblinfo[i].dobj.dump)
1698                         makeTableDataInfo(&(tblinfo[i]), oids);
1699         }
1700 }
1701
1702 /*
1703  * Make a dumpable object for the data of this specific table
1704  *
1705  * Note: we make a TableDataInfo if and only if we are going to dump the
1706  * table data; the "dump" flag in such objects isn't used.
1707  */
1708 static void
1709 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1710 {
1711         TableDataInfo *tdinfo;
1712
1713         /*
1714          * Nothing to do if we already decided to dump the table.  This will
1715          * happen for "config" tables.
1716          */
1717         if (tbinfo->dataObj != NULL)
1718                 return;
1719
1720         /* Skip VIEWs (no data to dump) */
1721         if (tbinfo->relkind == RELKIND_VIEW)
1722                 return;
1723         /* Skip FOREIGN TABLEs (no data to dump) */
1724         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1725                 return;
1726
1727         /* Don't dump data in unlogged tables, if so requested */
1728         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1729                 no_unlogged_table_data)
1730                 return;
1731
1732         /* Check that the data is not explicitly excluded */
1733         if (simple_oid_list_member(&tabledata_exclude_oids,
1734                                                            tbinfo->dobj.catId.oid))
1735                 return;
1736
1737         /* OK, let's dump it */
1738         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1739
1740         if (tbinfo->relkind == RELKIND_MATVIEW)
1741                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
1742         else
1743                 tdinfo->dobj.objType = DO_TABLE_DATA;
1744
1745         /*
1746          * Note: use tableoid 0 so that this object won't be mistaken for
1747          * something that pg_depend entries apply to.
1748          */
1749         tdinfo->dobj.catId.tableoid = 0;
1750         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1751         AssignDumpId(&tdinfo->dobj);
1752         tdinfo->dobj.name = tbinfo->dobj.name;
1753         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1754         tdinfo->tdtable = tbinfo;
1755         tdinfo->oids = oids;
1756         tdinfo->filtercond = NULL;      /* might get set later */
1757         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1758
1759         tbinfo->dataObj = tdinfo;
1760 }
1761
1762 /*
1763  * The refresh for a materialized view must be dependent on the refresh for
1764  * any materialized view that this one is dependent on.
1765  *
1766  * This must be called after all the objects are created, but before they are
1767  * sorted.
1768  */
1769 static void
1770 buildMatViewRefreshDependencies(Archive *fout)
1771 {
1772         PQExpBuffer query = createPQExpBuffer();
1773         PGresult   *res;
1774         int                     ntups,
1775                                 i;
1776         int                     i_classid,
1777                                 i_objid,
1778                                 i_refobjid;
1779
1780         /* Make sure we are in proper schema */
1781         selectSourceSchema(fout, "pg_catalog");
1782
1783         if (fout->remoteVersion >= 90300)
1784         {
1785                 appendPQExpBuffer(query, "with recursive w as "
1786                                                   "( "
1787                                                   "select d1.objid, d2.refobjid, c2.relkind as refrelkind "
1788                                                   "from pg_depend d1 "
1789                                                   "join pg_class c1 on c1.oid = d1.objid "
1790                                                   "and c1.relkind = 'm' "
1791                                                   "join pg_rewrite r1 on r1.ev_class = d1.objid "
1792                                                   "join pg_depend d2 on d2.classid = 'pg_rewrite'::regclass "
1793                                                   "and d2.objid = r1.oid "
1794                                                   "and d2.refobjid <> d1.objid "
1795                                                   "join pg_class c2 on c2.oid = d2.refobjid "
1796                                                   "and c2.relkind in ('m','v') "
1797                                                   "where d1.classid = 'pg_class'::regclass "
1798                                                   "union "
1799                                                   "select w.objid, d3.refobjid, c3.relkind "
1800                                                   "from w "
1801                                                   "join pg_rewrite r3 on r3.ev_class = w.refobjid "
1802                                                   "join pg_depend d3 on d3.classid = 'pg_rewrite'::regclass "
1803                                                   "and d3.objid = r3.oid "
1804                                                   "and d3.refobjid <> w.refobjid "
1805                                                   "join pg_class c3 on c3.oid = d3.refobjid "
1806                                                   "and c3.relkind in ('m','v') "
1807                                                   ") "
1808                                                   "select 'pg_class'::regclass::oid as classid, objid, refobjid "
1809                                                   "from w "
1810                                                   "where refrelkind = 'm'");
1811         }
1812
1813         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1814
1815         ntups = PQntuples(res);
1816
1817         i_classid = PQfnumber(res, "classid");
1818         i_objid = PQfnumber(res, "objid");
1819         i_refobjid = PQfnumber(res, "refobjid");
1820
1821         for (i = 0; i < ntups; i++)
1822         {
1823                 CatalogId       objId;
1824                 CatalogId       refobjId;
1825                 DumpableObject  *dobj;
1826                 DumpableObject  *refdobj;
1827                 TableInfo          *tbinfo;
1828                 TableInfo          *reftbinfo;
1829
1830                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
1831                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
1832                 refobjId.tableoid = objId.tableoid;
1833                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
1834
1835                 dobj = findObjectByCatalogId(objId);
1836                 if (dobj == NULL)
1837                         continue;
1838
1839                 Assert(dobj->objType == DO_TABLE);
1840                 tbinfo = (TableInfo *) dobj;
1841                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
1842                 dobj = (DumpableObject *) tbinfo->dataObj;
1843                 if (dobj == NULL)
1844                         continue;
1845                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
1846
1847                 refdobj = findObjectByCatalogId(refobjId);
1848                 if (refdobj == NULL)
1849                         continue;
1850
1851                 Assert(refdobj->objType == DO_TABLE);
1852                 reftbinfo = (TableInfo *) refdobj;
1853                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
1854                 refdobj = (DumpableObject *) reftbinfo->dataObj;
1855                 if (refdobj == NULL)
1856                         continue;
1857                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
1858
1859                 addObjectDependency(dobj, refdobj->dumpId);
1860
1861                 if (!reftbinfo->isscannable)
1862                         tbinfo->isscannable = false;
1863         }
1864
1865         PQclear(res);
1866
1867         destroyPQExpBuffer(query);
1868 }
1869
1870 /*
1871  * getTableDataFKConstraints -
1872  *        add dump-order dependencies reflecting foreign key constraints
1873  *
1874  * This code is executed only in a data-only dump --- in schema+data dumps
1875  * we handle foreign key issues by not creating the FK constraints until
1876  * after the data is loaded.  In a data-only dump, however, we want to
1877  * order the table data objects in such a way that a table's referenced
1878  * tables are restored first.  (In the presence of circular references or
1879  * self-references this may be impossible; we'll detect and complain about
1880  * that during the dependency sorting step.)
1881  */
1882 static void
1883 getTableDataFKConstraints(void)
1884 {
1885         DumpableObject **dobjs;
1886         int                     numObjs;
1887         int                     i;
1888
1889         /* Search through all the dumpable objects for FK constraints */
1890         getDumpableObjects(&dobjs, &numObjs);
1891         for (i = 0; i < numObjs; i++)
1892         {
1893                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1894                 {
1895                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1896                         TableInfo  *ftable;
1897
1898                         /* Not interesting unless both tables are to be dumped */
1899                         if (cinfo->contable == NULL ||
1900                                 cinfo->contable->dataObj == NULL)
1901                                 continue;
1902                         ftable = findTableByOid(cinfo->confrelid);
1903                         if (ftable == NULL ||
1904                                 ftable->dataObj == NULL)
1905                                 continue;
1906
1907                         /*
1908                          * Okay, make referencing table's TABLE_DATA object depend on the
1909                          * referenced table's TABLE_DATA object.
1910                          */
1911                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1912                                                                 ftable->dataObj->dobj.dumpId);
1913                 }
1914         }
1915         free(dobjs);
1916 }
1917
1918
1919 /*
1920  * guessConstraintInheritance:
1921  *      In pre-8.4 databases, we can't tell for certain which constraints
1922  *      are inherited.  We assume a CHECK constraint is inherited if its name
1923  *      matches the name of any constraint in the parent.  Originally this code
1924  *      tried to compare the expression texts, but that can fail for various
1925  *      reasons --- for example, if the parent and child tables are in different
1926  *      schemas, reverse-listing of function calls may produce different text
1927  *      (schema-qualified or not) depending on search path.
1928  *
1929  *      In 8.4 and up we can rely on the conislocal field to decide which
1930  *      constraints must be dumped; much safer.
1931  *
1932  *      This function assumes all conislocal flags were initialized to TRUE.
1933  *      It clears the flag on anything that seems to be inherited.
1934  */
1935 static void
1936 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1937 {
1938         int                     i,
1939                                 j,
1940                                 k;
1941
1942         for (i = 0; i < numTables; i++)
1943         {
1944                 TableInfo  *tbinfo = &(tblinfo[i]);
1945                 int                     numParents;
1946                 TableInfo **parents;
1947                 TableInfo  *parent;
1948
1949                 /* Sequences and views never have parents */
1950                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1951                         tbinfo->relkind == RELKIND_VIEW)
1952                         continue;
1953
1954                 /* Don't bother computing anything for non-target tables, either */
1955                 if (!tbinfo->dobj.dump)
1956                         continue;
1957
1958                 numParents = tbinfo->numParents;
1959                 parents = tbinfo->parents;
1960
1961                 if (numParents == 0)
1962                         continue;                       /* nothing to see here, move along */
1963
1964                 /* scan for inherited CHECK constraints */
1965                 for (j = 0; j < tbinfo->ncheck; j++)
1966                 {
1967                         ConstraintInfo *constr;
1968
1969                         constr = &(tbinfo->checkexprs[j]);
1970
1971                         for (k = 0; k < numParents; k++)
1972                         {
1973                                 int                     l;
1974
1975                                 parent = parents[k];
1976                                 for (l = 0; l < parent->ncheck; l++)
1977                                 {
1978                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1979
1980                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1981                                         {
1982                                                 constr->conislocal = false;
1983                                                 break;
1984                                         }
1985                                 }
1986                                 if (!constr->conislocal)
1987                                         break;
1988                         }
1989                 }
1990         }
1991 }
1992
1993
1994 /*
1995  * dumpDatabase:
1996  *      dump the database definition
1997  */
1998 static void
1999 dumpDatabase(Archive *fout)
2000 {
2001         PQExpBuffer dbQry = createPQExpBuffer();
2002         PQExpBuffer delQry = createPQExpBuffer();
2003         PQExpBuffer creaQry = createPQExpBuffer();
2004         PGconn     *conn = GetConnection(fout);
2005         PGresult   *res;
2006         int                     i_tableoid,
2007                                 i_oid,
2008                                 i_dba,
2009                                 i_encoding,
2010                                 i_collate,
2011                                 i_ctype,
2012                                 i_frozenxid,
2013                                 i_tablespace;
2014         CatalogId       dbCatId;
2015         DumpId          dbDumpId;
2016         const char *datname,
2017                            *dba,
2018                            *encoding,
2019                            *collate,
2020                            *ctype,
2021                            *tablespace;
2022         uint32          frozenxid;
2023
2024         datname = PQdb(conn);
2025
2026         if (g_verbose)
2027                 write_msg(NULL, "saving database definition\n");
2028
2029         /* Make sure we are in proper schema */
2030         selectSourceSchema(fout, "pg_catalog");
2031
2032         /* Get the database owner and parameters from pg_database */
2033         if (fout->remoteVersion >= 80400)
2034         {
2035                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2036                                                   "(%s datdba) AS dba, "
2037                                                   "pg_encoding_to_char(encoding) AS encoding, "
2038                                                   "datcollate, datctype, datfrozenxid, "
2039                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2040                                           "shobj_description(oid, 'pg_database') AS description "
2041
2042                                                   "FROM pg_database "
2043                                                   "WHERE datname = ",
2044                                                   username_subquery);
2045                 appendStringLiteralAH(dbQry, datname, fout);
2046         }
2047         else if (fout->remoteVersion >= 80200)
2048         {
2049                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2050                                                   "(%s datdba) AS dba, "
2051                                                   "pg_encoding_to_char(encoding) AS encoding, "
2052                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2053                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2054                                           "shobj_description(oid, 'pg_database') AS description "
2055
2056                                                   "FROM pg_database "
2057                                                   "WHERE datname = ",
2058                                                   username_subquery);
2059                 appendStringLiteralAH(dbQry, datname, fout);
2060         }
2061         else if (fout->remoteVersion >= 80000)
2062         {
2063                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2064                                                   "(%s datdba) AS dba, "
2065                                                   "pg_encoding_to_char(encoding) AS encoding, "
2066                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2067                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2068                                                   "FROM pg_database "
2069                                                   "WHERE datname = ",
2070                                                   username_subquery);
2071                 appendStringLiteralAH(dbQry, datname, fout);
2072         }
2073         else if (fout->remoteVersion >= 70100)
2074         {
2075                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2076                                                   "(%s datdba) AS dba, "
2077                                                   "pg_encoding_to_char(encoding) AS encoding, "
2078                                                   "NULL AS datcollate, NULL AS datctype, "
2079                                                   "0 AS datfrozenxid, "
2080                                                   "NULL AS tablespace "
2081                                                   "FROM pg_database "
2082                                                   "WHERE datname = ",
2083                                                   username_subquery);
2084                 appendStringLiteralAH(dbQry, datname, fout);
2085         }
2086         else
2087         {
2088                 appendPQExpBuffer(dbQry, "SELECT "
2089                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
2090                                                   "oid, "
2091                                                   "(%s datdba) AS dba, "
2092                                                   "pg_encoding_to_char(encoding) AS encoding, "
2093                                                   "NULL AS datcollate, NULL AS datctype, "
2094                                                   "0 AS datfrozenxid, "
2095                                                   "NULL AS tablespace "
2096                                                   "FROM pg_database "
2097                                                   "WHERE datname = ",
2098                                                   username_subquery);
2099                 appendStringLiteralAH(dbQry, datname, fout);
2100         }
2101
2102         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2103
2104         i_tableoid = PQfnumber(res, "tableoid");
2105         i_oid = PQfnumber(res, "oid");
2106         i_dba = PQfnumber(res, "dba");
2107         i_encoding = PQfnumber(res, "encoding");
2108         i_collate = PQfnumber(res, "datcollate");
2109         i_ctype = PQfnumber(res, "datctype");
2110         i_frozenxid = PQfnumber(res, "datfrozenxid");
2111         i_tablespace = PQfnumber(res, "tablespace");
2112
2113         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2114         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2115         dba = PQgetvalue(res, 0, i_dba);
2116         encoding = PQgetvalue(res, 0, i_encoding);
2117         collate = PQgetvalue(res, 0, i_collate);
2118         ctype = PQgetvalue(res, 0, i_ctype);
2119         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2120         tablespace = PQgetvalue(res, 0, i_tablespace);
2121
2122         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2123                                           fmtId(datname));
2124         if (strlen(encoding) > 0)
2125         {
2126                 appendPQExpBuffer(creaQry, " ENCODING = ");
2127                 appendStringLiteralAH(creaQry, encoding, fout);
2128         }
2129         if (strlen(collate) > 0)
2130         {
2131                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
2132                 appendStringLiteralAH(creaQry, collate, fout);
2133         }
2134         if (strlen(ctype) > 0)
2135         {
2136                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
2137                 appendStringLiteralAH(creaQry, ctype, fout);
2138         }
2139         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
2140                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2141                                                   fmtId(tablespace));
2142         appendPQExpBuffer(creaQry, ";\n");
2143
2144         if (binary_upgrade)
2145         {
2146                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
2147                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2148                                                   "SET datfrozenxid = '%u'\n"
2149                                                   "WHERE        datname = ",
2150                                                   frozenxid);
2151                 appendStringLiteralAH(creaQry, datname, fout);
2152                 appendPQExpBuffer(creaQry, ";\n");
2153
2154         }
2155
2156         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2157                                           fmtId(datname));
2158
2159         dbDumpId = createDumpId();
2160
2161         ArchiveEntry(fout,
2162                                  dbCatId,               /* catalog ID */
2163                                  dbDumpId,              /* dump ID */
2164                                  datname,               /* Name */
2165                                  NULL,                  /* Namespace */
2166                                  NULL,                  /* Tablespace */
2167                                  dba,                   /* Owner */
2168                                  false,                 /* with oids */
2169                                  "DATABASE",    /* Desc */
2170                                  SECTION_PRE_DATA,              /* Section */
2171                                  creaQry->data, /* Create */
2172                                  delQry->data,  /* Del */
2173                                  NULL,                  /* Copy */
2174                                  NULL,                  /* Deps */
2175                                  0,                             /* # Deps */
2176                                  NULL,                  /* Dumper */
2177                                  NULL);                 /* Dumper Arg */
2178
2179         /*
2180          * pg_largeobject and pg_largeobject_metadata come from the old system
2181          * intact, so set their relfrozenxids.
2182          */
2183         if (binary_upgrade)
2184         {
2185                 PGresult   *lo_res;
2186                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2187                 PQExpBuffer loOutQry = createPQExpBuffer();
2188                 int                     i_relfrozenxid;
2189
2190                 /*
2191                  * pg_largeobject
2192                  */
2193                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2194                                                   "FROM pg_catalog.pg_class\n"
2195                                                   "WHERE oid = %u;\n",
2196                                                   LargeObjectRelationId);
2197
2198                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2199
2200                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2201
2202                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2203                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2204                                                   "SET relfrozenxid = '%u'\n"
2205                                                   "WHERE oid = %u;\n",
2206                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2207                                                   LargeObjectRelationId);
2208                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2209                                          "pg_largeobject", NULL, NULL, "",
2210                                          false, "pg_largeobject", SECTION_PRE_DATA,
2211                                          loOutQry->data, "", NULL,
2212                                          NULL, 0,
2213                                          NULL, NULL);
2214
2215                 PQclear(lo_res);
2216
2217                 /*
2218                  * pg_largeobject_metadata
2219                  */
2220                 if (fout->remoteVersion >= 90000)
2221                 {
2222                         resetPQExpBuffer(loFrozenQry);
2223                         resetPQExpBuffer(loOutQry);
2224
2225                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2226                                                           "FROM pg_catalog.pg_class\n"
2227                                                           "WHERE oid = %u;\n",
2228                                                           LargeObjectMetadataRelationId);
2229
2230                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2231
2232                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2233
2234                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2235                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2236                                                           "SET relfrozenxid = '%u'\n"
2237                                                           "WHERE oid = %u;\n",
2238                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2239                                                           LargeObjectMetadataRelationId);
2240                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2241                                                  "pg_largeobject_metadata", NULL, NULL, "",
2242                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2243                                                  loOutQry->data, "", NULL,
2244                                                  NULL, 0,
2245                                                  NULL, NULL);
2246
2247                         PQclear(lo_res);
2248                 }
2249
2250                 destroyPQExpBuffer(loFrozenQry);
2251                 destroyPQExpBuffer(loOutQry);
2252         }
2253
2254         /* Dump DB comment if any */
2255         if (fout->remoteVersion >= 80200)
2256         {
2257                 /*
2258                  * 8.2 keeps comments on shared objects in a shared table, so we
2259                  * cannot use the dumpComment used for other database objects.
2260                  */
2261                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2262
2263                 if (comment && strlen(comment))
2264                 {
2265                         resetPQExpBuffer(dbQry);
2266
2267                         /*
2268                          * Generates warning when loaded into a differently-named
2269                          * database.
2270                          */
2271                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2272                         appendStringLiteralAH(dbQry, comment, fout);
2273                         appendPQExpBuffer(dbQry, ";\n");
2274
2275                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2276                                                  dba, false, "COMMENT", SECTION_NONE,
2277                                                  dbQry->data, "", NULL,
2278                                                  &dbDumpId, 1, NULL, NULL);
2279                 }
2280         }
2281         else
2282         {
2283                 resetPQExpBuffer(dbQry);
2284                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2285                 dumpComment(fout, dbQry->data, NULL, "",
2286                                         dbCatId, 0, dbDumpId);
2287         }
2288
2289         PQclear(res);
2290
2291         /* Dump shared security label. */
2292         if (!no_security_labels && fout->remoteVersion >= 90200)
2293         {
2294                 PQExpBuffer seclabelQry = createPQExpBuffer();
2295
2296                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2297                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2298                 resetPQExpBuffer(seclabelQry);
2299                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2300                 if (strlen(seclabelQry->data))
2301                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2302                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2303                                                  seclabelQry->data, "", NULL,
2304                                                  &dbDumpId, 1, NULL, NULL);
2305                 destroyPQExpBuffer(seclabelQry);
2306         }
2307
2308         destroyPQExpBuffer(dbQry);
2309         destroyPQExpBuffer(delQry);
2310         destroyPQExpBuffer(creaQry);
2311 }
2312
2313
2314 /*
2315  * dumpEncoding: put the correct encoding into the archive
2316  */
2317 static void
2318 dumpEncoding(Archive *AH)
2319 {
2320         const char *encname = pg_encoding_to_char(AH->encoding);
2321         PQExpBuffer qry = createPQExpBuffer();
2322
2323         if (g_verbose)
2324                 write_msg(NULL, "saving encoding = %s\n", encname);
2325
2326         appendPQExpBuffer(qry, "SET client_encoding = ");
2327         appendStringLiteralAH(qry, encname, AH);
2328         appendPQExpBuffer(qry, ";\n");
2329
2330         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2331                                  "ENCODING", NULL, NULL, "",
2332                                  false, "ENCODING", SECTION_PRE_DATA,
2333                                  qry->data, "", NULL,
2334                                  NULL, 0,
2335                                  NULL, NULL);
2336
2337         destroyPQExpBuffer(qry);
2338 }
2339
2340
2341 /*
2342  * dumpStdStrings: put the correct escape string behavior into the archive
2343  */
2344 static void
2345 dumpStdStrings(Archive *AH)
2346 {
2347         const char *stdstrings = AH->std_strings ? "on" : "off";
2348         PQExpBuffer qry = createPQExpBuffer();
2349
2350         if (g_verbose)
2351                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2352                                   stdstrings);
2353
2354         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2355                                           stdstrings);
2356
2357         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2358                                  "STDSTRINGS", NULL, NULL, "",
2359                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2360                                  qry->data, "", NULL,
2361                                  NULL, 0,
2362                                  NULL, NULL);
2363
2364         destroyPQExpBuffer(qry);
2365 }
2366
2367
2368 /*
2369  * getBlobs:
2370  *      Collect schema-level data about large objects
2371  */
2372 static void
2373 getBlobs(Archive *fout)
2374 {
2375         PQExpBuffer blobQry = createPQExpBuffer();
2376         BlobInfo   *binfo;
2377         DumpableObject *bdata;
2378         PGresult   *res;
2379         int                     ntups;
2380         int                     i;
2381
2382         /* Verbose message */
2383         if (g_verbose)
2384                 write_msg(NULL, "reading large objects\n");
2385
2386         /* Make sure we are in proper schema */
2387         selectSourceSchema(fout, "pg_catalog");
2388
2389         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2390         if (fout->remoteVersion >= 90000)
2391                 appendPQExpBuffer(blobQry,
2392                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2393                                                   " FROM pg_largeobject_metadata",
2394                                                   username_subquery);
2395         else if (fout->remoteVersion >= 70100)
2396                 appendPQExpBuffer(blobQry,
2397                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2398                                                   " FROM pg_largeobject");
2399         else
2400                 appendPQExpBuffer(blobQry,
2401                                                   "SELECT oid, NULL::oid, NULL::oid"
2402                                                   " FROM pg_class WHERE relkind = 'l'");
2403
2404         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2405
2406         ntups = PQntuples(res);
2407         if (ntups > 0)
2408         {
2409                 /*
2410                  * Each large object has its own BLOB archive entry.
2411                  */
2412                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2413
2414                 for (i = 0; i < ntups; i++)
2415                 {
2416                         binfo[i].dobj.objType = DO_BLOB;
2417                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2418                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2419                         AssignDumpId(&binfo[i].dobj);
2420
2421                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2422                         if (!PQgetisnull(res, i, 1))
2423                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2424                         else
2425                                 binfo[i].rolname = "";
2426                         if (!PQgetisnull(res, i, 2))
2427                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2428                         else
2429                                 binfo[i].blobacl = NULL;
2430                 }
2431
2432                 /*
2433                  * If we have any large objects, a "BLOBS" archive entry is needed.
2434                  * This is just a placeholder for sorting; it carries no data now.
2435                  */
2436                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2437                 bdata->objType = DO_BLOB_DATA;
2438                 bdata->catId = nilCatalogId;
2439                 AssignDumpId(bdata);
2440                 bdata->name = pg_strdup("BLOBS");
2441         }
2442
2443         PQclear(res);
2444         destroyPQExpBuffer(blobQry);
2445 }
2446
2447 /*
2448  * dumpBlob
2449  *
2450  * dump the definition (metadata) of the given large object
2451  */
2452 static void
2453 dumpBlob(Archive *fout, BlobInfo *binfo)
2454 {
2455         PQExpBuffer cquery = createPQExpBuffer();
2456         PQExpBuffer dquery = createPQExpBuffer();
2457
2458         appendPQExpBuffer(cquery,
2459                                           "SELECT pg_catalog.lo_create('%s');\n",
2460                                           binfo->dobj.name);
2461
2462         appendPQExpBuffer(dquery,
2463                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2464                                           binfo->dobj.name);
2465
2466         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2467                                  binfo->dobj.name,
2468                                  NULL, NULL,
2469                                  binfo->rolname, false,
2470                                  "BLOB", SECTION_PRE_DATA,
2471                                  cquery->data, dquery->data, NULL,
2472                                  NULL, 0,
2473                                  NULL, NULL);
2474
2475         /* set up tag for comment and/or ACL */
2476         resetPQExpBuffer(cquery);
2477         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2478
2479         /* Dump comment if any */
2480         dumpComment(fout, cquery->data,
2481                                 NULL, binfo->rolname,
2482                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2483
2484         /* Dump security label if any */
2485         dumpSecLabel(fout, cquery->data,
2486                                  NULL, binfo->rolname,
2487                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2488
2489         /* Dump ACL if any */
2490         if (binfo->blobacl)
2491                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2492                                 binfo->dobj.name, NULL, cquery->data,
2493                                 NULL, binfo->rolname, binfo->blobacl);
2494
2495         destroyPQExpBuffer(cquery);
2496         destroyPQExpBuffer(dquery);
2497 }
2498
2499 /*
2500  * dumpBlobs:
2501  *      dump the data contents of all large objects
2502  */
2503 static int
2504 dumpBlobs(Archive *fout, void *arg)
2505 {
2506         const char *blobQry;
2507         const char *blobFetchQry;
2508         PGconn     *conn = GetConnection(fout);
2509         PGresult   *res;
2510         char            buf[LOBBUFSIZE];
2511         int                     ntups;
2512         int                     i;
2513         int                     cnt;
2514
2515         if (g_verbose)
2516                 write_msg(NULL, "saving large objects\n");
2517
2518         /* Make sure we are in proper schema */
2519         selectSourceSchema(fout, "pg_catalog");
2520
2521         /*
2522          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2523          * the already-in-memory dumpable objects instead...
2524          */
2525         if (fout->remoteVersion >= 90000)
2526                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2527         else if (fout->remoteVersion >= 70100)
2528                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2529         else
2530                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2531
2532         ExecuteSqlStatement(fout, blobQry);
2533
2534         /* Command to fetch from cursor */
2535         blobFetchQry = "FETCH 1000 IN bloboid";
2536
2537         do
2538         {
2539                 /* Do a fetch */
2540                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2541
2542                 /* Process the tuples, if any */
2543                 ntups = PQntuples(res);
2544                 for (i = 0; i < ntups; i++)
2545                 {
2546                         Oid                     blobOid;
2547                         int                     loFd;
2548
2549                         blobOid = atooid(PQgetvalue(res, i, 0));
2550                         /* Open the BLOB */
2551                         loFd = lo_open(conn, blobOid, INV_READ);
2552                         if (loFd == -1)
2553                                 exit_horribly(NULL, "could not open large object %u: %s",
2554                                                           blobOid, PQerrorMessage(conn));
2555
2556                         StartBlob(fout, blobOid);
2557
2558                         /* Now read it in chunks, sending data to archive */
2559                         do
2560                         {
2561                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2562                                 if (cnt < 0)
2563                                         exit_horribly(NULL, "error reading large object %u: %s",
2564                                                                   blobOid, PQerrorMessage(conn));
2565
2566                                 WriteData(fout, buf, cnt);
2567                         } while (cnt > 0);
2568
2569                         lo_close(conn, loFd);
2570
2571                         EndBlob(fout, blobOid);
2572                 }
2573
2574                 PQclear(res);
2575         } while (ntups > 0);
2576
2577         return 1;
2578 }
2579
2580 static void
2581 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2582                                                                                  PQExpBuffer upgrade_buffer,
2583                                                                                  Oid pg_type_oid)
2584 {
2585         PQExpBuffer upgrade_query = createPQExpBuffer();
2586         PGresult   *upgrade_res;
2587         Oid                     pg_type_array_oid;
2588
2589         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2590         appendPQExpBuffer(upgrade_buffer,
2591          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2592                                           pg_type_oid);
2593
2594         /* we only support old >= 8.3 for binary upgrades */
2595         appendPQExpBuffer(upgrade_query,
2596                                           "SELECT typarray "
2597                                           "FROM pg_catalog.pg_type "
2598                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2599                                           pg_type_oid);
2600
2601         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2602
2603         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2604
2605         if (OidIsValid(pg_type_array_oid))
2606         {
2607                 appendPQExpBuffer(upgrade_buffer,
2608                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2609                 appendPQExpBuffer(upgrade_buffer,
2610                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2611                                                   pg_type_array_oid);
2612         }
2613
2614         PQclear(upgrade_res);
2615         destroyPQExpBuffer(upgrade_query);
2616 }
2617
2618 static bool
2619 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2620                                                                                 PQExpBuffer upgrade_buffer,
2621                                                                                 Oid pg_rel_oid)
2622 {
2623         PQExpBuffer upgrade_query = createPQExpBuffer();
2624         PGresult   *upgrade_res;
2625         Oid                     pg_type_oid;
2626         bool            toast_set = false;
2627
2628         /* we only support old >= 8.3 for binary upgrades */
2629         appendPQExpBuffer(upgrade_query,
2630                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2631                                           "FROM pg_catalog.pg_class c "
2632                                           "LEFT JOIN pg_catalog.pg_class t ON "
2633                                           "  (c.reltoastrelid = t.oid) "
2634                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2635                                           pg_rel_oid);
2636
2637         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2638
2639         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2640
2641         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2642                                                                                          pg_type_oid);
2643
2644         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2645         {
2646                 /* Toast tables do not have pg_type array rows */
2647                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2648                                                                                         PQfnumber(upgrade_res, "trel")));
2649
2650                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2651                 appendPQExpBuffer(upgrade_buffer,
2652                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2653                                                   pg_type_toast_oid);
2654
2655                 toast_set = true;
2656         }
2657
2658         PQclear(upgrade_res);
2659         destroyPQExpBuffer(upgrade_query);
2660
2661         return toast_set;
2662 }
2663
2664 static void
2665 binary_upgrade_set_pg_class_oids(Archive *fout,
2666                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2667                                                                  bool is_index)
2668 {
2669         PQExpBuffer upgrade_query = createPQExpBuffer();
2670         PGresult   *upgrade_res;
2671         Oid                     pg_class_reltoastrelid;
2672         Oid                     pg_class_reltoastidxid;
2673
2674         appendPQExpBuffer(upgrade_query,
2675                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2676                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2677                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2678                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2679                                           pg_class_oid);
2680
2681         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2682
2683         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2684         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2685
2686         appendPQExpBuffer(upgrade_buffer,
2687                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2688
2689         if (!is_index)
2690         {
2691                 appendPQExpBuffer(upgrade_buffer,
2692                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2693                                                   pg_class_oid);
2694                 /* only tables have toast tables, not indexes */
2695                 if (OidIsValid(pg_class_reltoastrelid))
2696                 {
2697                         /*
2698                          * One complexity is that the table definition might not require
2699                          * the creation of a TOAST table, and the TOAST table might have
2700                          * been created long after table creation, when the table was
2701                          * loaded with wide data.  By setting the TOAST oid we force
2702                          * creation of the TOAST heap and TOAST index by the backend so we
2703                          * can cleanly copy the files during binary upgrade.
2704                          */
2705
2706                         appendPQExpBuffer(upgrade_buffer,
2707                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2708                                                           pg_class_reltoastrelid);
2709
2710                         /* every toast table has an index */
2711                         appendPQExpBuffer(upgrade_buffer,
2712                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2713                                                           pg_class_reltoastidxid);
2714                 }
2715         }
2716         else
2717                 appendPQExpBuffer(upgrade_buffer,
2718                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2719                                                   pg_class_oid);
2720
2721         appendPQExpBuffer(upgrade_buffer, "\n");
2722
2723         PQclear(upgrade_res);
2724         destroyPQExpBuffer(upgrade_query);
2725 }
2726
2727 /*
2728  * If the DumpableObject is a member of an extension, add a suitable
2729  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2730  */
2731 static void
2732 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2733                                                                 DumpableObject *dobj,
2734                                                                 const char *objlabel)
2735 {
2736         DumpableObject *extobj = NULL;
2737         int                     i;
2738
2739         if (!dobj->ext_member)
2740                 return;
2741
2742         /*
2743          * Find the parent extension.  We could avoid this search if we wanted to
2744          * add a link field to DumpableObject, but the space costs of that would
2745          * be considerable.  We assume that member objects could only have a
2746          * direct dependency on their own extension, not any others.
2747          */
2748         for (i = 0; i < dobj->nDeps; i++)
2749         {
2750                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2751                 if (extobj && extobj->objType == DO_EXTENSION)
2752                         break;
2753                 extobj = NULL;
2754         }
2755         if (extobj == NULL)
2756                 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2757
2758         appendPQExpBuffer(upgrade_buffer,
2759           "\n-- For binary upgrade, handle extension membership the hard way\n");
2760         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2761                                           fmtId(extobj->name),
2762                                           objlabel);
2763 }
2764
2765 /*
2766  * getNamespaces:
2767  *        read all namespaces in the system catalogs and return them in the
2768  * NamespaceInfo* structure
2769  *
2770  *      numNamespaces is set to the number of namespaces read in
2771  */
2772 NamespaceInfo *
2773 getNamespaces(Archive *fout, int *numNamespaces)
2774 {
2775         PGresult   *res;
2776         int                     ntups;
2777         int                     i;
2778         PQExpBuffer query;
2779         NamespaceInfo *nsinfo;
2780         int                     i_tableoid;
2781         int                     i_oid;
2782         int                     i_nspname;
2783         int                     i_rolname;
2784         int                     i_nspacl;
2785
2786         /*
2787          * Before 7.3, there are no real namespaces; create two dummy entries, one
2788          * for user stuff and one for system stuff.
2789          */
2790         if (fout->remoteVersion < 70300)
2791         {
2792                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2793
2794                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2795                 nsinfo[0].dobj.catId.tableoid = 0;
2796                 nsinfo[0].dobj.catId.oid = 0;
2797                 AssignDumpId(&nsinfo[0].dobj);
2798                 nsinfo[0].dobj.name = pg_strdup("public");
2799                 nsinfo[0].rolname = pg_strdup("");
2800                 nsinfo[0].nspacl = pg_strdup("");
2801
2802                 selectDumpableNamespace(&nsinfo[0]);
2803
2804                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2805                 nsinfo[1].dobj.catId.tableoid = 0;
2806                 nsinfo[1].dobj.catId.oid = 1;
2807                 AssignDumpId(&nsinfo[1].dobj);
2808                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2809                 nsinfo[1].rolname = pg_strdup("");
2810                 nsinfo[1].nspacl = pg_strdup("");
2811
2812                 selectDumpableNamespace(&nsinfo[1]);
2813
2814                 *numNamespaces = 2;
2815
2816                 return nsinfo;
2817         }
2818
2819         query = createPQExpBuffer();
2820
2821         /* Make sure we are in proper schema */
2822         selectSourceSchema(fout, "pg_catalog");
2823
2824         /*
2825          * we fetch all namespaces including system ones, so that every object we
2826          * read in can be linked to a containing namespace.
2827          */
2828         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2829                                           "(%s nspowner) AS rolname, "
2830                                           "nspacl FROM pg_namespace",
2831                                           username_subquery);
2832
2833         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2834
2835         ntups = PQntuples(res);
2836
2837         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2838
2839         i_tableoid = PQfnumber(res, "tableoid");
2840         i_oid = PQfnumber(res, "oid");
2841         i_nspname = PQfnumber(res, "nspname");
2842         i_rolname = PQfnumber(res, "rolname");
2843         i_nspacl = PQfnumber(res, "nspacl");
2844
2845         for (i = 0; i < ntups; i++)
2846         {
2847                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2848                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2849                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2850                 AssignDumpId(&nsinfo[i].dobj);
2851                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2852                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2853                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2854
2855                 /* Decide whether to dump this namespace */
2856                 selectDumpableNamespace(&nsinfo[i]);
2857
2858                 if (strlen(nsinfo[i].rolname) == 0)
2859                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2860                                           nsinfo[i].dobj.name);
2861         }
2862
2863         PQclear(res);
2864         destroyPQExpBuffer(query);
2865
2866         *numNamespaces = ntups;
2867
2868         return nsinfo;
2869 }
2870
2871 /*
2872  * findNamespace:
2873  *              given a namespace OID and an object OID, look up the info read by
2874  *              getNamespaces
2875  *
2876  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2877  * a system object or not.      In 7.3 and later there is no guessing, and we
2878  * don't use objoid at all.
2879  */
2880 static NamespaceInfo *
2881 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2882 {
2883         NamespaceInfo *nsinfo;
2884
2885         if (fout->remoteVersion >= 70300)
2886         {
2887                 nsinfo = findNamespaceByOid(nsoid);
2888         }
2889         else
2890         {
2891                 /* This code depends on the dummy objects set up by getNamespaces. */
2892                 Oid                     i;
2893
2894                 if (objoid > g_last_builtin_oid)
2895                         i = 0;                          /* user object */
2896                 else
2897                         i = 1;                          /* system object */
2898                 nsinfo = findNamespaceByOid(i);
2899         }
2900
2901         if (nsinfo == NULL)
2902                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2903
2904         return nsinfo;
2905 }
2906
2907 /*
2908  * getExtensions:
2909  *        read all extensions in the system catalogs and return them in the
2910  * ExtensionInfo* structure
2911  *
2912  *      numExtensions is set to the number of extensions read in
2913  */
2914 ExtensionInfo *
2915 getExtensions(Archive *fout, int *numExtensions)
2916 {
2917         PGresult   *res;
2918         int                     ntups;
2919         int                     i;
2920         PQExpBuffer query;
2921         ExtensionInfo *extinfo;
2922         int                     i_tableoid;
2923         int                     i_oid;
2924         int                     i_extname;
2925         int                     i_nspname;
2926         int                     i_extrelocatable;
2927         int                     i_extversion;
2928         int                     i_extconfig;
2929         int                     i_extcondition;
2930
2931         /*
2932          * Before 9.1, there are no extensions.
2933          */
2934         if (fout->remoteVersion < 90100)
2935         {
2936                 *numExtensions = 0;
2937                 return NULL;
2938         }
2939
2940         query = createPQExpBuffer();
2941
2942         /* Make sure we are in proper schema */
2943         selectSourceSchema(fout, "pg_catalog");
2944
2945         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2946                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2947                                           "FROM pg_extension x "
2948                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2949
2950         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2951
2952         ntups = PQntuples(res);
2953
2954         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2955
2956         i_tableoid = PQfnumber(res, "tableoid");
2957         i_oid = PQfnumber(res, "oid");
2958         i_extname = PQfnumber(res, "extname");
2959         i_nspname = PQfnumber(res, "nspname");
2960         i_extrelocatable = PQfnumber(res, "extrelocatable");
2961         i_extversion = PQfnumber(res, "extversion");
2962         i_extconfig = PQfnumber(res, "extconfig");
2963         i_extcondition = PQfnumber(res, "extcondition");
2964
2965         for (i = 0; i < ntups; i++)
2966         {
2967                 extinfo[i].dobj.objType = DO_EXTENSION;
2968                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2969                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2970                 AssignDumpId(&extinfo[i].dobj);
2971                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2972                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2973                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2974                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2975                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2976                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2977
2978                 /* Decide whether we want to dump it */
2979                 selectDumpableExtension(&(extinfo[i]));
2980         }
2981
2982         PQclear(res);
2983         destroyPQExpBuffer(query);
2984
2985         *numExtensions = ntups;
2986
2987         return extinfo;
2988 }
2989
2990 /*
2991  * getTypes:
2992  *        read all types in the system catalogs and return them in the
2993  * TypeInfo* structure
2994  *
2995  *      numTypes is set to the number of types read in
2996  *
2997  * NB: this must run after getFuncs() because we assume we can do
2998  * findFuncByOid().
2999  */
3000 TypeInfo *
3001 getTypes(Archive *fout, int *numTypes)
3002 {
3003         PGresult   *res;
3004         int                     ntups;
3005         int                     i;
3006         PQExpBuffer query = createPQExpBuffer();
3007         TypeInfo   *tyinfo;
3008         ShellTypeInfo *stinfo;
3009         int                     i_tableoid;
3010         int                     i_oid;
3011         int                     i_typname;
3012         int                     i_typnamespace;
3013         int                     i_typacl;
3014         int                     i_rolname;
3015         int                     i_typinput;
3016         int                     i_typoutput;
3017         int                     i_typelem;
3018         int                     i_typrelid;
3019         int                     i_typrelkind;
3020         int                     i_typtype;
3021         int                     i_typisdefined;
3022         int                     i_isarray;
3023
3024         /*
3025          * we include even the built-in types because those may be used as array
3026          * elements by user-defined types
3027          *
3028          * we filter out the built-in types when we dump out the types
3029          *
3030          * same approach for undefined (shell) types and array types
3031          *
3032          * Note: as of 8.3 we can reliably detect whether a type is an
3033          * auto-generated array type by checking the element type's typarray.
3034          * (Before that the test is capable of generating false positives.) We
3035          * still check for name beginning with '_', though, so as to avoid the
3036          * cost of the subselect probe for all standard types.  This would have to
3037          * be revisited if the backend ever allows renaming of array types.
3038          */
3039
3040         /* Make sure we are in proper schema */
3041         selectSourceSchema(fout, "pg_catalog");
3042
3043         if (fout->remoteVersion >= 90200)
3044         {
3045                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3046                                                   "typnamespace, typacl, "
3047                                                   "(%s typowner) AS rolname, "
3048                                                   "typinput::oid AS typinput, "
3049                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3050                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3051                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3052                                                   "typtype, typisdefined, "
3053                                                   "typname[0] = '_' AND typelem != 0 AND "
3054                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3055                                                   "FROM pg_type",
3056                                                   username_subquery);
3057         }
3058         else if (fout->remoteVersion >= 80300)
3059         {
3060                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3061                                                   "typnamespace, '{=U}' AS typacl, "
3062                                                   "(%s typowner) AS rolname, "
3063                                                   "typinput::oid AS typinput, "
3064                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3065                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3066                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3067                                                   "typtype, typisdefined, "
3068                                                   "typname[0] = '_' AND typelem != 0 AND "
3069                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3070                                                   "FROM pg_type",
3071                                                   username_subquery);
3072         }
3073         else if (fout->remoteVersion >= 70300)
3074         {
3075                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3076                                                   "typnamespace, '{=U}' AS typacl, "
3077                                                   "(%s typowner) AS rolname, "
3078                                                   "typinput::oid AS typinput, "
3079                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3080                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3081                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3082                                                   "typtype, typisdefined, "
3083                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3084                                                   "FROM pg_type",
3085                                                   username_subquery);
3086         }
3087         else if (fout->remoteVersion >= 70100)
3088         {
3089                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3090                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
3091                                                   "(%s typowner) AS rolname, "
3092                                                   "typinput::oid AS typinput, "
3093                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3094                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3095                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3096                                                   "typtype, typisdefined, "
3097                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3098                                                   "FROM pg_type",
3099                                                   username_subquery);
3100         }
3101         else
3102         {
3103                 appendPQExpBuffer(query, "SELECT "
3104                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
3105                                                   "oid, typname, "
3106                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
3107                                                   "(%s typowner) AS rolname, "
3108                                                   "typinput::oid AS typinput, "
3109                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3110                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3111                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3112                                                   "typtype, typisdefined, "
3113                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3114                                                   "FROM pg_type",
3115                                                   username_subquery);
3116         }
3117
3118         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3119
3120         ntups = PQntuples(res);
3121
3122         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3123
3124         i_tableoid = PQfnumber(res, "tableoid");
3125         i_oid = PQfnumber(res, "oid");
3126         i_typname = PQfnumber(res, "typname");
3127         i_typnamespace = PQfnumber(res, "typnamespace");
3128         i_typacl = PQfnumber(res, "typacl");
3129         i_rolname = PQfnumber(res, "rolname");
3130         i_typinput = PQfnumber(res, "typinput");
3131         i_typoutput = PQfnumber(res, "typoutput");
3132         i_typelem = PQfnumber(res, "typelem");
3133         i_typrelid = PQfnumber(res, "typrelid");
3134         i_typrelkind = PQfnumber(res, "typrelkind");
3135         i_typtype = PQfnumber(res, "typtype");
3136         i_typisdefined = PQfnumber(res, "typisdefined");
3137         i_isarray = PQfnumber(res, "isarray");
3138
3139         for (i = 0; i < ntups; i++)
3140         {
3141                 tyinfo[i].dobj.objType = DO_TYPE;
3142                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3143                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3144                 AssignDumpId(&tyinfo[i].dobj);
3145                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3146                 tyinfo[i].dobj.namespace =
3147                         findNamespace(fout,
3148                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
3149                                                   tyinfo[i].dobj.catId.oid);
3150                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3151                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
3152                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3153                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3154                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3155                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3156                 tyinfo[i].shellType = NULL;
3157
3158                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3159                         tyinfo[i].isDefined = true;
3160                 else
3161                         tyinfo[i].isDefined = false;
3162
3163                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3164                         tyinfo[i].isArray = true;
3165                 else
3166                         tyinfo[i].isArray = false;
3167
3168                 /* Decide whether we want to dump it */
3169                 selectDumpableType(&tyinfo[i]);
3170
3171                 /*
3172                  * If it's a domain, fetch info about its constraints, if any
3173                  */
3174                 tyinfo[i].nDomChecks = 0;
3175                 tyinfo[i].domChecks = NULL;
3176                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3177                         getDomainConstraints(fout, &(tyinfo[i]));
3178
3179                 /*
3180                  * If it's a base type, make a DumpableObject representing a shell
3181                  * definition of the type.      We will need to dump that ahead of the I/O
3182                  * functions for the type.      Similarly, range types need a shell
3183                  * definition in case they have a canonicalize function.
3184                  *
3185                  * Note: the shell type doesn't have a catId.  You might think it
3186                  * should copy the base type's catId, but then it might capture the
3187                  * pg_depend entries for the type, which we don't want.
3188                  */
3189                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3190                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
3191                 {
3192                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3193                         stinfo->dobj.objType = DO_SHELL_TYPE;
3194                         stinfo->dobj.catId = nilCatalogId;
3195                         AssignDumpId(&stinfo->dobj);
3196                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3197                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3198                         stinfo->baseType = &(tyinfo[i]);
3199                         tyinfo[i].shellType = stinfo;
3200
3201                         /*
3202                          * Initially mark the shell type as not to be dumped.  We'll only
3203                          * dump it if the I/O or canonicalize functions need to be dumped;
3204                          * this is taken care of while sorting dependencies.
3205                          */
3206                         stinfo->dobj.dump = false;
3207
3208                         /*
3209                          * However, if dumping from pre-7.3, there will be no dependency
3210                          * info so we have to fake it here.  We only need to worry about
3211                          * typinput and typoutput since the other functions only exist
3212                          * post-7.3.
3213                          */
3214                         if (fout->remoteVersion < 70300)
3215                         {
3216                                 Oid                     typinput;
3217                                 Oid                     typoutput;
3218                                 FuncInfo   *funcInfo;
3219
3220                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3221                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3222
3223                                 funcInfo = findFuncByOid(typinput);
3224                                 if (funcInfo && funcInfo->dobj.dump)
3225                                 {
3226                                         /* base type depends on function */
3227                                         addObjectDependency(&tyinfo[i].dobj,
3228                                                                                 funcInfo->dobj.dumpId);
3229                                         /* function depends on shell type */
3230                                         addObjectDependency(&funcInfo->dobj,
3231                                                                                 stinfo->dobj.dumpId);
3232                                         /* mark shell type as to be dumped */
3233                                         stinfo->dobj.dump = true;
3234                                 }
3235
3236                                 funcInfo = findFuncByOid(typoutput);
3237                                 if (funcInfo && funcInfo->dobj.dump)
3238                                 {
3239                                         /* base type depends on function */
3240                                         addObjectDependency(&tyinfo[i].dobj,
3241                                                                                 funcInfo->dobj.dumpId);
3242                                         /* function depends on shell type */
3243                                         addObjectDependency(&funcInfo->dobj,
3244                                                                                 stinfo->dobj.dumpId);
3245                                         /* mark shell type as to be dumped */
3246                                         stinfo->dobj.dump = true;
3247                                 }
3248                         }
3249                 }
3250
3251                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3252                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3253                                           tyinfo[i].dobj.name);
3254         }
3255
3256         *numTypes = ntups;
3257
3258         PQclear(res);
3259
3260         destroyPQExpBuffer(query);
3261
3262         return tyinfo;
3263 }
3264
3265 /*
3266  * getOperators:
3267  *        read all operators in the system catalogs and return them in the
3268  * OprInfo* structure
3269  *
3270  *      numOprs is set to the number of operators read in
3271  */
3272 OprInfo *
3273 getOperators(Archive *fout, int *numOprs)
3274 {
3275         PGresult   *res;
3276         int                     ntups;
3277         int                     i;
3278         PQExpBuffer query = createPQExpBuffer();
3279         OprInfo    *oprinfo;
3280         int                     i_tableoid;
3281         int                     i_oid;
3282         int                     i_oprname;
3283         int                     i_oprnamespace;
3284         int                     i_rolname;
3285         int                     i_oprkind;
3286         int                     i_oprcode;
3287
3288         /*
3289          * find all operators, including builtin operators; we filter out
3290          * system-defined operators at dump-out time.
3291          */
3292
3293         /* Make sure we are in proper schema */
3294         selectSourceSchema(fout, "pg_catalog");
3295
3296         if (fout->remoteVersion >= 70300)
3297         {
3298                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3299                                                   "oprnamespace, "
3300                                                   "(%s oprowner) AS rolname, "
3301                                                   "oprkind, "
3302                                                   "oprcode::oid AS oprcode "
3303                                                   "FROM pg_operator",
3304                                                   username_subquery);
3305         }
3306         else if (fout->remoteVersion >= 70100)
3307         {
3308                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3309                                                   "0::oid AS oprnamespace, "
3310                                                   "(%s oprowner) AS rolname, "
3311                                                   "oprkind, "
3312                                                   "oprcode::oid AS oprcode "
3313                                                   "FROM pg_operator",
3314                                                   username_subquery);
3315         }
3316         else
3317         {
3318                 appendPQExpBuffer(query, "SELECT "
3319                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3320                                                   "oid, oprname, "
3321                                                   "0::oid AS oprnamespace, "
3322                                                   "(%s oprowner) AS rolname, "
3323                                                   "oprkind, "
3324                                                   "oprcode::oid AS oprcode "
3325                                                   "FROM pg_operator",
3326                                                   username_subquery);
3327         }
3328
3329         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3330
3331         ntups = PQntuples(res);
3332         *numOprs = ntups;
3333
3334         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3335
3336         i_tableoid = PQfnumber(res, "tableoid");
3337         i_oid = PQfnumber(res, "oid");
3338         i_oprname = PQfnumber(res, "oprname");
3339         i_oprnamespace = PQfnumber(res, "oprnamespace");
3340         i_rolname = PQfnumber(res, "rolname");
3341         i_oprkind = PQfnumber(res, "oprkind");
3342         i_oprcode = PQfnumber(res, "oprcode");
3343
3344         for (i = 0; i < ntups; i++)
3345         {
3346                 oprinfo[i].dobj.objType = DO_OPERATOR;
3347                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3348                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3349                 AssignDumpId(&oprinfo[i].dobj);
3350                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3351                 oprinfo[i].dobj.namespace =
3352                         findNamespace(fout,
3353                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3354                                                   oprinfo[i].dobj.catId.oid);
3355                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3356                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3357                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3358
3359                 /* Decide whether we want to dump it */
3360                 selectDumpableObject(&(oprinfo[i].dobj));
3361
3362                 if (strlen(oprinfo[i].rolname) == 0)
3363                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3364                                           oprinfo[i].dobj.name);
3365         }
3366
3367         PQclear(res);
3368
3369         destroyPQExpBuffer(query);
3370
3371         return oprinfo;
3372 }
3373
3374 /*
3375  * getCollations:
3376  *        read all collations in the system catalogs and return them in the
3377  * CollInfo* structure
3378  *
3379  *      numCollations is set to the number of collations read in
3380  */
3381 CollInfo *
3382 getCollations(Archive *fout, int *numCollations)
3383 {
3384         PGresult   *res;
3385         int                     ntups;
3386         int                     i;
3387         PQExpBuffer query;
3388         CollInfo   *collinfo;
3389         int                     i_tableoid;
3390         int                     i_oid;
3391         int                     i_collname;
3392         int                     i_collnamespace;
3393         int                     i_rolname;
3394
3395         /* Collations didn't exist pre-9.1 */
3396         if (fout->remoteVersion < 90100)
3397         {
3398                 *numCollations = 0;
3399                 return NULL;
3400         }
3401
3402         query = createPQExpBuffer();
3403
3404         /*
3405          * find all collations, including builtin collations; we filter out
3406          * system-defined collations at dump-out time.
3407          */
3408
3409         /* Make sure we are in proper schema */
3410         selectSourceSchema(fout, "pg_catalog");
3411
3412         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3413                                           "collnamespace, "
3414                                           "(%s collowner) AS rolname "
3415                                           "FROM pg_collation",
3416                                           username_subquery);
3417
3418         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3419
3420         ntups = PQntuples(res);
3421         *numCollations = ntups;
3422
3423         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3424
3425         i_tableoid = PQfnumber(res, "tableoid");
3426         i_oid = PQfnumber(res, "oid");
3427         i_collname = PQfnumber(res, "collname");
3428         i_collnamespace = PQfnumber(res, "collnamespace");
3429         i_rolname = PQfnumber(res, "rolname");
3430
3431         for (i = 0; i < ntups; i++)
3432         {
3433                 collinfo[i].dobj.objType = DO_COLLATION;
3434                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3435                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3436                 AssignDumpId(&collinfo[i].dobj);
3437                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3438                 collinfo[i].dobj.namespace =
3439                         findNamespace(fout,
3440                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3441                                                   collinfo[i].dobj.catId.oid);
3442                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3443
3444                 /* Decide whether we want to dump it */
3445                 selectDumpableObject(&(collinfo[i].dobj));
3446         }
3447
3448         PQclear(res);
3449
3450         destroyPQExpBuffer(query);
3451
3452         return collinfo;
3453 }
3454
3455 /*
3456  * getConversions:
3457  *        read all conversions in the system catalogs and return them in the
3458  * ConvInfo* structure
3459  *
3460  *      numConversions is set to the number of conversions read in
3461  */
3462 ConvInfo *
3463 getConversions(Archive *fout, int *numConversions)
3464 {
3465         PGresult   *res;
3466         int                     ntups;
3467         int                     i;
3468         PQExpBuffer query = createPQExpBuffer();
3469         ConvInfo   *convinfo;
3470         int                     i_tableoid;
3471         int                     i_oid;
3472         int                     i_conname;
3473         int                     i_connamespace;
3474         int                     i_rolname;
3475
3476         /* Conversions didn't exist pre-7.3 */
3477         if (fout->remoteVersion < 70300)
3478         {
3479                 *numConversions = 0;
3480                 return NULL;
3481         }
3482
3483         /*
3484          * find all conversions, including builtin conversions; we filter out
3485          * system-defined conversions at dump-out time.
3486          */
3487
3488         /* Make sure we are in proper schema */
3489         selectSourceSchema(fout, "pg_catalog");
3490
3491         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3492                                           "connamespace, "
3493                                           "(%s conowner) AS rolname "
3494                                           "FROM pg_conversion",
3495                                           username_subquery);
3496
3497         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3498
3499         ntups = PQntuples(res);
3500         *numConversions = ntups;
3501
3502         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3503
3504         i_tableoid = PQfnumber(res, "tableoid");
3505         i_oid = PQfnumber(res, "oid");
3506         i_conname = PQfnumber(res, "conname");
3507         i_connamespace = PQfnumber(res, "connamespace");
3508         i_rolname = PQfnumber(res, "rolname");
3509
3510         for (i = 0; i < ntups; i++)
3511         {
3512                 convinfo[i].dobj.objType = DO_CONVERSION;
3513                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3514                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3515                 AssignDumpId(&convinfo[i].dobj);
3516                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3517                 convinfo[i].dobj.namespace =
3518                         findNamespace(fout,
3519                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3520                                                   convinfo[i].dobj.catId.oid);
3521                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3522
3523                 /* Decide whether we want to dump it */
3524                 selectDumpableObject(&(convinfo[i].dobj));
3525         }
3526
3527         PQclear(res);
3528
3529         destroyPQExpBuffer(query);
3530
3531         return convinfo;
3532 }
3533
3534 /*
3535  * getOpclasses:
3536  *        read all opclasses in the system catalogs and return them in the
3537  * OpclassInfo* structure
3538  *
3539  *      numOpclasses is set to the number of opclasses read in
3540  */
3541 OpclassInfo *
3542 getOpclasses(Archive *fout, int *numOpclasses)
3543 {
3544         PGresult   *res;
3545         int                     ntups;
3546         int                     i;
3547         PQExpBuffer query = createPQExpBuffer();
3548         OpclassInfo *opcinfo;
3549         int                     i_tableoid;
3550         int                     i_oid;
3551         int                     i_opcname;
3552         int                     i_opcnamespace;
3553         int                     i_rolname;
3554
3555         /*
3556          * find all opclasses, including builtin opclasses; we filter out
3557          * system-defined opclasses at dump-out time.
3558          */
3559
3560         /* Make sure we are in proper schema */
3561         selectSourceSchema(fout, "pg_catalog");
3562
3563         if (fout->remoteVersion >= 70300)
3564         {
3565                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3566                                                   "opcnamespace, "
3567                                                   "(%s opcowner) AS rolname "
3568                                                   "FROM pg_opclass",
3569                                                   username_subquery);
3570         }
3571         else if (fout->remoteVersion >= 70100)
3572         {
3573                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3574                                                   "0::oid AS opcnamespace, "
3575                                                   "''::name AS rolname "
3576                                                   "FROM pg_opclass");
3577         }
3578         else
3579         {
3580                 appendPQExpBuffer(query, "SELECT "
3581                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3582                                                   "oid, opcname, "
3583                                                   "0::oid AS opcnamespace, "
3584                                                   "''::name AS rolname "
3585                                                   "FROM pg_opclass");
3586         }
3587
3588         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3589
3590         ntups = PQntuples(res);
3591         *numOpclasses = ntups;
3592
3593         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3594
3595         i_tableoid = PQfnumber(res, "tableoid");
3596         i_oid = PQfnumber(res, "oid");
3597         i_opcname = PQfnumber(res, "opcname");
3598         i_opcnamespace = PQfnumber(res, "opcnamespace");
3599         i_rolname = PQfnumber(res, "rolname");
3600
3601         for (i = 0; i < ntups; i++)
3602         {
3603                 opcinfo[i].dobj.objType = DO_OPCLASS;
3604                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3605                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3606                 AssignDumpId(&opcinfo[i].dobj);
3607                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3608                 opcinfo[i].dobj.namespace =
3609                         findNamespace(fout,
3610                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3611                                                   opcinfo[i].dobj.catId.oid);
3612                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3613
3614                 /* Decide whether we want to dump it */
3615                 selectDumpableObject(&(opcinfo[i].dobj));
3616
3617                 if (fout->remoteVersion >= 70300)
3618                 {
3619                         if (strlen(opcinfo[i].rolname) == 0)
3620                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3621                                                   opcinfo[i].dobj.name);
3622                 }
3623         }
3624
3625         PQclear(res);
3626
3627         destroyPQExpBuffer(query);
3628
3629         return opcinfo;
3630 }
3631
3632 /*
3633  * getOpfamilies:
3634  *        read all opfamilies in the system catalogs and return them in the
3635  * OpfamilyInfo* structure
3636  *
3637  *      numOpfamilies is set to the number of opfamilies read in
3638  */
3639 OpfamilyInfo *
3640 getOpfamilies(Archive *fout, int *numOpfamilies)
3641 {
3642         PGresult   *res;
3643         int                     ntups;
3644         int                     i;
3645         PQExpBuffer query;
3646         OpfamilyInfo *opfinfo;
3647         int                     i_tableoid;
3648         int                     i_oid;
3649         int                     i_opfname;
3650         int                     i_opfnamespace;
3651         int                     i_rolname;
3652
3653         /* Before 8.3, there is no separate concept of opfamilies */
3654         if (fout->remoteVersion < 80300)
3655         {
3656                 *numOpfamilies = 0;
3657                 return NULL;
3658         }
3659
3660         query = createPQExpBuffer();
3661
3662         /*
3663          * find all opfamilies, including builtin opfamilies; we filter out
3664          * system-defined opfamilies at dump-out time.
3665          */
3666
3667         /* Make sure we are in proper schema */
3668         selectSourceSchema(fout, "pg_catalog");
3669
3670         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3671                                           "opfnamespace, "
3672                                           "(%s opfowner) AS rolname "
3673                                           "FROM pg_opfamily",
3674                                           username_subquery);
3675
3676         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3677
3678         ntups = PQntuples(res);
3679         *numOpfamilies = ntups;
3680
3681         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3682
3683         i_tableoid = PQfnumber(res, "tableoid");
3684         i_oid = PQfnumber(res, "oid");
3685         i_opfname = PQfnumber(res, "opfname");
3686         i_opfnamespace = PQfnumber(res, "opfnamespace");
3687         i_rolname = PQfnumber(res, "rolname");
3688
3689         for (i = 0; i < ntups; i++)
3690         {
3691                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3692                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3693                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3694                 AssignDumpId(&opfinfo[i].dobj);
3695                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3696                 opfinfo[i].dobj.namespace =
3697                         findNamespace(fout,
3698                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3699                                                   opfinfo[i].dobj.catId.oid);
3700                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3701
3702                 /* Decide whether we want to dump it */
3703                 selectDumpableObject(&(opfinfo[i].dobj));
3704
3705                 if (fout->remoteVersion >= 70300)
3706                 {
3707                         if (strlen(opfinfo[i].rolname) == 0)
3708                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3709                                                   opfinfo[i].dobj.name);
3710                 }
3711         }
3712
3713         PQclear(res);
3714
3715         destroyPQExpBuffer(query);
3716
3717         return opfinfo;
3718 }
3719
3720 /*
3721  * getAggregates:
3722  *        read all the user-defined aggregates in the system catalogs and
3723  * return them in the AggInfo* structure
3724  *
3725  * numAggs is set to the number of aggregates read in
3726  */
3727 AggInfo *
3728 getAggregates(Archive *fout, int *numAggs)
3729 {
3730         PGresult   *res;
3731         int                     ntups;
3732         int                     i;
3733         PQExpBuffer query = createPQExpBuffer();
3734         AggInfo    *agginfo;
3735         int                     i_tableoid;
3736         int                     i_oid;
3737         int                     i_aggname;
3738         int                     i_aggnamespace;
3739         int                     i_pronargs;
3740         int                     i_proargtypes;
3741         int                     i_rolname;
3742         int                     i_aggacl;
3743         int                     i_proiargs;
3744
3745         /* Make sure we are in proper schema */
3746         selectSourceSchema(fout, "pg_catalog");
3747
3748         /*
3749          * Find all user-defined aggregates.  See comment in getFuncs() for the
3750          * rationale behind the filtering logic.
3751          */
3752
3753         if (fout->remoteVersion >= 80400)
3754         {
3755                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3756                                                   "pronamespace AS aggnamespace, "
3757                                                   "pronargs, proargtypes, "
3758                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3759                                                   "(%s proowner) AS rolname, "
3760                                                   "proacl AS aggacl "
3761                                                   "FROM pg_proc p "
3762                                                   "WHERE proisagg AND ("
3763                                                   "pronamespace != "
3764                                                   "(SELECT oid FROM pg_namespace "
3765                                                   "WHERE nspname = 'pg_catalog')",
3766                                                   username_subquery);
3767                 if (binary_upgrade && fout->remoteVersion >= 90100)
3768                         appendPQExpBuffer(query,
3769                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3770                                                           "classid = 'pg_proc'::regclass AND "
3771                                                           "objid = p.oid AND "
3772                                                           "refclassid = 'pg_extension'::regclass AND "
3773                                                           "deptype = 'e')");
3774                 appendPQExpBuffer(query, ")");
3775         }
3776         else if (fout->remoteVersion >= 80200)
3777         {
3778                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3779                                                   "pronamespace AS aggnamespace, "
3780                                                   "pronargs, proargtypes, "
3781                                                   "NULL::text AS proiargs,"
3782                                                   "(%s proowner) AS rolname, "
3783                                                   "proacl AS aggacl "
3784                                                   "FROM pg_proc p "
3785                                                   "WHERE proisagg AND ("
3786                                                   "pronamespace != "
3787                                                   "(SELECT oid FROM pg_namespace "
3788                                                   "WHERE nspname = 'pg_catalog'))",
3789                                                   username_subquery);
3790         }
3791         else if (fout->remoteVersion >= 70300)
3792         {
3793                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3794                                                   "pronamespace AS aggnamespace, "
3795                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3796                                                   "proargtypes, "
3797                                                   "NULL::text AS proiargs, "
3798                                                   "(%s proowner) AS rolname, "
3799                                                   "proacl AS aggacl "
3800                                                   "FROM pg_proc "
3801                                                   "WHERE proisagg "
3802                                                   "AND pronamespace != "
3803                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3804                                                   username_subquery);
3805         }
3806         else if (fout->remoteVersion >= 70100)
3807         {
3808                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3809                                                   "0::oid AS aggnamespace, "
3810                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3811                                                   "aggbasetype AS proargtypes, "
3812                                                   "NULL::text AS proiargs, "
3813                                                   "(%s aggowner) AS rolname, "
3814                                                   "'{=X}' AS aggacl "
3815                                                   "FROM pg_aggregate "
3816                                                   "where oid > '%u'::oid",
3817                                                   username_subquery,
3818                                                   g_last_builtin_oid);
3819         }
3820         else
3821         {
3822                 appendPQExpBuffer(query, "SELECT "
3823                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3824                                                   "oid, aggname, "
3825                                                   "0::oid AS aggnamespace, "
3826                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3827                                                   "aggbasetype AS proargtypes, "
3828                                                   "NULL::text AS proiargs, "
3829                                                   "(%s aggowner) AS rolname, "
3830                                                   "'{=X}' AS aggacl "
3831                                                   "FROM pg_aggregate "
3832                                                   "where oid > '%u'::oid",
3833                                                   username_subquery,
3834                                                   g_last_builtin_oid);
3835         }
3836
3837         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3838
3839         ntups = PQntuples(res);
3840         *numAggs = ntups;
3841
3842         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3843
3844         i_tableoid = PQfnumber(res, "tableoid");
3845         i_oid = PQfnumber(res, "oid");
3846         i_aggname = PQfnumber(res, "aggname");
3847         i_aggnamespace = PQfnumber(res, "aggnamespace");
3848         i_pronargs = PQfnumber(res, "pronargs");
3849         i_proargtypes = PQfnumber(res, "proargtypes");
3850         i_rolname = PQfnumber(res, "rolname");
3851         i_aggacl = PQfnumber(res, "aggacl");
3852         i_proiargs = PQfnumber(res, "proiargs");
3853
3854         for (i = 0; i < ntups; i++)
3855         {
3856                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3857                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3858                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3859                 AssignDumpId(&agginfo[i].aggfn.dobj);
3860                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3861                 agginfo[i].aggfn.dobj.namespace =
3862                         findNamespace(fout,
3863                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3864                                                   agginfo[i].aggfn.dobj.catId.oid);
3865                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3866                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3867                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3868                                           agginfo[i].aggfn.dobj.name);
3869                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3870                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3871                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3872                 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3873                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3874                 if (agginfo[i].aggfn.nargs == 0)
3875                         agginfo[i].aggfn.argtypes = NULL;
3876                 else
3877                 {
3878                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3879                         if (fout->remoteVersion >= 70300)
3880                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3881                                                           agginfo[i].aggfn.argtypes,
3882                                                           agginfo[i].aggfn.nargs);
3883                         else
3884                                 /* it's just aggbasetype */
3885                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3886                 }
3887
3888                 /* Decide whether we want to dump it */
3889                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3890         }
3891
3892         PQclear(res);
3893
3894         destroyPQExpBuffer(query);
3895
3896         return agginfo;
3897 }
3898
3899 /*
3900  * getFuncs:
3901  *        read all the user-defined functions in the system catalogs and
3902  * return them in the FuncInfo* structure
3903  *
3904  * numFuncs is set to the number of functions read in
3905  */
3906 FuncInfo *
3907 getFuncs(Archive *fout, int *numFuncs)
3908 {
3909         PGresult   *res;
3910         int                     ntups;
3911         int                     i;
3912         PQExpBuffer query = createPQExpBuffer();
3913         FuncInfo   *finfo;
3914         int                     i_tableoid;
3915         int                     i_oid;
3916         int                     i_proname;
3917         int                     i_pronamespace;
3918         int                     i_rolname;
3919         int                     i_prolang;
3920         int                     i_pronargs;
3921         int                     i_proargtypes;
3922         int                     i_prorettype;
3923         int                     i_proacl;
3924         int                     i_proiargs;
3925
3926         /* Make sure we are in proper schema */
3927         selectSourceSchema(fout, "pg_catalog");
3928
3929         /*
3930          * Find all user-defined functions.  Normally we can exclude functions in
3931          * pg_catalog, which is worth doing since there are several thousand of
3932          * 'em.  However, there are some extensions that create functions in
3933          * pg_catalog.  In normal dumps we can still ignore those --- but in
3934          * binary-upgrade mode, we must dump the member objects of the extension,
3935          * so be sure to fetch any such functions.
3936          *
3937          * Also, in 9.2 and up, exclude functions that are internally dependent on
3938          * something else, since presumably those will be created as a result of
3939          * creating the something else.  This currently only acts to suppress
3940          * constructor functions for range types.  Note that this is OK only
3941          * because the constructors don't have any dependencies the range type
3942          * doesn't have; otherwise we might not get creation ordering correct.
3943          */
3944
3945         if (fout->remoteVersion >= 80400)
3946         {
3947                 appendPQExpBuffer(query,
3948                                                   "SELECT tableoid, oid, proname, prolang, "
3949                                                   "pronargs, proargtypes, prorettype, proacl, "
3950                                                   "pronamespace, "
3951                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3952                                                   "(%s proowner) AS rolname "
3953                                                   "FROM pg_proc p "
3954                                                   "WHERE NOT proisagg AND ("
3955                                                   "pronamespace != "
3956                                                   "(SELECT oid FROM pg_namespace "
3957                                                   "WHERE nspname = 'pg_catalog')",
3958                                                   username_subquery);
3959                 if (fout->remoteVersion >= 90200)
3960                         appendPQExpBuffer(query,
3961                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3962                                                           "WHERE classid = 'pg_proc'::regclass AND "
3963                                                           "objid = p.oid AND deptype = 'i')");
3964                 if (binary_upgrade && fout->remoteVersion >= 90100)
3965                         appendPQExpBuffer(query,
3966                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3967                                                           "classid = 'pg_proc'::regclass AND "
3968                                                           "objid = p.oid AND "
3969                                                           "refclassid = 'pg_extension'::regclass AND "
3970                                                           "deptype = 'e')");
3971                 appendPQExpBuffer(query, ")");
3972         }
3973         else if (fout->remoteVersion >= 70300)
3974         {
3975                 appendPQExpBuffer(query,
3976                                                   "SELECT tableoid, oid, proname, prolang, "
3977                                                   "pronargs, proargtypes, prorettype, proacl, "
3978                                                   "pronamespace, "
3979                                                   "NULL::text AS proiargs,"
3980                                                   "(%s proowner) AS rolname "
3981                                                   "FROM pg_proc p "
3982                                                   "WHERE NOT proisagg AND ("
3983                                                   "pronamespace != "
3984                                                   "(SELECT oid FROM pg_namespace "
3985                                                   "WHERE nspname = 'pg_catalog'))",
3986                                                   username_subquery);
3987         }
3988         else if (fout->remoteVersion >= 70100)
3989         {
3990                 appendPQExpBuffer(query,
3991                                                   "SELECT tableoid, oid, proname, prolang, "
3992                                                   "pronargs, proargtypes, prorettype, "
3993                                                   "'{=X}' AS proacl, "
3994                                                   "0::oid AS pronamespace, "
3995                                                   "NULL::text AS proiargs,"
3996                                                   "(%s proowner) AS rolname "
3997                                                   "FROM pg_proc "
3998                                                   "WHERE pg_proc.oid > '%u'::oid",
3999                                                   username_subquery,
4000                                                   g_last_builtin_oid);
4001         }
4002         else
4003         {
4004                 appendPQExpBuffer(query,
4005                                                   "SELECT "
4006                                                   "(SELECT oid FROM pg_class "
4007                                                   " WHERE relname = 'pg_proc') AS tableoid, "
4008                                                   "oid, proname, prolang, "
4009                                                   "pronargs, proargtypes, prorettype, "
4010                                                   "'{=X}' AS proacl, "
4011                                                   "0::oid AS pronamespace, "
4012                                                   "NULL::text AS proiargs,"
4013                                                   "(%s proowner) AS rolname "
4014                                                   "FROM pg_proc "
4015                                                   "where pg_proc.oid > '%u'::oid",
4016                                                   username_subquery,
4017                                                   g_last_builtin_oid);
4018         }
4019
4020         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4021
4022         ntups = PQntuples(res);
4023
4024         *numFuncs = ntups;
4025
4026         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
4027
4028         i_tableoid = PQfnumber(res, "tableoid");
4029         i_oid = PQfnumber(res, "oid");
4030         i_proname = PQfnumber(res, "proname");
4031         i_pronamespace = PQfnumber(res, "pronamespace");
4032         i_rolname = PQfnumber(res, "rolname");
4033         i_prolang = PQfnumber(res, "prolang");
4034         i_pronargs = PQfnumber(res, "pronargs");
4035         i_proargtypes = PQfnumber(res, "proargtypes");
4036         i_prorettype = PQfnumber(res, "prorettype");
4037         i_proacl = PQfnumber(res, "proacl");
4038         i_proiargs = PQfnumber(res, "proiargs");
4039
4040         for (i = 0; i < ntups; i++)
4041         {
4042                 finfo[i].dobj.objType = DO_FUNC;
4043                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4044                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4045                 AssignDumpId(&finfo[i].dobj);
4046                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
4047                 finfo[i].dobj.namespace =
4048                         findNamespace(fout,
4049                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
4050                                                   finfo[i].dobj.catId.oid);
4051                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4052                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
4053                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
4054                 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
4055                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
4056                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
4057                 if (finfo[i].nargs == 0)
4058                         finfo[i].argtypes = NULL;
4059                 else
4060                 {
4061                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
4062                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
4063                                                   finfo[i].argtypes, finfo[i].nargs);
4064                 }
4065
4066                 /* Decide whether we want to dump it */
4067                 selectDumpableObject(&(finfo[i].dobj));
4068
4069                 if (strlen(finfo[i].rolname) == 0)
4070                         write_msg(NULL,
4071                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
4072                                           finfo[i].dobj.name);
4073         }
4074
4075         PQclear(res);
4076
4077         destroyPQExpBuffer(query);
4078
4079         return finfo;
4080 }
4081
4082 /*
4083  * getTables
4084  *        read all the user-defined tables (no indexes, no catalogs)
4085  * in the system catalogs return them in the TableInfo* structure
4086  *
4087  * numTables is set to the number of tables read in
4088  */
4089 TableInfo *
4090 getTables(Archive *fout, int *numTables)
4091 {
4092         PGresult   *res;
4093         int                     ntups;
4094         int                     i;
4095         PQExpBuffer query = createPQExpBuffer();
4096         TableInfo  *tblinfo;
4097         int                     i_reltableoid;
4098         int                     i_reloid;
4099         int                     i_relname;
4100         int                     i_relnamespace;
4101         int                     i_relkind;
4102         int                     i_relacl;
4103         int                     i_rolname;
4104         int                     i_relchecks;
4105         int                     i_relhastriggers;
4106         int                     i_relhasindex;
4107         int                     i_relhasrules;
4108         int                     i_relhasoids;
4109         int                     i_relfrozenxid;
4110         int                     i_toastoid;
4111         int                     i_toastfrozenxid;
4112         int                     i_relpersistence;
4113         int                     i_isscannable;
4114         int                     i_owning_tab;
4115         int                     i_owning_col;
4116         int                     i_reltablespace;
4117         int                     i_reloptions;
4118         int                     i_toastreloptions;
4119         int                     i_reloftype;
4120
4121         /* Make sure we are in proper schema */
4122         selectSourceSchema(fout, "pg_catalog");
4123
4124         /*
4125          * Find all the tables and table-like objects.
4126          *
4127          * We include system catalogs, so that we can work if a user table is
4128          * defined to inherit from a system catalog (pretty weird, but...)
4129          *
4130          * We ignore relations that are not ordinary tables, sequences, views,
4131          * materialized views, composite types, or foreign tables.
4132          *
4133          * Composite-type table entries won't be dumped as such, but we have to
4134          * make a DumpableObject for them so that we can track dependencies of the
4135          * composite type (pg_depend entries for columns of the composite type
4136          * link to the pg_class entry not the pg_type entry).
4137          *
4138          * Note: in this phase we should collect only a minimal amount of
4139          * information about each table, basically just enough to decide if it is
4140          * interesting. We must fetch all tables in this phase because otherwise
4141          * we cannot correctly identify inherited columns, owned sequences, etc.
4142          */
4143
4144         if (fout->remoteVersion >= 90100)
4145         {
4146                 /*
4147                  * Left join to pick up dependency info linking sequences to their
4148                  * owning column, if any (note this dependency is AUTO as of 8.2)
4149                  */
4150                 appendPQExpBuffer(query,
4151                                                   "SELECT c.tableoid, c.oid, c.relname, "
4152                                                   "c.relacl, c.relkind, c.relnamespace, "
4153                                                   "(%s c.relowner) AS rolname, "
4154                                                   "c.relchecks, c.relhastriggers, "
4155                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4156                                                   "c.relfrozenxid, tc.oid AS toid, "
4157                                                   "tc.relfrozenxid AS tfrozenxid, "
4158                                                   "c.relpersistence, pg_relation_is_scannable(c.oid) as isscannable, "
4159                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4160                                                   "d.refobjid AS owning_tab, "
4161                                                   "d.refobjsubid AS owning_col, "
4162                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4163                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4164                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4165                                                   "FROM pg_class c "
4166                                                   "LEFT JOIN pg_depend d ON "
4167                                                   "(c.relkind = '%c' AND "
4168                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4169                                                   "d.objsubid = 0 AND "
4170                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4171                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4172                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4173                                                   "ORDER BY c.oid",
4174                                                   username_subquery,
4175                                                   RELKIND_SEQUENCE,
4176                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4177                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4178                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4179         }
4180         else if (fout->remoteVersion >= 90000)
4181         {
4182                 /*
4183                  * Left join to pick up dependency info linking sequences to their
4184                  * owning column, if any (note this dependency is AUTO as of 8.2)
4185                  */
4186                 appendPQExpBuffer(query,
4187                                                   "SELECT c.tableoid, c.oid, c.relname, "
4188                                                   "c.relacl, c.relkind, c.relnamespace, "
4189                                                   "(%s c.relowner) AS rolname, "
4190                                                   "c.relchecks, c.relhastriggers, "
4191                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4192                                                   "c.relfrozenxid, tc.oid AS toid, "
4193                                                   "tc.relfrozenxid AS tfrozenxid, "
4194                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4195                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4196                                                   "d.refobjid AS owning_tab, "
4197                                                   "d.refobjsubid AS owning_col, "
4198                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4199                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4200                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4201                                                   "FROM pg_class c "
4202                                                   "LEFT JOIN pg_depend d ON "
4203                                                   "(c.relkind = '%c' AND "
4204                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4205                                                   "d.objsubid = 0 AND "
4206                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4207                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4208                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4209                                                   "ORDER BY c.oid",
4210                                                   username_subquery,
4211                                                   RELKIND_SEQUENCE,
4212                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4213                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4214         }
4215         else if (fout->remoteVersion >= 80400)
4216         {
4217                 /*
4218                  * Left join to pick up dependency info linking sequences to their
4219                  * owning column, if any (note this dependency is AUTO as of 8.2)
4220                  */
4221                 appendPQExpBuffer(query,
4222                                                   "SELECT c.tableoid, c.oid, c.relname, "
4223                                                   "c.relacl, c.relkind, c.relnamespace, "
4224                                                   "(%s c.relowner) AS rolname, "
4225                                                   "c.relchecks, c.relhastriggers, "
4226                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4227                                                   "c.relfrozenxid, tc.oid AS toid, "
4228                                                   "tc.relfrozenxid AS tfrozenxid, "
4229                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4230                                                   "NULL AS reloftype, "
4231                                                   "d.refobjid AS owning_tab, "
4232                                                   "d.refobjsubid AS owning_col, "
4233                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4234                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4235                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4236                                                   "FROM pg_class c "
4237                                                   "LEFT JOIN pg_depend d ON "
4238                                                   "(c.relkind = '%c' AND "
4239                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4240                                                   "d.objsubid = 0 AND "
4241                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4242                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4243                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4244                                                   "ORDER BY c.oid",
4245                                                   username_subquery,
4246                                                   RELKIND_SEQUENCE,
4247                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4248                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4249         }
4250         else if (fout->remoteVersion >= 80200)
4251         {
4252                 /*
4253                  * Left join to pick up dependency info linking sequences to their
4254                  * owning column, if any (note this dependency is AUTO as of 8.2)
4255                  */
4256                 appendPQExpBuffer(query,
4257                                                   "SELECT c.tableoid, c.oid, c.relname, "
4258                                                   "c.relacl, c.relkind, c.relnamespace, "
4259                                                   "(%s c.relowner) AS rolname, "
4260                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4261                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4262                                                   "c.relfrozenxid, tc.oid AS toid, "
4263                                                   "tc.relfrozenxid AS tfrozenxid, "
4264                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4265                                                   "NULL AS reloftype, "
4266                                                   "d.refobjid AS owning_tab, "
4267                                                   "d.refobjsubid AS owning_col, "
4268                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4269                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4270                                                   "NULL AS toast_reloptions "
4271                                                   "FROM pg_class c "
4272                                                   "LEFT JOIN pg_depend d ON "
4273                                                   "(c.relkind = '%c' AND "
4274                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4275                                                   "d.objsubid = 0 AND "
4276                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4277                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4278                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4279                                                   "ORDER BY c.oid",
4280                                                   username_subquery,
4281                                                   RELKIND_SEQUENCE,
4282                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4283                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4284         }
4285         else if (fout->remoteVersion >= 80000)
4286         {
4287                 /*
4288                  * Left join to pick up dependency info linking sequences to their
4289                  * owning column, if any
4290                  */
4291                 appendPQExpBuffer(query,
4292                                                   "SELECT c.tableoid, c.oid, relname, "
4293                                                   "relacl, relkind, relnamespace, "
4294                                                   "(%s relowner) AS rolname, "
4295                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4296                                                   "relhasindex, relhasrules, relhasoids, "
4297                                                   "0 AS relfrozenxid, "
4298                                                   "0 AS toid, "
4299                                                   "0 AS tfrozenxid, "
4300                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4301                                                   "NULL AS reloftype, "
4302                                                   "d.refobjid AS owning_tab, "
4303                                                   "d.refobjsubid AS owning_col, "
4304                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4305                                                   "NULL AS reloptions, "
4306                                                   "NULL AS toast_reloptions "
4307                                                   "FROM pg_class c "
4308                                                   "LEFT JOIN pg_depend d ON "
4309                                                   "(c.relkind = '%c' AND "
4310                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4311                                                   "d.objsubid = 0 AND "
4312                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4313                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4314                                                   "ORDER BY c.oid",
4315                                                   username_subquery,
4316                                                   RELKIND_SEQUENCE,
4317                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4318                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4319         }
4320         else if (fout->remoteVersion >= 70300)
4321         {
4322                 /*
4323                  * Left join to pick up dependency info linking sequences to their
4324                  * owning column, if any
4325                  */
4326                 appendPQExpBuffer(query,
4327                                                   "SELECT c.tableoid, c.oid, relname, "
4328                                                   "relacl, relkind, relnamespace, "
4329                                                   "(%s relowner) AS rolname, "
4330                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4331                                                   "relhasindex, relhasrules, relhasoids, "
4332                                                   "0 AS relfrozenxid, "
4333                                                   "0 AS toid, "
4334                                                   "0 AS tfrozenxid, "
4335                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4336                                                   "NULL AS reloftype, "
4337                                                   "d.refobjid AS owning_tab, "
4338                                                   "d.refobjsubid AS owning_col, "
4339                                                   "NULL AS reltablespace, "
4340                                                   "NULL AS reloptions, "
4341                                                   "NULL AS toast_reloptions "
4342                                                   "FROM pg_class c "
4343                                                   "LEFT JOIN pg_depend d ON "
4344                                                   "(c.relkind = '%c' AND "
4345                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4346                                                   "d.objsubid = 0 AND "
4347                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4348                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4349                                                   "ORDER BY c.oid",
4350                                                   username_subquery,
4351                                                   RELKIND_SEQUENCE,
4352                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4353                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4354         }
4355         else if (fout->remoteVersion >= 70200)
4356         {
4357                 appendPQExpBuffer(query,
4358                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4359                                                   "0::oid AS relnamespace, "
4360                                                   "(%s relowner) AS rolname, "
4361                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4362                                                   "relhasindex, relhasrules, relhasoids, "
4363                                                   "0 AS relfrozenxid, "
4364                                                   "0 AS toid, "
4365                                                   "0 AS tfrozenxid, "
4366                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4367                                                   "NULL AS reloftype, "
4368                                                   "NULL::oid AS owning_tab, "
4369                                                   "NULL::int4 AS owning_col, "
4370                                                   "NULL AS reltablespace, "
4371                                                   "NULL AS reloptions, "
4372                                                   "NULL AS toast_reloptions "
4373                                                   "FROM pg_class "
4374                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4375                                                   "ORDER BY oid",
4376                                                   username_subquery,
4377                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4378         }
4379         else if (fout->remoteVersion >= 70100)
4380         {
4381                 /* all tables have oids in 7.1 */
4382                 appendPQExpBuffer(query,
4383                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4384                                                   "0::oid AS relnamespace, "
4385                                                   "(%s relowner) AS rolname, "
4386                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4387                                                   "relhasindex, relhasrules, "
4388                                                   "'t'::bool AS relhasoids, "
4389                                                   "0 AS relfrozenxid, "
4390                                                   "0 AS toid, "
4391                                                   "0 AS tfrozenxid, "
4392                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4393                                                   "NULL AS reloftype, "
4394                                                   "NULL::oid AS owning_tab, "
4395                                                   "NULL::int4 AS owning_col, "
4396                                                   "NULL AS reltablespace, "
4397                                                   "NULL AS reloptions, "
4398                                                   "NULL AS toast_reloptions "
4399                                                   "FROM pg_class "
4400                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4401                                                   "ORDER BY oid",
4402                                                   username_subquery,
4403                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4404         }
4405         else
4406         {
4407                 /*
4408                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4409                  * have a view by looking for a rule in pg_rewrite.
4410                  */
4411                 appendPQExpBuffer(query,
4412                                                   "SELECT "
4413                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4414                                                   "oid, relname, relacl, "
4415                                                   "CASE WHEN relhasrules and relkind = 'r' "
4416                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4417                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4418                                                   "THEN '%c'::\"char\" "
4419                                                   "ELSE relkind END AS relkind,"
4420                                                   "0::oid AS relnamespace, "
4421                                                   "(%s relowner) AS rolname, "
4422                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4423                                                   "relhasindex, relhasrules, "
4424                                                   "'t'::bool AS relhasoids, "
4425                                                   "0 as relfrozenxid, "
4426                                                   "0 AS toid, "
4427                                                   "0 AS tfrozenxid, "
4428                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4429                                                   "NULL AS reloftype, "
4430                                                   "NULL::oid AS owning_tab, "
4431                                                   "NULL::int4 AS owning_col, "
4432                                                   "NULL AS reltablespace, "
4433                                                   "NULL AS reloptions, "
4434                                                   "NULL AS toast_reloptions "
4435                                                   "FROM pg_class c "
4436                                                   "WHERE relkind IN ('%c', '%c') "
4437                                                   "ORDER BY oid",
4438                                                   RELKIND_VIEW,
4439                                                   username_subquery,
4440                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4441         }
4442
4443         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4444
4445         ntups = PQntuples(res);
4446
4447         *numTables = ntups;
4448
4449         /*
4450          * Extract data from result and lock dumpable tables.  We do the locking
4451          * before anything else, to minimize the window wherein a table could
4452          * disappear under us.
4453          *
4454          * Note that we have to save info about all tables here, even when dumping
4455          * only one, because we don't yet know which tables might be inheritance
4456          * ancestors of the target table.
4457          */
4458         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4459
4460         i_reltableoid = PQfnumber(res, "tableoid");
4461         i_reloid = PQfnumber(res, "oid");
4462         i_relname = PQfnumber(res, "relname");
4463         i_relnamespace = PQfnumber(res, "relnamespace");
4464         i_relacl = PQfnumber(res, "relacl");
4465         i_relkind = PQfnumber(res, "relkind");
4466         i_rolname = PQfnumber(res, "rolname");
4467         i_relchecks = PQfnumber(res, "relchecks");
4468         i_relhastriggers = PQfnumber(res, "relhastriggers");
4469         i_relhasindex = PQfnumber(res, "relhasindex");
4470         i_relhasrules = PQfnumber(res, "relhasrules");
4471         i_relhasoids = PQfnumber(res, "relhasoids");
4472         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4473         i_toastoid = PQfnumber(res, "toid");
4474         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4475         i_relpersistence = PQfnumber(res, "relpersistence");
4476         i_isscannable = PQfnumber(res, "isscannable");
4477         i_owning_tab = PQfnumber(res, "owning_tab");
4478         i_owning_col = PQfnumber(res, "owning_col");
4479         i_reltablespace = PQfnumber(res, "reltablespace");
4480         i_reloptions = PQfnumber(res, "reloptions");
4481         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4482         i_reloftype = PQfnumber(res, "reloftype");
4483
4484         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4485         {
4486                 /*
4487                  * Arrange to fail instead of waiting forever for a table lock.
4488                  *
4489                  * NB: this coding assumes that the only queries issued within the
4490                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4491                  * applied to other things too.
4492                  */
4493                 resetPQExpBuffer(query);
4494                 appendPQExpBuffer(query, "SET statement_timeout = ");
4495                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4496                 ExecuteSqlStatement(fout, query->data);
4497         }
4498
4499         for (i = 0; i < ntups; i++)
4500         {
4501                 tblinfo[i].dobj.objType = DO_TABLE;
4502                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4503                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4504                 AssignDumpId(&tblinfo[i].dobj);
4505                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4506                 tblinfo[i].dobj.namespace =
4507                         findNamespace(fout,
4508                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4509                                                   tblinfo[i].dobj.catId.oid);
4510                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4511                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4512                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4513                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4514                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4515                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4516                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4517                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4518                 tblinfo[i].isscannable = (strcmp(PQgetvalue(res, i, i_isscannable), "t") == 0);
4519                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4520                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4521                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4522                 if (PQgetisnull(res, i, i_reloftype))
4523                         tblinfo[i].reloftype = NULL;
4524                 else
4525                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4526                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4527                 if (PQgetisnull(res, i, i_owning_tab))
4528                 {
4529                         tblinfo[i].owning_tab = InvalidOid;
4530                         tblinfo[i].owning_col = 0;
4531                 }
4532                 else
4533                 {
4534                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4535                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4536                 }
4537                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4538                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4539                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4540
4541                 /* other fields were zeroed above */
4542
4543                 /*
4544                  * Decide whether we want to dump this table.
4545                  */
4546                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4547                         tblinfo[i].dobj.dump = false;
4548                 else
4549                         selectDumpableTable(&tblinfo[i]);
4550                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4551
4552                 /*
4553                  * Read-lock target tables to make sure they aren't DROPPED or altered
4554                  * in schema before we get around to dumping them.
4555                  *
4556                  * Note that we don't explicitly lock parents of the target tables; we
4557                  * assume our lock on the child is enough to prevent schema
4558                  * alterations to parent tables.
4559                  *
4560                  * NOTE: it'd be kinda nice to lock other relations too, not only
4561                  * plain tables, but the backend doesn't presently allow that.
4562                  */
4563                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4564                 {
4565                         resetPQExpBuffer(query);
4566                         appendPQExpBuffer(query,
4567                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4568                                                           fmtQualifiedId(fout,
4569                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4570                                                                                          tblinfo[i].dobj.name));
4571                         ExecuteSqlStatement(fout, query->data);
4572                 }
4573
4574                 /* Emit notice if join for owner failed */
4575                 if (strlen(tblinfo[i].rolname) == 0)
4576                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4577                                           tblinfo[i].dobj.name);
4578         }
4579
4580         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4581         {
4582                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4583         }
4584
4585         PQclear(res);
4586
4587         destroyPQExpBuffer(query);
4588
4589         return tblinfo;
4590 }
4591
4592 /*
4593  * getOwnedSeqs
4594  *        identify owned sequences and mark them as dumpable if owning table is
4595  *
4596  * We used to do this in getTables(), but it's better to do it after the
4597  * index used by findTableByOid() has been set up.
4598  */
4599 void
4600 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4601 {
4602         int                     i;
4603
4604         /*
4605          * Force sequences that are "owned" by table columns to be dumped whenever
4606          * their owning table is being dumped.
4607          */
4608         for (i = 0; i < numTables; i++)
4609         {
4610                 TableInfo  *seqinfo = &tblinfo[i];
4611                 TableInfo  *owning_tab;
4612
4613                 if (!OidIsValid(seqinfo->owning_tab))
4614                         continue;                       /* not an owned sequence */
4615                 if (seqinfo->dobj.dump)
4616                         continue;                       /* no need to search */
4617                 owning_tab = findTableByOid(seqinfo->owning_tab);
4618                 if (owning_tab && owning_tab->dobj.dump)
4619                 {
4620                         seqinfo->interesting = true;
4621                         seqinfo->dobj.dump = true;
4622                 }
4623         }
4624 }
4625
4626 /*
4627  * getInherits
4628  *        read all the inheritance information
4629  * from the system catalogs return them in the InhInfo* structure
4630  *
4631  * numInherits is set to the number of pairs read in
4632  */
4633 InhInfo *
4634 getInherits(Archive *fout, int *numInherits)
4635 {
4636         PGresult   *res;
4637         int                     ntups;
4638         int                     i;
4639         PQExpBuffer query = createPQExpBuffer();
4640         InhInfo    *inhinfo;
4641
4642         int                     i_inhrelid;
4643         int                     i_inhparent;
4644
4645         /* Make sure we are in proper schema */
4646         selectSourceSchema(fout, "pg_catalog");
4647
4648         /* find all the inheritance information */
4649
4650         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4651
4652         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4653
4654         ntups = PQntuples(res);
4655
4656         *numInherits = ntups;
4657
4658         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4659
4660         i_inhrelid = PQfnumber(res, "inhrelid");
4661         i_inhparent = PQfnumber(res, "inhparent");
4662
4663         for (i = 0; i < ntups; i++)
4664         {
4665                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4666                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4667         }
4668
4669         PQclear(res);
4670
4671         destroyPQExpBuffer(query);
4672
4673         return inhinfo;
4674 }
4675
4676 /*
4677  * getIndexes
4678  *        get information about every index on a dumpable table
4679  *
4680  * Note: index data is not returned directly to the caller, but it
4681  * does get entered into the DumpableObject tables.
4682  */
4683 void
4684 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4685 {
4686         int                     i,
4687                                 j;
4688         PQExpBuffer query = createPQExpBuffer();
4689         PGresult   *res;
4690         IndxInfo   *indxinfo;
4691         ConstraintInfo *constrinfo;
4692         int                     i_tableoid,
4693                                 i_oid,
4694                                 i_indexname,
4695                                 i_indexdef,
4696                                 i_indnkeys,
4697                                 i_indkey,
4698                                 i_indisclustered,
4699                                 i_contype,
4700                                 i_conname,
4701                                 i_condeferrable,
4702                                 i_condeferred,
4703                                 i_contableoid,
4704                                 i_conoid,
4705                                 i_condef,
4706                                 i_tablespace,
4707                                 i_options;
4708         int                     ntups;
4709
4710         for (i = 0; i < numTables; i++)
4711         {
4712                 TableInfo  *tbinfo = &tblinfo[i];
4713
4714                 /* Only plain tables and materialized views have indexes. */
4715                 if (tbinfo->relkind != RELKIND_RELATION &&
4716                         tbinfo->relkind != RELKIND_MATVIEW)
4717                         continue;
4718                 if (!tbinfo->hasindex)
4719                         continue;
4720
4721                 /* Ignore indexes of tables not to be dumped */
4722                 if (!tbinfo->dobj.dump)
4723                         continue;
4724
4725                 if (g_verbose)
4726                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4727                                           tbinfo->dobj.name);
4728
4729                 /* Make sure we are in proper schema so indexdef is right */
4730                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4731
4732                 /*
4733                  * The point of the messy-looking outer join is to find a constraint
4734                  * that is related by an internal dependency link to the index. If we
4735                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4736                  * assume an index won't have more than one internal dependency.
4737                  *
4738                  * As of 9.0 we don't need to look at pg_depend but can check for a
4739                  * match to pg_constraint.conindid.  The check on conrelid is
4740                  * redundant but useful because that column is indexed while conindid
4741                  * is not.
4742                  */
4743                 resetPQExpBuffer(query);
4744                 if (fout->remoteVersion >= 90000)
4745                 {
4746                         appendPQExpBuffer(query,
4747                                                           "SELECT t.tableoid, t.oid, "
4748                                                           "t.relname AS indexname, "
4749                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4750                                                           "t.relnatts AS indnkeys, "
4751                                                           "i.indkey, i.indisclustered, "
4752                                                           "c.contype, c.conname, "
4753                                                           "c.condeferrable, c.condeferred, "
4754                                                           "c.tableoid AS contableoid, "
4755                                                           "c.oid AS conoid, "
4756                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4757                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4758                                                         "array_to_string(t.reloptions, ', ') AS options "
4759                                                           "FROM pg_catalog.pg_index i "
4760                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4761                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4762                                                           "ON (i.indrelid = c.conrelid AND "
4763                                                           "i.indexrelid = c.conindid AND "
4764                                                           "c.contype IN ('p','u','x')) "
4765                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4766                                                           "ORDER BY indexname",
4767                                                           tbinfo->dobj.catId.oid);
4768                 }
4769                 else if (fout->remoteVersion >= 80200)
4770                 {
4771                         appendPQExpBuffer(query,
4772                                                           "SELECT t.tableoid, t.oid, "
4773                                                           "t.relname AS indexname, "
4774                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4775                                                           "t.relnatts AS indnkeys, "
4776                                                           "i.indkey, i.indisclustered, "
4777                                                           "c.contype, c.conname, "
4778                                                           "c.condeferrable, c.condeferred, "
4779                                                           "c.tableoid AS contableoid, "
4780                                                           "c.oid AS conoid, "
4781                                                           "null AS condef, "
4782                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4783                                                         "array_to_string(t.reloptions, ', ') AS options "
4784                                                           "FROM pg_catalog.pg_index i "
4785                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4786                                                           "LEFT JOIN pg_catalog.pg_depend d "
4787                                                           "ON (d.classid = t.tableoid "
4788                                                           "AND d.objid = t.oid "
4789                                                           "AND d.deptype = 'i') "
4790                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4791                                                           "ON (d.refclassid = c.tableoid "
4792                                                           "AND d.refobjid = c.oid) "
4793                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4794                                                           "ORDER BY indexname",
4795                                                           tbinfo->dobj.catId.oid);
4796                 }
4797                 else if (fout->remoteVersion >= 80000)
4798                 {
4799                         appendPQExpBuffer(query,
4800                                                           "SELECT t.tableoid, t.oid, "
4801                                                           "t.relname AS indexname, "
4802                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4803                                                           "t.relnatts AS indnkeys, "
4804                                                           "i.indkey, i.indisclustered, "
4805                                                           "c.contype, c.conname, "
4806                                                           "c.condeferrable, c.condeferred, "
4807                                                           "c.tableoid AS contableoid, "
4808                                                           "c.oid AS conoid, "
4809                                                           "null AS condef, "
4810                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4811                                                           "null AS options "
4812                                                           "FROM pg_catalog.pg_index i "
4813                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4814                                                           "LEFT JOIN pg_catalog.pg_depend d "
4815                                                           "ON (d.classid = t.tableoid "
4816                                                           "AND d.objid = t.oid "
4817                                                           "AND d.deptype = 'i') "
4818                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4819                                                           "ON (d.refclassid = c.tableoid "
4820                                                           "AND d.refobjid = c.oid) "
4821                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4822                                                           "ORDER BY indexname",
4823                                                           tbinfo->dobj.catId.oid);
4824                 }
4825                 else if (fout->remoteVersion >= 70300)
4826                 {
4827                         appendPQExpBuffer(query,
4828                                                           "SELECT t.tableoid, t.oid, "
4829                                                           "t.relname AS indexname, "
4830                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4831                                                           "t.relnatts AS indnkeys, "
4832                                                           "i.indkey, i.indisclustered, "
4833                                                           "c.contype, c.conname, "
4834                                                           "c.condeferrable, c.condeferred, "
4835                                                           "c.tableoid AS contableoid, "
4836                                                           "c.oid AS conoid, "
4837                                                           "null AS condef, "
4838                                                           "NULL AS tablespace, "
4839                                                           "null AS options "
4840                                                           "FROM pg_catalog.pg_index i "
4841                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4842                                                           "LEFT JOIN pg_catalog.pg_depend d "
4843                                                           "ON (d.classid = t.tableoid "
4844                                                           "AND d.objid = t.oid "
4845                                                           "AND d.deptype = 'i') "
4846                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4847                                                           "ON (d.refclassid = c.tableoid "
4848                                                           "AND d.refobjid = c.oid) "
4849                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4850                                                           "ORDER BY indexname",
4851                                                           tbinfo->dobj.catId.oid);
4852                 }
4853                 else if (fout->remoteVersion >= 70100)
4854                 {
4855                         appendPQExpBuffer(query,
4856                                                           "SELECT t.tableoid, t.oid, "
4857                                                           "t.relname AS indexname, "
4858                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4859                                                           "t.relnatts AS indnkeys, "
4860                                                           "i.indkey, false AS indisclustered, "
4861                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4862                                                           "ELSE '0'::char END AS contype, "
4863                                                           "t.relname AS conname, "
4864                                                           "false AS condeferrable, "
4865                                                           "false AS condeferred, "
4866                                                           "0::oid AS contableoid, "
4867                                                           "t.oid AS conoid, "
4868                                                           "null AS condef, "
4869                                                           "NULL AS tablespace, "
4870                                                           "null AS options "
4871                                                           "FROM pg_index i, pg_class t "
4872                                                           "WHERE t.oid = i.indexrelid "
4873                                                           "AND i.indrelid = '%u'::oid "
4874                                                           "ORDER BY indexname",
4875                                                           tbinfo->dobj.catId.oid);
4876                 }
4877                 else
4878                 {
4879                         appendPQExpBuffer(query,
4880                                                           "SELECT "
4881                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4882                                                           "t.oid, "
4883                                                           "t.relname AS indexname, "
4884                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4885                                                           "t.relnatts AS indnkeys, "
4886                                                           "i.indkey, false AS indisclustered, "
4887                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4888                                                           "ELSE '0'::char END AS contype, "
4889                                                           "t.relname AS conname, "
4890                                                           "false AS condeferrable, "
4891                                                           "false AS condeferred, "
4892                                                           "0::oid AS contableoid, "
4893                                                           "t.oid AS conoid, "
4894                                                           "null AS condef, "
4895                                                           "NULL AS tablespace, "
4896                                                           "null AS options "
4897                                                           "FROM pg_index i, pg_class t "
4898                                                           "WHERE t.oid = i.indexrelid "
4899                                                           "AND i.indrelid = '%u'::oid "
4900                                                           "ORDER BY indexname",
4901                                                           tbinfo->dobj.catId.oid);
4902                 }
4903
4904                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4905
4906                 ntups = PQntuples(res);
4907
4908                 i_tableoid = PQfnumber(res, "tableoid");
4909                 i_oid = PQfnumber(res, "oid");
4910                 i_indexname = PQfnumber(res, "indexname");
4911                 i_indexdef = PQfnumber(res, "indexdef");
4912                 i_indnkeys = PQfnumber(res, "indnkeys");
4913                 i_indkey = PQfnumber(res, "indkey");
4914                 i_indisclustered = PQfnumber(res, "indisclustered");
4915                 i_contype = PQfnumber(res, "contype");
4916                 i_conname = PQfnumber(res, "conname");
4917                 i_condeferrable = PQfnumber(res, "condeferrable");
4918                 i_condeferred = PQfnumber(res, "condeferred");
4919                 i_contableoid = PQfnumber(res, "contableoid");
4920                 i_conoid = PQfnumber(res, "conoid");
4921                 i_condef = PQfnumber(res, "condef");
4922                 i_tablespace = PQfnumber(res, "tablespace");
4923                 i_options = PQfnumber(res, "options");
4924
4925                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4926                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4927
4928                 for (j = 0; j < ntups; j++)
4929                 {
4930                         char            contype;
4931
4932                         indxinfo[j].dobj.objType = DO_INDEX;
4933                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4934                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4935                         AssignDumpId(&indxinfo[j].dobj);
4936                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4937                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4938                         indxinfo[j].indextable = tbinfo;
4939                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4940                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4941                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4942                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4943
4944                         /*
4945                          * In pre-7.4 releases, indkeys may contain more entries than
4946                          * indnkeys says (since indnkeys will be 1 for a functional
4947                          * index).      We don't actually care about this case since we don't
4948                          * examine indkeys except for indexes associated with PRIMARY and
4949                          * UNIQUE constraints, which are never functional indexes. But we
4950                          * have to allocate enough space to keep parseOidArray from
4951                          * complaining.
4952                          */
4953                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4954                         parseOidArray(PQgetvalue(res, j, i_indkey),
4955                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4956                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4957                         contype = *(PQgetvalue(res, j, i_contype));
4958
4959                         if (contype == 'p' || contype == 'u' || contype == 'x')
4960                         {
4961                                 /*
4962                                  * If we found a constraint matching the index, create an
4963                                  * entry for it.
4964                                  *
4965                                  * In a pre-7.3 database, we take this path iff the index was
4966                                  * marked indisprimary.
4967                                  */
4968                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4969                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4970                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4971                                 AssignDumpId(&constrinfo[j].dobj);
4972                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4973                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4974                                 constrinfo[j].contable = tbinfo;
4975                                 constrinfo[j].condomain = NULL;
4976                                 constrinfo[j].contype = contype;
4977                                 if (contype == 'x')
4978                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4979                                 else
4980                                         constrinfo[j].condef = NULL;
4981                                 constrinfo[j].confrelid = InvalidOid;
4982                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4983                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4984                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4985                                 constrinfo[j].conislocal = true;
4986                                 constrinfo[j].separate = true;
4987
4988                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4989
4990                                 /* If pre-7.3 DB, better make sure table comes first */
4991                                 addObjectDependency(&constrinfo[j].dobj,
4992                                                                         tbinfo->dobj.dumpId);
4993                         }
4994                         else
4995                         {
4996                                 /* Plain secondary index */
4997                                 indxinfo[j].indexconstraint = 0;
4998                         }
4999                 }
5000
5001                 PQclear(res);
5002         }
5003
5004         destroyPQExpBuffer(query);
5005 }
5006
5007 /*
5008  * getConstraints
5009  *
5010  * Get info about constraints on dumpable tables.
5011  *
5012  * Currently handles foreign keys only.
5013  * Unique and primary key constraints are handled with indexes,
5014  * while check constraints are processed in getTableAttrs().
5015  */
5016 void
5017 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
5018 {
5019         int                     i,
5020                                 j;
5021         ConstraintInfo *constrinfo;
5022         PQExpBuffer query;
5023         PGresult   *res;
5024         int                     i_contableoid,
5025                                 i_conoid,
5026                                 i_conname,
5027                                 i_confrelid,
5028                                 i_condef;
5029         int                     ntups;
5030
5031         /* pg_constraint was created in 7.3, so nothing to do if older */
5032         if (fout->remoteVersion < 70300)
5033                 return;
5034
5035         query = createPQExpBuffer();
5036
5037         for (i = 0; i < numTables; i++)
5038         {
5039                 TableInfo  *tbinfo = &tblinfo[i];
5040
5041                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5042                         continue;
5043
5044                 if (g_verbose)
5045                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
5046                                           tbinfo->dobj.name);
5047
5048                 /*
5049                  * select table schema to ensure constraint expr is qualified if
5050                  * needed
5051                  */
5052                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5053
5054                 resetPQExpBuffer(query);
5055                 appendPQExpBuffer(query,
5056                                                   "SELECT tableoid, oid, conname, confrelid, "
5057                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
5058                                                   "FROM pg_catalog.pg_constraint "
5059                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5060                                                   "AND contype = 'f'",
5061                                                   tbinfo->dobj.catId.oid);
5062                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5063
5064                 ntups = PQntuples(res);
5065
5066                 i_contableoid = PQfnumber(res, "tableoid");
5067                 i_conoid = PQfnumber(res, "oid");
5068                 i_conname = PQfnumber(res, "conname");
5069                 i_confrelid = PQfnumber(res, "confrelid");
5070                 i_condef = PQfnumber(res, "condef");
5071
5072                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5073
5074                 for (j = 0; j < ntups; j++)
5075                 {
5076                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
5077                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5078                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5079                         AssignDumpId(&constrinfo[j].dobj);
5080                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5081                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5082                         constrinfo[j].contable = tbinfo;
5083                         constrinfo[j].condomain = NULL;
5084                         constrinfo[j].contype = 'f';
5085                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5086                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
5087                         constrinfo[j].conindex = 0;
5088                         constrinfo[j].condeferrable = false;
5089                         constrinfo[j].condeferred = false;
5090                         constrinfo[j].conislocal = true;
5091                         constrinfo[j].separate = true;
5092                 }
5093
5094                 PQclear(res);
5095         }
5096
5097         destroyPQExpBuffer(query);
5098 }
5099
5100 /*
5101  * getDomainConstraints
5102  *
5103  * Get info about constraints on a domain.
5104  */
5105 static void
5106 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
5107 {
5108         int                     i;
5109         ConstraintInfo *constrinfo;
5110         PQExpBuffer query;
5111         PGresult   *res;
5112         int                     i_tableoid,
5113                                 i_oid,
5114                                 i_conname,
5115                                 i_consrc;
5116         int                     ntups;
5117
5118         /* pg_constraint was created in 7.3, so nothing to do if older */
5119         if (fout->remoteVersion < 70300)
5120                 return;
5121
5122         /*
5123          * select appropriate schema to ensure names in constraint are properly
5124          * qualified
5125          */
5126         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
5127
5128         query = createPQExpBuffer();
5129
5130         if (fout->remoteVersion >= 90100)
5131                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5132                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5133                                                   "convalidated "
5134                                                   "FROM pg_catalog.pg_constraint "
5135                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5136                                                   "ORDER BY conname",
5137                                                   tyinfo->dobj.catId.oid);
5138
5139         else if (fout->remoteVersion >= 70400)
5140                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5141                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5142                                                   "true as convalidated "
5143                                                   "FROM pg_catalog.pg_constraint "
5144                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5145                                                   "ORDER BY conname",
5146                                                   tyinfo->dobj.catId.oid);
5147         else
5148                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5149                                                   "'CHECK (' || consrc || ')' AS consrc, "
5150                                                   "true as convalidated "
5151                                                   "FROM pg_catalog.pg_constraint "
5152                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5153                                                   "ORDER BY conname",
5154                                                   tyinfo->dobj.catId.oid);
5155
5156         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5157
5158         ntups = PQntuples(res);
5159
5160         i_tableoid = PQfnumber(res, "tableoid");
5161         i_oid = PQfnumber(res, "oid");
5162         i_conname = PQfnumber(res, "conname");
5163         i_consrc = PQfnumber(res, "consrc");
5164
5165         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5166
5167         tyinfo->nDomChecks = ntups;
5168         tyinfo->domChecks = constrinfo;
5169
5170         for (i = 0; i < ntups; i++)
5171         {
5172                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
5173
5174                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5175                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5176                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5177                 AssignDumpId(&constrinfo[i].dobj);
5178                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5179                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5180                 constrinfo[i].contable = NULL;
5181                 constrinfo[i].condomain = tyinfo;
5182                 constrinfo[i].contype = 'c';
5183                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5184                 constrinfo[i].confrelid = InvalidOid;
5185                 constrinfo[i].conindex = 0;
5186                 constrinfo[i].condeferrable = false;
5187                 constrinfo[i].condeferred = false;
5188                 constrinfo[i].conislocal = true;
5189
5190                 constrinfo[i].separate = !validated;
5191
5192                 /*
5193                  * Make the domain depend on the constraint, ensuring it won't be
5194                  * output till any constraint dependencies are OK.      If the constraint
5195                  * has not been validated, it's going to be dumped after the domain
5196                  * anyway, so this doesn't matter.
5197                  */
5198                 if (validated)
5199                         addObjectDependency(&tyinfo->dobj,
5200                                                                 constrinfo[i].dobj.dumpId);
5201         }
5202
5203         PQclear(res);
5204
5205         destroyPQExpBuffer(query);
5206 }
5207
5208 /*
5209  * getRules
5210  *        get basic information about every rule in the system
5211  *
5212  * numRules is set to the number of rules read in
5213  */
5214 RuleInfo *
5215 getRules(Archive *fout, int *numRules)
5216 {
5217         PGresult   *res;
5218         int                     ntups;
5219         int                     i;
5220         PQExpBuffer query = createPQExpBuffer();
5221         RuleInfo   *ruleinfo;
5222         int                     i_tableoid;
5223         int                     i_oid;
5224         int                     i_rulename;
5225         int                     i_ruletable;
5226         int                     i_ev_type;
5227         int                     i_is_instead;
5228         int                     i_ev_enabled;
5229
5230         /* Make sure we are in proper schema */
5231         selectSourceSchema(fout, "pg_catalog");
5232
5233         if (fout->remoteVersion >= 80300)
5234         {
5235                 appendPQExpBuffer(query, "SELECT "
5236                                                   "tableoid, oid, rulename, "
5237                                                   "ev_class AS ruletable, ev_type, is_instead, "
5238                                                   "ev_enabled "
5239                                                   "FROM pg_rewrite "
5240                                                   "ORDER BY oid");
5241         }
5242         else if (fout->remoteVersion >= 70100)
5243         {
5244                 appendPQExpBuffer(query, "SELECT "
5245                                                   "tableoid, oid, rulename, "
5246                                                   "ev_class AS ruletable, ev_type, is_instead, "
5247                                                   "'O'::char AS ev_enabled "
5248                                                   "FROM pg_rewrite "
5249                                                   "ORDER BY oid");
5250         }
5251         else
5252         {
5253                 appendPQExpBuffer(query, "SELECT "
5254                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5255                                                   "oid, rulename, "
5256                                                   "ev_class AS ruletable, ev_type, is_instead, "
5257                                                   "'O'::char AS ev_enabled "
5258                                                   "FROM pg_rewrite "
5259                                                   "ORDER BY oid");
5260         }
5261
5262         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5263
5264         ntups = PQntuples(res);
5265
5266         *numRules = ntups;
5267
5268         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5269
5270         i_tableoid = PQfnumber(res, "tableoid");
5271         i_oid = PQfnumber(res, "oid");
5272         i_rulename = PQfnumber(res, "rulename");
5273         i_ruletable = PQfnumber(res, "ruletable");
5274         i_ev_type = PQfnumber(res, "ev_type");
5275         i_is_instead = PQfnumber(res, "is_instead");
5276         i_ev_enabled = PQfnumber(res, "ev_enabled");
5277
5278         for (i = 0; i < ntups; i++)
5279         {
5280                 Oid                     ruletableoid;
5281
5282                 ruleinfo[i].dobj.objType = DO_RULE;
5283                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5284                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5285                 AssignDumpId(&ruleinfo[i].dobj);
5286                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5287                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5288                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5289                 if (ruleinfo[i].ruletable == NULL)
5290                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5291                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5292                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5293                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5294                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5295                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5296                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5297                 if (ruleinfo[i].ruletable)
5298                 {
5299                         /*
5300                          * If the table is a view or materialized view, force its ON
5301                          * SELECT rule to be sorted before the view itself --- this
5302                          * ensures that any dependencies for the rule affect the table's
5303                          * positioning. Other rules are forced to appear after their
5304                          * table.
5305                          */
5306                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
5307                              ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
5308                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5309                         {
5310                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5311                                                                         ruleinfo[i].dobj.dumpId);
5312                                 /* We'll merge the rule into CREATE VIEW, if possible */
5313                                 ruleinfo[i].separate = false;
5314                         }
5315                         else
5316                         {
5317                                 addObjectDependency(&ruleinfo[i].dobj,
5318                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5319                                 ruleinfo[i].separate = true;
5320                         }
5321                 }
5322                 else
5323                         ruleinfo[i].separate = true;
5324
5325                 /*
5326                  * If we're forced to break a dependency loop by dumping a view as a
5327                  * table and separate _RETURN rule, we'll move the view's reloptions
5328                  * to the rule.  (This is necessary because tables and views have
5329                  * different valid reloptions, so we can't apply the options until the
5330                  * backend knows it's a view.)  Otherwise the rule's reloptions stay
5331                  * NULL.
5332                  */
5333                 ruleinfo[i].reloptions = NULL;
5334         }
5335
5336         PQclear(res);
5337
5338         destroyPQExpBuffer(query);
5339
5340         return ruleinfo;
5341 }
5342
5343 /*
5344  * getTriggers
5345  *        get information about every trigger on a dumpable table
5346  *
5347  * Note: trigger data is not returned directly to the caller, but it
5348  * does get entered into the DumpableObject tables.
5349  */
5350 void
5351 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5352 {
5353         int                     i,
5354                                 j;
5355         PQExpBuffer query = createPQExpBuffer();
5356         PGresult   *res;
5357         TriggerInfo *tginfo;
5358         int                     i_tableoid,
5359                                 i_oid,
5360                                 i_tgname,
5361                                 i_tgfname,
5362                                 i_tgtype,
5363                                 i_tgnargs,
5364                                 i_tgargs,
5365                                 i_tgisconstraint,
5366                                 i_tgconstrname,
5367                                 i_tgconstrrelid,
5368                                 i_tgconstrrelname,
5369                                 i_tgenabled,
5370                                 i_tgdeferrable,
5371                                 i_tginitdeferred,
5372                                 i_tgdef;
5373         int                     ntups;
5374
5375         for (i = 0; i < numTables; i++)
5376         {
5377                 TableInfo  *tbinfo = &tblinfo[i];
5378
5379                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5380                         continue;
5381
5382                 if (g_verbose)
5383                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5384                                           tbinfo->dobj.name);
5385
5386                 /*
5387                  * select table schema to ensure regproc name is qualified if needed
5388                  */
5389                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5390
5391                 resetPQExpBuffer(query);
5392                 if (fout->remoteVersion >= 90000)
5393                 {
5394                         /*
5395                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5396                          * could result in non-forward-compatible dumps of WHEN clauses
5397                          * due to under-parenthesization.
5398                          */
5399                         appendPQExpBuffer(query,
5400                                                           "SELECT tgname, "
5401                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5402                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5403                                                           "tgenabled, tableoid, oid "
5404                                                           "FROM pg_catalog.pg_trigger t "
5405                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5406                                                           "AND NOT tgisinternal",
5407                                                           tbinfo->dobj.catId.oid);
5408                 }
5409                 else if (fout->remoteVersion >= 80300)
5410                 {
5411                         /*
5412                          * We ignore triggers that are tied to a foreign-key constraint
5413                          */
5414                         appendPQExpBuffer(query,
5415                                                           "SELECT tgname, "
5416                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5417                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5418                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5419                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5420                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5421                                                           "FROM pg_catalog.pg_trigger t "
5422                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5423                                                           "AND tgconstraint = 0",
5424                                                           tbinfo->dobj.catId.oid);
5425                 }
5426                 else if (fout->remoteVersion >= 70300)
5427                 {
5428                         /*
5429                          * We ignore triggers that are tied to a foreign-key constraint,
5430                          * but in these versions we have to grovel through pg_constraint
5431                          * to find out
5432                          */
5433                         appendPQExpBuffer(query,
5434                                                           "SELECT tgname, "
5435                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5436                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5437                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5438                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5439                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5440                                                           "FROM pg_catalog.pg_trigger t "
5441                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5442                                                           "AND (NOT tgisconstraint "
5443                                                           " OR NOT EXISTS"
5444                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5445                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5446                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5447                                                           tbinfo->dobj.catId.oid);
5448                 }
5449                 else if (fout->remoteVersion >= 70100)
5450                 {
5451                         appendPQExpBuffer(query,
5452                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5453                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5454                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5455                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5456                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5457                                                           "             AS tgconstrrelname "
5458                                                           "FROM pg_trigger "
5459                                                           "WHERE tgrelid = '%u'::oid",
5460                                                           tbinfo->dobj.catId.oid);
5461                 }
5462                 else
5463                 {
5464                         appendPQExpBuffer(query,
5465                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5466                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5467                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5468                                                           "tgconstrrelid, tginitdeferred, "
5469                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5470                                                           "oid, "
5471                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5472                                                           "             AS tgconstrrelname "
5473                                                           "FROM pg_trigger "
5474                                                           "WHERE tgrelid = '%u'::oid",
5475                                                           tbinfo->dobj.catId.oid);
5476                 }
5477                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5478
5479                 ntups = PQntuples(res);
5480
5481                 i_tableoid = PQfnumber(res, "tableoid");
5482                 i_oid = PQfnumber(res, "oid");
5483                 i_tgname = PQfnumber(res, "tgname");
5484                 i_tgfname = PQfnumber(res, "tgfname");
5485                 i_tgtype = PQfnumber(res, "tgtype");
5486                 i_tgnargs = PQfnumber(res, "tgnargs");
5487                 i_tgargs = PQfnumber(res, "tgargs");
5488                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5489                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5490                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5491                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5492                 i_tgenabled = PQfnumber(res, "tgenabled");
5493                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5494                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5495                 i_tgdef = PQfnumber(res, "tgdef");
5496
5497                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5498
5499                 for (j = 0; j < ntups; j++)
5500                 {
5501                         tginfo[j].dobj.objType = DO_TRIGGER;
5502                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5503                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5504                         AssignDumpId(&tginfo[j].dobj);
5505                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5506                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5507                         tginfo[j].tgtable = tbinfo;
5508                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5509                         if (i_tgdef >= 0)
5510                         {
5511                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5512
5513                                 /* remaining fields are not valid if we have tgdef */
5514                                 tginfo[j].tgfname = NULL;
5515                                 tginfo[j].tgtype = 0;
5516                                 tginfo[j].tgnargs = 0;
5517                                 tginfo[j].tgargs = NULL;
5518                                 tginfo[j].tgisconstraint = false;
5519                                 tginfo[j].tgdeferrable = false;
5520                                 tginfo[j].tginitdeferred = false;
5521                                 tginfo[j].tgconstrname = NULL;
5522                                 tginfo[j].tgconstrrelid = InvalidOid;
5523                                 tginfo[j].tgconstrrelname = NULL;
5524                         }
5525                         else
5526                         {
5527                                 tginfo[j].tgdef = NULL;
5528
5529                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5530                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5531                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5532                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5533                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5534                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5535                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5536
5537                                 if (tginfo[j].tgisconstraint)
5538                                 {
5539                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5540                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5541                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5542                                         {
5543                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5544                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5545                                                                                   tginfo[j].dobj.name,
5546                                                                                   tbinfo->dobj.name,
5547                                                                                   tginfo[j].tgconstrrelid);
5548                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5549                                         }
5550                                         else
5551                                                 tginfo[j].tgconstrrelname = NULL;
5552                                 }
5553                                 else
5554                                 {
5555                                         tginfo[j].tgconstrname = NULL;
5556                                         tginfo[j].tgconstrrelid = InvalidOid;
5557                                         tginfo[j].tgconstrrelname = NULL;
5558                                 }
5559                         }
5560                 }
5561
5562                 PQclear(res);
5563         }
5564
5565         destroyPQExpBuffer(query);
5566 }
5567
5568 /*
5569  * getEventTriggers
5570  *        get information about event triggers
5571  */
5572 EventTriggerInfo *
5573 getEventTriggers(Archive *fout, int *numEventTriggers)
5574 {
5575         int                     i;
5576         PQExpBuffer query = createPQExpBuffer();
5577         PGresult   *res;
5578         EventTriggerInfo *evtinfo;
5579         int                     i_tableoid,
5580                                 i_oid,
5581                                 i_evtname,
5582                                 i_evtevent,
5583                                 i_evtowner,
5584                                 i_evttags,
5585                                 i_evtfname,
5586                                 i_evtenabled;
5587         int                     ntups;
5588
5589         /* Before 9.3, there are no event triggers */
5590         if (fout->remoteVersion < 90300)
5591         {
5592                 *numEventTriggers = 0;
5593                 return NULL;
5594         }
5595
5596         /* Make sure we are in proper schema */
5597         selectSourceSchema(fout, "pg_catalog");
5598
5599         appendPQExpBuffer(query,
5600                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5601                                           "evtevent, (%s evtowner) AS evtowner, "
5602                                           "array_to_string(array("
5603                                           "select quote_literal(x) "
5604                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
5605                                           "e.evtfoid::regproc as evtfname "
5606                                           "FROM pg_event_trigger e "
5607                                           "ORDER BY e.oid",
5608                                           username_subquery);
5609
5610         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5611
5612         ntups = PQntuples(res);
5613
5614         *numEventTriggers = ntups;
5615
5616         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5617
5618         i_tableoid = PQfnumber(res, "tableoid");
5619         i_oid = PQfnumber(res, "oid");
5620         i_evtname = PQfnumber(res, "evtname");
5621         i_evtevent = PQfnumber(res, "evtevent");
5622         i_evtowner = PQfnumber(res, "evtowner");
5623         i_evttags = PQfnumber(res, "evttags");
5624         i_evtfname = PQfnumber(res, "evtfname");
5625         i_evtenabled = PQfnumber(res, "evtenabled");
5626
5627         for (i = 0; i < ntups; i++)
5628         {
5629                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5630                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5631                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5632                 AssignDumpId(&evtinfo[i].dobj);
5633                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5634                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5635                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5636                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5637                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5638                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5639                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5640         }
5641
5642         PQclear(res);
5643
5644         destroyPQExpBuffer(query);
5645
5646         return evtinfo;
5647 }
5648
5649 /*
5650  * getProcLangs
5651  *        get basic information about every procedural language in the system
5652  *
5653  * numProcLangs is set to the number of langs read in
5654  *
5655  * NB: this must run after getFuncs() because we assume we can do
5656  * findFuncByOid().
5657  */
5658 ProcLangInfo *
5659 getProcLangs(Archive *fout, int *numProcLangs)
5660 {
5661         PGresult   *res;
5662         int                     ntups;
5663         int                     i;
5664         PQExpBuffer query = createPQExpBuffer();
5665         ProcLangInfo *planginfo;
5666         int                     i_tableoid;
5667         int                     i_oid;
5668         int                     i_lanname;
5669         int                     i_lanpltrusted;
5670         int                     i_lanplcallfoid;
5671         int                     i_laninline;
5672         int                     i_lanvalidator;
5673         int                     i_lanacl;
5674         int                     i_lanowner;
5675
5676         /* Make sure we are in proper schema */
5677         selectSourceSchema(fout, "pg_catalog");
5678
5679         if (fout->remoteVersion >= 90000)
5680         {
5681                 /* pg_language has a laninline column */
5682                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5683                                                   "lanname, lanpltrusted, lanplcallfoid, "
5684                                                   "laninline, lanvalidator,  lanacl, "
5685                                                   "(%s lanowner) AS lanowner "
5686                                                   "FROM pg_language "
5687                                                   "WHERE lanispl "
5688                                                   "ORDER BY oid",
5689                                                   username_subquery);
5690         }
5691         else if (fout->remoteVersion >= 80300)
5692         {
5693                 /* pg_language has a lanowner column */
5694                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5695                                                   "lanname, lanpltrusted, lanplcallfoid, "
5696                                                   "lanvalidator,  lanacl, "
5697                                                   "(%s lanowner) AS lanowner "
5698                                                   "FROM pg_language "
5699                                                   "WHERE lanispl "
5700                                                   "ORDER BY oid",
5701                                                   username_subquery);
5702         }
5703         else if (fout->remoteVersion >= 80100)
5704         {
5705                 /* Languages are owned by the bootstrap superuser, OID 10 */
5706                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5707                                                   "(%s '10') AS lanowner "
5708                                                   "FROM pg_language "
5709                                                   "WHERE lanispl "
5710                                                   "ORDER BY oid",
5711                                                   username_subquery);
5712         }
5713         else if (fout->remoteVersion >= 70400)
5714         {
5715                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5716                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5717                                                   "(%s '1') AS lanowner "
5718                                                   "FROM pg_language "
5719                                                   "WHERE lanispl "
5720                                                   "ORDER BY oid",
5721                                                   username_subquery);
5722         }
5723         else if (fout->remoteVersion >= 70100)
5724         {
5725                 /* No clear notion of an owner at all before 7.4 ... */
5726                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5727                                                   "WHERE lanispl "
5728                                                   "ORDER BY oid");
5729         }
5730         else
5731         {
5732                 appendPQExpBuffer(query, "SELECT "
5733                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5734                                                   "oid, * FROM pg_language "
5735                                                   "WHERE lanispl "
5736                                                   "ORDER BY oid");
5737         }
5738
5739         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5740
5741         ntups = PQntuples(res);
5742
5743         *numProcLangs = ntups;
5744
5745         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5746
5747         i_tableoid = PQfnumber(res, "tableoid");
5748         i_oid = PQfnumber(res, "oid");
5749         i_lanname = PQfnumber(res, "lanname");
5750         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5751         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5752         /* these may fail and return -1: */
5753         i_laninline = PQfnumber(res, "laninline");
5754         i_lanvalidator = PQfnumber(res, "lanvalidator");
5755         i_lanacl = PQfnumber(res, "lanacl");
5756         i_lanowner = PQfnumber(res, "lanowner");
5757
5758         for (i = 0; i < ntups; i++)
5759         {
5760                 planginfo[i].dobj.objType = DO_PROCLANG;
5761                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5762                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5763                 AssignDumpId(&planginfo[i].dobj);
5764
5765                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5766                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5767                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5768                 if (i_laninline >= 0)
5769                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5770                 else
5771                         planginfo[i].laninline = InvalidOid;
5772                 if (i_lanvalidator >= 0)
5773                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5774                 else
5775                         planginfo[i].lanvalidator = InvalidOid;
5776                 if (i_lanacl >= 0)
5777                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5778                 else
5779                         planginfo[i].lanacl = pg_strdup("{=U}");
5780                 if (i_lanowner >= 0)
5781                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5782                 else
5783                         planginfo[i].lanowner = pg_strdup("");
5784
5785                 if (fout->remoteVersion < 70300)
5786                 {
5787                         /*
5788                          * We need to make a dependency to ensure the function will be
5789                          * dumped first.  (In 7.3 and later the regular dependency
5790                          * mechanism will handle this for us.)
5791                          */
5792                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5793
5794                         if (funcInfo)
5795                                 addObjectDependency(&planginfo[i].dobj,
5796                                                                         funcInfo->dobj.dumpId);
5797                 }
5798         }
5799
5800         PQclear(res);
5801
5802         destroyPQExpBuffer(query);
5803
5804         return planginfo;
5805 }
5806
5807 /*
5808  * getCasts
5809  *        get basic information about every cast in the system
5810  *
5811  * numCasts is set to the number of casts read in
5812  */
5813 CastInfo *
5814 getCasts(Archive *fout, int *numCasts)
5815 {
5816         PGresult   *res;
5817         int                     ntups;
5818         int                     i;
5819         PQExpBuffer query = createPQExpBuffer();
5820         CastInfo   *castinfo;
5821         int                     i_tableoid;
5822         int                     i_oid;
5823         int                     i_castsource;
5824         int                     i_casttarget;
5825         int                     i_castfunc;
5826         int                     i_castcontext;
5827         int                     i_castmethod;
5828
5829         /* Make sure we are in proper schema */
5830         selectSourceSchema(fout, "pg_catalog");
5831
5832         if (fout->remoteVersion >= 80400)
5833         {
5834                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5835                                                   "castsource, casttarget, castfunc, castcontext, "
5836                                                   "castmethod "
5837                                                   "FROM pg_cast ORDER BY 3,4");
5838         }
5839         else if (fout->remoteVersion >= 70300)
5840         {
5841                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5842                                                   "castsource, casttarget, castfunc, castcontext, "
5843                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5844                                                   "FROM pg_cast ORDER BY 3,4");
5845         }
5846         else
5847         {
5848                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5849                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5850                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5851                                                   "'f' AS castmethod "
5852                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5853                                                   "WHERE p.pronargs = 1 AND "
5854                                                   "p.proargtypes[0] = t1.oid AND "
5855                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5856                                                   "ORDER BY 3,4");
5857         }
5858
5859         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5860
5861         ntups = PQntuples(res);
5862
5863         *numCasts = ntups;
5864
5865         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5866
5867         i_tableoid = PQfnumber(res, "tableoid");
5868         i_oid = PQfnumber(res, "oid");
5869         i_castsource = PQfnumber(res, "castsource");
5870         i_casttarget = PQfnumber(res, "casttarget");
5871         i_castfunc = PQfnumber(res, "castfunc");
5872         i_castcontext = PQfnumber(res, "castcontext");
5873         i_castmethod = PQfnumber(res, "castmethod");
5874
5875         for (i = 0; i < ntups; i++)
5876         {
5877                 PQExpBufferData namebuf;
5878                 TypeInfo   *sTypeInfo;
5879                 TypeInfo   *tTypeInfo;
5880
5881                 castinfo[i].dobj.objType = DO_CAST;
5882                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5883                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5884                 AssignDumpId(&castinfo[i].dobj);
5885                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5886                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5887                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5888                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5889                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5890
5891                 /*
5892                  * Try to name cast as concatenation of typnames.  This is only used
5893                  * for purposes of sorting.  If we fail to find either type, the name
5894                  * will be an empty string.
5895                  */
5896                 initPQExpBuffer(&namebuf);
5897                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5898                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5899                 if (sTypeInfo && tTypeInfo)
5900                         appendPQExpBuffer(&namebuf, "%s %s",
5901                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5902                 castinfo[i].dobj.name = namebuf.data;
5903
5904                 if (OidIsValid(castinfo[i].castfunc))
5905                 {
5906                         /*
5907                          * We need to make a dependency to ensure the function will be
5908                          * dumped first.  (In 7.3 and later the regular dependency
5909                          * mechanism will handle this for us.)
5910                          */
5911                         FuncInfo   *funcInfo;
5912
5913                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5914                         if (funcInfo)
5915                                 addObjectDependency(&castinfo[i].dobj,
5916                                                                         funcInfo->dobj.dumpId);
5917                 }
5918         }
5919
5920         PQclear(res);
5921
5922         destroyPQExpBuffer(query);
5923
5924         return castinfo;
5925 }
5926
5927 /*
5928  * getTableAttrs -
5929  *        for each interesting table, read info about its attributes
5930  *        (names, types, default values, CHECK constraints, etc)
5931  *
5932  * This is implemented in a very inefficient way right now, looping
5933  * through the tblinfo and doing a join per table to find the attrs and their
5934  * types.  However, because we want type names and so forth to be named
5935  * relative to the schema of each table, we couldn't do it in just one
5936  * query.  (Maybe one query per schema?)
5937  *
5938  *      modifies tblinfo
5939  */
5940 void
5941 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5942 {
5943         int                     i,
5944                                 j;
5945         PQExpBuffer q = createPQExpBuffer();
5946         int                     i_attnum;
5947         int                     i_attname;
5948         int                     i_atttypname;
5949         int                     i_atttypmod;
5950         int                     i_attstattarget;
5951         int                     i_attstorage;
5952         int                     i_typstorage;
5953         int                     i_attnotnull;
5954         int                     i_atthasdef;
5955         int                     i_attisdropped;
5956         int                     i_attlen;
5957         int                     i_attalign;
5958         int                     i_attislocal;
5959         int                     i_attoptions;
5960         int                     i_attcollation;
5961         int                     i_attfdwoptions;
5962         PGresult   *res;
5963         int                     ntups;
5964         bool            hasdefaults;
5965
5966         for (i = 0; i < numTables; i++)
5967         {
5968                 TableInfo  *tbinfo = &tblinfo[i];
5969
5970                 /* Don't bother to collect info for sequences */
5971                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5972                         continue;
5973
5974                 /* Don't bother with uninteresting tables, either */
5975                 if (!tbinfo->interesting)
5976                         continue;
5977
5978                 /*
5979                  * Make sure we are in proper schema for this table; this allows
5980                  * correct retrieval of formatted type names and default exprs
5981                  */
5982                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5983
5984                 /* find all the user attributes and their types */
5985
5986                 /*
5987                  * we must read the attribute names in attribute number order! because
5988                  * we will use the attnum to index into the attnames array later.  We
5989                  * actually ask to order by "attrelid, attnum" because (at least up to
5990                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5991                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5992                  */
5993                 if (g_verbose)
5994                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5995                                           tbinfo->dobj.name);
5996
5997                 resetPQExpBuffer(q);
5998
5999                 if (fout->remoteVersion >= 90200)
6000                 {
6001                         /*
6002                          * attfdwoptions is new in 9.2.
6003                          */
6004                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6005                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6006                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6007                                                           "a.attlen, a.attalign, a.attislocal, "
6008                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6009                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6010                                                           "CASE WHEN a.attcollation <> t.typcollation "
6011                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
6012                                                           "pg_catalog.array_to_string(ARRAY("
6013                                                           "SELECT pg_catalog.quote_ident(option_name) || "
6014                                                           "' ' || pg_catalog.quote_literal(option_value) "
6015                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
6016                                                           "ORDER BY option_name"
6017                                                           "), E',\n    ') AS attfdwoptions "
6018                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6019                                                           "ON a.atttypid = t.oid "
6020                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6021                                                           "AND a.attnum > 0::pg_catalog.int2 "
6022                                                           "ORDER BY a.attrelid, a.attnum",
6023                                                           tbinfo->dobj.catId.oid);
6024                 }
6025                 else if (fout->remoteVersion >= 90100)
6026                 {
6027                         /*
6028                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
6029                          * clauses for attributes whose collation is different from their
6030                          * type's default, we use a CASE here to suppress uninteresting
6031                          * attcollations cheaply.
6032                          */
6033                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6034                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6035                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6036                                                           "a.attlen, a.attalign, a.attislocal, "
6037                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6038                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6039                                                           "CASE WHEN a.attcollation <> t.typcollation "
6040                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
6041                                                           "NULL AS attfdwoptions "
6042                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6043                                                           "ON a.atttypid = t.oid "
6044                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6045                                                           "AND a.attnum > 0::pg_catalog.int2 "
6046                                                           "ORDER BY a.attrelid, a.attnum",
6047                                                           tbinfo->dobj.catId.oid);
6048                 }
6049                 else if (fout->remoteVersion >= 90000)
6050                 {
6051                         /* attoptions is new in 9.0 */
6052                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6053                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6054                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6055                                                           "a.attlen, a.attalign, a.attislocal, "
6056                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6057                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6058                                                           "0 AS attcollation, "
6059                                                           "NULL AS attfdwoptions "
6060                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6061                                                           "ON a.atttypid = t.oid "
6062                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6063                                                           "AND a.attnum > 0::pg_catalog.int2 "
6064                                                           "ORDER BY a.attrelid, a.attnum",
6065                                                           tbinfo->dobj.catId.oid);
6066                 }
6067                 else if (fout->remoteVersion >= 70300)
6068                 {
6069                         /* need left join here to not fail on dropped columns ... */
6070                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6071                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6072                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6073                                                           "a.attlen, a.attalign, a.attislocal, "
6074                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6075                                                           "'' AS attoptions, 0 AS attcollation, "
6076                                                           "NULL AS attfdwoptions "
6077                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6078                                                           "ON a.atttypid = t.oid "
6079                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6080                                                           "AND a.attnum > 0::pg_catalog.int2 "
6081                                                           "ORDER BY a.attrelid, a.attnum",
6082                                                           tbinfo->dobj.catId.oid);
6083                 }
6084                 else if (fout->remoteVersion >= 70100)
6085                 {
6086                         /*
6087                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
6088                          * we don't dump it because we can't tell whether it's been
6089                          * explicitly set or was just a default.
6090                          *
6091                          * attislocal doesn't exist before 7.3, either; in older databases
6092                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
6093                          */
6094                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6095                                                           "-1 AS attstattarget, a.attstorage, "
6096                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
6097                                                           "false AS attisdropped, a.attlen, "
6098                                                           "a.attalign, true AS attislocal, "
6099                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
6100                                                           "'' AS attoptions, 0 AS attcollation, "
6101                                                           "NULL AS attfdwoptions "
6102                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
6103                                                           "ON a.atttypid = t.oid "
6104                                                           "WHERE a.attrelid = '%u'::oid "
6105                                                           "AND a.attnum > 0::int2 "
6106                                                           "ORDER BY a.attrelid, a.attnum",
6107                                                           tbinfo->dobj.catId.oid);
6108                 }
6109                 else
6110                 {
6111                         /* format_type not available before 7.1 */
6112                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
6113                                                           "-1 AS attstattarget, "
6114                                                           "attstorage, attstorage AS typstorage, "
6115                                                           "attnotnull, atthasdef, false AS attisdropped, "
6116                                                           "attlen, attalign, "
6117                                                           "true AS attislocal, "
6118                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
6119                                                           "'' AS attoptions, 0 AS attcollation, "
6120                                                           "NULL AS attfdwoptions "
6121                                                           "FROM pg_attribute a "
6122                                                           "WHERE attrelid = '%u'::oid "
6123                                                           "AND attnum > 0::int2 "
6124                                                           "ORDER BY attrelid, attnum",
6125                                                           tbinfo->dobj.catId.oid);
6126                 }
6127
6128                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6129
6130                 ntups = PQntuples(res);
6131
6132                 i_attnum = PQfnumber(res, "attnum");
6133                 i_attname = PQfnumber(res, "attname");
6134                 i_atttypname = PQfnumber(res, "atttypname");
6135                 i_atttypmod = PQfnumber(res, "atttypmod");
6136                 i_attstattarget = PQfnumber(res, "attstattarget");
6137                 i_attstorage = PQfnumber(res, "attstorage");
6138                 i_typstorage = PQfnumber(res, "typstorage");
6139                 i_attnotnull = PQfnumber(res, "attnotnull");
6140                 i_atthasdef = PQfnumber(res, "atthasdef");
6141                 i_attisdropped = PQfnumber(res, "attisdropped");
6142                 i_attlen = PQfnumber(res, "attlen");
6143                 i_attalign = PQfnumber(res, "attalign");
6144                 i_attislocal = PQfnumber(res, "attislocal");
6145                 i_attoptions = PQfnumber(res, "attoptions");
6146                 i_attcollation = PQfnumber(res, "attcollation");
6147                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
6148
6149                 tbinfo->numatts = ntups;
6150                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
6151                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
6152                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
6153                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
6154                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
6155                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
6156                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
6157                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
6158                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
6159                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
6160                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
6161                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
6162                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
6163                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
6164                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
6165                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
6166                 hasdefaults = false;
6167
6168                 for (j = 0; j < ntups; j++)
6169                 {
6170                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
6171                                 exit_horribly(NULL,
6172                                                           "invalid column numbering in table \"%s\"\n",
6173                                                           tbinfo->dobj.name);
6174                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6175                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6176                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6177                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6178                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6179                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6180                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6181                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6182                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6183                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6184                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6185                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6186                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6187                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6188                         tbinfo->attrdefs[j] = NULL; /* fix below */
6189                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6190                                 hasdefaults = true;
6191                         /* these flags will be set in flagInhAttrs() */
6192                         tbinfo->inhNotNull[j] = false;
6193                 }
6194
6195                 PQclear(res);
6196
6197                 /*
6198                  * Get info about column defaults
6199                  */
6200                 if (hasdefaults)
6201                 {
6202                         AttrDefInfo *attrdefs;
6203                         int                     numDefaults;
6204
6205                         if (g_verbose)
6206                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6207                                                   tbinfo->dobj.name);
6208
6209                         resetPQExpBuffer(q);
6210                         if (fout->remoteVersion >= 70300)
6211                         {
6212                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6213                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6214                                                                   "FROM pg_catalog.pg_attrdef "
6215                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
6216                                                                   tbinfo->dobj.catId.oid);
6217                         }
6218                         else if (fout->remoteVersion >= 70200)
6219                         {
6220                                 /* 7.2 did not have OIDs in pg_attrdef */
6221                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6222                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
6223                                                                   "FROM pg_attrdef "
6224                                                                   "WHERE adrelid = '%u'::oid",
6225                                                                   tbinfo->dobj.catId.oid);
6226                         }
6227                         else if (fout->remoteVersion >= 70100)
6228                         {
6229                                 /* no pg_get_expr, so must rely on adsrc */
6230                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6231                                                                   "FROM pg_attrdef "
6232                                                                   "WHERE adrelid = '%u'::oid",
6233                                                                   tbinfo->dobj.catId.oid);
6234                         }
6235                         else
6236                         {
6237                                 /* no pg_get_expr, no tableoid either */
6238                                 appendPQExpBuffer(q, "SELECT "
6239                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6240                                                                   "oid, adnum, adsrc "
6241                                                                   "FROM pg_attrdef "
6242                                                                   "WHERE adrelid = '%u'::oid",
6243                                                                   tbinfo->dobj.catId.oid);
6244                         }
6245                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6246
6247                         numDefaults = PQntuples(res);
6248                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6249
6250                         for (j = 0; j < numDefaults; j++)
6251                         {
6252                                 int                     adnum;
6253
6254                                 adnum = atoi(PQgetvalue(res, j, 2));
6255
6256                                 if (adnum <= 0 || adnum > ntups)
6257                                         exit_horribly(NULL,
6258                                                                   "invalid adnum value %d for table \"%s\"\n",
6259                                                                   adnum, tbinfo->dobj.name);
6260
6261                                 /*
6262                                  * dropped columns shouldn't have defaults, but just in case,
6263                                  * ignore 'em
6264                                  */
6265                                 if (tbinfo->attisdropped[adnum - 1])
6266                                         continue;
6267
6268                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
6269                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6270                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6271                                 AssignDumpId(&attrdefs[j].dobj);
6272                                 attrdefs[j].adtable = tbinfo;
6273                                 attrdefs[j].adnum = adnum;
6274                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6275
6276                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6277                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6278
6279                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6280
6281                                 /*
6282                                  * Defaults on a VIEW must always be dumped as separate ALTER
6283                                  * TABLE commands.      Defaults on regular tables are dumped as
6284                                  * part of the CREATE TABLE if possible, which it won't be if
6285                                  * the column is not going to be emitted explicitly.
6286                                  */
6287                                 if (tbinfo->relkind == RELKIND_VIEW)
6288                                 {
6289                                         attrdefs[j].separate = true;
6290                                         /* needed in case pre-7.3 DB: */
6291                                         addObjectDependency(&attrdefs[j].dobj,
6292                                                                                 tbinfo->dobj.dumpId);
6293                                 }
6294                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6295                                 {
6296                                         /* column will be suppressed, print default separately */
6297                                         attrdefs[j].separate = true;
6298                                         /* needed in case pre-7.3 DB: */
6299                                         addObjectDependency(&attrdefs[j].dobj,
6300                                                                                 tbinfo->dobj.dumpId);
6301                                 }
6302                                 else
6303                                 {
6304                                         attrdefs[j].separate = false;
6305
6306                                         /*
6307                                          * Mark the default as needing to appear before the table,
6308                                          * so that any dependencies it has must be emitted before
6309                                          * the CREATE TABLE.  If this is not possible, we'll
6310                                          * change to "separate" mode while sorting dependencies.
6311                                          */
6312                                         addObjectDependency(&tbinfo->dobj,
6313                                                                                 attrdefs[j].dobj.dumpId);
6314                                 }
6315
6316                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6317                         }
6318                         PQclear(res);
6319                 }
6320
6321                 /*
6322                  * Get info about table CHECK constraints
6323                  */
6324                 if (tbinfo->ncheck > 0)
6325                 {
6326                         ConstraintInfo *constrs;
6327                         int                     numConstrs;
6328
6329                         if (g_verbose)
6330                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6331                                                   tbinfo->dobj.name);
6332
6333                         resetPQExpBuffer(q);
6334                         if (fout->remoteVersion >= 90200)
6335                         {
6336                                 /*
6337                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
6338                                  * but it wasn't ever false for check constraints until 9.2).
6339                                  */
6340                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6341                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6342                                                                   "conislocal, convalidated "
6343                                                                   "FROM pg_catalog.pg_constraint "
6344                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6345                                                                   "   AND contype = 'c' "
6346                                                                   "ORDER BY conname",
6347                                                                   tbinfo->dobj.catId.oid);
6348                         }
6349                         else if (fout->remoteVersion >= 80400)
6350                         {
6351                                 /* conislocal is new in 8.4 */
6352                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6353                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6354                                                                   "conislocal, true AS convalidated "
6355                                                                   "FROM pg_catalog.pg_constraint "
6356                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6357                                                                   "   AND contype = 'c' "
6358                                                                   "ORDER BY conname",
6359                                                                   tbinfo->dobj.catId.oid);
6360                         }
6361                         else if (fout->remoteVersion >= 70400)
6362                         {
6363                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6364                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6365                                                                   "true AS conislocal, true AS convalidated "
6366                                                                   "FROM pg_catalog.pg_constraint "
6367                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6368                                                                   "   AND contype = 'c' "
6369                                                                   "ORDER BY conname",
6370                                                                   tbinfo->dobj.catId.oid);
6371                         }
6372                         else if (fout->remoteVersion >= 70300)
6373                         {
6374                                 /* no pg_get_constraintdef, must use consrc */
6375                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6376                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6377                                                                   "true AS conislocal, true AS convalidated "
6378                                                                   "FROM pg_catalog.pg_constraint "
6379                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6380                                                                   "   AND contype = 'c' "
6381                                                                   "ORDER BY conname",
6382                                                                   tbinfo->dobj.catId.oid);
6383                         }
6384                         else if (fout->remoteVersion >= 70200)
6385                         {
6386                                 /* 7.2 did not have OIDs in pg_relcheck */
6387                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6388                                                                   "rcname AS conname, "
6389                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6390                                                                   "true AS conislocal, true AS convalidated "
6391                                                                   "FROM pg_relcheck "
6392                                                                   "WHERE rcrelid = '%u'::oid "
6393                                                                   "ORDER BY rcname",
6394                                                                   tbinfo->dobj.catId.oid);
6395                         }
6396                         else if (fout->remoteVersion >= 70100)
6397                         {
6398                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6399                                                                   "rcname AS conname, "
6400                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6401                                                                   "true AS conislocal, true AS convalidated "
6402                                                                   "FROM pg_relcheck "
6403                                                                   "WHERE rcrelid = '%u'::oid "
6404                                                                   "ORDER BY rcname",
6405                                                                   tbinfo->dobj.catId.oid);
6406                         }
6407                         else
6408                         {
6409                                 /* no tableoid in 7.0 */
6410                                 appendPQExpBuffer(q, "SELECT "
6411                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6412                                                                   "oid, rcname AS conname, "
6413                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6414                                                                   "true AS conislocal, true AS convalidated "
6415                                                                   "FROM pg_relcheck "
6416                                                                   "WHERE rcrelid = '%u'::oid "
6417                                                                   "ORDER BY rcname",
6418                                                                   tbinfo->dobj.catId.oid);
6419                         }
6420                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6421
6422                         numConstrs = PQntuples(res);
6423                         if (numConstrs != tbinfo->ncheck)
6424                         {
6425                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6426                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6427                                                                                  tbinfo->ncheck),
6428                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6429                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6430                                 exit_nicely(1);
6431                         }
6432
6433                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6434                         tbinfo->checkexprs = constrs;
6435
6436                         for (j = 0; j < numConstrs; j++)
6437                         {
6438                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6439
6440                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6441                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6442                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6443                                 AssignDumpId(&constrs[j].dobj);
6444                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6445                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6446                                 constrs[j].contable = tbinfo;
6447                                 constrs[j].condomain = NULL;
6448                                 constrs[j].contype = 'c';
6449                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6450                                 constrs[j].confrelid = InvalidOid;
6451                                 constrs[j].conindex = 0;
6452                                 constrs[j].condeferrable = false;
6453                                 constrs[j].condeferred = false;
6454                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6455
6456                                 /*
6457                                  * An unvalidated constraint needs to be dumped separately, so
6458                                  * that potentially-violating existing data is loaded before
6459                                  * the constraint.
6460                                  */
6461                                 constrs[j].separate = !validated;
6462
6463                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6464
6465                                 /*
6466                                  * Mark the constraint as needing to appear before the table
6467                                  * --- this is so that any other dependencies of the
6468                                  * constraint will be emitted before we try to create the
6469                                  * table.  If the constraint is to be dumped separately, it
6470                                  * will be dumped after data is loaded anyway, so don't do it.
6471                                  * (There's an automatic dependency in the opposite direction
6472                                  * anyway, so don't need to add one manually here.)
6473                                  */
6474                                 if (!constrs[j].separate)
6475                                         addObjectDependency(&tbinfo->dobj,
6476                                                                                 constrs[j].dobj.dumpId);
6477
6478                                 /*
6479                                  * If the constraint is inherited, this will be detected later
6480                                  * (in pre-8.4 databases).      We also detect later if the
6481                                  * constraint must be split out from the table definition.
6482                                  */
6483                         }
6484                         PQclear(res);
6485                 }
6486         }
6487
6488         destroyPQExpBuffer(q);
6489 }
6490
6491 /*
6492  * Test whether a column should be printed as part of table's CREATE TABLE.
6493  * Column number is zero-based.
6494  *
6495  * Normally this is always true, but it's false for dropped columns, as well
6496  * as those that were inherited without any local definition.  (If we print
6497  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6498  * However, in binary_upgrade mode, we must print all such columns anyway and
6499  * fix the attislocal/attisdropped state later, so as to keep control of the
6500  * physical column order.
6501  *
6502  * This function exists because there are scattered nonobvious places that
6503  * must be kept in sync with this decision.
6504  */
6505 bool
6506 shouldPrintColumn(TableInfo *tbinfo, int colno)
6507 {
6508         if (binary_upgrade)
6509                 return true;
6510         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6511 }
6512
6513
6514 /*
6515  * getTSParsers:
6516  *        read all text search parsers in the system catalogs and return them
6517  *        in the TSParserInfo* structure
6518  *
6519  *      numTSParsers is set to the number of parsers read in
6520  */
6521 TSParserInfo *
6522 getTSParsers(Archive *fout, int *numTSParsers)
6523 {
6524         PGresult   *res;
6525         int                     ntups;
6526         int                     i;
6527         PQExpBuffer query;
6528         TSParserInfo *prsinfo;
6529         int                     i_tableoid;
6530         int                     i_oid;
6531         int                     i_prsname;
6532         int                     i_prsnamespace;
6533         int                     i_prsstart;
6534         int                     i_prstoken;
6535         int                     i_prsend;
6536         int                     i_prsheadline;
6537         int                     i_prslextype;
6538
6539         /* Before 8.3, there is no built-in text search support */
6540         if (fout->remoteVersion < 80300)
6541         {
6542                 *numTSParsers = 0;
6543                 return NULL;
6544         }
6545
6546         query = createPQExpBuffer();
6547
6548         /*
6549          * find all text search objects, including builtin ones; we filter out
6550          * system-defined objects at dump-out time.
6551          */
6552
6553         /* Make sure we are in proper schema */
6554         selectSourceSchema(fout, "pg_catalog");
6555
6556         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6557                                           "prsstart::oid, prstoken::oid, "
6558                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6559                                           "FROM pg_ts_parser");
6560
6561         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6562
6563         ntups = PQntuples(res);
6564         *numTSParsers = ntups;
6565
6566         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6567
6568         i_tableoid = PQfnumber(res, "tableoid");
6569         i_oid = PQfnumber(res, "oid");
6570         i_prsname = PQfnumber(res, "prsname");
6571         i_prsnamespace = PQfnumber(res, "prsnamespace");
6572         i_prsstart = PQfnumber(res, "prsstart");
6573         i_prstoken = PQfnumber(res, "prstoken");
6574         i_prsend = PQfnumber(res, "prsend");
6575         i_prsheadline = PQfnumber(res, "prsheadline");
6576         i_prslextype = PQfnumber(res, "prslextype");
6577
6578         for (i = 0; i < ntups; i++)
6579         {
6580                 prsinfo[i].dobj.objType = DO_TSPARSER;
6581                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6582                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6583                 AssignDumpId(&prsinfo[i].dobj);
6584                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6585                 prsinfo[i].dobj.namespace =
6586                         findNamespace(fout,
6587                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6588                                                   prsinfo[i].dobj.catId.oid);
6589                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6590                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6591                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6592                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6593                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6594
6595                 /* Decide whether we want to dump it */
6596                 selectDumpableObject(&(prsinfo[i].dobj));
6597         }
6598
6599         PQclear(res);
6600
6601         destroyPQExpBuffer(query);
6602
6603         return prsinfo;
6604 }
6605
6606 /*
6607  * getTSDictionaries:
6608  *        read all text search dictionaries in the system catalogs and return them
6609  *        in the TSDictInfo* structure
6610  *
6611  *      numTSDicts is set to the number of dictionaries read in
6612  */
6613 TSDictInfo *
6614 getTSDictionaries(Archive *fout, int *numTSDicts)
6615 {
6616         PGresult   *res;
6617         int                     ntups;
6618         int                     i;
6619         PQExpBuffer query;
6620         TSDictInfo *dictinfo;
6621         int                     i_tableoid;
6622         int                     i_oid;
6623         int                     i_dictname;
6624         int                     i_dictnamespace;
6625         int                     i_rolname;
6626         int                     i_dicttemplate;
6627         int                     i_dictinitoption;
6628
6629         /* Before 8.3, there is no built-in text search support */
6630         if (fout->remoteVersion < 80300)
6631         {
6632                 *numTSDicts = 0;
6633                 return NULL;
6634         }
6635
6636         query = createPQExpBuffer();
6637
6638         /* Make sure we are in proper schema */
6639         selectSourceSchema(fout, "pg_catalog");
6640
6641         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6642                                           "dictnamespace, (%s dictowner) AS rolname, "
6643                                           "dicttemplate, dictinitoption "
6644                                           "FROM pg_ts_dict",
6645                                           username_subquery);
6646
6647         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6648
6649         ntups = PQntuples(res);
6650         *numTSDicts = ntups;
6651
6652         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6653
6654         i_tableoid = PQfnumber(res, "tableoid");
6655         i_oid = PQfnumber(res, "oid");
6656         i_dictname = PQfnumber(res, "dictname");
6657         i_dictnamespace = PQfnumber(res, "dictnamespace");
6658         i_rolname = PQfnumber(res, "rolname");
6659         i_dictinitoption = PQfnumber(res, "dictinitoption");
6660         i_dicttemplate = PQfnumber(res, "dicttemplate");
6661
6662         for (i = 0; i < ntups; i++)
6663         {
6664                 dictinfo[i].dobj.objType = DO_TSDICT;
6665                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6666                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6667                 AssignDumpId(&dictinfo[i].dobj);
6668                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6669                 dictinfo[i].dobj.namespace =
6670                         findNamespace(fout,
6671                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6672                                                   dictinfo[i].dobj.catId.oid);
6673                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6674                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6675                 if (PQgetisnull(res, i, i_dictinitoption))
6676                         dictinfo[i].dictinitoption = NULL;
6677                 else
6678                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6679
6680                 /* Decide whether we want to dump it */
6681                 selectDumpableObject(&(dictinfo[i].dobj));
6682         }
6683
6684         PQclear(res);
6685
6686         destroyPQExpBuffer(query);
6687
6688         return dictinfo;
6689 }
6690
6691 /*
6692  * getTSTemplates:
6693  *        read all text search templates in the system catalogs and return them
6694  *        in the TSTemplateInfo* structure
6695  *
6696  *      numTSTemplates is set to the number of templates read in
6697  */
6698 TSTemplateInfo *
6699 getTSTemplates(Archive *fout, int *numTSTemplates)
6700 {
6701         PGresult   *res;
6702         int                     ntups;
6703         int                     i;
6704         PQExpBuffer query;
6705         TSTemplateInfo *tmplinfo;
6706         int                     i_tableoid;
6707         int                     i_oid;
6708         int                     i_tmplname;
6709         int                     i_tmplnamespace;
6710         int                     i_tmplinit;
6711         int                     i_tmpllexize;
6712
6713         /* Before 8.3, there is no built-in text search support */
6714         if (fout->remoteVersion < 80300)
6715         {
6716                 *numTSTemplates = 0;
6717                 return NULL;
6718         }
6719
6720         query = createPQExpBuffer();
6721
6722         /* Make sure we are in proper schema */
6723         selectSourceSchema(fout, "pg_catalog");
6724
6725         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6726                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6727                                           "FROM pg_ts_template");
6728
6729         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6730
6731         ntups = PQntuples(res);
6732         *numTSTemplates = ntups;
6733
6734         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6735
6736         i_tableoid = PQfnumber(res, "tableoid");
6737         i_oid = PQfnumber(res, "oid");
6738         i_tmplname = PQfnumber(res, "tmplname");
6739         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6740         i_tmplinit = PQfnumber(res, "tmplinit");
6741         i_tmpllexize = PQfnumber(res, "tmpllexize");
6742
6743         for (i = 0; i < ntups; i++)
6744         {
6745                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6746                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6747                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6748                 AssignDumpId(&tmplinfo[i].dobj);
6749                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6750                 tmplinfo[i].dobj.namespace =
6751                         findNamespace(fout,
6752                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6753                                                   tmplinfo[i].dobj.catId.oid);
6754                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6755                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6756
6757                 /* Decide whether we want to dump it */
6758                 selectDumpableObject(&(tmplinfo[i].dobj));
6759         }
6760
6761         PQclear(res);
6762
6763         destroyPQExpBuffer(query);
6764
6765         return tmplinfo;
6766 }
6767
6768 /*
6769  * getTSConfigurations:
6770  *        read all text search configurations in the system catalogs and return
6771  *        them in the TSConfigInfo* structure
6772  *
6773  *      numTSConfigs is set to the number of configurations read in
6774  */
6775 TSConfigInfo *
6776 getTSConfigurations(Archive *fout, int *numTSConfigs)
6777 {
6778         PGresult   *res;
6779         int                     ntups;
6780         int                     i;
6781         PQExpBuffer query;
6782         TSConfigInfo *cfginfo;
6783         int                     i_tableoid;
6784         int                     i_oid;
6785         int                     i_cfgname;
6786         int                     i_cfgnamespace;
6787         int                     i_rolname;
6788         int                     i_cfgparser;
6789
6790         /* Before 8.3, there is no built-in text search support */
6791         if (fout->remoteVersion < 80300)
6792         {
6793                 *numTSConfigs = 0;
6794                 return NULL;
6795         }
6796
6797         query = createPQExpBuffer();
6798
6799         /* Make sure we are in proper schema */
6800         selectSourceSchema(fout, "pg_catalog");
6801
6802         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6803                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6804                                           "FROM pg_ts_config",
6805                                           username_subquery);
6806
6807         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6808
6809         ntups = PQntuples(res);
6810         *numTSConfigs = ntups;
6811
6812         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6813
6814         i_tableoid = PQfnumber(res, "tableoid");
6815         i_oid = PQfnumber(res, "oid");
6816         i_cfgname = PQfnumber(res, "cfgname");
6817         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6818         i_rolname = PQfnumber(res, "rolname");
6819         i_cfgparser = PQfnumber(res, "cfgparser");
6820
6821         for (i = 0; i < ntups; i++)
6822         {
6823                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6824                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6825                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6826                 AssignDumpId(&cfginfo[i].dobj);
6827                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6828                 cfginfo[i].dobj.namespace =
6829                         findNamespace(fout,
6830                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6831                                                   cfginfo[i].dobj.catId.oid);
6832                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6833                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6834
6835                 /* Decide whether we want to dump it */
6836                 selectDumpableObject(&(cfginfo[i].dobj));
6837         }
6838
6839         PQclear(res);
6840
6841         destroyPQExpBuffer(query);
6842
6843         return cfginfo;
6844 }
6845
6846 /*
6847  * getForeignDataWrappers:
6848  *        read all foreign-data wrappers in the system catalogs and return
6849  *        them in the FdwInfo* structure
6850  *
6851  *      numForeignDataWrappers is set to the number of fdws read in
6852  */
6853 FdwInfo *
6854 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6855 {
6856         PGresult   *res;
6857         int                     ntups;
6858         int                     i;
6859         PQExpBuffer query = createPQExpBuffer();
6860         FdwInfo    *fdwinfo;
6861         int                     i_tableoid;
6862         int                     i_oid;
6863         int                     i_fdwname;
6864         int                     i_rolname;
6865         int                     i_fdwhandler;
6866         int                     i_fdwvalidator;
6867         int                     i_fdwacl;
6868         int                     i_fdwoptions;
6869
6870         /* Before 8.4, there are no foreign-data wrappers */
6871         if (fout->remoteVersion < 80400)
6872         {
6873                 *numForeignDataWrappers = 0;
6874                 return NULL;
6875         }
6876
6877         /* Make sure we are in proper schema */
6878         selectSourceSchema(fout, "pg_catalog");
6879
6880         if (fout->remoteVersion >= 90100)
6881         {
6882                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6883                                                   "(%s fdwowner) AS rolname, "
6884                                                   "fdwhandler::pg_catalog.regproc, "
6885                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6886                                                   "array_to_string(ARRAY("
6887                                                   "SELECT quote_ident(option_name) || ' ' || "
6888                                                   "quote_literal(option_value) "
6889                                                   "FROM pg_options_to_table(fdwoptions) "
6890                                                   "ORDER BY option_name"
6891                                                   "), E',\n    ') AS fdwoptions "
6892                                                   "FROM pg_foreign_data_wrapper",
6893                                                   username_subquery);
6894         }
6895         else
6896         {
6897                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6898                                                   "(%s fdwowner) AS rolname, "
6899                                                   "'-' AS fdwhandler, "
6900                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6901                                                   "array_to_string(ARRAY("
6902                                                   "SELECT quote_ident(option_name) || ' ' || "
6903                                                   "quote_literal(option_value) "
6904                                                   "FROM pg_options_to_table(fdwoptions) "
6905                                                   "ORDER BY option_name"
6906                                                   "), E',\n    ') AS fdwoptions "
6907                                                   "FROM pg_foreign_data_wrapper",
6908                                                   username_subquery);
6909         }
6910
6911         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6912
6913         ntups = PQntuples(res);
6914         *numForeignDataWrappers = ntups;
6915
6916         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6917
6918         i_tableoid = PQfnumber(res, "tableoid");
6919         i_oid = PQfnumber(res, "oid");
6920         i_fdwname = PQfnumber(res, "fdwname");
6921         i_rolname = PQfnumber(res, "rolname");
6922         i_fdwhandler = PQfnumber(res, "fdwhandler");
6923         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6924         i_fdwacl = PQfnumber(res, "fdwacl");
6925         i_fdwoptions = PQfnumber(res, "fdwoptions");
6926
6927         for (i = 0; i < ntups; i++)
6928         {
6929                 fdwinfo[i].dobj.objType = DO_FDW;
6930                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6931                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6932                 AssignDumpId(&fdwinfo[i].dobj);
6933                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6934                 fdwinfo[i].dobj.namespace = NULL;
6935                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6936                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6937                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6938                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6939                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6940
6941                 /* Decide whether we want to dump it */
6942                 selectDumpableObject(&(fdwinfo[i].dobj));
6943         }
6944
6945         PQclear(res);
6946
6947         destroyPQExpBuffer(query);
6948
6949         return fdwinfo;
6950 }
6951
6952 /*
6953  * getForeignServers:
6954  *        read all foreign servers in the system catalogs and return
6955  *        them in the ForeignServerInfo * structure
6956  *
6957  *      numForeignServers is set to the number of servers read in
6958  */
6959 ForeignServerInfo *
6960 getForeignServers(Archive *fout, int *numForeignServers)
6961 {
6962         PGresult   *res;
6963         int                     ntups;
6964         int                     i;
6965         PQExpBuffer query = createPQExpBuffer();
6966         ForeignServerInfo *srvinfo;
6967         int                     i_tableoid;
6968         int                     i_oid;
6969         int                     i_srvname;
6970         int                     i_rolname;
6971         int                     i_srvfdw;
6972         int                     i_srvtype;
6973         int                     i_srvversion;
6974         int                     i_srvacl;
6975         int                     i_srvoptions;
6976
6977         /* Before 8.4, there are no foreign servers */
6978         if (fout->remoteVersion < 80400)
6979         {
6980                 *numForeignServers = 0;
6981                 return NULL;
6982         }
6983
6984         /* Make sure we are in proper schema */
6985         selectSourceSchema(fout, "pg_catalog");
6986
6987         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6988                                           "(%s srvowner) AS rolname, "
6989                                           "srvfdw, srvtype, srvversion, srvacl,"
6990                                           "array_to_string(ARRAY("
6991                                           "SELECT quote_ident(option_name) || ' ' || "
6992                                           "quote_literal(option_value) "
6993                                           "FROM pg_options_to_table(srvoptions) "
6994                                           "ORDER BY option_name"
6995                                           "), E',\n    ') AS srvoptions "
6996                                           "FROM pg_foreign_server",
6997                                           username_subquery);
6998
6999         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7000
7001         ntups = PQntuples(res);
7002         *numForeignServers = ntups;
7003
7004         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
7005
7006         i_tableoid = PQfnumber(res, "tableoid");
7007         i_oid = PQfnumber(res, "oid");
7008         i_srvname = PQfnumber(res, "srvname");
7009         i_rolname = PQfnumber(res, "rolname");
7010         i_srvfdw = PQfnumber(res, "srvfdw");
7011         i_srvtype = PQfnumber(res, "srvtype");
7012         i_srvversion = PQfnumber(res, "srvversion");
7013         i_srvacl = PQfnumber(res, "srvacl");
7014         i_srvoptions = PQfnumber(res, "srvoptions");
7015
7016         for (i = 0; i < ntups; i++)
7017         {
7018                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
7019                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7020                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7021                 AssignDumpId(&srvinfo[i].dobj);
7022                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
7023                 srvinfo[i].dobj.namespace = NULL;
7024                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7025                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
7026                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
7027                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
7028                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
7029                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
7030
7031                 /* Decide whether we want to dump it */
7032                 selectDumpableObject(&(srvinfo[i].dobj));
7033         }
7034
7035         PQclear(res);
7036
7037         destroyPQExpBuffer(query);
7038
7039         return srvinfo;
7040 }
7041
7042 /*
7043  * getDefaultACLs:
7044  *        read all default ACL information in the system catalogs and return
7045  *        them in the DefaultACLInfo structure
7046  *
7047  *      numDefaultACLs is set to the number of ACLs read in
7048  */
7049 DefaultACLInfo *
7050 getDefaultACLs(Archive *fout, int *numDefaultACLs)
7051 {
7052         DefaultACLInfo *daclinfo;
7053         PQExpBuffer query;
7054         PGresult   *res;
7055         int                     i_oid;
7056         int                     i_tableoid;
7057         int                     i_defaclrole;
7058         int                     i_defaclnamespace;
7059         int                     i_defaclobjtype;
7060         int                     i_defaclacl;
7061         int                     i,
7062                                 ntups;
7063
7064         if (fout->remoteVersion < 90000)
7065         {
7066                 *numDefaultACLs = 0;
7067                 return NULL;
7068         }
7069
7070         query = createPQExpBuffer();
7071
7072         /* Make sure we are in proper schema */
7073         selectSourceSchema(fout, "pg_catalog");
7074
7075         appendPQExpBuffer(query, "SELECT oid, tableoid, "
7076                                           "(%s defaclrole) AS defaclrole, "
7077                                           "defaclnamespace, "
7078                                           "defaclobjtype, "
7079                                           "defaclacl "
7080                                           "FROM pg_default_acl",
7081                                           username_subquery);
7082
7083         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7084
7085         ntups = PQntuples(res);
7086         *numDefaultACLs = ntups;
7087
7088         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
7089
7090         i_oid = PQfnumber(res, "oid");
7091         i_tableoid = PQfnumber(res, "tableoid");
7092         i_defaclrole = PQfnumber(res, "defaclrole");
7093         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
7094         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
7095         i_defaclacl = PQfnumber(res, "defaclacl");
7096
7097         for (i = 0; i < ntups; i++)
7098         {
7099                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
7100
7101                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
7102                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7103                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7104                 AssignDumpId(&daclinfo[i].dobj);
7105                 /* cheesy ... is it worth coming up with a better object name? */
7106                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
7107
7108                 if (nspid != InvalidOid)
7109                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
7110                                                                                                  daclinfo[i].dobj.catId.oid);
7111                 else
7112                         daclinfo[i].dobj.namespace = NULL;
7113
7114                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
7115                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
7116                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
7117
7118                 /* Decide whether we want to dump it */
7119                 selectDumpableDefaultACL(&(daclinfo[i]));
7120         }
7121
7122         PQclear(res);
7123
7124         destroyPQExpBuffer(query);
7125
7126         return daclinfo;
7127 }
7128
7129 /*
7130  * dumpComment --
7131  *
7132  * This routine is used to dump any comments associated with the
7133  * object handed to this routine. The routine takes a constant character
7134  * string for the target part of the comment-creation command, plus
7135  * the namespace and owner of the object (for labeling the ArchiveEntry),
7136  * plus catalog ID and subid which are the lookup key for pg_description,
7137  * plus the dump ID for the object (for setting a dependency).
7138  * If a matching pg_description entry is found, it is dumped.
7139  *
7140  * Note: although this routine takes a dumpId for dependency purposes,
7141  * that purpose is just to mark the dependency in the emitted dump file
7142  * for possible future use by pg_restore.  We do NOT use it for determining
7143  * ordering of the comment in the dump file, because this routine is called
7144  * after dependency sorting occurs.  This routine should be called just after
7145  * calling ArchiveEntry() for the specified object.
7146  */
7147 static void
7148 dumpComment(Archive *fout, const char *target,
7149                         const char *namespace, const char *owner,
7150                         CatalogId catalogId, int subid, DumpId dumpId)
7151 {
7152         CommentItem *comments;
7153         int                     ncomments;
7154
7155         /* Comments are schema not data ... except blob comments are data */
7156         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
7157         {
7158                 if (dataOnly)
7159                         return;
7160         }
7161         else
7162         {
7163                 if (schemaOnly)
7164                         return;
7165         }
7166
7167         /* Search for comments associated with catalogId, using table */
7168         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
7169                                                          &comments);
7170
7171         /* Is there one matching the subid? */
7172         while (ncomments > 0)
7173         {
7174                 if (comments->objsubid == subid)
7175                         break;
7176                 comments++;
7177                 ncomments--;
7178         }
7179
7180         /* If a comment exists, build COMMENT ON statement */
7181         if (ncomments > 0)
7182         {
7183                 PQExpBuffer query = createPQExpBuffer();
7184
7185                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7186                 appendStringLiteralAH(query, comments->descr, fout);
7187                 appendPQExpBuffer(query, ";\n");
7188
7189                 /*
7190                  * We mark comments as SECTION_NONE because they really belong in the
7191                  * same section as their parent, whether that is pre-data or
7192                  * post-data.
7193                  */
7194                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7195                                          target, namespace, NULL, owner,
7196                                          false, "COMMENT", SECTION_NONE,
7197                                          query->data, "", NULL,
7198                                          &(dumpId), 1,
7199                                          NULL, NULL);
7200
7201                 destroyPQExpBuffer(query);
7202         }
7203 }
7204
7205 /*
7206  * dumpTableComment --
7207  *
7208  * As above, but dump comments for both the specified table (or view)
7209  * and its columns.
7210  */
7211 static void
7212 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7213                                  const char *reltypename)
7214 {
7215         CommentItem *comments;
7216         int                     ncomments;
7217         PQExpBuffer query;
7218         PQExpBuffer target;
7219
7220         /* Comments are SCHEMA not data */
7221         if (dataOnly)
7222                 return;
7223
7224         /* Search for comments associated with relation, using table */
7225         ncomments = findComments(fout,
7226                                                          tbinfo->dobj.catId.tableoid,
7227                                                          tbinfo->dobj.catId.oid,
7228                                                          &comments);
7229
7230         /* If comments exist, build COMMENT ON statements */
7231         if (ncomments <= 0)
7232                 return;
7233
7234         query = createPQExpBuffer();
7235         target = createPQExpBuffer();
7236
7237         while (ncomments > 0)
7238         {
7239                 const char *descr = comments->descr;
7240                 int                     objsubid = comments->objsubid;
7241
7242                 if (objsubid == 0)
7243                 {
7244                         resetPQExpBuffer(target);
7245                         appendPQExpBuffer(target, "%s %s", reltypename,
7246                                                           fmtId(tbinfo->dobj.name));
7247
7248                         resetPQExpBuffer(query);
7249                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7250                         appendStringLiteralAH(query, descr, fout);
7251                         appendPQExpBuffer(query, ";\n");
7252
7253                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7254                                                  target->data,
7255                                                  tbinfo->dobj.namespace->dobj.name,
7256                                                  NULL, tbinfo->rolname,
7257                                                  false, "COMMENT", SECTION_NONE,
7258                                                  query->data, "", NULL,
7259                                                  &(tbinfo->dobj.dumpId), 1,
7260                                                  NULL, NULL);
7261                 }
7262                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7263                 {
7264                         resetPQExpBuffer(target);
7265                         appendPQExpBuffer(target, "COLUMN %s.",
7266                                                           fmtId(tbinfo->dobj.name));
7267                         appendPQExpBuffer(target, "%s",
7268                                                           fmtId(tbinfo->attnames[objsubid - 1]));
7269
7270                         resetPQExpBuffer(query);
7271                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7272                         appendStringLiteralAH(query, descr, fout);
7273                         appendPQExpBuffer(query, ";\n");
7274
7275                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7276                                                  target->data,
7277                                                  tbinfo->dobj.namespace->dobj.name,
7278                                                  NULL, tbinfo->rolname,
7279                                                  false, "COMMENT", SECTION_NONE,
7280                                                  query->data, "", NULL,
7281                                                  &(tbinfo->dobj.dumpId), 1,
7282                                                  NULL, NULL);
7283                 }
7284
7285                 comments++;
7286                 ncomments--;
7287         }
7288
7289         destroyPQExpBuffer(query);
7290         destroyPQExpBuffer(target);
7291 }
7292
7293 /*
7294  * findComments --
7295  *
7296  * Find the comment(s), if any, associated with the given object.  All the
7297  * objsubid values associated with the given classoid/objoid are found with
7298  * one search.
7299  */
7300 static int
7301 findComments(Archive *fout, Oid classoid, Oid objoid,
7302                          CommentItem **items)
7303 {
7304         /* static storage for table of comments */
7305         static CommentItem *comments = NULL;
7306         static int      ncomments = -1;
7307
7308         CommentItem *middle = NULL;
7309         CommentItem *low;
7310         CommentItem *high;
7311         int                     nmatch;
7312
7313         /* Get comments if we didn't already */
7314         if (ncomments < 0)
7315                 ncomments = collectComments(fout, &comments);
7316
7317         /*
7318          * Pre-7.2, pg_description does not contain classoid, so collectComments
7319          * just stores a zero.  If there's a collision on object OID, well, you
7320          * get duplicate comments.
7321          */
7322         if (fout->remoteVersion < 70200)
7323                 classoid = 0;
7324
7325         /*
7326          * Do binary search to find some item matching the object.
7327          */
7328         low = &comments[0];
7329         high = &comments[ncomments - 1];
7330         while (low <= high)
7331         {
7332                 middle = low + (high - low) / 2;
7333
7334                 if (classoid < middle->classoid)
7335                         high = middle - 1;
7336                 else if (classoid > middle->classoid)
7337                         low = middle + 1;
7338                 else if (objoid < middle->objoid)
7339                         high = middle - 1;
7340                 else if (objoid > middle->objoid)
7341                         low = middle + 1;
7342                 else
7343                         break;                          /* found a match */
7344         }
7345
7346         if (low > high)                         /* no matches */
7347         {
7348                 *items = NULL;
7349                 return 0;
7350         }
7351
7352         /*
7353          * Now determine how many items match the object.  The search loop
7354          * invariant still holds: only items between low and high inclusive could
7355          * match.
7356          */
7357         nmatch = 1;
7358         while (middle > low)
7359         {
7360                 if (classoid != middle[-1].classoid ||
7361                         objoid != middle[-1].objoid)
7362                         break;
7363                 middle--;
7364                 nmatch++;
7365         }
7366
7367         *items = middle;
7368
7369         middle += nmatch;
7370         while (middle <= high)
7371         {
7372                 if (classoid != middle->classoid ||
7373                         objoid != middle->objoid)
7374                         break;
7375                 middle++;
7376                 nmatch++;
7377         }
7378
7379         return nmatch;
7380 }
7381
7382 /*
7383  * collectComments --
7384  *
7385  * Construct a table of all comments available for database objects.
7386  * We used to do per-object queries for the comments, but it's much faster
7387  * to pull them all over at once, and on most databases the memory cost
7388  * isn't high.
7389  *
7390  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7391  */
7392 static int
7393 collectComments(Archive *fout, CommentItem **items)
7394 {
7395         PGresult   *res;
7396         PQExpBuffer query;
7397         int                     i_description;
7398         int                     i_classoid;
7399         int                     i_objoid;
7400         int                     i_objsubid;
7401         int                     ntups;
7402         int                     i;
7403         CommentItem *comments;
7404
7405         /*
7406          * Note we do NOT change source schema here; preserve the caller's
7407          * setting, instead.
7408          */
7409
7410         query = createPQExpBuffer();
7411
7412         if (fout->remoteVersion >= 70300)
7413         {
7414                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7415                                                   "FROM pg_catalog.pg_description "
7416                                                   "ORDER BY classoid, objoid, objsubid");
7417         }
7418         else if (fout->remoteVersion >= 70200)
7419         {
7420                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7421                                                   "FROM pg_description "
7422                                                   "ORDER BY classoid, objoid, objsubid");
7423         }
7424         else
7425         {
7426                 /* Note: this will fail to find attribute comments in pre-7.2... */
7427                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7428                                                   "FROM pg_description "
7429                                                   "ORDER BY objoid");
7430         }
7431
7432         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7433
7434         /* Construct lookup table containing OIDs in numeric form */
7435
7436         i_description = PQfnumber(res, "description");
7437         i_classoid = PQfnumber(res, "classoid");
7438         i_objoid = PQfnumber(res, "objoid");
7439         i_objsubid = PQfnumber(res, "objsubid");
7440
7441         ntups = PQntuples(res);
7442
7443         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7444
7445         for (i = 0; i < ntups; i++)
7446         {
7447                 comments[i].descr = PQgetvalue(res, i, i_description);
7448                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7449                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7450                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7451         }
7452
7453         /* Do NOT free the PGresult since we are keeping pointers into it */
7454         destroyPQExpBuffer(query);
7455
7456         *items = comments;
7457         return ntups;
7458 }
7459
7460 /*
7461  * dumpDumpableObject
7462  *
7463  * This routine and its subsidiaries are responsible for creating
7464  * ArchiveEntries (TOC objects) for each object to be dumped.
7465  */
7466 static void
7467 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7468 {
7469         switch (dobj->objType)
7470         {
7471                 case DO_NAMESPACE:
7472                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7473                         break;
7474                 case DO_EXTENSION:
7475                         dumpExtension(fout, (ExtensionInfo *) dobj);
7476                         break;
7477                 case DO_TYPE:
7478                         dumpType(fout, (TypeInfo *) dobj);
7479                         break;
7480                 case DO_SHELL_TYPE:
7481                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7482                         break;
7483                 case DO_FUNC:
7484                         dumpFunc(fout, (FuncInfo *) dobj);
7485                         break;
7486                 case DO_AGG:
7487                         dumpAgg(fout, (AggInfo *) dobj);
7488                         break;
7489                 case DO_OPERATOR:
7490                         dumpOpr(fout, (OprInfo *) dobj);
7491                         break;
7492                 case DO_OPCLASS:
7493                         dumpOpclass(fout, (OpclassInfo *) dobj);
7494                         break;
7495                 case DO_OPFAMILY:
7496                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7497                         break;
7498                 case DO_COLLATION:
7499                         dumpCollation(fout, (CollInfo *) dobj);
7500                         break;
7501                 case DO_CONVERSION:
7502                         dumpConversion(fout, (ConvInfo *) dobj);
7503                         break;
7504                 case DO_TABLE:
7505                         dumpTable(fout, (TableInfo *) dobj);
7506                         break;
7507                 case DO_ATTRDEF:
7508                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7509                         break;
7510                 case DO_INDEX:
7511                         dumpIndex(fout, (IndxInfo *) dobj);
7512                         break;
7513                 case DO_REFRESH_MATVIEW:
7514                         refreshMatViewData(fout, (TableDataInfo *) dobj);
7515                         break;
7516                 case DO_RULE:
7517                         dumpRule(fout, (RuleInfo *) dobj);
7518                         break;
7519                 case DO_TRIGGER:
7520                         dumpTrigger(fout, (TriggerInfo *) dobj);
7521                         break;
7522                 case DO_EVENT_TRIGGER:
7523                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7524                         break;
7525                 case DO_CONSTRAINT:
7526                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7527                         break;
7528                 case DO_FK_CONSTRAINT:
7529                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7530                         break;
7531                 case DO_PROCLANG:
7532                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7533                         break;
7534                 case DO_CAST:
7535                         dumpCast(fout, (CastInfo *) dobj);
7536                         break;
7537                 case DO_TABLE_DATA:
7538                         if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7539                                 dumpSequenceData(fout, (TableDataInfo *) dobj);
7540                         else
7541                                 dumpTableData(fout, (TableDataInfo *) dobj);
7542                         break;
7543                 case DO_DUMMY_TYPE:
7544                         /* table rowtypes and array types are never dumped separately */
7545                         break;
7546                 case DO_TSPARSER:
7547                         dumpTSParser(fout, (TSParserInfo *) dobj);
7548                         break;
7549                 case DO_TSDICT:
7550                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7551                         break;
7552                 case DO_TSTEMPLATE:
7553                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7554                         break;
7555                 case DO_TSCONFIG:
7556                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7557                         break;
7558                 case DO_FDW:
7559                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7560                         break;
7561                 case DO_FOREIGN_SERVER:
7562                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7563                         break;
7564                 case DO_DEFAULT_ACL:
7565                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7566                         break;
7567                 case DO_BLOB:
7568                         dumpBlob(fout, (BlobInfo *) dobj);
7569                         break;
7570                 case DO_BLOB_DATA:
7571                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7572                                                  dobj->name, NULL, NULL, "",
7573                                                  false, "BLOBS", SECTION_DATA,
7574                                                  "", "", NULL,
7575                                                  NULL, 0,
7576                                                  dumpBlobs, NULL);
7577                         break;
7578                 case DO_PRE_DATA_BOUNDARY:
7579                 case DO_POST_DATA_BOUNDARY:
7580                         /* never dumped, nothing to do */
7581                         break;
7582         }
7583 }
7584
7585 /*
7586  * dumpNamespace
7587  *        writes out to fout the queries to recreate a user-defined namespace
7588  */
7589 static void
7590 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7591 {
7592         PQExpBuffer q;
7593         PQExpBuffer delq;
7594         PQExpBuffer labelq;
7595         char       *qnspname;
7596
7597         /* Skip if not to be dumped */
7598         if (!nspinfo->dobj.dump || dataOnly)
7599                 return;
7600
7601         /* don't dump dummy namespace from pre-7.3 source */
7602         if (strlen(nspinfo->dobj.name) == 0)
7603                 return;
7604
7605         q = createPQExpBuffer();
7606         delq = createPQExpBuffer();
7607         labelq = createPQExpBuffer();
7608
7609         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7610
7611         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7612
7613         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7614
7615         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7616
7617         if (binary_upgrade)
7618                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7619
7620         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7621                                  nspinfo->dobj.name,
7622                                  NULL, NULL,
7623                                  nspinfo->rolname,
7624                                  false, "SCHEMA", SECTION_PRE_DATA,
7625                                  q->data, delq->data, NULL,
7626                                  NULL, 0,
7627                                  NULL, NULL);
7628
7629         /* Dump Schema Comments and Security Labels */
7630         dumpComment(fout, labelq->data,
7631                                 NULL, nspinfo->rolname,
7632                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7633         dumpSecLabel(fout, labelq->data,
7634                                  NULL, nspinfo->rolname,
7635                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7636
7637         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7638                         qnspname, NULL, nspinfo->dobj.name, NULL,
7639                         nspinfo->rolname, nspinfo->nspacl);
7640
7641         free(qnspname);
7642
7643         destroyPQExpBuffer(q);
7644         destroyPQExpBuffer(delq);
7645         destroyPQExpBuffer(labelq);
7646 }
7647
7648 /*
7649  * dumpExtension
7650  *        writes out to fout the queries to recreate an extension
7651  */
7652 static void
7653 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7654 {
7655         PQExpBuffer q;
7656         PQExpBuffer delq;
7657         PQExpBuffer labelq;
7658         char       *qextname;
7659
7660         /* Skip if not to be dumped */
7661         if (!extinfo->dobj.dump || dataOnly)
7662                 return;
7663
7664         q = createPQExpBuffer();
7665         delq = createPQExpBuffer();
7666         labelq = createPQExpBuffer();
7667
7668         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7669
7670         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7671
7672         if (!binary_upgrade)
7673         {
7674                 /*
7675                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7676                  * problem if the extension already exists in the target database;
7677                  * this is essential for installed-by-default extensions such as
7678                  * plpgsql.
7679                  *
7680                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7681                  * built-in extensions based on their OIDs; see
7682                  * selectDumpableExtension.
7683                  */
7684                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7685                                                   qextname, fmtId(extinfo->namespace));
7686         }
7687         else
7688         {
7689                 int                     i;
7690                 int                     n;
7691
7692                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7693
7694                 /*
7695                  *      We unconditionally create the extension, so we must drop it if it
7696                  *      exists.  This could happen if the user deleted 'plpgsql' and then
7697                  *      readded it, causing its oid to be greater than FirstNormalObjectId.
7698                  *      The FirstNormalObjectId test was kept to avoid repeatedly dropping
7699                  *      and recreating extensions like 'plpgsql'.
7700                  */
7701                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7702
7703                 appendPQExpBuffer(q,
7704                                                   "SELECT binary_upgrade.create_empty_extension(");
7705                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7706                 appendPQExpBuffer(q, ", ");
7707                 appendStringLiteralAH(q, extinfo->namespace, fout);
7708                 appendPQExpBuffer(q, ", ");
7709                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7710                 appendStringLiteralAH(q, extinfo->extversion, fout);
7711                 appendPQExpBuffer(q, ", ");
7712
7713                 /*
7714                  * Note that we're pushing extconfig (an OID array) back into
7715                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7716                  * preserved in binary upgrade.
7717                  */
7718                 if (strlen(extinfo->extconfig) > 2)
7719                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7720                 else
7721                         appendPQExpBuffer(q, "NULL");
7722                 appendPQExpBuffer(q, ", ");
7723                 if (strlen(extinfo->extcondition) > 2)
7724                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7725                 else
7726                         appendPQExpBuffer(q, "NULL");
7727                 appendPQExpBuffer(q, ", ");
7728                 appendPQExpBuffer(q, "ARRAY[");
7729                 n = 0;
7730                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7731                 {
7732                         DumpableObject *extobj;
7733
7734                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7735                         if (extobj && extobj->objType == DO_EXTENSION)
7736                         {
7737                                 if (n++ > 0)
7738                                         appendPQExpBuffer(q, ",");
7739                                 appendStringLiteralAH(q, extobj->name, fout);
7740                         }
7741                 }
7742                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7743                 appendPQExpBuffer(q, ");\n");
7744         }
7745
7746         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7747
7748         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7749                                  extinfo->dobj.name,
7750                                  NULL, NULL,
7751                                  "",
7752                                  false, "EXTENSION", SECTION_PRE_DATA,
7753                                  q->data, delq->data, NULL,
7754                                  NULL, 0,
7755                                  NULL, NULL);
7756
7757         /* Dump Extension Comments and Security Labels */
7758         dumpComment(fout, labelq->data,
7759                                 NULL, "",
7760                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7761         dumpSecLabel(fout, labelq->data,
7762                                  NULL, "",
7763                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7764
7765         free(qextname);
7766
7767         destroyPQExpBuffer(q);
7768         destroyPQExpBuffer(delq);
7769         destroyPQExpBuffer(labelq);
7770 }
7771
7772 /*
7773  * dumpType
7774  *        writes out to fout the queries to recreate a user-defined type
7775  */
7776 static void
7777 dumpType(Archive *fout, TypeInfo *tyinfo)
7778 {
7779         /* Skip if not to be dumped */
7780         if (!tyinfo->dobj.dump || dataOnly)
7781                 return;
7782
7783         /* Dump out in proper style */
7784         if (tyinfo->typtype == TYPTYPE_BASE)
7785                 dumpBaseType(fout, tyinfo);
7786         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7787                 dumpDomain(fout, tyinfo);
7788         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7789                 dumpCompositeType(fout, tyinfo);
7790         else if (tyinfo->typtype == TYPTYPE_ENUM)
7791                 dumpEnumType(fout, tyinfo);
7792         else if (tyinfo->typtype == TYPTYPE_RANGE)
7793                 dumpRangeType(fout, tyinfo);
7794         else
7795                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7796                                   tyinfo->dobj.name);
7797 }
7798
7799 /*
7800  * dumpEnumType
7801  *        writes out to fout the queries to recreate a user-defined enum type
7802  */
7803 static void
7804 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7805 {
7806         PQExpBuffer q = createPQExpBuffer();
7807         PQExpBuffer delq = createPQExpBuffer();
7808         PQExpBuffer labelq = createPQExpBuffer();
7809         PQExpBuffer query = createPQExpBuffer();
7810         PGresult   *res;
7811         int                     num,
7812                                 i;
7813         Oid                     enum_oid;
7814         char       *qtypname;
7815         char       *label;
7816
7817         /* Set proper schema search path */
7818         selectSourceSchema(fout, "pg_catalog");
7819
7820         if (fout->remoteVersion >= 90100)
7821                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7822                                                   "FROM pg_catalog.pg_enum "
7823                                                   "WHERE enumtypid = '%u'"
7824                                                   "ORDER BY enumsortorder",
7825                                                   tyinfo->dobj.catId.oid);
7826         else
7827                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7828                                                   "FROM pg_catalog.pg_enum "
7829                                                   "WHERE enumtypid = '%u'"
7830                                                   "ORDER BY oid",
7831                                                   tyinfo->dobj.catId.oid);
7832
7833         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7834
7835         num = PQntuples(res);
7836
7837         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7838
7839         /*
7840          * DROP must be fully qualified in case same name appears in pg_catalog.
7841          * CASCADE shouldn't be required here as for normal types since the I/O
7842          * functions are generic and do not get dropped.
7843          */
7844         appendPQExpBuffer(delq, "DROP TYPE %s.",
7845                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7846         appendPQExpBuffer(delq, "%s;\n",
7847                                           qtypname);
7848
7849         if (binary_upgrade)
7850                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7851                                                                                                  tyinfo->dobj.catId.oid);
7852
7853         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7854                                           qtypname);
7855
7856         if (!binary_upgrade)
7857         {
7858                 /* Labels with server-assigned oids */
7859                 for (i = 0; i < num; i++)
7860                 {
7861                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7862                         if (i > 0)
7863                                 appendPQExpBuffer(q, ",");
7864                         appendPQExpBuffer(q, "\n    ");
7865                         appendStringLiteralAH(q, label, fout);
7866                 }
7867         }
7868
7869         appendPQExpBuffer(q, "\n);\n");
7870
7871         if (binary_upgrade)
7872         {
7873                 /* Labels with dump-assigned (preserved) oids */
7874                 for (i = 0; i < num; i++)
7875                 {
7876                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7877                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7878
7879                         if (i == 0)
7880                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7881                         appendPQExpBuffer(q,
7882                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7883                                                           enum_oid);
7884                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7885                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7886                         appendPQExpBuffer(q, "%s ADD VALUE ",
7887                                                           qtypname);
7888                         appendStringLiteralAH(q, label, fout);
7889                         appendPQExpBuffer(q, ";\n\n");
7890                 }
7891         }
7892
7893         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7894
7895         if (binary_upgrade)
7896                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7897
7898         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7899                                  tyinfo->dobj.name,
7900                                  tyinfo->dobj.namespace->dobj.name,
7901                                  NULL,
7902                                  tyinfo->rolname, false,
7903                                  "TYPE", SECTION_PRE_DATA,
7904                                  q->data, delq->data, NULL,
7905                                  NULL, 0,
7906                                  NULL, NULL);
7907
7908         /* Dump Type Comments and Security Labels */
7909         dumpComment(fout, labelq->data,
7910                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7911                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7912         dumpSecLabel(fout, labelq->data,
7913                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7914                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7915
7916         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7917                         qtypname, NULL, tyinfo->dobj.name,
7918                         tyinfo->dobj.namespace->dobj.name,
7919                         tyinfo->rolname, tyinfo->typacl);
7920
7921         PQclear(res);
7922         destroyPQExpBuffer(q);
7923         destroyPQExpBuffer(delq);
7924         destroyPQExpBuffer(labelq);
7925         destroyPQExpBuffer(query);
7926 }
7927
7928 /*
7929  * dumpRangeType
7930  *        writes out to fout the queries to recreate a user-defined range type
7931  */
7932 static void
7933 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7934 {
7935         PQExpBuffer q = createPQExpBuffer();
7936         PQExpBuffer delq = createPQExpBuffer();
7937         PQExpBuffer labelq = createPQExpBuffer();
7938         PQExpBuffer query = createPQExpBuffer();
7939         PGresult   *res;
7940         Oid                     collationOid;
7941         char       *qtypname;
7942         char       *procname;
7943
7944         /*
7945          * select appropriate schema to ensure names in CREATE are properly
7946          * qualified
7947          */
7948         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7949
7950         appendPQExpBuffer(query,
7951                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7952                                           "opc.opcname AS opcname, "
7953                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7954                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7955                                           "opc.opcdefault, "
7956                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7957                                           "     ELSE rngcollation END AS collation, "
7958                                           "rngcanonical, rngsubdiff "
7959                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7960                                           "     pg_catalog.pg_opclass opc "
7961                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7962                                           "rngtypid = '%u'",
7963                                           tyinfo->dobj.catId.oid);
7964
7965         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7966
7967         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7968
7969         /*
7970          * DROP must be fully qualified in case same name appears in pg_catalog.
7971          * CASCADE shouldn't be required here as for normal types since the I/O
7972          * functions are generic and do not get dropped.
7973          */
7974         appendPQExpBuffer(delq, "DROP TYPE %s.",
7975                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7976         appendPQExpBuffer(delq, "%s;\n",
7977                                           qtypname);
7978
7979         if (binary_upgrade)
7980                 binary_upgrade_set_type_oids_by_type_oid(fout,
7981                                                                                                  q, tyinfo->dobj.catId.oid);
7982
7983         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7984                                           qtypname);
7985
7986         appendPQExpBuffer(q, "\n    subtype = %s",
7987                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7988
7989         /* print subtype_opclass only if not default for subtype */
7990         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7991         {
7992                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7993                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7994
7995                 /* always schema-qualify, don't try to be smart */
7996                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7997                                                   fmtId(nspname));
7998                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7999         }
8000
8001         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
8002         if (OidIsValid(collationOid))
8003         {
8004                 CollInfo   *coll = findCollationByOid(collationOid);
8005
8006                 if (coll)
8007                 {
8008                         /* always schema-qualify, don't try to be smart */
8009                         appendPQExpBuffer(q, ",\n    collation = %s.",
8010                                                           fmtId(coll->dobj.namespace->dobj.name));
8011                         appendPQExpBuffer(q, "%s",
8012                                                           fmtId(coll->dobj.name));
8013                 }
8014         }
8015
8016         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
8017         if (strcmp(procname, "-") != 0)
8018                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
8019
8020         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
8021         if (strcmp(procname, "-") != 0)
8022                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
8023
8024         appendPQExpBuffer(q, "\n);\n");
8025
8026         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8027
8028         if (binary_upgrade)
8029                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8030
8031         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8032                                  tyinfo->dobj.name,
8033                                  tyinfo->dobj.namespace->dobj.name,
8034                                  NULL,
8035                                  tyinfo->rolname, false,
8036                                  "TYPE", SECTION_PRE_DATA,
8037                                  q->data, delq->data, NULL,
8038                                  NULL, 0,
8039                                  NULL, NULL);
8040
8041         /* Dump Type Comments and Security Labels */
8042         dumpComment(fout, labelq->data,
8043                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8044                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8045         dumpSecLabel(fout, labelq->data,
8046                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8047                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8048
8049         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8050                         qtypname, NULL, tyinfo->dobj.name,
8051                         tyinfo->dobj.namespace->dobj.name,
8052                         tyinfo->rolname, tyinfo->typacl);
8053
8054         PQclear(res);
8055         destroyPQExpBuffer(q);
8056         destroyPQExpBuffer(delq);
8057         destroyPQExpBuffer(labelq);
8058         destroyPQExpBuffer(query);
8059 }
8060
8061 /*
8062  * dumpBaseType
8063  *        writes out to fout the queries to recreate a user-defined base type
8064  */
8065 static void
8066 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
8067 {
8068         PQExpBuffer q = createPQExpBuffer();
8069         PQExpBuffer delq = createPQExpBuffer();
8070         PQExpBuffer labelq = createPQExpBuffer();
8071         PQExpBuffer query = createPQExpBuffer();
8072         PGresult   *res;
8073         char       *qtypname;
8074         char       *typlen;
8075         char       *typinput;
8076         char       *typoutput;
8077         char       *typreceive;
8078         char       *typsend;
8079         char       *typmodin;
8080         char       *typmodout;
8081         char       *typanalyze;
8082         Oid                     typreceiveoid;
8083         Oid                     typsendoid;
8084         Oid                     typmodinoid;
8085         Oid                     typmodoutoid;
8086         Oid                     typanalyzeoid;
8087         char       *typcategory;
8088         char       *typispreferred;
8089         char       *typdelim;
8090         char       *typbyval;
8091         char       *typalign;
8092         char       *typstorage;
8093         char       *typcollatable;
8094         char       *typdefault;
8095         bool            typdefault_is_literal = false;
8096
8097         /* Set proper schema search path so regproc references list correctly */
8098         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8099
8100         /* Fetch type-specific details */
8101         if (fout->remoteVersion >= 90100)
8102         {
8103                 appendPQExpBuffer(query, "SELECT typlen, "
8104                                                   "typinput, typoutput, typreceive, typsend, "
8105                                                   "typmodin, typmodout, typanalyze, "
8106                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8107                                                   "typsend::pg_catalog.oid AS typsendoid, "
8108                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8109                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8110                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8111                                                   "typcategory, typispreferred, "
8112                                                   "typdelim, typbyval, typalign, typstorage, "
8113                                                   "(typcollation <> 0) AS typcollatable, "
8114                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8115                                                   "FROM pg_catalog.pg_type "
8116                                                   "WHERE oid = '%u'::pg_catalog.oid",
8117                                                   tyinfo->dobj.catId.oid);
8118         }
8119         else if (fout->remoteVersion >= 80400)
8120         {
8121                 appendPQExpBuffer(query, "SELECT typlen, "
8122                                                   "typinput, typoutput, typreceive, typsend, "
8123                                                   "typmodin, typmodout, typanalyze, "
8124                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8125                                                   "typsend::pg_catalog.oid AS typsendoid, "
8126                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8127                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8128                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8129                                                   "typcategory, typispreferred, "
8130                                                   "typdelim, typbyval, typalign, typstorage, "
8131                                                   "false AS typcollatable, "
8132                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8133                                                   "FROM pg_catalog.pg_type "
8134                                                   "WHERE oid = '%u'::pg_catalog.oid",
8135                                                   tyinfo->dobj.catId.oid);
8136         }
8137         else if (fout->remoteVersion >= 80300)
8138         {
8139                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
8140                 appendPQExpBuffer(query, "SELECT typlen, "
8141                                                   "typinput, typoutput, typreceive, typsend, "
8142                                                   "typmodin, typmodout, typanalyze, "
8143                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8144                                                   "typsend::pg_catalog.oid AS typsendoid, "
8145                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8146                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8147                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8148                                                   "'U' AS typcategory, false AS typispreferred, "
8149                                                   "typdelim, typbyval, typalign, typstorage, "
8150                                                   "false AS typcollatable, "
8151                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8152                                                   "FROM pg_catalog.pg_type "
8153                                                   "WHERE oid = '%u'::pg_catalog.oid",
8154                                                   tyinfo->dobj.catId.oid);
8155         }
8156         else if (fout->remoteVersion >= 80000)
8157         {
8158                 appendPQExpBuffer(query, "SELECT typlen, "
8159                                                   "typinput, typoutput, typreceive, typsend, "
8160                                                   "'-' AS typmodin, '-' AS typmodout, "
8161                                                   "typanalyze, "
8162                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8163                                                   "typsend::pg_catalog.oid AS typsendoid, "
8164                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8165                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8166                                                   "'U' AS typcategory, false AS typispreferred, "
8167                                                   "typdelim, typbyval, typalign, typstorage, "
8168                                                   "false AS typcollatable, "
8169                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8170                                                   "FROM pg_catalog.pg_type "
8171                                                   "WHERE oid = '%u'::pg_catalog.oid",
8172                                                   tyinfo->dobj.catId.oid);
8173         }
8174         else if (fout->remoteVersion >= 70400)
8175         {
8176                 appendPQExpBuffer(query, "SELECT typlen, "
8177                                                   "typinput, typoutput, typreceive, typsend, "
8178                                                   "'-' AS typmodin, '-' AS typmodout, "
8179                                                   "'-' AS typanalyze, "
8180                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8181                                                   "typsend::pg_catalog.oid AS typsendoid, "
8182                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8183                                                   "0 AS typanalyzeoid, "
8184                                                   "'U' AS typcategory, false AS typispreferred, "
8185                                                   "typdelim, typbyval, typalign, typstorage, "
8186                                                   "false AS typcollatable, "
8187                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8188                                                   "FROM pg_catalog.pg_type "
8189                                                   "WHERE oid = '%u'::pg_catalog.oid",
8190                                                   tyinfo->dobj.catId.oid);
8191         }
8192         else if (fout->remoteVersion >= 70300)
8193         {
8194                 appendPQExpBuffer(query, "SELECT typlen, "
8195                                                   "typinput, typoutput, "
8196                                                   "'-' AS typreceive, '-' AS typsend, "
8197                                                   "'-' AS typmodin, '-' AS typmodout, "
8198                                                   "'-' AS typanalyze, "
8199                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8200                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8201                                                   "0 AS typanalyzeoid, "
8202                                                   "'U' AS typcategory, false AS typispreferred, "
8203                                                   "typdelim, typbyval, typalign, typstorage, "
8204                                                   "false AS typcollatable, "
8205                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8206                                                   "FROM pg_catalog.pg_type "
8207                                                   "WHERE oid = '%u'::pg_catalog.oid",
8208                                                   tyinfo->dobj.catId.oid);
8209         }
8210         else if (fout->remoteVersion >= 70200)
8211         {
8212                 /*
8213                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
8214                  * ignore them because they are not right.
8215                  */
8216                 appendPQExpBuffer(query, "SELECT typlen, "
8217                                                   "typinput, typoutput, "
8218                                                   "'-' AS typreceive, '-' AS typsend, "
8219                                                   "'-' AS typmodin, '-' AS typmodout, "
8220                                                   "'-' AS typanalyze, "
8221                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8222                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8223                                                   "0 AS typanalyzeoid, "
8224                                                   "'U' AS typcategory, false AS typispreferred, "
8225                                                   "typdelim, typbyval, typalign, typstorage, "
8226                                                   "false AS typcollatable, "
8227                                                   "NULL AS typdefaultbin, typdefault "
8228                                                   "FROM pg_type "
8229                                                   "WHERE oid = '%u'::oid",
8230                                                   tyinfo->dobj.catId.oid);
8231         }
8232         else if (fout->remoteVersion >= 70100)
8233         {
8234                 /*
8235                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
8236                  * representation.
8237                  */
8238                 appendPQExpBuffer(query, "SELECT typlen, "
8239                                                   "typinput, typoutput, "
8240                                                   "'-' AS typreceive, '-' AS typsend, "
8241                                                   "'-' AS typmodin, '-' AS typmodout, "
8242                                                   "'-' AS typanalyze, "
8243                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8244                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8245                                                   "0 AS typanalyzeoid, "
8246                                                   "'U' AS typcategory, false AS typispreferred, "
8247                                                   "typdelim, typbyval, typalign, typstorage, "
8248                                                   "false AS typcollatable, "
8249                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8250                                                   "FROM pg_type "
8251                                                   "WHERE oid = '%u'::oid",
8252                                                   tyinfo->dobj.catId.oid);
8253         }
8254         else
8255         {
8256                 appendPQExpBuffer(query, "SELECT typlen, "
8257                                                   "typinput, typoutput, "
8258                                                   "'-' AS typreceive, '-' AS typsend, "
8259                                                   "'-' AS typmodin, '-' AS typmodout, "
8260                                                   "'-' AS typanalyze, "
8261                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8262                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8263                                                   "0 AS typanalyzeoid, "
8264                                                   "'U' AS typcategory, false AS typispreferred, "
8265                                                   "typdelim, typbyval, typalign, "
8266                                                   "'p'::char AS typstorage, "
8267                                                   "false AS typcollatable, "
8268                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8269                                                   "FROM pg_type "
8270                                                   "WHERE oid = '%u'::oid",
8271                                                   tyinfo->dobj.catId.oid);
8272         }
8273
8274         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8275
8276         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8277         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8278         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8279         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8280         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8281         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8282         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8283         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8284         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8285         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8286         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8287         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8288         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8289         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8290         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8291         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8292         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8293         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8294         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8295         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8296         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8297                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8298         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8299         {
8300                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8301                 typdefault_is_literal = true;   /* it needs quotes */
8302         }
8303         else
8304                 typdefault = NULL;
8305
8306         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8307
8308         /*
8309          * DROP must be fully qualified in case same name appears in pg_catalog.
8310          * The reason we include CASCADE is that the circular dependency between
8311          * the type and its I/O functions makes it impossible to drop the type any
8312          * other way.
8313          */
8314         appendPQExpBuffer(delq, "DROP TYPE %s.",
8315                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8316         appendPQExpBuffer(delq, "%s CASCADE;\n",
8317                                           qtypname);
8318
8319         /* We might already have a shell type, but setting pg_type_oid is harmless */
8320         if (binary_upgrade)
8321                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8322                                                                                                  tyinfo->dobj.catId.oid);
8323
8324         appendPQExpBuffer(q,
8325                                           "CREATE TYPE %s (\n"
8326                                           "    INTERNALLENGTH = %s",
8327                                           qtypname,
8328                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8329
8330         if (fout->remoteVersion >= 70300)
8331         {
8332                 /* regproc result is correctly quoted as of 7.3 */
8333                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
8334                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
8335                 if (OidIsValid(typreceiveoid))
8336                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
8337                 if (OidIsValid(typsendoid))
8338                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
8339                 if (OidIsValid(typmodinoid))
8340                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
8341                 if (OidIsValid(typmodoutoid))
8342                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
8343                 if (OidIsValid(typanalyzeoid))
8344                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
8345         }
8346         else
8347         {
8348                 /* regproc delivers an unquoted name before 7.3 */
8349                 /* cannot combine these because fmtId uses static result area */
8350                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
8351                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
8352                 /* receive/send/typmodin/typmodout/analyze need not be printed */
8353         }
8354
8355         if (strcmp(typcollatable, "t") == 0)
8356                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
8357
8358         if (typdefault != NULL)
8359         {
8360                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
8361                 if (typdefault_is_literal)
8362                         appendStringLiteralAH(q, typdefault, fout);
8363                 else
8364                         appendPQExpBufferStr(q, typdefault);
8365         }
8366
8367         if (OidIsValid(tyinfo->typelem))
8368         {
8369                 char       *elemType;
8370
8371                 /* reselect schema in case changed by function dump */
8372                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8373                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8374                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8375                 free(elemType);
8376         }
8377
8378         if (strcmp(typcategory, "U") != 0)
8379         {
8380                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8381                 appendStringLiteralAH(q, typcategory, fout);
8382         }
8383
8384         if (strcmp(typispreferred, "t") == 0)
8385                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8386
8387         if (typdelim && strcmp(typdelim, ",") != 0)
8388         {
8389                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8390                 appendStringLiteralAH(q, typdelim, fout);
8391         }
8392
8393         if (strcmp(typalign, "c") == 0)
8394                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8395         else if (strcmp(typalign, "s") == 0)
8396                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8397         else if (strcmp(typalign, "i") == 0)
8398                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8399         else if (strcmp(typalign, "d") == 0)
8400                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8401
8402         if (strcmp(typstorage, "p") == 0)
8403                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8404         else if (strcmp(typstorage, "e") == 0)
8405                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8406         else if (strcmp(typstorage, "x") == 0)
8407                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8408         else if (strcmp(typstorage, "m") == 0)
8409                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8410
8411         if (strcmp(typbyval, "t") == 0)
8412                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8413
8414         appendPQExpBuffer(q, "\n);\n");
8415
8416         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8417
8418         if (binary_upgrade)
8419                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8420
8421         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8422                                  tyinfo->dobj.name,
8423                                  tyinfo->dobj.namespace->dobj.name,
8424                                  NULL,
8425                                  tyinfo->rolname, false,
8426                                  "TYPE", SECTION_PRE_DATA,
8427                                  q->data, delq->data, NULL,
8428                                  NULL, 0,
8429                                  NULL, NULL);
8430
8431         /* Dump Type Comments and Security Labels */
8432         dumpComment(fout, labelq->data,
8433                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8434                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8435         dumpSecLabel(fout, labelq->data,
8436                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8437                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8438
8439         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8440                         qtypname, NULL, tyinfo->dobj.name,
8441                         tyinfo->dobj.namespace->dobj.name,
8442                         tyinfo->rolname, tyinfo->typacl);
8443
8444         PQclear(res);
8445         destroyPQExpBuffer(q);
8446         destroyPQExpBuffer(delq);
8447         destroyPQExpBuffer(labelq);
8448         destroyPQExpBuffer(query);
8449 }
8450
8451 /*
8452  * dumpDomain
8453  *        writes out to fout the queries to recreate a user-defined domain
8454  */
8455 static void
8456 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8457 {
8458         PQExpBuffer q = createPQExpBuffer();
8459         PQExpBuffer delq = createPQExpBuffer();
8460         PQExpBuffer labelq = createPQExpBuffer();
8461         PQExpBuffer query = createPQExpBuffer();
8462         PGresult   *res;
8463         int                     i;
8464         char       *qtypname;
8465         char       *typnotnull;
8466         char       *typdefn;
8467         char       *typdefault;
8468         Oid                     typcollation;
8469         bool            typdefault_is_literal = false;
8470
8471         /* Set proper schema search path so type references list correctly */
8472         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8473
8474         /* Fetch domain specific details */
8475         if (fout->remoteVersion >= 90100)
8476         {
8477                 /* typcollation is new in 9.1 */
8478                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8479                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8480                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8481                                                   "t.typdefault, "
8482                                                   "CASE WHEN t.typcollation <> u.typcollation "
8483                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8484                                                   "FROM pg_catalog.pg_type t "
8485                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8486                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8487                                                   tyinfo->dobj.catId.oid);
8488         }
8489         else
8490         {
8491                 /* We assume here that remoteVersion must be at least 70300 */
8492                 appendPQExpBuffer(query, "SELECT typnotnull, "
8493                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8494                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8495                                                   "typdefault, 0 AS typcollation "
8496                                                   "FROM pg_catalog.pg_type "
8497                                                   "WHERE oid = '%u'::pg_catalog.oid",
8498                                                   tyinfo->dobj.catId.oid);
8499         }
8500
8501         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8502
8503         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8504         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8505         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8506                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8507         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8508         {
8509                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8510                 typdefault_is_literal = true;   /* it needs quotes */
8511         }
8512         else
8513                 typdefault = NULL;
8514         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8515
8516         if (binary_upgrade)
8517                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8518                                                                                                  tyinfo->dobj.catId.oid);
8519
8520         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8521
8522         appendPQExpBuffer(q,
8523                                           "CREATE DOMAIN %s AS %s",
8524                                           qtypname,
8525                                           typdefn);
8526
8527         /* Print collation only if different from base type's collation */
8528         if (OidIsValid(typcollation))
8529         {
8530                 CollInfo   *coll;
8531
8532                 coll = findCollationByOid(typcollation);
8533                 if (coll)
8534                 {
8535                         /* always schema-qualify, don't try to be smart */
8536                         appendPQExpBuffer(q, " COLLATE %s.",
8537                                                           fmtId(coll->dobj.namespace->dobj.name));
8538                         appendPQExpBuffer(q, "%s",
8539                                                           fmtId(coll->dobj.name));
8540                 }
8541         }
8542
8543         if (typnotnull[0] == 't')
8544                 appendPQExpBuffer(q, " NOT NULL");
8545
8546         if (typdefault != NULL)
8547         {
8548                 appendPQExpBuffer(q, " DEFAULT ");
8549                 if (typdefault_is_literal)
8550                         appendStringLiteralAH(q, typdefault, fout);
8551                 else
8552                         appendPQExpBufferStr(q, typdefault);
8553         }
8554
8555         PQclear(res);
8556
8557         /*
8558          * Add any CHECK constraints for the domain
8559          */
8560         for (i = 0; i < tyinfo->nDomChecks; i++)
8561         {
8562                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8563
8564                 if (!domcheck->separate)
8565                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8566                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8567         }
8568
8569         appendPQExpBuffer(q, ";\n");
8570
8571         /*
8572          * DROP must be fully qualified in case same name appears in pg_catalog
8573          */
8574         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8575                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8576         appendPQExpBuffer(delq, "%s;\n",
8577                                           qtypname);
8578
8579         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8580
8581         if (binary_upgrade)
8582                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8583
8584         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8585                                  tyinfo->dobj.name,
8586                                  tyinfo->dobj.namespace->dobj.name,
8587                                  NULL,
8588                                  tyinfo->rolname, false,
8589                                  "DOMAIN", SECTION_PRE_DATA,
8590                                  q->data, delq->data, NULL,
8591                                  NULL, 0,
8592                                  NULL, NULL);
8593
8594         /* Dump Domain Comments and Security Labels */
8595         dumpComment(fout, labelq->data,
8596                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8597                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8598         dumpSecLabel(fout, labelq->data,
8599                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8600                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8601
8602         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8603                         qtypname, NULL, tyinfo->dobj.name,
8604                         tyinfo->dobj.namespace->dobj.name,
8605                         tyinfo->rolname, tyinfo->typacl);
8606
8607         destroyPQExpBuffer(q);
8608         destroyPQExpBuffer(delq);
8609         destroyPQExpBuffer(labelq);
8610         destroyPQExpBuffer(query);
8611 }
8612
8613 /*
8614  * dumpCompositeType
8615  *        writes out to fout the queries to recreate a user-defined stand-alone
8616  *        composite type
8617  */
8618 static void
8619 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8620 {
8621         PQExpBuffer q = createPQExpBuffer();
8622         PQExpBuffer dropped = createPQExpBuffer();
8623         PQExpBuffer delq = createPQExpBuffer();
8624         PQExpBuffer labelq = createPQExpBuffer();
8625         PQExpBuffer query = createPQExpBuffer();
8626         PGresult   *res;
8627         char       *qtypname;
8628         int                     ntups;
8629         int                     i_attname;
8630         int                     i_atttypdefn;
8631         int                     i_attlen;
8632         int                     i_attalign;
8633         int                     i_attisdropped;
8634         int                     i_attcollation;
8635         int                     i_typrelid;
8636         int                     i;
8637         int                     actual_atts;
8638
8639         /* Set proper schema search path so type references list correctly */
8640         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8641
8642         /* Fetch type specific details */
8643         if (fout->remoteVersion >= 90100)
8644         {
8645                 /*
8646                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8647                  * clauses for attributes whose collation is different from their
8648                  * type's default, we use a CASE here to suppress uninteresting
8649                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8650                  * collation does not matter for those.
8651                  */
8652                 appendPQExpBuffer(query, "SELECT a.attname, "
8653                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8654                                                   "a.attlen, a.attalign, a.attisdropped, "
8655                                                   "CASE WHEN a.attcollation <> at.typcollation "
8656                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8657                                                   "ct.typrelid "
8658                                                   "FROM pg_catalog.pg_type ct "
8659                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8660                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8661                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8662                                                   "ORDER BY a.attnum ",
8663                                                   tyinfo->dobj.catId.oid);
8664         }
8665         else
8666         {
8667                 /*
8668                  * We assume here that remoteVersion must be at least 70300.  Since
8669                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8670                  * always be false.
8671                  */
8672                 appendPQExpBuffer(query, "SELECT a.attname, "
8673                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8674                                                   "a.attlen, a.attalign, a.attisdropped, "
8675                                                   "0 AS attcollation, "
8676                                                   "ct.typrelid "
8677                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8678                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8679                                                   "AND a.attrelid = ct.typrelid "
8680                                                   "ORDER BY a.attnum ",
8681                                                   tyinfo->dobj.catId.oid);
8682         }
8683
8684         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8685
8686         ntups = PQntuples(res);
8687
8688         i_attname = PQfnumber(res, "attname");
8689         i_atttypdefn = PQfnumber(res, "atttypdefn");
8690         i_attlen = PQfnumber(res, "attlen");
8691         i_attalign = PQfnumber(res, "attalign");
8692         i_attisdropped = PQfnumber(res, "attisdropped");
8693         i_attcollation = PQfnumber(res, "attcollation");
8694         i_typrelid = PQfnumber(res, "typrelid");
8695
8696         if (binary_upgrade)
8697         {
8698                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8699
8700                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8701                                                                                                  tyinfo->dobj.catId.oid);
8702                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8703         }
8704
8705         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8706
8707         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8708                                           qtypname);
8709
8710         actual_atts = 0;
8711         for (i = 0; i < ntups; i++)
8712         {
8713                 char       *attname;
8714                 char       *atttypdefn;
8715                 char       *attlen;
8716                 char       *attalign;
8717                 bool            attisdropped;
8718                 Oid                     attcollation;
8719
8720                 attname = PQgetvalue(res, i, i_attname);
8721                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8722                 attlen = PQgetvalue(res, i, i_attlen);
8723                 attalign = PQgetvalue(res, i, i_attalign);
8724                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8725                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8726
8727                 if (attisdropped && !binary_upgrade)
8728                         continue;
8729
8730                 /* Format properly if not first attr */
8731                 if (actual_atts++ > 0)
8732                         appendPQExpBuffer(q, ",");
8733                 appendPQExpBuffer(q, "\n\t");
8734
8735                 if (!attisdropped)
8736                 {
8737                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8738
8739                         /* Add collation if not default for the column type */
8740                         if (OidIsValid(attcollation))
8741                         {
8742                                 CollInfo   *coll;
8743
8744                                 coll = findCollationByOid(attcollation);
8745                                 if (coll)
8746                                 {
8747                                         /* always schema-qualify, don't try to be smart */
8748                                         appendPQExpBuffer(q, " COLLATE %s.",
8749                                                                           fmtId(coll->dobj.namespace->dobj.name));
8750                                         appendPQExpBuffer(q, "%s",
8751                                                                           fmtId(coll->dobj.name));
8752                                 }
8753                         }
8754                 }
8755                 else
8756                 {
8757                         /*
8758                          * This is a dropped attribute and we're in binary_upgrade mode.
8759                          * Insert a placeholder for it in the CREATE TYPE command, and set
8760                          * length and alignment with direct UPDATE to the catalogs
8761                          * afterwards. See similar code in dumpTableSchema().
8762                          */
8763                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8764
8765                         /* stash separately for insertion after the CREATE TYPE */
8766                         appendPQExpBuffer(dropped,
8767                                           "\n-- For binary upgrade, recreate dropped column.\n");
8768                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8769                                                           "SET attlen = %s, "
8770                                                           "attalign = '%s', attbyval = false\n"
8771                                                           "WHERE attname = ", attlen, attalign);
8772                         appendStringLiteralAH(dropped, attname, fout);
8773                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8774                         appendStringLiteralAH(dropped, qtypname, fout);
8775                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8776
8777                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8778                                                           qtypname);
8779                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8780                                                           fmtId(attname));
8781                 }
8782         }
8783         appendPQExpBuffer(q, "\n);\n");
8784         appendPQExpBufferStr(q, dropped->data);
8785
8786         /*
8787          * DROP must be fully qualified in case same name appears in pg_catalog
8788          */
8789         appendPQExpBuffer(delq, "DROP TYPE %s.",
8790                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8791         appendPQExpBuffer(delq, "%s;\n",
8792                                           qtypname);
8793
8794         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8795
8796         if (binary_upgrade)
8797                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8798
8799         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8800                                  tyinfo->dobj.name,
8801                                  tyinfo->dobj.namespace->dobj.name,
8802                                  NULL,
8803                                  tyinfo->rolname, false,
8804                                  "TYPE", SECTION_PRE_DATA,
8805                                  q->data, delq->data, NULL,
8806                                  NULL, 0,
8807                                  NULL, NULL);
8808
8809
8810         /* Dump Type Comments and Security Labels */
8811         dumpComment(fout, labelq->data,
8812                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8813                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8814         dumpSecLabel(fout, labelq->data,
8815                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8816                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8817
8818         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8819                         qtypname, NULL, tyinfo->dobj.name,
8820                         tyinfo->dobj.namespace->dobj.name,
8821                         tyinfo->rolname, tyinfo->typacl);
8822
8823         PQclear(res);
8824         destroyPQExpBuffer(q);
8825         destroyPQExpBuffer(dropped);
8826         destroyPQExpBuffer(delq);
8827         destroyPQExpBuffer(labelq);
8828         destroyPQExpBuffer(query);
8829
8830         /* Dump any per-column comments */
8831         dumpCompositeTypeColComments(fout, tyinfo);
8832 }
8833
8834 /*
8835  * dumpCompositeTypeColComments
8836  *        writes out to fout the queries to recreate comments on the columns of
8837  *        a user-defined stand-alone composite type
8838  */
8839 static void
8840 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8841 {
8842         CommentItem *comments;
8843         int                     ncomments;
8844         PGresult   *res;
8845         PQExpBuffer query;
8846         PQExpBuffer target;
8847         Oid                     pgClassOid;
8848         int                     i;
8849         int                     ntups;
8850         int                     i_attname;
8851         int                     i_attnum;
8852
8853         query = createPQExpBuffer();
8854
8855         /* We assume here that remoteVersion must be at least 70300 */
8856         appendPQExpBuffer(query,
8857                                           "SELECT c.tableoid, a.attname, a.attnum "
8858                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8859                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8860                                           "  AND NOT a.attisdropped "
8861                                           "ORDER BY a.attnum ",
8862                                           tyinfo->typrelid);
8863
8864         /* Fetch column attnames */
8865         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8866
8867         ntups = PQntuples(res);
8868         if (ntups < 1)
8869         {
8870                 PQclear(res);
8871                 destroyPQExpBuffer(query);
8872                 return;
8873         }
8874
8875         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8876
8877         /* Search for comments associated with type's pg_class OID */
8878         ncomments = findComments(fout,
8879                                                          pgClassOid,
8880                                                          tyinfo->typrelid,
8881                                                          &comments);
8882
8883         /* If no comments exist, we're done */
8884         if (ncomments <= 0)
8885         {
8886                 PQclear(res);
8887                 destroyPQExpBuffer(query);
8888                 return;
8889         }
8890
8891         /* Build COMMENT ON statements */
8892         target = createPQExpBuffer();
8893
8894         i_attnum = PQfnumber(res, "attnum");
8895         i_attname = PQfnumber(res, "attname");
8896         while (ncomments > 0)
8897         {
8898                 const char *attname;
8899
8900                 attname = NULL;
8901                 for (i = 0; i < ntups; i++)
8902                 {
8903                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8904                         {
8905                                 attname = PQgetvalue(res, i, i_attname);
8906                                 break;
8907                         }
8908                 }
8909                 if (attname)                    /* just in case we don't find it */
8910                 {
8911                         const char *descr = comments->descr;
8912
8913                         resetPQExpBuffer(target);
8914                         appendPQExpBuffer(target, "COLUMN %s.",
8915                                                           fmtId(tyinfo->dobj.name));
8916                         appendPQExpBuffer(target, "%s",
8917                                                           fmtId(attname));
8918
8919                         resetPQExpBuffer(query);
8920                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8921                         appendStringLiteralAH(query, descr, fout);
8922                         appendPQExpBuffer(query, ";\n");
8923
8924                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8925                                                  target->data,
8926                                                  tyinfo->dobj.namespace->dobj.name,
8927                                                  NULL, tyinfo->rolname,
8928                                                  false, "COMMENT", SECTION_NONE,
8929                                                  query->data, "", NULL,
8930                                                  &(tyinfo->dobj.dumpId), 1,
8931                                                  NULL, NULL);
8932                 }
8933
8934                 comments++;
8935                 ncomments--;
8936         }
8937
8938         PQclear(res);
8939         destroyPQExpBuffer(query);
8940         destroyPQExpBuffer(target);
8941 }
8942
8943 /*
8944  * dumpShellType
8945  *        writes out to fout the queries to create a shell type
8946  *
8947  * We dump a shell definition in advance of the I/O functions for the type.
8948  */
8949 static void
8950 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8951 {
8952         PQExpBuffer q;
8953
8954         /* Skip if not to be dumped */
8955         if (!stinfo->dobj.dump || dataOnly)
8956                 return;
8957
8958         q = createPQExpBuffer();
8959
8960         /*
8961          * Note the lack of a DROP command for the shell type; any required DROP
8962          * is driven off the base type entry, instead.  This interacts with
8963          * _printTocEntry()'s use of the presence of a DROP command to decide
8964          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8965          * the shell type's owner immediately on creation; that should happen only
8966          * after it's filled in, otherwise the backend complains.
8967          */
8968
8969         if (binary_upgrade)
8970                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8971                                                                                    stinfo->baseType->dobj.catId.oid);
8972
8973         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8974                                           fmtId(stinfo->dobj.name));
8975
8976         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8977                                  stinfo->dobj.name,
8978                                  stinfo->dobj.namespace->dobj.name,
8979                                  NULL,
8980                                  stinfo->baseType->rolname, false,
8981                                  "SHELL TYPE", SECTION_PRE_DATA,
8982                                  q->data, "", NULL,
8983                                  NULL, 0,
8984                                  NULL, NULL);
8985
8986         destroyPQExpBuffer(q);
8987 }
8988
8989 /*
8990  * Determine whether we want to dump definitions for procedural languages.
8991  * Since the languages themselves don't have schemas, we can't rely on
8992  * the normal schema-based selection mechanism.  We choose to dump them
8993  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8994  * the dump flag of the PL's call handler function, but in 8.1 this will
8995  * probably always be false since call handlers are created in pg_catalog.)
8996  *
8997  * For some backwards compatibility with the older behavior, we forcibly
8998  * dump a PL if its handler function (and validator if any) are in a
8999  * dumpable namespace.  That case is not checked here.
9000  *
9001  * Also, if the PL belongs to an extension, we do not use this heuristic.
9002  * That case isn't checked here either.
9003  */
9004 static bool
9005 shouldDumpProcLangs(void)
9006 {
9007         if (!include_everything)
9008                 return false;
9009         /* And they're schema not data */
9010         if (dataOnly)
9011                 return false;
9012         return true;
9013 }
9014
9015 /*
9016  * dumpProcLang
9017  *                writes out to fout the queries to recreate a user-defined
9018  *                procedural language
9019  */
9020 static void
9021 dumpProcLang(Archive *fout, ProcLangInfo *plang)
9022 {
9023         PQExpBuffer defqry;
9024         PQExpBuffer delqry;
9025         PQExpBuffer labelq;
9026         bool            useParams;
9027         char       *qlanname;
9028         char       *lanschema;
9029         FuncInfo   *funcInfo;
9030         FuncInfo   *inlineInfo = NULL;
9031         FuncInfo   *validatorInfo = NULL;
9032
9033         /* Skip if not to be dumped */
9034         if (!plang->dobj.dump || dataOnly)
9035                 return;
9036
9037         /*
9038          * Try to find the support function(s).  It is not an error if we don't
9039          * find them --- if the functions are in the pg_catalog schema, as is
9040          * standard in 8.1 and up, then we won't have loaded them. (In this case
9041          * we will emit a parameterless CREATE LANGUAGE command, which will
9042          * require PL template knowledge in the backend to reload.)
9043          */
9044
9045         funcInfo = findFuncByOid(plang->lanplcallfoid);
9046         if (funcInfo != NULL && !funcInfo->dobj.dump)
9047                 funcInfo = NULL;                /* treat not-dumped same as not-found */
9048
9049         if (OidIsValid(plang->laninline))
9050         {
9051                 inlineInfo = findFuncByOid(plang->laninline);
9052                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
9053                         inlineInfo = NULL;
9054         }
9055
9056         if (OidIsValid(plang->lanvalidator))
9057         {
9058                 validatorInfo = findFuncByOid(plang->lanvalidator);
9059                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
9060                         validatorInfo = NULL;
9061         }
9062
9063         /*
9064          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
9065          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
9066          * dump it.
9067          *
9068          * However, for a language that belongs to an extension, we must not use
9069          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
9070          * told to (via dobj.dump).  Generally the support functions will belong
9071          * to the same extension and so have the same dump flags ... if they
9072          * don't, this might not work terribly nicely.
9073          */
9074         useParams = (funcInfo != NULL &&
9075                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
9076                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
9077
9078         if (!plang->dobj.ext_member)
9079         {
9080                 if (!useParams && !shouldDumpProcLangs())
9081                         return;
9082         }
9083
9084         defqry = createPQExpBuffer();
9085         delqry = createPQExpBuffer();
9086         labelq = createPQExpBuffer();
9087
9088         qlanname = pg_strdup(fmtId(plang->dobj.name));
9089
9090         /*
9091          * If dumping a HANDLER clause, treat the language as being in the handler
9092          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
9093          * it doesn't really have a schema.
9094          */
9095         if (useParams)
9096                 lanschema = funcInfo->dobj.namespace->dobj.name;
9097         else
9098                 lanschema = NULL;
9099
9100         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
9101                                           qlanname);
9102
9103         if (useParams)
9104         {
9105                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
9106                                                   plang->lanpltrusted ? "TRUSTED " : "",
9107                                                   qlanname);
9108                 appendPQExpBuffer(defqry, " HANDLER %s",
9109                                                   fmtId(funcInfo->dobj.name));
9110                 if (OidIsValid(plang->laninline))
9111                 {
9112                         appendPQExpBuffer(defqry, " INLINE ");
9113                         /* Cope with possibility that inline is in different schema */
9114                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
9115                                 appendPQExpBuffer(defqry, "%s.",
9116                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
9117                         appendPQExpBuffer(defqry, "%s",
9118                                                           fmtId(inlineInfo->dobj.name));
9119                 }
9120                 if (OidIsValid(plang->lanvalidator))
9121                 {
9122                         appendPQExpBuffer(defqry, " VALIDATOR ");
9123                         /* Cope with possibility that validator is in different schema */
9124                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
9125                                 appendPQExpBuffer(defqry, "%s.",
9126                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
9127                         appendPQExpBuffer(defqry, "%s",
9128                                                           fmtId(validatorInfo->dobj.name));
9129                 }
9130         }
9131         else
9132         {
9133                 /*
9134                  * If not dumping parameters, then use CREATE OR REPLACE so that the
9135                  * command will not fail if the language is preinstalled in the target
9136                  * database.  We restrict the use of REPLACE to this case so as to
9137                  * eliminate the risk of replacing a language with incompatible
9138                  * parameter settings: this command will only succeed at all if there
9139                  * is a pg_pltemplate entry, and if there is one, the existing entry
9140                  * must match it too.
9141                  */
9142                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
9143                                                   qlanname);
9144         }
9145         appendPQExpBuffer(defqry, ";\n");
9146
9147         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
9148
9149         if (binary_upgrade)
9150                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
9151
9152         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
9153                                  plang->dobj.name,
9154                                  lanschema, NULL, plang->lanowner,
9155                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
9156                                  defqry->data, delqry->data, NULL,
9157                                  NULL, 0,
9158                                  NULL, NULL);
9159
9160         /* Dump Proc Lang Comments and Security Labels */
9161         dumpComment(fout, labelq->data,
9162                                 NULL, "",
9163                                 plang->dobj.catId, 0, plang->dobj.dumpId);
9164         dumpSecLabel(fout, labelq->data,
9165                                  NULL, "",
9166                                  plang->dobj.catId, 0, plang->dobj.dumpId);
9167
9168         if (plang->lanpltrusted)
9169                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
9170                                 qlanname, NULL, plang->dobj.name,
9171                                 lanschema,
9172                                 plang->lanowner, plang->lanacl);
9173
9174         free(qlanname);
9175
9176         destroyPQExpBuffer(defqry);
9177         destroyPQExpBuffer(delqry);
9178         destroyPQExpBuffer(labelq);
9179 }
9180
9181 /*
9182  * format_function_arguments: generate function name and argument list
9183  *
9184  * This is used when we can rely on pg_get_function_arguments to format
9185  * the argument list.
9186  */
9187 static char *
9188 format_function_arguments(FuncInfo *finfo, char *funcargs)
9189 {
9190         PQExpBufferData fn;
9191
9192         initPQExpBuffer(&fn);
9193         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9194         return fn.data;
9195 }
9196
9197 /*
9198  * format_function_arguments_old: generate function name and argument list
9199  *
9200  * The argument type names are qualified if needed.  The function name
9201  * is never qualified.
9202  *
9203  * This is used only with pre-8.4 servers, so we aren't expecting to see
9204  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9205  *
9206  * Any or all of allargtypes, argmodes, argnames may be NULL.
9207  */
9208 static char *
9209 format_function_arguments_old(Archive *fout,
9210                                                           FuncInfo *finfo, int nallargs,
9211                                                           char **allargtypes,
9212                                                           char **argmodes,
9213                                                           char **argnames)
9214 {
9215         PQExpBufferData fn;
9216         int                     j;
9217
9218         initPQExpBuffer(&fn);
9219         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9220         for (j = 0; j < nallargs; j++)
9221         {
9222                 Oid                     typid;
9223                 char       *typname;
9224                 const char *argmode;
9225                 const char *argname;
9226
9227                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9228                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9229
9230                 if (argmodes)
9231                 {
9232                         switch (argmodes[j][0])
9233                         {
9234                                 case PROARGMODE_IN:
9235                                         argmode = "";
9236                                         break;
9237                                 case PROARGMODE_OUT:
9238                                         argmode = "OUT ";
9239                                         break;
9240                                 case PROARGMODE_INOUT:
9241                                         argmode = "INOUT ";
9242                                         break;
9243                                 default:
9244                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9245                                         argmode = "";
9246                                         break;
9247                         }
9248                 }
9249                 else
9250                         argmode = "";
9251
9252                 argname = argnames ? argnames[j] : (char *) NULL;
9253                 if (argname && argname[0] == '\0')
9254                         argname = NULL;
9255
9256                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9257                                                   (j > 0) ? ", " : "",
9258                                                   argmode,
9259                                                   argname ? fmtId(argname) : "",
9260                                                   argname ? " " : "",
9261                                                   typname);
9262                 free(typname);
9263         }
9264         appendPQExpBuffer(&fn, ")");
9265         return fn.data;
9266 }
9267
9268 /*
9269  * format_function_signature: generate function name and argument list
9270  *
9271  * This is like format_function_arguments_old except that only a minimal
9272  * list of input argument types is generated; this is sufficient to
9273  * reference the function, but not to define it.
9274  *
9275  * If honor_quotes is false then the function name is never quoted.
9276  * This is appropriate for use in TOC tags, but not in SQL commands.
9277  */
9278 static char *
9279 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9280 {
9281         PQExpBufferData fn;
9282         int                     j;
9283
9284         initPQExpBuffer(&fn);
9285         if (honor_quotes)
9286                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9287         else
9288                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9289         for (j = 0; j < finfo->nargs; j++)
9290         {
9291                 char       *typname;
9292
9293                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9294                                                                            zeroAsOpaque);
9295
9296                 appendPQExpBuffer(&fn, "%s%s",
9297                                                   (j > 0) ? ", " : "",
9298                                                   typname);
9299                 free(typname);
9300         }
9301         appendPQExpBuffer(&fn, ")");
9302         return fn.data;
9303 }
9304
9305
9306 /*
9307  * dumpFunc:
9308  *        dump out one function
9309  */
9310 static void
9311 dumpFunc(Archive *fout, FuncInfo *finfo)
9312 {
9313         PQExpBuffer query;
9314         PQExpBuffer q;
9315         PQExpBuffer delqry;
9316         PQExpBuffer labelq;
9317         PQExpBuffer asPart;
9318         PGresult   *res;
9319         char       *funcsig;            /* identity signature */
9320         char       *funcfullsig;        /* full signature */
9321         char       *funcsig_tag;
9322         char       *proretset;
9323         char       *prosrc;
9324         char       *probin;
9325         char       *funcargs;
9326         char       *funciargs;
9327         char       *funcresult;
9328         char       *proallargtypes;
9329         char       *proargmodes;
9330         char       *proargnames;
9331         char       *proiswindow;
9332         char       *provolatile;
9333         char       *proisstrict;
9334         char       *prosecdef;
9335         char       *proleakproof;
9336         char       *proconfig;
9337         char       *procost;
9338         char       *prorows;
9339         char       *lanname;
9340         char       *rettypename;
9341         int                     nallargs;
9342         char      **allargtypes = NULL;
9343         char      **argmodes = NULL;
9344         char      **argnames = NULL;
9345         char      **configitems = NULL;
9346         int                     nconfigitems = 0;
9347         int                     i;
9348
9349         /* Skip if not to be dumped */
9350         if (!finfo->dobj.dump || dataOnly)
9351                 return;
9352
9353         query = createPQExpBuffer();
9354         q = createPQExpBuffer();
9355         delqry = createPQExpBuffer();
9356         labelq = createPQExpBuffer();
9357         asPart = createPQExpBuffer();
9358
9359         /* Set proper schema search path so type references list correctly */
9360         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9361
9362         /* Fetch function-specific details */
9363         if (fout->remoteVersion >= 90200)
9364         {
9365                 /*
9366                  * proleakproof was added at v9.2
9367                  */
9368                 appendPQExpBuffer(query,
9369                                                   "SELECT proretset, prosrc, probin, "
9370                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9371                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9372                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9373                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9374                                                   "proleakproof, proconfig, procost, prorows, "
9375                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9376                                                   "FROM pg_catalog.pg_proc "
9377                                                   "WHERE oid = '%u'::pg_catalog.oid",
9378                                                   finfo->dobj.catId.oid);
9379         }
9380         else if (fout->remoteVersion >= 80400)
9381         {
9382                 /*
9383                  * In 8.4 and up we rely on pg_get_function_arguments and
9384                  * pg_get_function_result instead of examining proallargtypes etc.
9385                  */
9386                 appendPQExpBuffer(query,
9387                                                   "SELECT proretset, prosrc, probin, "
9388                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9389                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9390                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9391                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9392                                                   "false AS proleakproof, "
9393                                                   " proconfig, procost, prorows, "
9394                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9395                                                   "FROM pg_catalog.pg_proc "
9396                                                   "WHERE oid = '%u'::pg_catalog.oid",
9397                                                   finfo->dobj.catId.oid);
9398         }
9399         else if (fout->remoteVersion >= 80300)
9400         {
9401                 appendPQExpBuffer(query,
9402                                                   "SELECT proretset, prosrc, probin, "
9403                                                   "proallargtypes, proargmodes, proargnames, "
9404                                                   "false AS proiswindow, "
9405                                                   "provolatile, proisstrict, prosecdef, "
9406                                                   "false AS proleakproof, "
9407                                                   "proconfig, procost, prorows, "
9408                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9409                                                   "FROM pg_catalog.pg_proc "
9410                                                   "WHERE oid = '%u'::pg_catalog.oid",
9411                                                   finfo->dobj.catId.oid);
9412         }
9413         else if (fout->remoteVersion >= 80100)
9414         {
9415                 appendPQExpBuffer(query,
9416                                                   "SELECT proretset, prosrc, probin, "
9417                                                   "proallargtypes, proargmodes, proargnames, "
9418                                                   "false AS proiswindow, "
9419                                                   "provolatile, proisstrict, prosecdef, "
9420                                                   "false AS proleakproof, "
9421                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9422                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9423                                                   "FROM pg_catalog.pg_proc "
9424                                                   "WHERE oid = '%u'::pg_catalog.oid",
9425                                                   finfo->dobj.catId.oid);
9426         }
9427         else if (fout->remoteVersion >= 80000)
9428         {
9429                 appendPQExpBuffer(query,
9430                                                   "SELECT proretset, prosrc, probin, "
9431                                                   "null AS proallargtypes, "
9432                                                   "null AS proargmodes, "
9433                                                   "proargnames, "
9434                                                   "false AS proiswindow, "
9435                                                   "provolatile, proisstrict, prosecdef, "
9436                                                   "false AS proleakproof, "
9437                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9438                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9439                                                   "FROM pg_catalog.pg_proc "
9440                                                   "WHERE oid = '%u'::pg_catalog.oid",
9441                                                   finfo->dobj.catId.oid);
9442         }
9443         else if (fout->remoteVersion >= 70300)
9444         {
9445                 appendPQExpBuffer(query,
9446                                                   "SELECT proretset, prosrc, probin, "
9447                                                   "null AS proallargtypes, "
9448                                                   "null AS proargmodes, "
9449                                                   "null AS proargnames, "
9450                                                   "false AS proiswindow, "
9451                                                   "provolatile, proisstrict, prosecdef, "
9452                                                   "false AS proleakproof, "
9453                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9454                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9455                                                   "FROM pg_catalog.pg_proc "
9456                                                   "WHERE oid = '%u'::pg_catalog.oid",
9457                                                   finfo->dobj.catId.oid);
9458         }
9459         else if (fout->remoteVersion >= 70100)
9460         {
9461                 appendPQExpBuffer(query,
9462                                                   "SELECT proretset, prosrc, probin, "
9463                                                   "null AS proallargtypes, "
9464                                                   "null AS proargmodes, "
9465                                                   "null AS proargnames, "
9466                                                   "false AS proiswindow, "
9467                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9468                                                   "proisstrict, "
9469                                                   "false AS prosecdef, "
9470                                                   "false AS proleakproof, "
9471                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9472                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9473                                                   "FROM pg_proc "
9474                                                   "WHERE oid = '%u'::oid",
9475                                                   finfo->dobj.catId.oid);
9476         }
9477         else
9478         {
9479                 appendPQExpBuffer(query,
9480                                                   "SELECT proretset, prosrc, probin, "
9481                                                   "null AS proallargtypes, "
9482                                                   "null AS proargmodes, "
9483                                                   "null AS proargnames, "
9484                                                   "false AS proiswindow, "
9485                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9486                                                   "false AS proisstrict, "
9487                                                   "false AS prosecdef, "
9488                                                   "false AS proleakproof, "
9489                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9490                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9491                                                   "FROM pg_proc "
9492                                                   "WHERE oid = '%u'::oid",
9493                                                   finfo->dobj.catId.oid);
9494         }
9495
9496         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9497
9498         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9499         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9500         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9501         if (fout->remoteVersion >= 80400)
9502         {
9503                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9504                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9505                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9506                 proallargtypes = proargmodes = proargnames = NULL;
9507         }
9508         else
9509         {
9510                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9511                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9512                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9513                 funcargs = funciargs = funcresult = NULL;
9514         }
9515         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9516         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9517         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9518         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9519         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9520         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9521         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9522         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9523         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9524
9525         /*
9526          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9527          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9528          * versions would set it to "-".  There are no known cases in which prosrc
9529          * is unused, so the tests below for "-" are probably useless.
9530          */
9531         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9532         {
9533                 appendPQExpBuffer(asPart, "AS ");
9534                 appendStringLiteralAH(asPart, probin, fout);
9535                 if (strcmp(prosrc, "-") != 0)
9536                 {
9537                         appendPQExpBuffer(asPart, ", ");
9538
9539                         /*
9540                          * where we have bin, use dollar quoting if allowed and src
9541                          * contains quote or backslash; else use regular quoting.
9542                          */
9543                         if (disable_dollar_quoting ||
9544                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9545                                 appendStringLiteralAH(asPart, prosrc, fout);
9546                         else
9547                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9548                 }
9549         }
9550         else
9551         {
9552                 if (strcmp(prosrc, "-") != 0)
9553                 {
9554                         appendPQExpBuffer(asPart, "AS ");
9555                         /* with no bin, dollar quote src unconditionally if allowed */
9556                         if (disable_dollar_quoting)
9557                                 appendStringLiteralAH(asPart, prosrc, fout);
9558                         else
9559                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9560                 }
9561         }
9562
9563         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9564
9565         if (proallargtypes && *proallargtypes)
9566         {
9567                 int                     nitems = 0;
9568
9569                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9570                         nitems < finfo->nargs)
9571                 {
9572                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9573                         if (allargtypes)
9574                                 free(allargtypes);
9575                         allargtypes = NULL;
9576                 }
9577                 else
9578                         nallargs = nitems;
9579         }
9580
9581         if (proargmodes && *proargmodes)
9582         {
9583                 int                     nitems = 0;
9584
9585                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9586                         nitems != nallargs)
9587                 {
9588                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9589                         if (argmodes)
9590                                 free(argmodes);
9591                         argmodes = NULL;
9592                 }
9593         }
9594
9595         if (proargnames && *proargnames)
9596         {
9597                 int                     nitems = 0;
9598
9599                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9600                         nitems != nallargs)
9601                 {
9602                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9603                         if (argnames)
9604                                 free(argnames);
9605                         argnames = NULL;
9606                 }
9607         }
9608
9609         if (proconfig && *proconfig)
9610         {
9611                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9612                 {
9613                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9614                         if (configitems)
9615                                 free(configitems);
9616                         configitems = NULL;
9617                         nconfigitems = 0;
9618                 }
9619         }
9620
9621         if (funcargs)
9622         {
9623                 /* 8.4 or later; we rely on server-side code for most of the work */
9624                 funcfullsig = format_function_arguments(finfo, funcargs);
9625                 funcsig = format_function_arguments(finfo, funciargs);
9626         }
9627         else
9628         {
9629                 /* pre-8.4, do it ourselves */
9630                 funcsig = format_function_arguments_old(fout,
9631                                                                                                 finfo, nallargs, allargtypes,
9632                                                                                                 argmodes, argnames);
9633                 funcfullsig = funcsig;
9634         }
9635
9636         funcsig_tag = format_function_signature(fout, finfo, false);
9637
9638         /*
9639          * DROP must be fully qualified in case same name appears in pg_catalog
9640          */
9641         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9642                                           fmtId(finfo->dobj.namespace->dobj.name),
9643                                           funcsig);
9644
9645         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9646         if (funcresult)
9647                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9648         else
9649         {
9650                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9651                                                                                    zeroAsOpaque);
9652                 appendPQExpBuffer(q, "RETURNS %s%s",
9653                                                   (proretset[0] == 't') ? "SETOF " : "",
9654                                                   rettypename);
9655                 free(rettypename);
9656         }
9657
9658         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9659
9660         if (proiswindow[0] == 't')
9661                 appendPQExpBuffer(q, " WINDOW");
9662
9663         if (provolatile[0] != PROVOLATILE_VOLATILE)
9664         {
9665                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9666                         appendPQExpBuffer(q, " IMMUTABLE");
9667                 else if (provolatile[0] == PROVOLATILE_STABLE)
9668                         appendPQExpBuffer(q, " STABLE");
9669                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9670                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9671                                                   finfo->dobj.name);
9672         }
9673
9674         if (proisstrict[0] == 't')
9675                 appendPQExpBuffer(q, " STRICT");
9676
9677         if (prosecdef[0] == 't')
9678                 appendPQExpBuffer(q, " SECURITY DEFINER");
9679
9680         if (proleakproof[0] == 't')
9681                 appendPQExpBuffer(q, " LEAKPROOF");
9682
9683         /*
9684          * COST and ROWS are emitted only if present and not default, so as not to
9685          * break backwards-compatibility of the dump without need.      Keep this code
9686          * in sync with the defaults in functioncmds.c.
9687          */
9688         if (strcmp(procost, "0") != 0)
9689         {
9690                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9691                 {
9692                         /* default cost is 1 */
9693                         if (strcmp(procost, "1") != 0)
9694                                 appendPQExpBuffer(q, " COST %s", procost);
9695                 }
9696                 else
9697                 {
9698                         /* default cost is 100 */
9699                         if (strcmp(procost, "100") != 0)
9700                                 appendPQExpBuffer(q, " COST %s", procost);
9701                 }
9702         }
9703         if (proretset[0] == 't' &&
9704                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9705                 appendPQExpBuffer(q, " ROWS %s", prorows);
9706
9707         for (i = 0; i < nconfigitems; i++)
9708         {
9709                 /* we feel free to scribble on configitems[] here */
9710                 char       *configitem = configitems[i];
9711                 char       *pos;
9712
9713                 pos = strchr(configitem, '=');
9714                 if (pos == NULL)
9715                         continue;
9716                 *pos++ = '\0';
9717                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9718
9719                 /*
9720                  * Some GUC variable names are 'LIST' type and hence must not be
9721                  * quoted.
9722                  */
9723                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9724                         || pg_strcasecmp(configitem, "search_path") == 0)
9725                         appendPQExpBuffer(q, "%s", pos);
9726                 else
9727                         appendStringLiteralAH(q, pos, fout);
9728         }
9729
9730         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9731
9732         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9733
9734         if (binary_upgrade)
9735                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9736
9737         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9738                                  funcsig_tag,
9739                                  finfo->dobj.namespace->dobj.name,
9740                                  NULL,
9741                                  finfo->rolname, false,
9742                                  "FUNCTION", SECTION_PRE_DATA,
9743                                  q->data, delqry->data, NULL,
9744                                  NULL, 0,
9745                                  NULL, NULL);
9746
9747         /* Dump Function Comments and Security Labels */
9748         dumpComment(fout, labelq->data,
9749                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9750                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9751         dumpSecLabel(fout, labelq->data,
9752                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9753                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9754
9755         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9756                         funcsig, NULL, funcsig_tag,
9757                         finfo->dobj.namespace->dobj.name,
9758                         finfo->rolname, finfo->proacl);
9759
9760         PQclear(res);
9761
9762         destroyPQExpBuffer(query);
9763         destroyPQExpBuffer(q);
9764         destroyPQExpBuffer(delqry);
9765         destroyPQExpBuffer(labelq);
9766         destroyPQExpBuffer(asPart);
9767         free(funcsig);
9768         free(funcsig_tag);
9769         if (allargtypes)
9770                 free(allargtypes);
9771         if (argmodes)
9772                 free(argmodes);
9773         if (argnames)
9774                 free(argnames);
9775         if (configitems)
9776                 free(configitems);
9777 }
9778
9779
9780 /*
9781  * Dump a user-defined cast
9782  */
9783 static void
9784 dumpCast(Archive *fout, CastInfo *cast)
9785 {
9786         PQExpBuffer defqry;
9787         PQExpBuffer delqry;
9788         PQExpBuffer labelq;
9789         FuncInfo   *funcInfo = NULL;
9790
9791         /* Skip if not to be dumped */
9792         if (!cast->dobj.dump || dataOnly)
9793                 return;
9794
9795         /* Cannot dump if we don't have the cast function's info */
9796         if (OidIsValid(cast->castfunc))
9797         {
9798                 funcInfo = findFuncByOid(cast->castfunc);
9799                 if (funcInfo == NULL)
9800                         return;
9801         }
9802
9803         /*
9804          * As per discussion we dump casts if one or more of the underlying
9805          * objects (the conversion function and the two data types) are not
9806          * builtin AND if all of the non-builtin objects are included in the dump.
9807          * Builtin meaning, the namespace name does not start with "pg_".
9808          *
9809          * However, for a cast that belongs to an extension, we must not use this
9810          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9811          */
9812         if (!cast->dobj.ext_member)
9813         {
9814                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9815                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9816
9817                 if (sourceInfo == NULL || targetInfo == NULL)
9818                         return;
9819
9820                 /*
9821                  * Skip this cast if all objects are from pg_
9822                  */
9823                 if ((funcInfo == NULL ||
9824                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9825                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9826                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9827                         return;
9828
9829                 /*
9830                  * Skip cast if function isn't from pg_ and is not to be dumped.
9831                  */
9832                 if (funcInfo &&
9833                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9834                         !funcInfo->dobj.dump)
9835                         return;
9836
9837                 /*
9838                  * Same for the source type
9839                  */
9840                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9841                         !sourceInfo->dobj.dump)
9842                         return;
9843
9844                 /*
9845                  * and the target type.
9846                  */
9847                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9848                         !targetInfo->dobj.dump)
9849                         return;
9850         }
9851
9852         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9853         selectSourceSchema(fout, "pg_catalog");
9854
9855         defqry = createPQExpBuffer();
9856         delqry = createPQExpBuffer();
9857         labelq = createPQExpBuffer();
9858
9859         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9860                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9861                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9862
9863         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9864                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9865                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9866
9867         switch (cast->castmethod)
9868         {
9869                 case COERCION_METHOD_BINARY:
9870                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9871                         break;
9872                 case COERCION_METHOD_INOUT:
9873                         appendPQExpBuffer(defqry, "WITH INOUT");
9874                         break;
9875                 case COERCION_METHOD_FUNCTION:
9876                         if (funcInfo)
9877                         {
9878                                 char       *fsig = format_function_signature(fout, funcInfo, true);
9879
9880                                 /*
9881                                  * Always qualify the function name, in case it is not in
9882                                  * pg_catalog schema (format_function_signature won't qualify
9883                                  * it).
9884                                  */
9885                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9886                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9887                                 free(fsig);
9888                         }
9889                         else
9890                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9891                         break;
9892                 default:
9893                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9894         }
9895
9896         if (cast->castcontext == 'a')
9897                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9898         else if (cast->castcontext == 'i')
9899                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9900         appendPQExpBuffer(defqry, ";\n");
9901
9902         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9903                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9904                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9905
9906         if (binary_upgrade)
9907                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9908
9909         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9910                                  labelq->data,
9911                                  "pg_catalog", NULL, "",
9912                                  false, "CAST", SECTION_PRE_DATA,
9913                                  defqry->data, delqry->data, NULL,
9914                                  NULL, 0,
9915                                  NULL, NULL);
9916
9917         /* Dump Cast Comments */
9918         dumpComment(fout, labelq->data,
9919                                 NULL, "",
9920                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9921
9922         destroyPQExpBuffer(defqry);
9923         destroyPQExpBuffer(delqry);
9924         destroyPQExpBuffer(labelq);
9925 }
9926
9927 /*
9928  * dumpOpr
9929  *        write out a single operator definition
9930  */
9931 static void
9932 dumpOpr(Archive *fout, OprInfo *oprinfo)
9933 {
9934         PQExpBuffer query;
9935         PQExpBuffer q;
9936         PQExpBuffer delq;
9937         PQExpBuffer labelq;
9938         PQExpBuffer oprid;
9939         PQExpBuffer details;
9940         const char *name;
9941         PGresult   *res;
9942         int                     i_oprkind;
9943         int                     i_oprcode;
9944         int                     i_oprleft;
9945         int                     i_oprright;
9946         int                     i_oprcom;
9947         int                     i_oprnegate;
9948         int                     i_oprrest;
9949         int                     i_oprjoin;
9950         int                     i_oprcanmerge;
9951         int                     i_oprcanhash;
9952         char       *oprkind;
9953         char       *oprcode;
9954         char       *oprleft;
9955         char       *oprright;
9956         char       *oprcom;
9957         char       *oprnegate;
9958         char       *oprrest;
9959         char       *oprjoin;
9960         char       *oprcanmerge;
9961         char       *oprcanhash;
9962
9963         /* Skip if not to be dumped */
9964         if (!oprinfo->dobj.dump || dataOnly)
9965                 return;
9966
9967         /*
9968          * some operators are invalid because they were the result of user
9969          * defining operators before commutators exist
9970          */
9971         if (!OidIsValid(oprinfo->oprcode))
9972                 return;
9973
9974         query = createPQExpBuffer();
9975         q = createPQExpBuffer();
9976         delq = createPQExpBuffer();
9977         labelq = createPQExpBuffer();
9978         oprid = createPQExpBuffer();
9979         details = createPQExpBuffer();
9980
9981         /* Make sure we are in proper schema so regoperator works correctly */
9982         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9983
9984         if (fout->remoteVersion >= 80300)
9985         {
9986                 appendPQExpBuffer(query, "SELECT oprkind, "
9987                                                   "oprcode::pg_catalog.regprocedure, "
9988                                                   "oprleft::pg_catalog.regtype, "
9989                                                   "oprright::pg_catalog.regtype, "
9990                                                   "oprcom::pg_catalog.regoperator, "
9991                                                   "oprnegate::pg_catalog.regoperator, "
9992                                                   "oprrest::pg_catalog.regprocedure, "
9993                                                   "oprjoin::pg_catalog.regprocedure, "
9994                                                   "oprcanmerge, oprcanhash "
9995                                                   "FROM pg_catalog.pg_operator "
9996                                                   "WHERE oid = '%u'::pg_catalog.oid",
9997                                                   oprinfo->dobj.catId.oid);
9998         }
9999         else if (fout->remoteVersion >= 70300)
10000         {
10001                 appendPQExpBuffer(query, "SELECT oprkind, "
10002                                                   "oprcode::pg_catalog.regprocedure, "
10003                                                   "oprleft::pg_catalog.regtype, "
10004                                                   "oprright::pg_catalog.regtype, "
10005                                                   "oprcom::pg_catalog.regoperator, "
10006                                                   "oprnegate::pg_catalog.regoperator, "
10007                                                   "oprrest::pg_catalog.regprocedure, "
10008                                                   "oprjoin::pg_catalog.regprocedure, "
10009                                                   "(oprlsortop != 0) AS oprcanmerge, "
10010                                                   "oprcanhash "
10011                                                   "FROM pg_catalog.pg_operator "
10012                                                   "WHERE oid = '%u'::pg_catalog.oid",
10013                                                   oprinfo->dobj.catId.oid);
10014         }
10015         else if (fout->remoteVersion >= 70100)
10016         {
10017                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10018                                                   "CASE WHEN oprleft = 0 THEN '-' "
10019                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
10020                                                   "CASE WHEN oprright = 0 THEN '-' "
10021                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
10022                                                   "oprcom, oprnegate, oprrest, oprjoin, "
10023                                                   "(oprlsortop != 0) AS oprcanmerge, "
10024                                                   "oprcanhash "
10025                                                   "FROM pg_operator "
10026                                                   "WHERE oid = '%u'::oid",
10027                                                   oprinfo->dobj.catId.oid);
10028         }
10029         else
10030         {
10031                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10032                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
10033                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
10034                                                   "CASE WHEN oprright = 0 THEN '-'::name "
10035                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
10036                                                   "oprcom, oprnegate, oprrest, oprjoin, "
10037                                                   "(oprlsortop != 0) AS oprcanmerge, "
10038                                                   "oprcanhash "
10039                                                   "FROM pg_operator "
10040                                                   "WHERE oid = '%u'::oid",
10041                                                   oprinfo->dobj.catId.oid);
10042         }
10043
10044         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10045
10046         i_oprkind = PQfnumber(res, "oprkind");
10047         i_oprcode = PQfnumber(res, "oprcode");
10048         i_oprleft = PQfnumber(res, "oprleft");
10049         i_oprright = PQfnumber(res, "oprright");
10050         i_oprcom = PQfnumber(res, "oprcom");
10051         i_oprnegate = PQfnumber(res, "oprnegate");
10052         i_oprrest = PQfnumber(res, "oprrest");
10053         i_oprjoin = PQfnumber(res, "oprjoin");
10054         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
10055         i_oprcanhash = PQfnumber(res, "oprcanhash");
10056
10057         oprkind = PQgetvalue(res, 0, i_oprkind);
10058         oprcode = PQgetvalue(res, 0, i_oprcode);
10059         oprleft = PQgetvalue(res, 0, i_oprleft);
10060         oprright = PQgetvalue(res, 0, i_oprright);
10061         oprcom = PQgetvalue(res, 0, i_oprcom);
10062         oprnegate = PQgetvalue(res, 0, i_oprnegate);
10063         oprrest = PQgetvalue(res, 0, i_oprrest);
10064         oprjoin = PQgetvalue(res, 0, i_oprjoin);
10065         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
10066         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
10067
10068         appendPQExpBuffer(details, "    PROCEDURE = %s",
10069                                           convertRegProcReference(fout, oprcode));
10070
10071         appendPQExpBuffer(oprid, "%s (",
10072                                           oprinfo->dobj.name);
10073
10074         /*
10075          * right unary means there's a left arg and left unary means there's a
10076          * right arg
10077          */
10078         if (strcmp(oprkind, "r") == 0 ||
10079                 strcmp(oprkind, "b") == 0)
10080         {
10081                 if (fout->remoteVersion >= 70100)
10082                         name = oprleft;
10083                 else
10084                         name = fmtId(oprleft);
10085                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
10086                 appendPQExpBuffer(oprid, "%s", name);
10087         }
10088         else
10089                 appendPQExpBuffer(oprid, "NONE");
10090
10091         if (strcmp(oprkind, "l") == 0 ||
10092                 strcmp(oprkind, "b") == 0)
10093         {
10094                 if (fout->remoteVersion >= 70100)
10095                         name = oprright;
10096                 else
10097                         name = fmtId(oprright);
10098                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
10099                 appendPQExpBuffer(oprid, ", %s)", name);
10100         }
10101         else
10102                 appendPQExpBuffer(oprid, ", NONE)");
10103
10104         name = convertOperatorReference(fout, oprcom);
10105         if (name)
10106                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
10107
10108         name = convertOperatorReference(fout, oprnegate);
10109         if (name)
10110                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
10111
10112         if (strcmp(oprcanmerge, "t") == 0)
10113                 appendPQExpBuffer(details, ",\n    MERGES");
10114
10115         if (strcmp(oprcanhash, "t") == 0)
10116                 appendPQExpBuffer(details, ",\n    HASHES");
10117
10118         name = convertRegProcReference(fout, oprrest);
10119         if (name)
10120                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
10121
10122         name = convertRegProcReference(fout, oprjoin);
10123         if (name)
10124                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
10125
10126         /*
10127          * DROP must be fully qualified in case same name appears in pg_catalog
10128          */
10129         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
10130                                           fmtId(oprinfo->dobj.namespace->dobj.name),
10131                                           oprid->data);
10132
10133         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
10134                                           oprinfo->dobj.name, details->data);
10135
10136         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
10137
10138         if (binary_upgrade)
10139                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
10140
10141         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
10142                                  oprinfo->dobj.name,
10143                                  oprinfo->dobj.namespace->dobj.name,
10144                                  NULL,
10145                                  oprinfo->rolname,
10146                                  false, "OPERATOR", SECTION_PRE_DATA,
10147                                  q->data, delq->data, NULL,
10148                                  NULL, 0,
10149                                  NULL, NULL);
10150
10151         /* Dump Operator Comments */
10152         dumpComment(fout, labelq->data,
10153                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
10154                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
10155
10156         PQclear(res);
10157
10158         destroyPQExpBuffer(query);
10159         destroyPQExpBuffer(q);
10160         destroyPQExpBuffer(delq);
10161         destroyPQExpBuffer(labelq);
10162         destroyPQExpBuffer(oprid);
10163         destroyPQExpBuffer(details);
10164 }
10165
10166 /*
10167  * Convert a function reference obtained from pg_operator
10168  *
10169  * Returns what to print, or NULL if function references is InvalidOid
10170  *
10171  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
10172  * argument-types part.  In prior versions, the input is a REGPROC display.
10173  */
10174 static const char *
10175 convertRegProcReference(Archive *fout, const char *proc)
10176 {
10177         /* In all cases "-" means a null reference */
10178         if (strcmp(proc, "-") == 0)
10179                 return NULL;
10180
10181         if (fout->remoteVersion >= 70300)
10182         {
10183                 char       *name;
10184                 char       *paren;
10185                 bool            inquote;
10186
10187                 name = pg_strdup(proc);
10188                 /* find non-double-quoted left paren */
10189                 inquote = false;
10190                 for (paren = name; *paren; paren++)
10191                 {
10192                         if (*paren == '(' && !inquote)
10193                         {
10194                                 *paren = '\0';
10195                                 break;
10196                         }
10197                         if (*paren == '"')
10198                                 inquote = !inquote;
10199                 }
10200                 return name;
10201         }
10202
10203         /* REGPROC before 7.3 does not quote its result */
10204         return fmtId(proc);
10205 }
10206
10207 /*
10208  * Convert an operator cross-reference obtained from pg_operator
10209  *
10210  * Returns what to print, or NULL to print nothing
10211  *
10212  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10213  * argument-types part, and add OPERATOR() decoration if the name is
10214  * schema-qualified.  In older versions, the input is just a numeric OID,
10215  * which we search our operator list for.
10216  */
10217 static const char *
10218 convertOperatorReference(Archive *fout, const char *opr)
10219 {
10220         OprInfo    *oprInfo;
10221
10222         /* In all cases "0" means a null reference */
10223         if (strcmp(opr, "0") == 0)
10224                 return NULL;
10225
10226         if (fout->remoteVersion >= 70300)
10227         {
10228                 char       *name;
10229                 char       *oname;
10230                 char       *ptr;
10231                 bool            inquote;
10232                 bool            sawdot;
10233
10234                 name = pg_strdup(opr);
10235                 /* find non-double-quoted left paren, and check for non-quoted dot */
10236                 inquote = false;
10237                 sawdot = false;
10238                 for (ptr = name; *ptr; ptr++)
10239                 {
10240                         if (*ptr == '"')
10241                                 inquote = !inquote;
10242                         else if (*ptr == '.' && !inquote)
10243                                 sawdot = true;
10244                         else if (*ptr == '(' && !inquote)
10245                         {
10246                                 *ptr = '\0';
10247                                 break;
10248                         }
10249                 }
10250                 /* If not schema-qualified, don't need to add OPERATOR() */
10251                 if (!sawdot)
10252                         return name;
10253                 oname = pg_malloc(strlen(name) + 11);
10254                 sprintf(oname, "OPERATOR(%s)", name);
10255                 free(name);
10256                 return oname;
10257         }
10258
10259         oprInfo = findOprByOid(atooid(opr));
10260         if (oprInfo == NULL)
10261         {
10262                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10263                                   opr);
10264                 return NULL;
10265         }
10266         return oprInfo->dobj.name;
10267 }
10268
10269 /*
10270  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10271  *
10272  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10273  * argument lists of these functions are predetermined.  Note that the
10274  * caller should ensure we are in the proper schema, because the results
10275  * are search path dependent!
10276  */
10277 static const char *
10278 convertTSFunction(Archive *fout, Oid funcOid)
10279 {
10280         char       *result;
10281         char            query[128];
10282         PGresult   *res;
10283
10284         snprintf(query, sizeof(query),
10285                          "SELECT '%u'::pg_catalog.regproc", funcOid);
10286         res = ExecuteSqlQueryForSingleRow(fout, query);
10287
10288         result = pg_strdup(PQgetvalue(res, 0, 0));
10289
10290         PQclear(res);
10291
10292         return result;
10293 }
10294
10295
10296 /*
10297  * dumpOpclass
10298  *        write out a single operator class definition
10299  */
10300 static void
10301 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10302 {
10303         PQExpBuffer query;
10304         PQExpBuffer q;
10305         PQExpBuffer delq;
10306         PQExpBuffer labelq;
10307         PGresult   *res;
10308         int                     ntups;
10309         int                     i_opcintype;
10310         int                     i_opckeytype;
10311         int                     i_opcdefault;
10312         int                     i_opcfamily;
10313         int                     i_opcfamilyname;
10314         int                     i_opcfamilynsp;
10315         int                     i_amname;
10316         int                     i_amopstrategy;
10317         int                     i_amopreqcheck;
10318         int                     i_amopopr;
10319         int                     i_sortfamily;
10320         int                     i_sortfamilynsp;
10321         int                     i_amprocnum;
10322         int                     i_amproc;
10323         int                     i_amproclefttype;
10324         int                     i_amprocrighttype;
10325         char       *opcintype;
10326         char       *opckeytype;
10327         char       *opcdefault;
10328         char       *opcfamily;
10329         char       *opcfamilyname;
10330         char       *opcfamilynsp;
10331         char       *amname;
10332         char       *amopstrategy;
10333         char       *amopreqcheck;
10334         char       *amopopr;
10335         char       *sortfamily;
10336         char       *sortfamilynsp;
10337         char       *amprocnum;
10338         char       *amproc;
10339         char       *amproclefttype;
10340         char       *amprocrighttype;
10341         bool            needComma;
10342         int                     i;
10343
10344         /* Skip if not to be dumped */
10345         if (!opcinfo->dobj.dump || dataOnly)
10346                 return;
10347
10348         /*
10349          * XXX currently we do not implement dumping of operator classes from
10350          * pre-7.3 databases.  This could be done but it seems not worth the
10351          * trouble.
10352          */
10353         if (fout->remoteVersion < 70300)
10354                 return;
10355
10356         query = createPQExpBuffer();
10357         q = createPQExpBuffer();
10358         delq = createPQExpBuffer();
10359         labelq = createPQExpBuffer();
10360
10361         /* Make sure we are in proper schema so regoperator works correctly */
10362         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10363
10364         /* Get additional fields from the pg_opclass row */
10365         if (fout->remoteVersion >= 80300)
10366         {
10367                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10368                                                   "opckeytype::pg_catalog.regtype, "
10369                                                   "opcdefault, opcfamily, "
10370                                                   "opfname AS opcfamilyname, "
10371                                                   "nspname AS opcfamilynsp, "
10372                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10373                                                   "FROM pg_catalog.pg_opclass c "
10374                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10375                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10376                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
10377                                                   opcinfo->dobj.catId.oid);
10378         }
10379         else
10380         {
10381                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10382                                                   "opckeytype::pg_catalog.regtype, "
10383                                                   "opcdefault, NULL AS opcfamily, "
10384                                                   "NULL AS opcfamilyname, "
10385                                                   "NULL AS opcfamilynsp, "
10386                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10387                                                   "FROM pg_catalog.pg_opclass "
10388                                                   "WHERE oid = '%u'::pg_catalog.oid",
10389                                                   opcinfo->dobj.catId.oid);
10390         }
10391
10392         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10393
10394         i_opcintype = PQfnumber(res, "opcintype");
10395         i_opckeytype = PQfnumber(res, "opckeytype");
10396         i_opcdefault = PQfnumber(res, "opcdefault");
10397         i_opcfamily = PQfnumber(res, "opcfamily");
10398         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10399         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10400         i_amname = PQfnumber(res, "amname");
10401
10402         opcintype = PQgetvalue(res, 0, i_opcintype);
10403         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10404         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10405         /* opcfamily will still be needed after we PQclear res */
10406         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10407         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10408         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10409         /* amname will still be needed after we PQclear res */
10410         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10411
10412         /*
10413          * DROP must be fully qualified in case same name appears in pg_catalog
10414          */
10415         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10416                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10417         appendPQExpBuffer(delq, ".%s",
10418                                           fmtId(opcinfo->dobj.name));
10419         appendPQExpBuffer(delq, " USING %s;\n",
10420                                           fmtId(amname));
10421
10422         /* Build the fixed portion of the CREATE command */
10423         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10424                                           fmtId(opcinfo->dobj.name));
10425         if (strcmp(opcdefault, "t") == 0)
10426                 appendPQExpBuffer(q, "DEFAULT ");
10427         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10428                                           opcintype,
10429                                           fmtId(amname));
10430         if (strlen(opcfamilyname) > 0 &&
10431                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10432                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10433         {
10434                 appendPQExpBuffer(q, " FAMILY ");
10435                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10436                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10437                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10438         }
10439         appendPQExpBuffer(q, " AS\n    ");
10440
10441         needComma = false;
10442
10443         if (strcmp(opckeytype, "-") != 0)
10444         {
10445                 appendPQExpBuffer(q, "STORAGE %s",
10446                                                   opckeytype);
10447                 needComma = true;
10448         }
10449
10450         PQclear(res);
10451
10452         /*
10453          * Now fetch and print the OPERATOR entries (pg_amop rows).
10454          *
10455          * Print only those opfamily members that are tied to the opclass by
10456          * pg_depend entries.
10457          *
10458          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10459          * older server's opclass in which it is used.  This is to avoid
10460          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10461          * older server and then reload into that old version.  This can go away
10462          * once 8.3 is so old as to not be of interest to anyone.
10463          */
10464         resetPQExpBuffer(query);
10465
10466         if (fout->remoteVersion >= 90100)
10467         {
10468                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10469                                                   "amopopr::pg_catalog.regoperator, "
10470                                                   "opfname AS sortfamily, "
10471                                                   "nspname AS sortfamilynsp "
10472                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10473                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10474                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10475                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10476                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10477                                                   "AND refobjid = '%u'::pg_catalog.oid "
10478                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10479                                                   "ORDER BY amopstrategy",
10480                                                   opcinfo->dobj.catId.oid,
10481                                                   opcfamily);
10482         }
10483         else if (fout->remoteVersion >= 80400)
10484         {
10485                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10486                                                   "amopopr::pg_catalog.regoperator, "
10487                                                   "NULL AS sortfamily, "
10488                                                   "NULL AS sortfamilynsp "
10489                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10490                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10491                                                   "AND refobjid = '%u'::pg_catalog.oid "
10492                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10493                                                   "AND objid = ao.oid "
10494                                                   "ORDER BY amopstrategy",
10495                                                   opcinfo->dobj.catId.oid);
10496         }
10497         else if (fout->remoteVersion >= 80300)
10498         {
10499                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10500                                                   "amopopr::pg_catalog.regoperator, "
10501                                                   "NULL AS sortfamily, "
10502                                                   "NULL AS sortfamilynsp "
10503                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10504                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10505                                                   "AND refobjid = '%u'::pg_catalog.oid "
10506                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10507                                                   "AND objid = ao.oid "
10508                                                   "ORDER BY amopstrategy",
10509                                                   opcinfo->dobj.catId.oid);
10510         }
10511         else
10512         {
10513                 /*
10514                  * Here, we print all entries since there are no opfamilies and hence
10515                  * no loose operators to worry about.
10516                  */
10517                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10518                                                   "amopopr::pg_catalog.regoperator, "
10519                                                   "NULL AS sortfamily, "
10520                                                   "NULL AS sortfamilynsp "
10521                                                   "FROM pg_catalog.pg_amop "
10522                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10523                                                   "ORDER BY amopstrategy",
10524                                                   opcinfo->dobj.catId.oid);
10525         }
10526
10527         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10528
10529         ntups = PQntuples(res);
10530
10531         i_amopstrategy = PQfnumber(res, "amopstrategy");
10532         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10533         i_amopopr = PQfnumber(res, "amopopr");
10534         i_sortfamily = PQfnumber(res, "sortfamily");
10535         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10536
10537         for (i = 0; i < ntups; i++)
10538         {
10539                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10540                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10541                 amopopr = PQgetvalue(res, i, i_amopopr);
10542                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10543                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10544
10545                 if (needComma)
10546                         appendPQExpBuffer(q, " ,\n    ");
10547
10548                 appendPQExpBuffer(q, "OPERATOR %s %s",
10549                                                   amopstrategy, amopopr);
10550
10551                 if (strlen(sortfamily) > 0)
10552                 {
10553                         appendPQExpBuffer(q, " FOR ORDER BY ");
10554                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10555                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10556                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10557                 }
10558
10559                 if (strcmp(amopreqcheck, "t") == 0)
10560                         appendPQExpBuffer(q, " RECHECK");
10561
10562                 needComma = true;
10563         }
10564
10565         PQclear(res);
10566
10567         /*
10568          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10569          *
10570          * Print only those opfamily members that are tied to the opclass by
10571          * pg_depend entries.
10572          *
10573          * We print the amproclefttype/amprocrighttype even though in most cases
10574          * the backend could deduce the right values, because of the corner case
10575          * of a btree sort support function for a cross-type comparison.  That's
10576          * only allowed in 9.2 and later, but for simplicity print them in all
10577          * versions that have the columns.
10578          */
10579         resetPQExpBuffer(query);
10580
10581         if (fout->remoteVersion >= 80300)
10582         {
10583                 appendPQExpBuffer(query, "SELECT amprocnum, "
10584                                                   "amproc::pg_catalog.regprocedure, "
10585                                                   "amproclefttype::pg_catalog.regtype, "
10586                                                   "amprocrighttype::pg_catalog.regtype "
10587                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10588                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10589                                                   "AND refobjid = '%u'::pg_catalog.oid "
10590                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10591                                                   "AND objid = ap.oid "
10592                                                   "ORDER BY amprocnum",
10593                                                   opcinfo->dobj.catId.oid);
10594         }
10595         else
10596         {
10597                 appendPQExpBuffer(query, "SELECT amprocnum, "
10598                                                   "amproc::pg_catalog.regprocedure, "
10599                                                   "'' AS amproclefttype, "
10600                                                   "'' AS amprocrighttype "
10601                                                   "FROM pg_catalog.pg_amproc "
10602                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10603                                                   "ORDER BY amprocnum",
10604                                                   opcinfo->dobj.catId.oid);
10605         }
10606
10607         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10608
10609         ntups = PQntuples(res);
10610
10611         i_amprocnum = PQfnumber(res, "amprocnum");
10612         i_amproc = PQfnumber(res, "amproc");
10613         i_amproclefttype = PQfnumber(res, "amproclefttype");
10614         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10615
10616         for (i = 0; i < ntups; i++)
10617         {
10618                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10619                 amproc = PQgetvalue(res, i, i_amproc);
10620                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10621                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10622
10623                 if (needComma)
10624                         appendPQExpBuffer(q, " ,\n    ");
10625
10626                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10627
10628                 if (*amproclefttype && *amprocrighttype)
10629                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10630
10631                 appendPQExpBuffer(q, " %s", amproc);
10632
10633                 needComma = true;
10634         }
10635
10636         PQclear(res);
10637
10638         appendPQExpBuffer(q, ";\n");
10639
10640         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10641                                           fmtId(opcinfo->dobj.name));
10642         appendPQExpBuffer(labelq, " USING %s",
10643                                           fmtId(amname));
10644
10645         if (binary_upgrade)
10646                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10647
10648         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10649                                  opcinfo->dobj.name,
10650                                  opcinfo->dobj.namespace->dobj.name,
10651                                  NULL,
10652                                  opcinfo->rolname,
10653                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10654                                  q->data, delq->data, NULL,
10655                                  NULL, 0,
10656                                  NULL, NULL);
10657
10658         /* Dump Operator Class Comments */
10659         dumpComment(fout, labelq->data,
10660                                 NULL, opcinfo->rolname,
10661                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10662
10663         free(amname);
10664         destroyPQExpBuffer(query);
10665         destroyPQExpBuffer(q);
10666         destroyPQExpBuffer(delq);
10667         destroyPQExpBuffer(labelq);
10668 }
10669
10670 /*
10671  * dumpOpfamily
10672  *        write out a single operator family definition
10673  *
10674  * Note: this also dumps any "loose" operator members that aren't bound to a
10675  * specific opclass within the opfamily.
10676  */
10677 static void
10678 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10679 {
10680         PQExpBuffer query;
10681         PQExpBuffer q;
10682         PQExpBuffer delq;
10683         PQExpBuffer labelq;
10684         PGresult   *res;
10685         PGresult   *res_ops;
10686         PGresult   *res_procs;
10687         int                     ntups;
10688         int                     i_amname;
10689         int                     i_amopstrategy;
10690         int                     i_amopreqcheck;
10691         int                     i_amopopr;
10692         int                     i_sortfamily;
10693         int                     i_sortfamilynsp;
10694         int                     i_amprocnum;
10695         int                     i_amproc;
10696         int                     i_amproclefttype;
10697         int                     i_amprocrighttype;
10698         char       *amname;
10699         char       *amopstrategy;
10700         char       *amopreqcheck;
10701         char       *amopopr;
10702         char       *sortfamily;
10703         char       *sortfamilynsp;
10704         char       *amprocnum;
10705         char       *amproc;
10706         char       *amproclefttype;
10707         char       *amprocrighttype;
10708         bool            needComma;
10709         int                     i;
10710
10711         /* Skip if not to be dumped */
10712         if (!opfinfo->dobj.dump || dataOnly)
10713                 return;
10714
10715         /*
10716          * We want to dump the opfamily only if (1) it contains "loose" operators
10717          * or functions, or (2) it contains an opclass with a different name or
10718          * owner.  Otherwise it's sufficient to let it be created during creation
10719          * of the contained opclass, and not dumping it improves portability of
10720          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10721          * that first.
10722          */
10723
10724         query = createPQExpBuffer();
10725         q = createPQExpBuffer();
10726         delq = createPQExpBuffer();
10727         labelq = createPQExpBuffer();
10728
10729         /* Make sure we are in proper schema so regoperator works correctly */
10730         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10731
10732         /*
10733          * Fetch only those opfamily members that are tied directly to the
10734          * opfamily by pg_depend entries.
10735          *
10736          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10737          * older server's opclass in which it is used.  This is to avoid
10738          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10739          * older server and then reload into that old version.  This can go away
10740          * once 8.3 is so old as to not be of interest to anyone.
10741          */
10742         if (fout->remoteVersion >= 90100)
10743         {
10744                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10745                                                   "amopopr::pg_catalog.regoperator, "
10746                                                   "opfname AS sortfamily, "
10747                                                   "nspname AS sortfamilynsp "
10748                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10749                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10750                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10751                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10752                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10753                                                   "AND refobjid = '%u'::pg_catalog.oid "
10754                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10755                                                   "ORDER BY amopstrategy",
10756                                                   opfinfo->dobj.catId.oid,
10757                                                   opfinfo->dobj.catId.oid);
10758         }
10759         else if (fout->remoteVersion >= 80400)
10760         {
10761                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10762                                                   "amopopr::pg_catalog.regoperator, "
10763                                                   "NULL AS sortfamily, "
10764                                                   "NULL AS sortfamilynsp "
10765                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10766                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10767                                                   "AND refobjid = '%u'::pg_catalog.oid "
10768                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10769                                                   "AND objid = ao.oid "
10770                                                   "ORDER BY amopstrategy",
10771                                                   opfinfo->dobj.catId.oid);
10772         }
10773         else
10774         {
10775                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10776                                                   "amopopr::pg_catalog.regoperator, "
10777                                                   "NULL AS sortfamily, "
10778                                                   "NULL AS sortfamilynsp "
10779                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10780                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10781                                                   "AND refobjid = '%u'::pg_catalog.oid "
10782                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10783                                                   "AND objid = ao.oid "
10784                                                   "ORDER BY amopstrategy",
10785                                                   opfinfo->dobj.catId.oid);
10786         }
10787
10788         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10789
10790         resetPQExpBuffer(query);
10791
10792         appendPQExpBuffer(query, "SELECT amprocnum, "
10793                                           "amproc::pg_catalog.regprocedure, "
10794                                           "amproclefttype::pg_catalog.regtype, "
10795                                           "amprocrighttype::pg_catalog.regtype "
10796                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10797                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10798                                           "AND refobjid = '%u'::pg_catalog.oid "
10799                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10800                                           "AND objid = ap.oid "
10801                                           "ORDER BY amprocnum",
10802                                           opfinfo->dobj.catId.oid);
10803
10804         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10805
10806         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10807         {
10808                 /* No loose members, so check contained opclasses */
10809                 resetPQExpBuffer(query);
10810
10811                 appendPQExpBuffer(query, "SELECT 1 "
10812                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10813                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10814                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10815                                                   "AND refobjid = f.oid "
10816                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10817                                                   "AND objid = c.oid "
10818                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10819                                                   "LIMIT 1",
10820                                                   opfinfo->dobj.catId.oid);
10821
10822                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10823
10824                 if (PQntuples(res) == 0)
10825                 {
10826                         /* no need to dump it, so bail out */
10827                         PQclear(res);
10828                         PQclear(res_ops);
10829                         PQclear(res_procs);
10830                         destroyPQExpBuffer(query);
10831                         destroyPQExpBuffer(q);
10832                         destroyPQExpBuffer(delq);
10833                         destroyPQExpBuffer(labelq);
10834                         return;
10835                 }
10836
10837                 PQclear(res);
10838         }
10839
10840         /* Get additional fields from the pg_opfamily row */
10841         resetPQExpBuffer(query);
10842
10843         appendPQExpBuffer(query, "SELECT "
10844          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10845                                           "FROM pg_catalog.pg_opfamily "
10846                                           "WHERE oid = '%u'::pg_catalog.oid",
10847                                           opfinfo->dobj.catId.oid);
10848
10849         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10850
10851         i_amname = PQfnumber(res, "amname");
10852
10853         /* amname will still be needed after we PQclear res */
10854         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10855
10856         /*
10857          * DROP must be fully qualified in case same name appears in pg_catalog
10858          */
10859         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10860                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10861         appendPQExpBuffer(delq, ".%s",
10862                                           fmtId(opfinfo->dobj.name));
10863         appendPQExpBuffer(delq, " USING %s;\n",
10864                                           fmtId(amname));
10865
10866         /* Build the fixed portion of the CREATE command */
10867         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10868                                           fmtId(opfinfo->dobj.name));
10869         appendPQExpBuffer(q, " USING %s;\n",
10870                                           fmtId(amname));
10871
10872         PQclear(res);
10873
10874         /* Do we need an ALTER to add loose members? */
10875         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10876         {
10877                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10878                                                   fmtId(opfinfo->dobj.name));
10879                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10880                                                   fmtId(amname));
10881
10882                 needComma = false;
10883
10884                 /*
10885                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10886                  */
10887                 ntups = PQntuples(res_ops);
10888
10889                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10890                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10891                 i_amopopr = PQfnumber(res_ops, "amopopr");
10892                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10893                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10894
10895                 for (i = 0; i < ntups; i++)
10896                 {
10897                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10898                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10899                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10900                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10901                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10902
10903                         if (needComma)
10904                                 appendPQExpBuffer(q, " ,\n    ");
10905
10906                         appendPQExpBuffer(q, "OPERATOR %s %s",
10907                                                           amopstrategy, amopopr);
10908
10909                         if (strlen(sortfamily) > 0)
10910                         {
10911                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10912                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10913                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10914                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10915                         }
10916
10917                         if (strcmp(amopreqcheck, "t") == 0)
10918                                 appendPQExpBuffer(q, " RECHECK");
10919
10920                         needComma = true;
10921                 }
10922
10923                 /*
10924                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10925                  */
10926                 ntups = PQntuples(res_procs);
10927
10928                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10929                 i_amproc = PQfnumber(res_procs, "amproc");
10930                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10931                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10932
10933                 for (i = 0; i < ntups; i++)
10934                 {
10935                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10936                         amproc = PQgetvalue(res_procs, i, i_amproc);
10937                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10938                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10939
10940                         if (needComma)
10941                                 appendPQExpBuffer(q, " ,\n    ");
10942
10943                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10944                                                           amprocnum, amproclefttype, amprocrighttype,
10945                                                           amproc);
10946
10947                         needComma = true;
10948                 }
10949
10950                 appendPQExpBuffer(q, ";\n");
10951         }
10952
10953         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10954                                           fmtId(opfinfo->dobj.name));
10955         appendPQExpBuffer(labelq, " USING %s",
10956                                           fmtId(amname));
10957
10958         if (binary_upgrade)
10959                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10960
10961         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10962                                  opfinfo->dobj.name,
10963                                  opfinfo->dobj.namespace->dobj.name,
10964                                  NULL,
10965                                  opfinfo->rolname,
10966                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10967                                  q->data, delq->data, NULL,
10968                                  NULL, 0,
10969                                  NULL, NULL);
10970
10971         /* Dump Operator Family Comments */
10972         dumpComment(fout, labelq->data,
10973                                 NULL, opfinfo->rolname,
10974                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10975
10976         free(amname);
10977         PQclear(res_ops);
10978         PQclear(res_procs);
10979         destroyPQExpBuffer(query);
10980         destroyPQExpBuffer(q);
10981         destroyPQExpBuffer(delq);
10982         destroyPQExpBuffer(labelq);
10983 }
10984
10985 /*
10986  * dumpCollation
10987  *        write out a single collation definition
10988  */
10989 static void
10990 dumpCollation(Archive *fout, CollInfo *collinfo)
10991 {
10992         PQExpBuffer query;
10993         PQExpBuffer q;
10994         PQExpBuffer delq;
10995         PQExpBuffer labelq;
10996         PGresult   *res;
10997         int                     i_collcollate;
10998         int                     i_collctype;
10999         const char *collcollate;
11000         const char *collctype;
11001
11002         /* Skip if not to be dumped */
11003         if (!collinfo->dobj.dump || dataOnly)
11004                 return;
11005
11006         query = createPQExpBuffer();
11007         q = createPQExpBuffer();
11008         delq = createPQExpBuffer();
11009         labelq = createPQExpBuffer();
11010
11011         /* Make sure we are in proper schema */
11012         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
11013
11014         /* Get conversion-specific details */
11015         appendPQExpBuffer(query, "SELECT "
11016                                           "collcollate, "
11017                                           "collctype "
11018                                           "FROM pg_catalog.pg_collation c "
11019                                           "WHERE c.oid = '%u'::pg_catalog.oid",
11020                                           collinfo->dobj.catId.oid);
11021
11022         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11023
11024         i_collcollate = PQfnumber(res, "collcollate");
11025         i_collctype = PQfnumber(res, "collctype");
11026
11027         collcollate = PQgetvalue(res, 0, i_collcollate);
11028         collctype = PQgetvalue(res, 0, i_collctype);
11029
11030         /*
11031          * DROP must be fully qualified in case same name appears in pg_catalog
11032          */
11033         appendPQExpBuffer(delq, "DROP COLLATION %s",
11034                                           fmtId(collinfo->dobj.namespace->dobj.name));
11035         appendPQExpBuffer(delq, ".%s;\n",
11036                                           fmtId(collinfo->dobj.name));
11037
11038         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
11039                                           fmtId(collinfo->dobj.name));
11040         appendStringLiteralAH(q, collcollate, fout);
11041         appendPQExpBuffer(q, ", lc_ctype = ");
11042         appendStringLiteralAH(q, collctype, fout);
11043         appendPQExpBuffer(q, ");\n");
11044
11045         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
11046
11047         if (binary_upgrade)
11048                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
11049
11050         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
11051                                  collinfo->dobj.name,
11052                                  collinfo->dobj.namespace->dobj.name,
11053                                  NULL,
11054                                  collinfo->rolname,
11055                                  false, "COLLATION", SECTION_PRE_DATA,
11056                                  q->data, delq->data, NULL,
11057                                  NULL, 0,
11058                                  NULL, NULL);
11059
11060         /* Dump Collation Comments */
11061         dumpComment(fout, labelq->data,
11062                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
11063                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
11064
11065         PQclear(res);
11066
11067         destroyPQExpBuffer(query);
11068         destroyPQExpBuffer(q);
11069         destroyPQExpBuffer(delq);
11070         destroyPQExpBuffer(labelq);
11071 }
11072
11073 /*
11074  * dumpConversion
11075  *        write out a single conversion definition
11076  */
11077 static void
11078 dumpConversion(Archive *fout, ConvInfo *convinfo)
11079 {
11080         PQExpBuffer query;
11081         PQExpBuffer q;
11082         PQExpBuffer delq;
11083         PQExpBuffer labelq;
11084         PGresult   *res;
11085         int                     i_conforencoding;
11086         int                     i_contoencoding;
11087         int                     i_conproc;
11088         int                     i_condefault;
11089         const char *conforencoding;
11090         const char *contoencoding;
11091         const char *conproc;
11092         bool            condefault;
11093
11094         /* Skip if not to be dumped */
11095         if (!convinfo->dobj.dump || dataOnly)
11096                 return;
11097
11098         query = createPQExpBuffer();
11099         q = createPQExpBuffer();
11100         delq = createPQExpBuffer();
11101         labelq = createPQExpBuffer();
11102
11103         /* Make sure we are in proper schema */
11104         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
11105
11106         /* Get conversion-specific details */
11107         appendPQExpBuffer(query, "SELECT "
11108                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
11109                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
11110                                           "conproc, condefault "
11111                                           "FROM pg_catalog.pg_conversion c "
11112                                           "WHERE c.oid = '%u'::pg_catalog.oid",
11113                                           convinfo->dobj.catId.oid);
11114
11115         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11116
11117         i_conforencoding = PQfnumber(res, "conforencoding");
11118         i_contoencoding = PQfnumber(res, "contoencoding");
11119         i_conproc = PQfnumber(res, "conproc");
11120         i_condefault = PQfnumber(res, "condefault");
11121
11122         conforencoding = PQgetvalue(res, 0, i_conforencoding);
11123         contoencoding = PQgetvalue(res, 0, i_contoencoding);
11124         conproc = PQgetvalue(res, 0, i_conproc);
11125         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
11126
11127         /*
11128          * DROP must be fully qualified in case same name appears in pg_catalog
11129          */
11130         appendPQExpBuffer(delq, "DROP CONVERSION %s",
11131                                           fmtId(convinfo->dobj.namespace->dobj.name));
11132         appendPQExpBuffer(delq, ".%s;\n",
11133                                           fmtId(convinfo->dobj.name));
11134
11135         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
11136                                           (condefault) ? "DEFAULT " : "",
11137                                           fmtId(convinfo->dobj.name));
11138         appendStringLiteralAH(q, conforencoding, fout);
11139         appendPQExpBuffer(q, " TO ");
11140         appendStringLiteralAH(q, contoencoding, fout);
11141         /* regproc is automatically quoted in 7.3 and above */
11142         appendPQExpBuffer(q, " FROM %s;\n", conproc);
11143
11144         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
11145
11146         if (binary_upgrade)
11147                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
11148
11149         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
11150                                  convinfo->dobj.name,
11151                                  convinfo->dobj.namespace->dobj.name,
11152                                  NULL,
11153                                  convinfo->rolname,
11154                                  false, "CONVERSION", SECTION_PRE_DATA,
11155                                  q->data, delq->data, NULL,
11156                                  NULL, 0,
11157                                  NULL, NULL);
11158
11159         /* Dump Conversion Comments */
11160         dumpComment(fout, labelq->data,
11161                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
11162                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
11163
11164         PQclear(res);
11165
11166         destroyPQExpBuffer(query);
11167         destroyPQExpBuffer(q);
11168         destroyPQExpBuffer(delq);
11169         destroyPQExpBuffer(labelq);
11170 }
11171
11172 /*
11173  * format_aggregate_signature: generate aggregate name and argument list
11174  *
11175  * The argument type names are qualified if needed.  The aggregate name
11176  * is never qualified.
11177  */
11178 static char *
11179 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11180 {
11181         PQExpBufferData buf;
11182         int                     j;
11183
11184         initPQExpBuffer(&buf);
11185         if (honor_quotes)
11186                 appendPQExpBuffer(&buf, "%s",
11187                                                   fmtId(agginfo->aggfn.dobj.name));
11188         else
11189                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11190
11191         if (agginfo->aggfn.nargs == 0)
11192                 appendPQExpBuffer(&buf, "(*)");
11193         else
11194         {
11195                 appendPQExpBuffer(&buf, "(");
11196                 for (j = 0; j < agginfo->aggfn.nargs; j++)
11197                 {
11198                         char       *typname;
11199
11200                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11201                                                                                    zeroAsOpaque);
11202
11203                         appendPQExpBuffer(&buf, "%s%s",
11204                                                           (j > 0) ? ", " : "",
11205                                                           typname);
11206                         free(typname);
11207                 }
11208                 appendPQExpBuffer(&buf, ")");
11209         }
11210         return buf.data;
11211 }
11212
11213 /*
11214  * dumpAgg
11215  *        write out a single aggregate definition
11216  */
11217 static void
11218 dumpAgg(Archive *fout, AggInfo *agginfo)
11219 {
11220         PQExpBuffer query;
11221         PQExpBuffer q;
11222         PQExpBuffer delq;
11223         PQExpBuffer labelq;
11224         PQExpBuffer details;
11225         char       *aggsig;
11226         char       *aggsig_tag;
11227         PGresult   *res;
11228         int                     i_aggtransfn;
11229         int                     i_aggfinalfn;
11230         int                     i_aggsortop;
11231         int                     i_aggtranstype;
11232         int                     i_agginitval;
11233         int                     i_convertok;
11234         const char *aggtransfn;
11235         const char *aggfinalfn;
11236         const char *aggsortop;
11237         const char *aggtranstype;
11238         const char *agginitval;
11239         bool            convertok;
11240
11241         /* Skip if not to be dumped */
11242         if (!agginfo->aggfn.dobj.dump || dataOnly)
11243                 return;
11244
11245         query = createPQExpBuffer();
11246         q = createPQExpBuffer();
11247         delq = createPQExpBuffer();
11248         labelq = createPQExpBuffer();
11249         details = createPQExpBuffer();
11250
11251         /* Make sure we are in proper schema */
11252         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11253
11254         /* Get aggregate-specific details */
11255         if (fout->remoteVersion >= 80100)
11256         {
11257                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11258                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11259                                                   "aggsortop::pg_catalog.regoperator, "
11260                                                   "agginitval, "
11261                                                   "'t'::boolean AS convertok "
11262                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11263                                                   "WHERE a.aggfnoid = p.oid "
11264                                                   "AND p.oid = '%u'::pg_catalog.oid",
11265                                                   agginfo->aggfn.dobj.catId.oid);
11266         }
11267         else if (fout->remoteVersion >= 70300)
11268         {
11269                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11270                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11271                                                   "0 AS aggsortop, "
11272                                                   "agginitval, "
11273                                                   "'t'::boolean AS convertok "
11274                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11275                                                   "WHERE a.aggfnoid = p.oid "
11276                                                   "AND p.oid = '%u'::pg_catalog.oid",
11277                                                   agginfo->aggfn.dobj.catId.oid);
11278         }
11279         else if (fout->remoteVersion >= 70100)
11280         {
11281                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11282                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
11283                                                   "0 AS aggsortop, "
11284                                                   "agginitval, "
11285                                                   "'t'::boolean AS convertok "
11286                                                   "FROM pg_aggregate "
11287                                                   "WHERE oid = '%u'::oid",
11288                                                   agginfo->aggfn.dobj.catId.oid);
11289         }
11290         else
11291         {
11292                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11293                                                   "aggfinalfn, "
11294                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11295                                                   "0 AS aggsortop, "
11296                                                   "agginitval1 AS agginitval, "
11297                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11298                                                   "FROM pg_aggregate "
11299                                                   "WHERE oid = '%u'::oid",
11300                                                   agginfo->aggfn.dobj.catId.oid);
11301         }
11302
11303         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11304
11305         i_aggtransfn = PQfnumber(res, "aggtransfn");
11306         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11307         i_aggsortop = PQfnumber(res, "aggsortop");
11308         i_aggtranstype = PQfnumber(res, "aggtranstype");
11309         i_agginitval = PQfnumber(res, "agginitval");
11310         i_convertok = PQfnumber(res, "convertok");
11311
11312         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11313         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11314         aggsortop = PQgetvalue(res, 0, i_aggsortop);
11315         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11316         agginitval = PQgetvalue(res, 0, i_agginitval);
11317         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11318
11319         aggsig = format_aggregate_signature(agginfo, fout, true);
11320         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11321
11322         if (!convertok)
11323         {
11324                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11325                                   aggsig);
11326                 return;
11327         }
11328
11329         if (fout->remoteVersion >= 70300)
11330         {
11331                 /* If using 7.3's regproc or regtype, data is already quoted */
11332                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11333                                                   aggtransfn,
11334                                                   aggtranstype);
11335         }
11336         else if (fout->remoteVersion >= 70100)
11337         {
11338                 /* format_type quotes, regproc does not */
11339                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11340                                                   fmtId(aggtransfn),
11341                                                   aggtranstype);
11342         }
11343         else
11344         {
11345                 /* need quotes all around */
11346                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
11347                                                   fmtId(aggtransfn));
11348                 appendPQExpBuffer(details, "    STYPE = %s",
11349                                                   fmtId(aggtranstype));
11350         }
11351
11352         if (!PQgetisnull(res, 0, i_agginitval))
11353         {
11354                 appendPQExpBuffer(details, ",\n    INITCOND = ");
11355                 appendStringLiteralAH(details, agginitval, fout);
11356         }
11357
11358         if (strcmp(aggfinalfn, "-") != 0)
11359         {
11360                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
11361                                                   aggfinalfn);
11362         }
11363
11364         aggsortop = convertOperatorReference(fout, aggsortop);
11365         if (aggsortop)
11366         {
11367                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
11368                                                   aggsortop);
11369         }
11370
11371         /*
11372          * DROP must be fully qualified in case same name appears in pg_catalog
11373          */
11374         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11375                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11376                                           aggsig);
11377
11378         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11379                                           aggsig, details->data);
11380
11381         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11382
11383         if (binary_upgrade)
11384                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11385
11386         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11387                                  aggsig_tag,
11388                                  agginfo->aggfn.dobj.namespace->dobj.name,
11389                                  NULL,
11390                                  agginfo->aggfn.rolname,
11391                                  false, "AGGREGATE", SECTION_PRE_DATA,
11392                                  q->data, delq->data, NULL,
11393                                  NULL, 0,
11394                                  NULL, NULL);
11395
11396         /* Dump Aggregate Comments */
11397         dumpComment(fout, labelq->data,
11398                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11399                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11400         dumpSecLabel(fout, labelq->data,
11401                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11402                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11403
11404         /*
11405          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11406          * command look like a function's GRANT; in particular this affects the
11407          * syntax for zero-argument aggregates.
11408          */
11409         free(aggsig);
11410         free(aggsig_tag);
11411
11412         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11413         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11414
11415         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11416                         "FUNCTION",
11417                         aggsig, NULL, aggsig_tag,
11418                         agginfo->aggfn.dobj.namespace->dobj.name,
11419                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11420
11421         free(aggsig);
11422         free(aggsig_tag);
11423
11424         PQclear(res);
11425
11426         destroyPQExpBuffer(query);
11427         destroyPQExpBuffer(q);
11428         destroyPQExpBuffer(delq);
11429         destroyPQExpBuffer(labelq);
11430         destroyPQExpBuffer(details);
11431 }
11432
11433 /*
11434  * dumpTSParser
11435  *        write out a single text search parser
11436  */
11437 static void
11438 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11439 {
11440         PQExpBuffer q;
11441         PQExpBuffer delq;
11442         PQExpBuffer labelq;
11443
11444         /* Skip if not to be dumped */
11445         if (!prsinfo->dobj.dump || dataOnly)
11446                 return;
11447
11448         q = createPQExpBuffer();
11449         delq = createPQExpBuffer();
11450         labelq = createPQExpBuffer();
11451
11452         /* Make sure we are in proper schema */
11453         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11454
11455         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11456                                           fmtId(prsinfo->dobj.name));
11457
11458         appendPQExpBuffer(q, "    START = %s,\n",
11459                                           convertTSFunction(fout, prsinfo->prsstart));
11460         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11461                                           convertTSFunction(fout, prsinfo->prstoken));
11462         appendPQExpBuffer(q, "    END = %s,\n",
11463                                           convertTSFunction(fout, prsinfo->prsend));
11464         if (prsinfo->prsheadline != InvalidOid)
11465                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11466                                                   convertTSFunction(fout, prsinfo->prsheadline));
11467         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11468                                           convertTSFunction(fout, prsinfo->prslextype));
11469
11470         /*
11471          * DROP must be fully qualified in case same name appears in pg_catalog
11472          */
11473         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11474                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11475         appendPQExpBuffer(delq, ".%s;\n",
11476                                           fmtId(prsinfo->dobj.name));
11477
11478         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11479                                           fmtId(prsinfo->dobj.name));
11480
11481         if (binary_upgrade)
11482                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11483
11484         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11485                                  prsinfo->dobj.name,
11486                                  prsinfo->dobj.namespace->dobj.name,
11487                                  NULL,
11488                                  "",
11489                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11490                                  q->data, delq->data, NULL,
11491                                  NULL, 0,
11492                                  NULL, NULL);
11493
11494         /* Dump Parser Comments */
11495         dumpComment(fout, labelq->data,
11496                                 NULL, "",
11497                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11498
11499         destroyPQExpBuffer(q);
11500         destroyPQExpBuffer(delq);
11501         destroyPQExpBuffer(labelq);
11502 }
11503
11504 /*
11505  * dumpTSDictionary
11506  *        write out a single text search dictionary
11507  */
11508 static void
11509 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11510 {
11511         PQExpBuffer q;
11512         PQExpBuffer delq;
11513         PQExpBuffer labelq;
11514         PQExpBuffer query;
11515         PGresult   *res;
11516         char       *nspname;
11517         char       *tmplname;
11518
11519         /* Skip if not to be dumped */
11520         if (!dictinfo->dobj.dump || dataOnly)
11521                 return;
11522
11523         q = createPQExpBuffer();
11524         delq = createPQExpBuffer();
11525         labelq = createPQExpBuffer();
11526         query = createPQExpBuffer();
11527
11528         /* Fetch name and namespace of the dictionary's template */
11529         selectSourceSchema(fout, "pg_catalog");
11530         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11531                                           "FROM pg_ts_template p, pg_namespace n "
11532                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11533                                           dictinfo->dicttemplate);
11534         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11535         nspname = PQgetvalue(res, 0, 0);
11536         tmplname = PQgetvalue(res, 0, 1);
11537
11538         /* Make sure we are in proper schema */
11539         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11540
11541         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11542                                           fmtId(dictinfo->dobj.name));
11543
11544         appendPQExpBuffer(q, "    TEMPLATE = ");
11545         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11546                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11547         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11548
11549         PQclear(res);
11550
11551         /* the dictinitoption can be dumped straight into the command */
11552         if (dictinfo->dictinitoption)
11553                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11554
11555         appendPQExpBuffer(q, " );\n");
11556
11557         /*
11558          * DROP must be fully qualified in case same name appears in pg_catalog
11559          */
11560         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11561                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11562         appendPQExpBuffer(delq, ".%s;\n",
11563                                           fmtId(dictinfo->dobj.name));
11564
11565         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11566                                           fmtId(dictinfo->dobj.name));
11567
11568         if (binary_upgrade)
11569                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11570
11571         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11572                                  dictinfo->dobj.name,
11573                                  dictinfo->dobj.namespace->dobj.name,
11574                                  NULL,
11575                                  dictinfo->rolname,
11576                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11577                                  q->data, delq->data, NULL,
11578                                  NULL, 0,
11579                                  NULL, NULL);
11580
11581         /* Dump Dictionary Comments */
11582         dumpComment(fout, labelq->data,
11583                                 NULL, dictinfo->rolname,
11584                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11585
11586         destroyPQExpBuffer(q);
11587         destroyPQExpBuffer(delq);
11588         destroyPQExpBuffer(labelq);
11589         destroyPQExpBuffer(query);
11590 }
11591
11592 /*
11593  * dumpTSTemplate
11594  *        write out a single text search template
11595  */
11596 static void
11597 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11598 {
11599         PQExpBuffer q;
11600         PQExpBuffer delq;
11601         PQExpBuffer labelq;
11602
11603         /* Skip if not to be dumped */
11604         if (!tmplinfo->dobj.dump || dataOnly)
11605                 return;
11606
11607         q = createPQExpBuffer();
11608         delq = createPQExpBuffer();
11609         labelq = createPQExpBuffer();
11610
11611         /* Make sure we are in proper schema */
11612         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11613
11614         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11615                                           fmtId(tmplinfo->dobj.name));
11616
11617         if (tmplinfo->tmplinit != InvalidOid)
11618                 appendPQExpBuffer(q, "    INIT = %s,\n",
11619                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11620         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11621                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11622
11623         /*
11624          * DROP must be fully qualified in case same name appears in pg_catalog
11625          */
11626         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11627                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11628         appendPQExpBuffer(delq, ".%s;\n",
11629                                           fmtId(tmplinfo->dobj.name));
11630
11631         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11632                                           fmtId(tmplinfo->dobj.name));
11633
11634         if (binary_upgrade)
11635                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11636
11637         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11638                                  tmplinfo->dobj.name,
11639                                  tmplinfo->dobj.namespace->dobj.name,
11640                                  NULL,
11641                                  "",
11642                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11643                                  q->data, delq->data, NULL,
11644                                  NULL, 0,
11645                                  NULL, NULL);
11646
11647         /* Dump Template Comments */
11648         dumpComment(fout, labelq->data,
11649                                 NULL, "",
11650                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11651
11652         destroyPQExpBuffer(q);
11653         destroyPQExpBuffer(delq);
11654         destroyPQExpBuffer(labelq);
11655 }
11656
11657 /*
11658  * dumpTSConfig
11659  *        write out a single text search configuration
11660  */
11661 static void
11662 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11663 {
11664         PQExpBuffer q;
11665         PQExpBuffer delq;
11666         PQExpBuffer labelq;
11667         PQExpBuffer query;
11668         PGresult   *res;
11669         char       *nspname;
11670         char       *prsname;
11671         int                     ntups,
11672                                 i;
11673         int                     i_tokenname;
11674         int                     i_dictname;
11675
11676         /* Skip if not to be dumped */
11677         if (!cfginfo->dobj.dump || dataOnly)
11678                 return;
11679
11680         q = createPQExpBuffer();
11681         delq = createPQExpBuffer();
11682         labelq = createPQExpBuffer();
11683         query = createPQExpBuffer();
11684
11685         /* Fetch name and namespace of the config's parser */
11686         selectSourceSchema(fout, "pg_catalog");
11687         appendPQExpBuffer(query, "SELECT nspname, prsname "
11688                                           "FROM pg_ts_parser p, pg_namespace n "
11689                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11690                                           cfginfo->cfgparser);
11691         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11692         nspname = PQgetvalue(res, 0, 0);
11693         prsname = PQgetvalue(res, 0, 1);
11694
11695         /* Make sure we are in proper schema */
11696         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11697
11698         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11699                                           fmtId(cfginfo->dobj.name));
11700
11701         appendPQExpBuffer(q, "    PARSER = ");
11702         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11703                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11704         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11705
11706         PQclear(res);
11707
11708         resetPQExpBuffer(query);
11709         appendPQExpBuffer(query,
11710                                           "SELECT \n"
11711                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11712                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11713                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11714                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11715                                           "WHERE m.mapcfg = '%u' \n"
11716                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11717                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11718
11719         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11720         ntups = PQntuples(res);
11721
11722         i_tokenname = PQfnumber(res, "tokenname");
11723         i_dictname = PQfnumber(res, "dictname");
11724
11725         for (i = 0; i < ntups; i++)
11726         {
11727                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11728                 char       *dictname = PQgetvalue(res, i, i_dictname);
11729
11730                 if (i == 0 ||
11731                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11732                 {
11733                         /* starting a new token type, so start a new command */
11734                         if (i > 0)
11735                                 appendPQExpBuffer(q, ";\n");
11736                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11737                                                           fmtId(cfginfo->dobj.name));
11738                         /* tokenname needs quoting, dictname does NOT */
11739                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11740                                                           fmtId(tokenname), dictname);
11741                 }
11742                 else
11743                         appendPQExpBuffer(q, ", %s", dictname);
11744         }
11745
11746         if (ntups > 0)
11747                 appendPQExpBuffer(q, ";\n");
11748
11749         PQclear(res);
11750
11751         /*
11752          * DROP must be fully qualified in case same name appears in pg_catalog
11753          */
11754         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11755                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11756         appendPQExpBuffer(delq, ".%s;\n",
11757                                           fmtId(cfginfo->dobj.name));
11758
11759         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11760                                           fmtId(cfginfo->dobj.name));
11761
11762         if (binary_upgrade)
11763                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11764
11765         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11766                                  cfginfo->dobj.name,
11767                                  cfginfo->dobj.namespace->dobj.name,
11768                                  NULL,
11769                                  cfginfo->rolname,
11770                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11771                                  q->data, delq->data, NULL,
11772                                  NULL, 0,
11773                                  NULL, NULL);
11774
11775         /* Dump Configuration Comments */
11776         dumpComment(fout, labelq->data,
11777                                 NULL, cfginfo->rolname,
11778                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11779
11780         destroyPQExpBuffer(q);
11781         destroyPQExpBuffer(delq);
11782         destroyPQExpBuffer(labelq);
11783         destroyPQExpBuffer(query);
11784 }
11785
11786 /*
11787  * dumpForeignDataWrapper
11788  *        write out a single foreign-data wrapper definition
11789  */
11790 static void
11791 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11792 {
11793         PQExpBuffer q;
11794         PQExpBuffer delq;
11795         PQExpBuffer labelq;
11796         char       *qfdwname;
11797
11798         /* Skip if not to be dumped */
11799         if (!fdwinfo->dobj.dump || dataOnly)
11800                 return;
11801
11802         /*
11803          * FDWs that belong to an extension are dumped based on their "dump"
11804          * field. Otherwise omit them if we are only dumping some specific object.
11805          */
11806         if (!fdwinfo->dobj.ext_member)
11807                 if (!include_everything)
11808                         return;
11809
11810         q = createPQExpBuffer();
11811         delq = createPQExpBuffer();
11812         labelq = createPQExpBuffer();
11813
11814         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11815
11816         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11817                                           qfdwname);
11818
11819         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11820                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11821
11822         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11823                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11824
11825         if (strlen(fdwinfo->fdwoptions) > 0)
11826                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11827
11828         appendPQExpBuffer(q, ";\n");
11829
11830         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11831                                           qfdwname);
11832
11833         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11834                                           qfdwname);
11835
11836         if (binary_upgrade)
11837                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11838
11839         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11840                                  fdwinfo->dobj.name,
11841                                  NULL,
11842                                  NULL,
11843                                  fdwinfo->rolname,
11844                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11845                                  q->data, delq->data, NULL,
11846                                  NULL, 0,
11847                                  NULL, NULL);
11848
11849         /* Handle the ACL */
11850         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11851                         "FOREIGN DATA WRAPPER",
11852                         qfdwname, NULL, fdwinfo->dobj.name,
11853                         NULL, fdwinfo->rolname,
11854                         fdwinfo->fdwacl);
11855
11856         /* Dump Foreign Data Wrapper Comments */
11857         dumpComment(fout, labelq->data,
11858                                 NULL, fdwinfo->rolname,
11859                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11860
11861         free(qfdwname);
11862
11863         destroyPQExpBuffer(q);
11864         destroyPQExpBuffer(delq);
11865         destroyPQExpBuffer(labelq);
11866 }
11867
11868 /*
11869  * dumpForeignServer
11870  *        write out a foreign server definition
11871  */
11872 static void
11873 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11874 {
11875         PQExpBuffer q;
11876         PQExpBuffer delq;
11877         PQExpBuffer labelq;
11878         PQExpBuffer query;
11879         PGresult   *res;
11880         char       *qsrvname;
11881         char       *fdwname;
11882
11883         /* Skip if not to be dumped */
11884         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11885                 return;
11886
11887         q = createPQExpBuffer();
11888         delq = createPQExpBuffer();
11889         labelq = createPQExpBuffer();
11890         query = createPQExpBuffer();
11891
11892         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11893
11894         /* look up the foreign-data wrapper */
11895         selectSourceSchema(fout, "pg_catalog");
11896         appendPQExpBuffer(query, "SELECT fdwname "
11897                                           "FROM pg_foreign_data_wrapper w "
11898                                           "WHERE w.oid = '%u'",
11899                                           srvinfo->srvfdw);
11900         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11901         fdwname = PQgetvalue(res, 0, 0);
11902
11903         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11904         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11905         {
11906                 appendPQExpBuffer(q, " TYPE ");
11907                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11908         }
11909         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11910         {
11911                 appendPQExpBuffer(q, " VERSION ");
11912                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11913         }
11914
11915         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11916         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11917
11918         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11919                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11920
11921         appendPQExpBuffer(q, ";\n");
11922
11923         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11924                                           qsrvname);
11925
11926         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11927
11928         if (binary_upgrade)
11929                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11930
11931         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11932                                  srvinfo->dobj.name,
11933                                  NULL,
11934                                  NULL,
11935                                  srvinfo->rolname,
11936                                  false, "SERVER", SECTION_PRE_DATA,
11937                                  q->data, delq->data, NULL,
11938                                  NULL, 0,
11939                                  NULL, NULL);
11940
11941         /* Handle the ACL */
11942         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11943                         "FOREIGN SERVER",
11944                         qsrvname, NULL, srvinfo->dobj.name,
11945                         NULL, srvinfo->rolname,
11946                         srvinfo->srvacl);
11947
11948         /* Dump user mappings */
11949         dumpUserMappings(fout,
11950                                          srvinfo->dobj.name, NULL,
11951                                          srvinfo->rolname,
11952                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11953
11954         /* Dump Foreign Server Comments */
11955         dumpComment(fout, labelq->data,
11956                                 NULL, srvinfo->rolname,
11957                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11958
11959         free(qsrvname);
11960
11961         destroyPQExpBuffer(q);
11962         destroyPQExpBuffer(delq);
11963         destroyPQExpBuffer(labelq);
11964 }
11965
11966 /*
11967  * dumpUserMappings
11968  *
11969  * This routine is used to dump any user mappings associated with the
11970  * server handed to this routine. Should be called after ArchiveEntry()
11971  * for the server.
11972  */
11973 static void
11974 dumpUserMappings(Archive *fout,
11975                                  const char *servername, const char *namespace,
11976                                  const char *owner,
11977                                  CatalogId catalogId, DumpId dumpId)
11978 {
11979         PQExpBuffer q;
11980         PQExpBuffer delq;
11981         PQExpBuffer query;
11982         PQExpBuffer tag;
11983         PGresult   *res;
11984         int                     ntups;
11985         int                     i_usename;
11986         int                     i_umoptions;
11987         int                     i;
11988
11989         q = createPQExpBuffer();
11990         tag = createPQExpBuffer();
11991         delq = createPQExpBuffer();
11992         query = createPQExpBuffer();
11993
11994         /*
11995          * We read from the publicly accessible view pg_user_mappings, so as not
11996          * to fail if run by a non-superuser.  Note that the view will show
11997          * umoptions as null if the user hasn't got privileges for the associated
11998          * server; this means that pg_dump will dump such a mapping, but with no
11999          * OPTIONS clause.      A possible alternative is to skip such mappings
12000          * altogether, but it's not clear that that's an improvement.
12001          */
12002         selectSourceSchema(fout, "pg_catalog");
12003
12004         appendPQExpBuffer(query,
12005                                           "SELECT usename, "
12006                                           "array_to_string(ARRAY("
12007                                           "SELECT quote_ident(option_name) || ' ' || "
12008                                           "quote_literal(option_value) "
12009                                           "FROM pg_options_to_table(umoptions) "
12010                                           "ORDER BY option_name"
12011                                           "), E',\n    ') AS umoptions "
12012                                           "FROM pg_user_mappings "
12013                                           "WHERE srvid = '%u' "
12014                                           "ORDER BY usename",
12015                                           catalogId.oid);
12016
12017         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12018
12019         ntups = PQntuples(res);
12020         i_usename = PQfnumber(res, "usename");
12021         i_umoptions = PQfnumber(res, "umoptions");
12022
12023         for (i = 0; i < ntups; i++)
12024         {
12025                 char       *usename;
12026                 char       *umoptions;
12027
12028                 usename = PQgetvalue(res, i, i_usename);
12029                 umoptions = PQgetvalue(res, i, i_umoptions);
12030
12031                 resetPQExpBuffer(q);
12032                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
12033                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
12034
12035                 if (umoptions && strlen(umoptions) > 0)
12036                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
12037
12038                 appendPQExpBuffer(q, ";\n");
12039
12040                 resetPQExpBuffer(delq);
12041                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
12042                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
12043
12044                 resetPQExpBuffer(tag);
12045                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
12046                                                   usename, servername);
12047
12048                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12049                                          tag->data,
12050                                          namespace,
12051                                          NULL,
12052                                          owner, false,
12053                                          "USER MAPPING", SECTION_PRE_DATA,
12054                                          q->data, delq->data, NULL,
12055                                          &dumpId, 1,
12056                                          NULL, NULL);
12057         }
12058
12059         PQclear(res);
12060
12061         destroyPQExpBuffer(query);
12062         destroyPQExpBuffer(delq);
12063         destroyPQExpBuffer(q);
12064 }
12065
12066 /*
12067  * Write out default privileges information
12068  */
12069 static void
12070 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
12071 {
12072         PQExpBuffer q;
12073         PQExpBuffer tag;
12074         const char *type;
12075
12076         /* Skip if not to be dumped */
12077         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
12078                 return;
12079
12080         q = createPQExpBuffer();
12081         tag = createPQExpBuffer();
12082
12083         switch (daclinfo->defaclobjtype)
12084         {
12085                 case DEFACLOBJ_RELATION:
12086                         type = "TABLES";
12087                         break;
12088                 case DEFACLOBJ_SEQUENCE:
12089                         type = "SEQUENCES";
12090                         break;
12091                 case DEFACLOBJ_FUNCTION:
12092                         type = "FUNCTIONS";
12093                         break;
12094                 case DEFACLOBJ_TYPE:
12095                         type = "TYPES";
12096                         break;
12097                 default:
12098                         /* shouldn't get here */
12099                         exit_horribly(NULL,
12100                                                   "unrecognized object type in default privileges: %d\n",
12101                                                   (int) daclinfo->defaclobjtype);
12102                         type = "";                      /* keep compiler quiet */
12103         }
12104
12105         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
12106
12107         /* build the actual command(s) for this tuple */
12108         if (!buildDefaultACLCommands(type,
12109                                                                  daclinfo->dobj.namespace != NULL ?
12110                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
12111                                                                  daclinfo->defaclacl,
12112                                                                  daclinfo->defaclrole,
12113                                                                  fout->remoteVersion,
12114                                                                  q))
12115                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
12116                                           daclinfo->defaclacl);
12117
12118         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
12119                                  tag->data,
12120            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
12121                                  NULL,
12122                                  daclinfo->defaclrole,
12123                                  false, "DEFAULT ACL", SECTION_POST_DATA,
12124                                  q->data, "", NULL,
12125                                  NULL, 0,
12126                                  NULL, NULL);
12127
12128         destroyPQExpBuffer(tag);
12129         destroyPQExpBuffer(q);
12130 }
12131
12132 /*----------
12133  * Write out grant/revoke information
12134  *
12135  * 'objCatId' is the catalog ID of the underlying object.
12136  * 'objDumpId' is the dump ID of the underlying object.
12137  * 'type' must be one of
12138  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
12139  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
12140  * 'name' is the formatted name of the object.  Must be quoted etc. already.
12141  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
12142  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12143  * 'nspname' is the namespace the object is in (NULL if none).
12144  * 'owner' is the owner, NULL if there is no owner (for languages).
12145  * 'acls' is the string read out of the fooacl system catalog field;
12146  *              it will be parsed here.
12147  *----------
12148  */
12149 static void
12150 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12151                 const char *type, const char *name, const char *subname,
12152                 const char *tag, const char *nspname, const char *owner,
12153                 const char *acls)
12154 {
12155         PQExpBuffer sql;
12156
12157         /* Do nothing if ACL dump is not enabled */
12158         if (aclsSkip)
12159                 return;
12160
12161         /* --data-only skips ACLs *except* BLOB ACLs */
12162         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12163                 return;
12164
12165         sql = createPQExpBuffer();
12166
12167         if (!buildACLCommands(name, subname, type, acls, owner,
12168                                                   "", fout->remoteVersion, sql))
12169                 exit_horribly(NULL,
12170                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12171                                           acls, name, type);
12172
12173         if (sql->len > 0)
12174                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12175                                          tag, nspname,
12176                                          NULL,
12177                                          owner ? owner : "",
12178                                          false, "ACL", SECTION_NONE,
12179                                          sql->data, "", NULL,
12180                                          &(objDumpId), 1,
12181                                          NULL, NULL);
12182
12183         destroyPQExpBuffer(sql);
12184 }
12185
12186 /*
12187  * dumpSecLabel
12188  *
12189  * This routine is used to dump any security labels associated with the
12190  * object handed to this routine. The routine takes a constant character
12191  * string for the target part of the security-label command, plus
12192  * the namespace and owner of the object (for labeling the ArchiveEntry),
12193  * plus catalog ID and subid which are the lookup key for pg_seclabel,
12194  * plus the dump ID for the object (for setting a dependency).
12195  * If a matching pg_seclabel entry is found, it is dumped.
12196  *
12197  * Note: although this routine takes a dumpId for dependency purposes,
12198  * that purpose is just to mark the dependency in the emitted dump file
12199  * for possible future use by pg_restore.  We do NOT use it for determining
12200  * ordering of the label in the dump file, because this routine is called
12201  * after dependency sorting occurs.  This routine should be called just after
12202  * calling ArchiveEntry() for the specified object.
12203  */
12204 static void
12205 dumpSecLabel(Archive *fout, const char *target,
12206                          const char *namespace, const char *owner,
12207                          CatalogId catalogId, int subid, DumpId dumpId)
12208 {
12209         SecLabelItem *labels;
12210         int                     nlabels;
12211         int                     i;
12212         PQExpBuffer query;
12213
12214         /* do nothing, if --no-security-labels is supplied */
12215         if (no_security_labels)
12216                 return;
12217
12218         /* Comments are schema not data ... except blob comments are data */
12219         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12220         {
12221                 if (dataOnly)
12222                         return;
12223         }
12224         else
12225         {
12226                 if (schemaOnly)
12227                         return;
12228         }
12229
12230         /* Search for security labels associated with catalogId, using table */
12231         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12232
12233         query = createPQExpBuffer();
12234
12235         for (i = 0; i < nlabels; i++)
12236         {
12237                 /*
12238                  * Ignore label entries for which the subid doesn't match.
12239                  */
12240                 if (labels[i].objsubid != subid)
12241                         continue;
12242
12243                 appendPQExpBuffer(query,
12244                                                   "SECURITY LABEL FOR %s ON %s IS ",
12245                                                   fmtId(labels[i].provider), target);
12246                 appendStringLiteralAH(query, labels[i].label, fout);
12247                 appendPQExpBuffer(query, ";\n");
12248         }
12249
12250         if (query->len > 0)
12251         {
12252                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12253                                          target, namespace, NULL, owner,
12254                                          false, "SECURITY LABEL", SECTION_NONE,
12255                                          query->data, "", NULL,
12256                                          &(dumpId), 1,
12257                                          NULL, NULL);
12258         }
12259         destroyPQExpBuffer(query);
12260 }
12261
12262 /*
12263  * dumpTableSecLabel
12264  *
12265  * As above, but dump security label for both the specified table (or view)
12266  * and its columns.
12267  */
12268 static void
12269 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12270 {
12271         SecLabelItem *labels;
12272         int                     nlabels;
12273         int                     i;
12274         PQExpBuffer query;
12275         PQExpBuffer target;
12276
12277         /* do nothing, if --no-security-labels is supplied */
12278         if (no_security_labels)
12279                 return;
12280
12281         /* SecLabel are SCHEMA not data */
12282         if (dataOnly)
12283                 return;
12284
12285         /* Search for comments associated with relation, using table */
12286         nlabels = findSecLabels(fout,
12287                                                         tbinfo->dobj.catId.tableoid,
12288                                                         tbinfo->dobj.catId.oid,
12289                                                         &labels);
12290
12291         /* If security labels exist, build SECURITY LABEL statements */
12292         if (nlabels <= 0)
12293                 return;
12294
12295         query = createPQExpBuffer();
12296         target = createPQExpBuffer();
12297
12298         for (i = 0; i < nlabels; i++)
12299         {
12300                 const char *colname;
12301                 const char *provider = labels[i].provider;
12302                 const char *label = labels[i].label;
12303                 int                     objsubid = labels[i].objsubid;
12304
12305                 resetPQExpBuffer(target);
12306                 if (objsubid == 0)
12307                 {
12308                         appendPQExpBuffer(target, "%s %s", reltypename,
12309                                                           fmtId(tbinfo->dobj.name));
12310                 }
12311                 else
12312                 {
12313                         colname = getAttrName(objsubid, tbinfo);
12314                         /* first fmtId result must be consumed before calling it again */
12315                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12316                         appendPQExpBuffer(target, ".%s", fmtId(colname));
12317                 }
12318                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12319                                                   fmtId(provider), target->data);
12320                 appendStringLiteralAH(query, label, fout);
12321                 appendPQExpBuffer(query, ";\n");
12322         }
12323         if (query->len > 0)
12324         {
12325                 resetPQExpBuffer(target);
12326                 appendPQExpBuffer(target, "%s %s", reltypename,
12327                                                   fmtId(tbinfo->dobj.name));
12328                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12329                                          target->data,
12330                                          tbinfo->dobj.namespace->dobj.name,
12331                                          NULL, tbinfo->rolname,
12332                                          false, "SECURITY LABEL", SECTION_NONE,
12333                                          query->data, "", NULL,
12334                                          &(tbinfo->dobj.dumpId), 1,
12335                                          NULL, NULL);
12336         }
12337         destroyPQExpBuffer(query);
12338         destroyPQExpBuffer(target);
12339 }
12340
12341 /*
12342  * findSecLabels
12343  *
12344  * Find the security label(s), if any, associated with the given object.
12345  * All the objsubid values associated with the given classoid/objoid are
12346  * found with one search.
12347  */
12348 static int
12349 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12350 {
12351         /* static storage for table of security labels */
12352         static SecLabelItem *labels = NULL;
12353         static int      nlabels = -1;
12354
12355         SecLabelItem *middle = NULL;
12356         SecLabelItem *low;
12357         SecLabelItem *high;
12358         int                     nmatch;
12359
12360         /* Get security labels if we didn't already */
12361         if (nlabels < 0)
12362                 nlabels = collectSecLabels(fout, &labels);
12363
12364         if (nlabels <= 0)                       /* no labels, so no match is possible */
12365         {
12366                 *items = NULL;
12367                 return 0;
12368         }
12369
12370         /*
12371          * Do binary search to find some item matching the object.
12372          */
12373         low = &labels[0];
12374         high = &labels[nlabels - 1];
12375         while (low <= high)
12376         {
12377                 middle = low + (high - low) / 2;
12378
12379                 if (classoid < middle->classoid)
12380                         high = middle - 1;
12381                 else if (classoid > middle->classoid)
12382                         low = middle + 1;
12383                 else if (objoid < middle->objoid)
12384                         high = middle - 1;
12385                 else if (objoid > middle->objoid)
12386                         low = middle + 1;
12387                 else
12388                         break;                          /* found a match */
12389         }
12390
12391         if (low > high)                         /* no matches */
12392         {
12393                 *items = NULL;
12394                 return 0;
12395         }
12396
12397         /*
12398          * Now determine how many items match the object.  The search loop
12399          * invariant still holds: only items between low and high inclusive could
12400          * match.
12401          */
12402         nmatch = 1;
12403         while (middle > low)
12404         {
12405                 if (classoid != middle[-1].classoid ||
12406                         objoid != middle[-1].objoid)
12407                         break;
12408                 middle--;
12409                 nmatch++;
12410         }
12411
12412         *items = middle;
12413
12414         middle += nmatch;
12415         while (middle <= high)
12416         {
12417                 if (classoid != middle->classoid ||
12418                         objoid != middle->objoid)
12419                         break;
12420                 middle++;
12421                 nmatch++;
12422         }
12423
12424         return nmatch;
12425 }
12426
12427 /*
12428  * collectSecLabels
12429  *
12430  * Construct a table of all security labels available for database objects.
12431  * It's much faster to pull them all at once.
12432  *
12433  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12434  */
12435 static int
12436 collectSecLabels(Archive *fout, SecLabelItem **items)
12437 {
12438         PGresult   *res;
12439         PQExpBuffer query;
12440         int                     i_label;
12441         int                     i_provider;
12442         int                     i_classoid;
12443         int                     i_objoid;
12444         int                     i_objsubid;
12445         int                     ntups;
12446         int                     i;
12447         SecLabelItem *labels;
12448
12449         query = createPQExpBuffer();
12450
12451         appendPQExpBuffer(query,
12452                                           "SELECT label, provider, classoid, objoid, objsubid "
12453                                           "FROM pg_catalog.pg_seclabel "
12454                                           "ORDER BY classoid, objoid, objsubid");
12455
12456         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12457
12458         /* Construct lookup table containing OIDs in numeric form */
12459         i_label = PQfnumber(res, "label");
12460         i_provider = PQfnumber(res, "provider");
12461         i_classoid = PQfnumber(res, "classoid");
12462         i_objoid = PQfnumber(res, "objoid");
12463         i_objsubid = PQfnumber(res, "objsubid");
12464
12465         ntups = PQntuples(res);
12466
12467         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12468
12469         for (i = 0; i < ntups; i++)
12470         {
12471                 labels[i].label = PQgetvalue(res, i, i_label);
12472                 labels[i].provider = PQgetvalue(res, i, i_provider);
12473                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12474                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12475                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12476         }
12477
12478         /* Do NOT free the PGresult since we are keeping pointers into it */
12479         destroyPQExpBuffer(query);
12480
12481         *items = labels;
12482         return ntups;
12483 }
12484
12485 /*
12486  * dumpTable
12487  *        write out to fout the declarations (not data) of a user-defined table
12488  */
12489 static void
12490 dumpTable(Archive *fout, TableInfo *tbinfo)
12491 {
12492         if (tbinfo->dobj.dump && !dataOnly)
12493         {
12494                 char       *namecopy;
12495
12496                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12497                         dumpSequence(fout, tbinfo);
12498                 else
12499                         dumpTableSchema(fout, tbinfo);
12500
12501                 /* Handle the ACL here */
12502                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12503                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12504                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12505                                 "TABLE",
12506                                 namecopy, NULL, tbinfo->dobj.name,
12507                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12508                                 tbinfo->relacl);
12509
12510                 /*
12511                  * Handle column ACLs, if any.  Note: we pull these with a separate
12512                  * query rather than trying to fetch them during getTableAttrs, so
12513                  * that we won't miss ACLs on system columns.
12514                  */
12515                 if (fout->remoteVersion >= 80400)
12516                 {
12517                         PQExpBuffer query = createPQExpBuffer();
12518                         PGresult   *res;
12519                         int                     i;
12520
12521                         appendPQExpBuffer(query,
12522                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12523                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12524                                                           "ORDER BY attnum",
12525                                                           tbinfo->dobj.catId.oid);
12526                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12527
12528                         for (i = 0; i < PQntuples(res); i++)
12529                         {
12530                                 char       *attname = PQgetvalue(res, i, 0);
12531                                 char       *attacl = PQgetvalue(res, i, 1);
12532                                 char       *attnamecopy;
12533                                 char       *acltag;
12534
12535                                 attnamecopy = pg_strdup(fmtId(attname));
12536                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12537                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12538                                 /* Column's GRANT type is always TABLE */
12539                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12540                                                 namecopy, attnamecopy, acltag,
12541                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12542                                                 attacl);
12543                                 free(attnamecopy);
12544                                 free(acltag);
12545                         }
12546                         PQclear(res);
12547                         destroyPQExpBuffer(query);
12548                 }
12549
12550                 free(namecopy);
12551         }
12552 }
12553
12554 /*
12555  * Create the AS clause for a view or materialized view. The semicolon is
12556  * stripped because a materialized view must add a WITH NO DATA clause.
12557  *
12558  * This returns a new buffer which must be freed by the caller.
12559  */
12560 static PQExpBuffer
12561 createViewAsClause(Archive *fout, TableInfo *tbinfo)
12562 {
12563         PQExpBuffer query = createPQExpBuffer();
12564         PQExpBuffer result = createPQExpBuffer();
12565         PGresult   *res;
12566         int                     len;
12567
12568         /* Fetch the view definition */
12569         if (fout->remoteVersion >= 70300)
12570         {
12571                 /* Beginning in 7.3, viewname is not unique; rely on OID */
12572                 appendPQExpBuffer(query,
12573                                                   "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12574                                                   tbinfo->dobj.catId.oid);
12575         }
12576         else
12577         {
12578                 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12579                                                   "FROM pg_views WHERE viewname = ");
12580                 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12581                 appendPQExpBuffer(query, ";");
12582         }
12583
12584         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12585
12586         if (PQntuples(res) != 1)
12587         {
12588                 if (PQntuples(res) < 1)
12589                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12590                                                   tbinfo->dobj.name);
12591                 else
12592                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12593                                                   tbinfo->dobj.name);
12594         }
12595
12596         len = PQgetlength(res, 0, 0);
12597
12598         if (len == 0)
12599                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12600                                           tbinfo->dobj.name);
12601
12602         /* Strip off the trailing semicolon so that other things may follow. */
12603         Assert(PQgetvalue(res, 0, 0)[len-1] == ';');
12604         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
12605
12606         PQclear(res);
12607         destroyPQExpBuffer(query);
12608
12609         return result;
12610 }
12611
12612 /*
12613  * dumpTableSchema
12614  *        write the declaration (not data) of one user-defined table or view
12615  */
12616 static void
12617 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12618 {
12619         PQExpBuffer q = createPQExpBuffer();
12620         PQExpBuffer delq = createPQExpBuffer();
12621         PQExpBuffer labelq = createPQExpBuffer();
12622         int                     numParents;
12623         TableInfo **parents;
12624         int                     actual_atts;    /* number of attrs in this CREATE statement */
12625         const char *reltypename;
12626         char       *storage;
12627         char       *srvname;
12628         char       *ftoptions;
12629         int                     j,
12630                                 k;
12631
12632         /* Make sure we are in proper schema */
12633         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12634
12635         if (binary_upgrade)
12636                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12637                                                                                                 tbinfo->dobj.catId.oid);
12638
12639         /* Is it a table or a view? */
12640         if (tbinfo->relkind == RELKIND_VIEW)
12641         {
12642                 PQExpBuffer result;
12643
12644                 reltypename = "VIEW";
12645
12646                 /*
12647                  * DROP must be fully qualified in case same name appears in
12648                  * pg_catalog
12649                  */
12650                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12651                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12652                 appendPQExpBuffer(delq, "%s;\n",
12653                                                   fmtId(tbinfo->dobj.name));
12654
12655                 if (binary_upgrade)
12656                         binary_upgrade_set_pg_class_oids(fout, q,
12657                                                                                          tbinfo->dobj.catId.oid, false);
12658
12659                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12660                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12661                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12662                 result = createViewAsClause(fout, tbinfo);
12663                 appendPQExpBuffer(q, " AS\n%s;\n", result->data);
12664                 destroyPQExpBuffer(result);
12665
12666                 appendPQExpBuffer(labelq, "VIEW %s",
12667                                                   fmtId(tbinfo->dobj.name));
12668         }
12669         else
12670         {
12671                 switch (tbinfo->relkind)
12672                 {
12673                         case (RELKIND_FOREIGN_TABLE):
12674                         {
12675                                 PQExpBuffer query = createPQExpBuffer();
12676                                 PGresult   *res;
12677                                 int                     i_srvname;
12678                                 int                     i_ftoptions;
12679
12680                                 reltypename = "FOREIGN TABLE";
12681
12682                                 /* retrieve name of foreign server and generic options */
12683                                 appendPQExpBuffer(query,
12684                                                                   "SELECT fs.srvname, "
12685                                                                   "pg_catalog.array_to_string(ARRAY("
12686                                                                   "SELECT pg_catalog.quote_ident(option_name) || "
12687                                                                   "' ' || pg_catalog.quote_literal(option_value) "
12688                                                                 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12689                                                                   "ORDER BY option_name"
12690                                                                   "), E',\n    ') AS ftoptions "
12691                                                                   "FROM pg_catalog.pg_foreign_table ft "
12692                                                                   "JOIN pg_catalog.pg_foreign_server fs "
12693                                                                   "ON (fs.oid = ft.ftserver) "
12694                                                                   "WHERE ft.ftrelid = '%u'",
12695                                                                   tbinfo->dobj.catId.oid);
12696                                 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12697                                 i_srvname = PQfnumber(res, "srvname");
12698                                 i_ftoptions = PQfnumber(res, "ftoptions");
12699                                 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12700                                 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12701                                 PQclear(res);
12702                                 destroyPQExpBuffer(query);
12703                                 break;
12704                         }
12705                         case (RELKIND_MATVIEW):
12706                                 reltypename = "MATERIALIZED VIEW";
12707                                 srvname = NULL;
12708                                 ftoptions = NULL;
12709                                 break;
12710                         default:
12711                                 reltypename = "TABLE";
12712                                 srvname = NULL;
12713                                 ftoptions = NULL;
12714                 }
12715
12716                 numParents = tbinfo->numParents;
12717                 parents = tbinfo->parents;
12718
12719                 /*
12720                  * DROP must be fully qualified in case same name appears in
12721                  * pg_catalog
12722                  */
12723                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12724                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12725                 appendPQExpBuffer(delq, "%s;\n",
12726                                                   fmtId(tbinfo->dobj.name));
12727
12728                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12729                                                   fmtId(tbinfo->dobj.name));
12730
12731                 if (binary_upgrade)
12732                         binary_upgrade_set_pg_class_oids(fout, q,
12733                                                                                          tbinfo->dobj.catId.oid, false);
12734
12735                 appendPQExpBuffer(q, "CREATE %s%s %s",
12736                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12737                                                   "UNLOGGED " : "",
12738                                                   reltypename,
12739                                                   fmtId(tbinfo->dobj.name));
12740
12741                 /*
12742                  * Attach to type, if reloftype; except in case of a binary upgrade,
12743                  * we dump the table normally and attach it to the type afterward.
12744                  */
12745                 if (tbinfo->reloftype && !binary_upgrade)
12746                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12747
12748                 if (tbinfo->relkind != RELKIND_MATVIEW)
12749                 {
12750                 /* Dump the attributes */
12751                 actual_atts = 0;
12752                 for (j = 0; j < tbinfo->numatts; j++)
12753                 {
12754                         /*
12755                          * Normally, dump if it's locally defined in this table, and not
12756                          * dropped.  But for binary upgrade, we'll dump all the columns,
12757                          * and then fix up the dropped and nonlocal cases below.
12758                          */
12759                         if (shouldPrintColumn(tbinfo, j))
12760                         {
12761                                 /*
12762                                  * Default value --- suppress if to be printed separately.
12763                                  */
12764                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12765                                                                                    !tbinfo->attrdefs[j]->separate);
12766
12767                                 /*
12768                                  * Not Null constraint --- suppress if inherited, except in
12769                                  * binary-upgrade case where that won't work.
12770                                  */
12771                                 bool            has_notnull = (tbinfo->notnull[j] &&
12772                                                                                    (!tbinfo->inhNotNull[j] ||
12773                                                                                         binary_upgrade));
12774
12775                                 /* Skip column if fully defined by reloftype */
12776                                 if (tbinfo->reloftype &&
12777                                         !has_default && !has_notnull && !binary_upgrade)
12778                                         continue;
12779
12780                                 /* Format properly if not first attr */
12781                                 if (actual_atts == 0)
12782                                         appendPQExpBuffer(q, " (");
12783                                 else
12784                                         appendPQExpBuffer(q, ",");
12785                                 appendPQExpBuffer(q, "\n    ");
12786                                 actual_atts++;
12787
12788                                 /* Attribute name */
12789                                 appendPQExpBuffer(q, "%s",
12790                                                                   fmtId(tbinfo->attnames[j]));
12791
12792                                 if (tbinfo->attisdropped[j])
12793                                 {
12794                                         /*
12795                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12796                                          * so we will not have gotten a valid type name; insert
12797                                          * INTEGER as a stopgap.  We'll clean things up later.
12798                                          */
12799                                         appendPQExpBuffer(q, " INTEGER /* dummy */");
12800                                         /* Skip all the rest, too */
12801                                         continue;
12802                                 }
12803
12804                                 /* Attribute type */
12805                                 if (tbinfo->reloftype && !binary_upgrade)
12806                                 {
12807                                         appendPQExpBuffer(q, " WITH OPTIONS");
12808                                 }
12809                                 else if (fout->remoteVersion >= 70100)
12810                                 {
12811                                         appendPQExpBuffer(q, " %s",
12812                                                                           tbinfo->atttypnames[j]);
12813                                 }
12814                                 else
12815                                 {
12816                                         /* If no format_type, fake it */
12817                                         appendPQExpBuffer(q, " %s",
12818                                                                           myFormatType(tbinfo->atttypnames[j],
12819                                                                                                    tbinfo->atttypmod[j]));
12820                                 }
12821
12822                                 /* Add collation if not default for the type */
12823                                 if (OidIsValid(tbinfo->attcollation[j]))
12824                                 {
12825                                         CollInfo   *coll;
12826
12827                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12828                                         if (coll)
12829                                         {
12830                                                 /* always schema-qualify, don't try to be smart */
12831                                                 appendPQExpBuffer(q, " COLLATE %s.",
12832                                                                          fmtId(coll->dobj.namespace->dobj.name));
12833                                                 appendPQExpBuffer(q, "%s",
12834                                                                                   fmtId(coll->dobj.name));
12835                                         }
12836                                 }
12837
12838                                 if (has_default)
12839                                         appendPQExpBuffer(q, " DEFAULT %s",
12840                                                                           tbinfo->attrdefs[j]->adef_expr);
12841
12842                                 if (has_notnull)
12843                                         appendPQExpBuffer(q, " NOT NULL");
12844                         }
12845                 }
12846
12847                 /*
12848                  * Add non-inherited CHECK constraints, if any.
12849                  */
12850                 for (j = 0; j < tbinfo->ncheck; j++)
12851                 {
12852                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12853
12854                         if (constr->separate || !constr->conislocal)
12855                                 continue;
12856
12857                         if (actual_atts == 0)
12858                                 appendPQExpBuffer(q, " (\n    ");
12859                         else
12860                                 appendPQExpBuffer(q, ",\n    ");
12861
12862                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12863                                                           fmtId(constr->dobj.name));
12864                         appendPQExpBuffer(q, "%s", constr->condef);
12865
12866                         actual_atts++;
12867                 }
12868
12869                 if (actual_atts)
12870                         appendPQExpBuffer(q, "\n)");
12871                 else if (!(tbinfo->reloftype && !binary_upgrade))
12872                 {
12873                         /*
12874                          * We must have a parenthesized attribute list, even though empty,
12875                          * when not using the OF TYPE syntax.
12876                          */
12877                         appendPQExpBuffer(q, " (\n)");
12878                 }
12879
12880                 if (numParents > 0 && !binary_upgrade)
12881                 {
12882                         appendPQExpBuffer(q, "\nINHERITS (");
12883                         for (k = 0; k < numParents; k++)
12884                         {
12885                                 TableInfo  *parentRel = parents[k];
12886
12887                                 if (k > 0)
12888                                         appendPQExpBuffer(q, ", ");
12889                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12890                                         appendPQExpBuffer(q, "%s.",
12891                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12892                                 appendPQExpBuffer(q, "%s",
12893                                                                   fmtId(parentRel->dobj.name));
12894                         }
12895                         appendPQExpBuffer(q, ")");
12896                 }
12897
12898                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12899                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12900                 }
12901
12902                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12903                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12904                 {
12905                         bool            addcomma = false;
12906
12907                         appendPQExpBuffer(q, "\nWITH (");
12908                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12909                         {
12910                                 addcomma = true;
12911                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12912                         }
12913                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12914                         {
12915                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12916                                                                   tbinfo->toast_reloptions);
12917                         }
12918                         appendPQExpBuffer(q, ")");
12919                 }
12920
12921                 /* Dump generic options if any */
12922                 if (ftoptions && ftoptions[0])
12923                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12924
12925                 /*
12926                  * For materialized views, create the AS clause just like a view.
12927                  */
12928                 if (tbinfo->relkind == RELKIND_MATVIEW)
12929                 {
12930                         PQExpBuffer result;
12931
12932                         result = createViewAsClause(fout, tbinfo);
12933                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
12934                                                           result->data);
12935                         destroyPQExpBuffer(result);
12936                 }
12937                 else
12938                         appendPQExpBuffer(q, ";\n");
12939
12940                 /*
12941                  * To create binary-compatible heap files, we have to ensure the same
12942                  * physical column order, including dropped columns, as in the
12943                  * original.  Therefore, we create dropped columns above and drop them
12944                  * here, also updating their attlen/attalign values so that the
12945                  * dropped column can be skipped properly.      (We do not bother with
12946                  * restoring the original attbyval setting.)  Also, inheritance
12947                  * relationships are set up by doing ALTER INHERIT rather than using
12948                  * an INHERITS clause --- the latter would possibly mess up the column
12949                  * order.  That also means we have to take care about setting
12950                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12951                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12952                  */
12953                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12954                 {
12955                         for (j = 0; j < tbinfo->numatts; j++)
12956                         {
12957                                 if (tbinfo->attisdropped[j])
12958                                 {
12959                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12960                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12961                                                                           "SET attlen = %d, "
12962                                                                           "attalign = '%c', attbyval = false\n"
12963                                                                           "WHERE attname = ",
12964                                                                           tbinfo->attlen[j],
12965                                                                           tbinfo->attalign[j]);
12966                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12967                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12968                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12969                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12970
12971                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12972                                                                           fmtId(tbinfo->dobj.name));
12973                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12974                                                                           fmtId(tbinfo->attnames[j]));
12975                                 }
12976                                 else if (!tbinfo->attislocal[j])
12977                                 {
12978                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12979                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12980                                                                           "SET attislocal = false\n"
12981                                                                           "WHERE attname = ");
12982                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12983                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12984                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12985                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12986                                 }
12987                         }
12988
12989                         for (k = 0; k < tbinfo->ncheck; k++)
12990                         {
12991                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12992
12993                                 if (constr->separate || constr->conislocal)
12994                                         continue;
12995
12996                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12997                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12998                                                                   fmtId(tbinfo->dobj.name));
12999                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13000                                                                   fmtId(constr->dobj.name));
13001                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
13002                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
13003                                                                   "SET conislocal = false\n"
13004                                                                   "WHERE contype = 'c' AND conname = ");
13005                                 appendStringLiteralAH(q, constr->dobj.name, fout);
13006                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
13007                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13008                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13009                         }
13010
13011                         if (numParents > 0)
13012                         {
13013                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
13014                                 for (k = 0; k < numParents; k++)
13015                                 {
13016                                         TableInfo  *parentRel = parents[k];
13017
13018                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
13019                                                                           fmtId(tbinfo->dobj.name));
13020                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13021                                                 appendPQExpBuffer(q, "%s.",
13022                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
13023                                         appendPQExpBuffer(q, "%s;\n",
13024                                                                           fmtId(parentRel->dobj.name));
13025                                 }
13026                         }
13027
13028                         if (tbinfo->reloftype)
13029                         {
13030                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
13031                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
13032                                                                   fmtId(tbinfo->dobj.name),
13033                                                                   tbinfo->reloftype);
13034                         }
13035
13036                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
13037                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13038                                                           "SET relfrozenxid = '%u'\n"
13039                                                           "WHERE oid = ",
13040                                                           tbinfo->frozenxid);
13041                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13042                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13043
13044                         if (tbinfo->toast_oid)
13045                         {
13046                                 /* We preserve the toast oids, so we can use it during restore */
13047                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
13048                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13049                                                                   "SET relfrozenxid = '%u'\n"
13050                                                                   "WHERE oid = '%u';\n",
13051                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
13052                         }
13053                 }
13054
13055                 /*
13056                  * Dump additional per-column properties that we can't handle in the
13057                  * main CREATE TABLE command.
13058                  */
13059                 for (j = 0; j < tbinfo->numatts; j++)
13060                 {
13061                         /* None of this applies to dropped columns */
13062                         if (tbinfo->attisdropped[j])
13063                                 continue;
13064
13065                         /*
13066                          * If we didn't dump the column definition explicitly above, and
13067                          * it is NOT NULL and did not inherit that property from a parent,
13068                          * we have to mark it separately.
13069                          */
13070                         if (!shouldPrintColumn(tbinfo, j) &&
13071                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
13072                         {
13073                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13074                                                                   fmtId(tbinfo->dobj.name));
13075                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
13076                                                                   fmtId(tbinfo->attnames[j]));
13077                         }
13078
13079                         /*
13080                          * Dump per-column statistics information. We only issue an ALTER
13081                          * TABLE statement if the attstattarget entry for this column is
13082                          * non-negative (i.e. it's not the default value)
13083                          */
13084                         if (tbinfo->attstattarget[j] >= 0)
13085                         {
13086                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13087                                                                   fmtId(tbinfo->dobj.name));
13088                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13089                                                                   fmtId(tbinfo->attnames[j]));
13090                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
13091                                                                   tbinfo->attstattarget[j]);
13092                         }
13093
13094                         /*
13095                          * Dump per-column storage information.  The statement is only
13096                          * dumped if the storage has been changed from the type's default.
13097                          */
13098                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
13099                         {
13100                                 switch (tbinfo->attstorage[j])
13101                                 {
13102                                         case 'p':
13103                                                 storage = "PLAIN";
13104                                                 break;
13105                                         case 'e':
13106                                                 storage = "EXTERNAL";
13107                                                 break;
13108                                         case 'm':
13109                                                 storage = "MAIN";
13110                                                 break;
13111                                         case 'x':
13112                                                 storage = "EXTENDED";
13113                                                 break;
13114                                         default:
13115                                                 storage = NULL;
13116                                 }
13117
13118                                 /*
13119                                  * Only dump the statement if it's a storage type we recognize
13120                                  */
13121                                 if (storage != NULL)
13122                                 {
13123                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13124                                                                           fmtId(tbinfo->dobj.name));
13125                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
13126                                                                           fmtId(tbinfo->attnames[j]));
13127                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
13128                                                                           storage);
13129                                 }
13130                         }
13131
13132                         /*
13133                          * Dump per-column attributes.
13134                          */
13135                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
13136                         {
13137                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13138                                                                   fmtId(tbinfo->dobj.name));
13139                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13140                                                                   fmtId(tbinfo->attnames[j]));
13141                                 appendPQExpBuffer(q, "SET (%s);\n",
13142                                                                   tbinfo->attoptions[j]);
13143                         }
13144
13145                         /*
13146                          * Dump per-column fdw options.
13147                          */
13148                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
13149                                 tbinfo->attfdwoptions[j] &&
13150                                 tbinfo->attfdwoptions[j][0] != '\0')
13151                         {
13152                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13153                                                                   fmtId(tbinfo->dobj.name));
13154                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13155                                                                   fmtId(tbinfo->attnames[j]));
13156                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
13157                                                                   tbinfo->attfdwoptions[j]);
13158                         }
13159                 }
13160         }
13161
13162         if (binary_upgrade)
13163                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
13164
13165         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13166                                  tbinfo->dobj.name,
13167                                  tbinfo->dobj.namespace->dobj.name,
13168                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
13169                                  tbinfo->rolname,
13170                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
13171                                  reltypename, SECTION_PRE_DATA,
13172                                  q->data, delq->data, NULL,
13173                                  NULL, 0,
13174                                  NULL, NULL);
13175
13176
13177         /* Dump Table Comments */
13178         dumpTableComment(fout, tbinfo, reltypename);
13179
13180         /* Dump Table Security Labels */
13181         dumpTableSecLabel(fout, tbinfo, reltypename);
13182
13183         /* Dump comments on inlined table constraints */
13184         for (j = 0; j < tbinfo->ncheck; j++)
13185         {
13186                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13187
13188                 if (constr->separate || !constr->conislocal)
13189                         continue;
13190
13191                 dumpTableConstraintComment(fout, constr);
13192         }
13193
13194         destroyPQExpBuffer(q);
13195         destroyPQExpBuffer(delq);
13196         destroyPQExpBuffer(labelq);
13197 }
13198
13199 /*
13200  * dumpAttrDef --- dump an attribute's default-value declaration
13201  */
13202 static void
13203 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13204 {
13205         TableInfo  *tbinfo = adinfo->adtable;
13206         int                     adnum = adinfo->adnum;
13207         PQExpBuffer q;
13208         PQExpBuffer delq;
13209
13210         /* Skip if table definition not to be dumped */
13211         if (!tbinfo->dobj.dump || dataOnly)
13212                 return;
13213
13214         /* Skip if not "separate"; it was dumped in the table's definition */
13215         if (!adinfo->separate)
13216                 return;
13217
13218         q = createPQExpBuffer();
13219         delq = createPQExpBuffer();
13220
13221         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13222                                           fmtId(tbinfo->dobj.name));
13223         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13224                                           fmtId(tbinfo->attnames[adnum - 1]),
13225                                           adinfo->adef_expr);
13226
13227         /*
13228          * DROP must be fully qualified in case same name appears in pg_catalog
13229          */
13230         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13231                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13232         appendPQExpBuffer(delq, "%s ",
13233                                           fmtId(tbinfo->dobj.name));
13234         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13235                                           fmtId(tbinfo->attnames[adnum - 1]));
13236
13237         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13238                                  tbinfo->attnames[adnum - 1],
13239                                  tbinfo->dobj.namespace->dobj.name,
13240                                  NULL,
13241                                  tbinfo->rolname,
13242                                  false, "DEFAULT", SECTION_PRE_DATA,
13243                                  q->data, delq->data, NULL,
13244                                  NULL, 0,
13245                                  NULL, NULL);
13246
13247         destroyPQExpBuffer(q);
13248         destroyPQExpBuffer(delq);
13249 }
13250
13251 /*
13252  * getAttrName: extract the correct name for an attribute
13253  *
13254  * The array tblInfo->attnames[] only provides names of user attributes;
13255  * if a system attribute number is supplied, we have to fake it.
13256  * We also do a little bit of bounds checking for safety's sake.
13257  */
13258 static const char *
13259 getAttrName(int attrnum, TableInfo *tblInfo)
13260 {
13261         if (attrnum > 0 && attrnum <= tblInfo->numatts)
13262                 return tblInfo->attnames[attrnum - 1];
13263         switch (attrnum)
13264         {
13265                 case SelfItemPointerAttributeNumber:
13266                         return "ctid";
13267                 case ObjectIdAttributeNumber:
13268                         return "oid";
13269                 case MinTransactionIdAttributeNumber:
13270                         return "xmin";
13271                 case MinCommandIdAttributeNumber:
13272                         return "cmin";
13273                 case MaxTransactionIdAttributeNumber:
13274                         return "xmax";
13275                 case MaxCommandIdAttributeNumber:
13276                         return "cmax";
13277                 case TableOidAttributeNumber:
13278                         return "tableoid";
13279         }
13280         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13281                                   attrnum, tblInfo->dobj.name);
13282         return NULL;                            /* keep compiler quiet */
13283 }
13284
13285 /*
13286  * dumpIndex
13287  *        write out to fout a user-defined index
13288  */
13289 static void
13290 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13291 {
13292         TableInfo  *tbinfo = indxinfo->indextable;
13293         PQExpBuffer q;
13294         PQExpBuffer delq;
13295         PQExpBuffer labelq;
13296
13297         if (dataOnly)
13298                 return;
13299
13300         q = createPQExpBuffer();
13301         delq = createPQExpBuffer();
13302         labelq = createPQExpBuffer();
13303
13304         appendPQExpBuffer(labelq, "INDEX %s",
13305                                           fmtId(indxinfo->dobj.name));
13306
13307         /*
13308          * If there's an associated constraint, don't dump the index per se, but
13309          * do dump any comment for it.  (This is safe because dependency ordering
13310          * will have ensured the constraint is emitted first.)
13311          */
13312         if (indxinfo->indexconstraint == 0)
13313         {
13314                 if (binary_upgrade)
13315                         binary_upgrade_set_pg_class_oids(fout, q,
13316                                                                                          indxinfo->dobj.catId.oid, true);
13317
13318                 /* Plain secondary index */
13319                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13320
13321                 /* If the index is clustered, we need to record that. */
13322                 if (indxinfo->indisclustered)
13323                 {
13324                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13325                                                           fmtId(tbinfo->dobj.name));
13326                         appendPQExpBuffer(q, " ON %s;\n",
13327                                                           fmtId(indxinfo->dobj.name));
13328                 }
13329
13330                 /*
13331                  * DROP must be fully qualified in case same name appears in
13332                  * pg_catalog
13333                  */
13334                 appendPQExpBuffer(delq, "DROP INDEX %s.",
13335                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13336                 appendPQExpBuffer(delq, "%s;\n",
13337                                                   fmtId(indxinfo->dobj.name));
13338
13339                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13340                                          indxinfo->dobj.name,
13341                                          tbinfo->dobj.namespace->dobj.name,
13342                                          indxinfo->tablespace,
13343                                          tbinfo->rolname, false,
13344                                          "INDEX", SECTION_POST_DATA,
13345                                          q->data, delq->data, NULL,
13346                                          NULL, 0,
13347                                          NULL, NULL);
13348         }
13349
13350         /* Dump Index Comments */
13351         dumpComment(fout, labelq->data,
13352                                 tbinfo->dobj.namespace->dobj.name,
13353                                 tbinfo->rolname,
13354                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13355
13356         destroyPQExpBuffer(q);
13357         destroyPQExpBuffer(delq);
13358         destroyPQExpBuffer(labelq);
13359 }
13360
13361 /*
13362  * dumpConstraint
13363  *        write out to fout a user-defined constraint
13364  */
13365 static void
13366 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13367 {
13368         TableInfo  *tbinfo = coninfo->contable;
13369         PQExpBuffer q;
13370         PQExpBuffer delq;
13371
13372         /* Skip if not to be dumped */
13373         if (!coninfo->dobj.dump || dataOnly)
13374                 return;
13375
13376         q = createPQExpBuffer();
13377         delq = createPQExpBuffer();
13378
13379         if (coninfo->contype == 'p' ||
13380                 coninfo->contype == 'u' ||
13381                 coninfo->contype == 'x')
13382         {
13383                 /* Index-related constraint */
13384                 IndxInfo   *indxinfo;
13385                 int                     k;
13386
13387                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13388
13389                 if (indxinfo == NULL)
13390                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13391                                                   coninfo->dobj.name);
13392
13393                 if (binary_upgrade)
13394                         binary_upgrade_set_pg_class_oids(fout, q,
13395                                                                                          indxinfo->dobj.catId.oid, true);
13396
13397                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13398                                                   fmtId(tbinfo->dobj.name));
13399                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
13400                                                   fmtId(coninfo->dobj.name));
13401
13402                 if (coninfo->condef)
13403                 {
13404                         /* pg_get_constraintdef should have provided everything */
13405                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13406                 }
13407                 else
13408                 {
13409                         appendPQExpBuffer(q, "%s (",
13410                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13411                         for (k = 0; k < indxinfo->indnkeys; k++)
13412                         {
13413                                 int                     indkey = (int) indxinfo->indkeys[k];
13414                                 const char *attname;
13415
13416                                 if (indkey == InvalidAttrNumber)
13417                                         break;
13418                                 attname = getAttrName(indkey, tbinfo);
13419
13420                                 appendPQExpBuffer(q, "%s%s",
13421                                                                   (k == 0) ? "" : ", ",
13422                                                                   fmtId(attname));
13423                         }
13424
13425                         appendPQExpBuffer(q, ")");
13426
13427                         if (indxinfo->options && strlen(indxinfo->options) > 0)
13428                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13429
13430                         if (coninfo->condeferrable)
13431                         {
13432                                 appendPQExpBuffer(q, " DEFERRABLE");
13433                                 if (coninfo->condeferred)
13434                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
13435                         }
13436
13437                         appendPQExpBuffer(q, ";\n");
13438                 }
13439
13440                 /* If the index is clustered, we need to record that. */
13441                 if (indxinfo->indisclustered)
13442                 {
13443                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13444                                                           fmtId(tbinfo->dobj.name));
13445                         appendPQExpBuffer(q, " ON %s;\n",
13446                                                           fmtId(indxinfo->dobj.name));
13447                 }
13448
13449                 /*
13450                  * DROP must be fully qualified in case same name appears in
13451                  * pg_catalog
13452                  */
13453                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13454                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13455                 appendPQExpBuffer(delq, "%s ",
13456                                                   fmtId(tbinfo->dobj.name));
13457                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13458                                                   fmtId(coninfo->dobj.name));
13459
13460                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13461                                          coninfo->dobj.name,
13462                                          tbinfo->dobj.namespace->dobj.name,
13463                                          indxinfo->tablespace,
13464                                          tbinfo->rolname, false,
13465                                          "CONSTRAINT", SECTION_POST_DATA,
13466                                          q->data, delq->data, NULL,
13467                                          NULL, 0,
13468                                          NULL, NULL);
13469         }
13470         else if (coninfo->contype == 'f')
13471         {
13472                 /*
13473                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13474                  * current table data is not processed
13475                  */
13476                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13477                                                   fmtId(tbinfo->dobj.name));
13478                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13479                                                   fmtId(coninfo->dobj.name),
13480                                                   coninfo->condef);
13481
13482                 /*
13483                  * DROP must be fully qualified in case same name appears in
13484                  * pg_catalog
13485                  */
13486                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13487                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13488                 appendPQExpBuffer(delq, "%s ",
13489                                                   fmtId(tbinfo->dobj.name));
13490                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13491                                                   fmtId(coninfo->dobj.name));
13492
13493                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13494                                          coninfo->dobj.name,
13495                                          tbinfo->dobj.namespace->dobj.name,
13496                                          NULL,
13497                                          tbinfo->rolname, false,
13498                                          "FK CONSTRAINT", SECTION_POST_DATA,
13499                                          q->data, delq->data, NULL,
13500                                          NULL, 0,
13501                                          NULL, NULL);
13502         }
13503         else if (coninfo->contype == 'c' && tbinfo)
13504         {
13505                 /* CHECK constraint on a table */
13506
13507                 /* Ignore if not to be dumped separately */
13508                 if (coninfo->separate)
13509                 {
13510                         /* not ONLY since we want it to propagate to children */
13511                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13512                                                           fmtId(tbinfo->dobj.name));
13513                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13514                                                           fmtId(coninfo->dobj.name),
13515                                                           coninfo->condef);
13516
13517                         /*
13518                          * DROP must be fully qualified in case same name appears in
13519                          * pg_catalog
13520                          */
13521                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13522                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13523                         appendPQExpBuffer(delq, "%s ",
13524                                                           fmtId(tbinfo->dobj.name));
13525                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13526                                                           fmtId(coninfo->dobj.name));
13527
13528                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13529                                                  coninfo->dobj.name,
13530                                                  tbinfo->dobj.namespace->dobj.name,
13531                                                  NULL,
13532                                                  tbinfo->rolname, false,
13533                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13534                                                  q->data, delq->data, NULL,
13535                                                  NULL, 0,
13536                                                  NULL, NULL);
13537                 }
13538         }
13539         else if (coninfo->contype == 'c' && tbinfo == NULL)
13540         {
13541                 /* CHECK constraint on a domain */
13542                 TypeInfo   *tyinfo = coninfo->condomain;
13543
13544                 /* Ignore if not to be dumped separately */
13545                 if (coninfo->separate)
13546                 {
13547                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13548                                                           fmtId(tyinfo->dobj.name));
13549                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13550                                                           fmtId(coninfo->dobj.name),
13551                                                           coninfo->condef);
13552
13553                         /*
13554                          * DROP must be fully qualified in case same name appears in
13555                          * pg_catalog
13556                          */
13557                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13558                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13559                         appendPQExpBuffer(delq, "%s ",
13560                                                           fmtId(tyinfo->dobj.name));
13561                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13562                                                           fmtId(coninfo->dobj.name));
13563
13564                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13565                                                  coninfo->dobj.name,
13566                                                  tyinfo->dobj.namespace->dobj.name,
13567                                                  NULL,
13568                                                  tyinfo->rolname, false,
13569                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13570                                                  q->data, delq->data, NULL,
13571                                                  NULL, 0,
13572                                                  NULL, NULL);
13573                 }
13574         }
13575         else
13576         {
13577                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13578                                           coninfo->contype);
13579         }
13580
13581         /* Dump Constraint Comments --- only works for table constraints */
13582         if (tbinfo && coninfo->separate)
13583                 dumpTableConstraintComment(fout, coninfo);
13584
13585         destroyPQExpBuffer(q);
13586         destroyPQExpBuffer(delq);
13587 }
13588
13589 /*
13590  * dumpTableConstraintComment --- dump a constraint's comment if any
13591  *
13592  * This is split out because we need the function in two different places
13593  * depending on whether the constraint is dumped as part of CREATE TABLE
13594  * or as a separate ALTER command.
13595  */
13596 static void
13597 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13598 {
13599         TableInfo  *tbinfo = coninfo->contable;
13600         PQExpBuffer labelq = createPQExpBuffer();
13601
13602         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13603                                           fmtId(coninfo->dobj.name));
13604         appendPQExpBuffer(labelq, "ON %s",
13605                                           fmtId(tbinfo->dobj.name));
13606         dumpComment(fout, labelq->data,
13607                                 tbinfo->dobj.namespace->dobj.name,
13608                                 tbinfo->rolname,
13609                                 coninfo->dobj.catId, 0,
13610                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13611
13612         destroyPQExpBuffer(labelq);
13613 }
13614
13615 /*
13616  * findLastBuiltInOid -
13617  * find the last built in oid
13618  *
13619  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13620  * pg_database entry for the current database
13621  */
13622 static Oid
13623 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13624 {
13625         PGresult   *res;
13626         Oid                     last_oid;
13627         PQExpBuffer query = createPQExpBuffer();
13628
13629         resetPQExpBuffer(query);
13630         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13631         appendStringLiteralAH(query, dbname, fout);
13632
13633         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13634         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13635         PQclear(res);
13636         destroyPQExpBuffer(query);
13637         return last_oid;
13638 }
13639
13640 /*
13641  * findLastBuiltInOid -
13642  * find the last built in oid
13643  *
13644  * For 7.0, we do this by assuming that the last thing that initdb does is to
13645  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13646  * initdb won't be changing anymore, it'll do.
13647  */
13648 static Oid
13649 findLastBuiltinOid_V70(Archive *fout)
13650 {
13651         PGresult   *res;
13652         int                     last_oid;
13653
13654         res = ExecuteSqlQueryForSingleRow(fout,
13655                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13656         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13657         PQclear(res);
13658         return last_oid;
13659 }
13660
13661 /*
13662  * dumpSequence
13663  *        write the declaration (not data) of one user-defined sequence
13664  */
13665 static void
13666 dumpSequence(Archive *fout, TableInfo *tbinfo)
13667 {
13668         PGresult   *res;
13669         char       *startv,
13670                            *incby,
13671                            *maxv = NULL,
13672                            *minv = NULL,
13673                            *cache;
13674         char            bufm[100],
13675                                 bufx[100];
13676         bool            cycled;
13677         PQExpBuffer query = createPQExpBuffer();
13678         PQExpBuffer delqry = createPQExpBuffer();
13679         PQExpBuffer labelq = createPQExpBuffer();
13680
13681         /* Make sure we are in proper schema */
13682         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13683
13684         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13685         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13686
13687         if (fout->remoteVersion >= 80400)
13688         {
13689                 appendPQExpBuffer(query,
13690                                                   "SELECT sequence_name, "
13691                                                   "start_value, increment_by, "
13692                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13693                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13694                                                   "     ELSE max_value "
13695                                                   "END AS max_value, "
13696                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13697                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13698                                                   "     ELSE min_value "
13699                                                   "END AS min_value, "
13700                                                   "cache_value, is_cycled FROM %s",
13701                                                   bufx, bufm,
13702                                                   fmtId(tbinfo->dobj.name));
13703         }
13704         else
13705         {
13706                 appendPQExpBuffer(query,
13707                                                   "SELECT sequence_name, "
13708                                                   "0 AS start_value, increment_by, "
13709                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13710                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13711                                                   "     ELSE max_value "
13712                                                   "END AS max_value, "
13713                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13714                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13715                                                   "     ELSE min_value "
13716                                                   "END AS min_value, "
13717                                                   "cache_value, is_cycled FROM %s",
13718                                                   bufx, bufm,
13719                                                   fmtId(tbinfo->dobj.name));
13720         }
13721
13722         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13723
13724         if (PQntuples(res) != 1)
13725         {
13726                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13727                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13728                                                                  PQntuples(res)),
13729                                   tbinfo->dobj.name, PQntuples(res));
13730                 exit_nicely(1);
13731         }
13732
13733         /* Disable this check: it fails if sequence has been renamed */
13734 #ifdef NOT_USED
13735         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13736         {
13737                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13738                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13739                 exit_nicely(1);
13740         }
13741 #endif
13742
13743         startv = PQgetvalue(res, 0, 1);
13744         incby = PQgetvalue(res, 0, 2);
13745         if (!PQgetisnull(res, 0, 3))
13746                 maxv = PQgetvalue(res, 0, 3);
13747         if (!PQgetisnull(res, 0, 4))
13748                 minv = PQgetvalue(res, 0, 4);
13749         cache = PQgetvalue(res, 0, 5);
13750         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13751
13752         /*
13753          * DROP must be fully qualified in case same name appears in pg_catalog
13754          */
13755         appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13756                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13757         appendPQExpBuffer(delqry, "%s;\n",
13758                                           fmtId(tbinfo->dobj.name));
13759
13760         resetPQExpBuffer(query);
13761
13762         if (binary_upgrade)
13763         {
13764                 binary_upgrade_set_pg_class_oids(fout, query,
13765                                                                                  tbinfo->dobj.catId.oid, false);
13766                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13767                                                                                                 tbinfo->dobj.catId.oid);
13768         }
13769
13770         appendPQExpBuffer(query,
13771                                           "CREATE SEQUENCE %s\n",
13772                                           fmtId(tbinfo->dobj.name));
13773
13774         if (fout->remoteVersion >= 80400)
13775                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
13776
13777         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13778
13779         if (minv)
13780                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13781         else
13782                 appendPQExpBuffer(query, "    NO MINVALUE\n");
13783
13784         if (maxv)
13785                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13786         else
13787                 appendPQExpBuffer(query, "    NO MAXVALUE\n");
13788
13789         appendPQExpBuffer(query,
13790                                           "    CACHE %s%s",
13791                                           cache, (cycled ? "\n    CYCLE" : ""));
13792
13793         appendPQExpBuffer(query, ";\n");
13794
13795         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13796
13797         /* binary_upgrade:      no need to clear TOAST table oid */
13798
13799         if (binary_upgrade)
13800                 binary_upgrade_extension_member(query, &tbinfo->dobj,
13801                                                                                 labelq->data);
13802
13803         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13804                                  tbinfo->dobj.name,
13805                                  tbinfo->dobj.namespace->dobj.name,
13806                                  NULL,
13807                                  tbinfo->rolname,
13808                                  false, "SEQUENCE", SECTION_PRE_DATA,
13809                                  query->data, delqry->data, NULL,
13810                                  NULL, 0,
13811                                  NULL, NULL);
13812
13813         /*
13814          * If the sequence is owned by a table column, emit the ALTER for it as a
13815          * separate TOC entry immediately following the sequence's own entry.
13816          * It's OK to do this rather than using full sorting logic, because the
13817          * dependency that tells us it's owned will have forced the table to be
13818          * created first.  We can't just include the ALTER in the TOC entry
13819          * because it will fail if we haven't reassigned the sequence owner to
13820          * match the table's owner.
13821          *
13822          * We need not schema-qualify the table reference because both sequence
13823          * and table must be in the same schema.
13824          */
13825         if (OidIsValid(tbinfo->owning_tab))
13826         {
13827                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13828
13829                 if (owning_tab && owning_tab->dobj.dump)
13830                 {
13831                         resetPQExpBuffer(query);
13832                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13833                                                           fmtId(tbinfo->dobj.name));
13834                         appendPQExpBuffer(query, " OWNED BY %s",
13835                                                           fmtId(owning_tab->dobj.name));
13836                         appendPQExpBuffer(query, ".%s;\n",
13837                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13838
13839                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
13840                                                  tbinfo->dobj.name,
13841                                                  tbinfo->dobj.namespace->dobj.name,
13842                                                  NULL,
13843                                                  tbinfo->rolname,
13844                                                  false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13845                                                  query->data, "", NULL,
13846                                                  &(tbinfo->dobj.dumpId), 1,
13847                                                  NULL, NULL);
13848                 }
13849         }
13850
13851         /* Dump Sequence Comments and Security Labels */
13852         dumpComment(fout, labelq->data,
13853                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13854                                 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13855         dumpSecLabel(fout, labelq->data,
13856                                  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13857                                  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13858
13859         PQclear(res);
13860
13861         destroyPQExpBuffer(query);
13862         destroyPQExpBuffer(delqry);
13863         destroyPQExpBuffer(labelq);
13864 }
13865
13866 /*
13867  * dumpSequenceData
13868  *        write the data of one user-defined sequence
13869  */
13870 static void
13871 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
13872 {
13873         TableInfo  *tbinfo = tdinfo->tdtable;
13874         PGresult   *res;
13875         char       *last;
13876         bool            called;
13877         PQExpBuffer query = createPQExpBuffer();
13878
13879         /* Make sure we are in proper schema */
13880         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13881
13882         appendPQExpBuffer(query,
13883                                           "SELECT last_value, is_called FROM %s",
13884                                           fmtId(tbinfo->dobj.name));
13885
13886         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13887
13888         if (PQntuples(res) != 1)
13889         {
13890                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13891                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13892                                                                  PQntuples(res)),
13893                                   tbinfo->dobj.name, PQntuples(res));
13894                 exit_nicely(1);
13895         }
13896
13897         last = PQgetvalue(res, 0, 0);
13898         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
13899
13900         resetPQExpBuffer(query);
13901         appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13902         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13903         appendPQExpBuffer(query, ", %s, %s);\n",
13904                                           last, (called ? "true" : "false"));
13905
13906         ArchiveEntry(fout, nilCatalogId, createDumpId(),
13907                                  tbinfo->dobj.name,
13908                                  tbinfo->dobj.namespace->dobj.name,
13909                                  NULL,
13910                                  tbinfo->rolname,
13911                                  false, "SEQUENCE SET", SECTION_DATA,
13912                                  query->data, "", NULL,
13913                                  &(tbinfo->dobj.dumpId), 1,
13914                                  NULL, NULL);
13915
13916         PQclear(res);
13917
13918         destroyPQExpBuffer(query);
13919 }
13920
13921 static void
13922 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13923 {
13924         TableInfo  *tbinfo = tginfo->tgtable;
13925         PQExpBuffer query;
13926         PQExpBuffer delqry;
13927         PQExpBuffer labelq;
13928         char       *tgargs;
13929         size_t          lentgargs;
13930         const char *p;
13931         int                     findx;
13932
13933         if (dataOnly)
13934                 return;
13935
13936         query = createPQExpBuffer();
13937         delqry = createPQExpBuffer();
13938         labelq = createPQExpBuffer();
13939
13940         /*
13941          * DROP must be fully qualified in case same name appears in pg_catalog
13942          */
13943         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13944                                           fmtId(tginfo->dobj.name));
13945         appendPQExpBuffer(delqry, "ON %s.",
13946                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13947         appendPQExpBuffer(delqry, "%s;\n",
13948                                           fmtId(tbinfo->dobj.name));
13949
13950         if (tginfo->tgdef)
13951         {
13952                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13953         }
13954         else
13955         {
13956                 if (tginfo->tgisconstraint)
13957                 {
13958                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13959                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13960                 }
13961                 else
13962                 {
13963                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13964                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13965                 }
13966                 appendPQExpBuffer(query, "\n    ");
13967
13968                 /* Trigger type */
13969                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13970                         appendPQExpBuffer(query, "BEFORE");
13971                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13972                         appendPQExpBuffer(query, "AFTER");
13973                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13974                         appendPQExpBuffer(query, "INSTEAD OF");
13975                 else
13976                 {
13977                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13978                         exit_nicely(1);
13979                 }
13980
13981                 findx = 0;
13982                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13983                 {
13984                         appendPQExpBuffer(query, " INSERT");
13985                         findx++;
13986                 }
13987                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13988                 {
13989                         if (findx > 0)
13990                                 appendPQExpBuffer(query, " OR DELETE");
13991                         else
13992                                 appendPQExpBuffer(query, " DELETE");
13993                         findx++;
13994                 }
13995                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13996                 {
13997                         if (findx > 0)
13998                                 appendPQExpBuffer(query, " OR UPDATE");
13999                         else
14000                                 appendPQExpBuffer(query, " UPDATE");
14001                         findx++;
14002                 }
14003                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
14004                 {
14005                         if (findx > 0)
14006                                 appendPQExpBuffer(query, " OR TRUNCATE");
14007                         else
14008                                 appendPQExpBuffer(query, " TRUNCATE");
14009                         findx++;
14010                 }
14011                 appendPQExpBuffer(query, " ON %s\n",
14012                                                   fmtId(tbinfo->dobj.name));
14013
14014                 if (tginfo->tgisconstraint)
14015                 {
14016                         if (OidIsValid(tginfo->tgconstrrelid))
14017                         {
14018                                 /* If we are using regclass, name is already quoted */
14019                                 if (fout->remoteVersion >= 70300)
14020                                         appendPQExpBuffer(query, "    FROM %s\n    ",
14021                                                                           tginfo->tgconstrrelname);
14022                                 else
14023                                         appendPQExpBuffer(query, "    FROM %s\n    ",
14024                                                                           fmtId(tginfo->tgconstrrelname));
14025                         }
14026                         if (!tginfo->tgdeferrable)
14027                                 appendPQExpBuffer(query, "NOT ");
14028                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
14029                         if (tginfo->tginitdeferred)
14030                                 appendPQExpBuffer(query, "DEFERRED\n");
14031                         else
14032                                 appendPQExpBuffer(query, "IMMEDIATE\n");
14033                 }
14034
14035                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
14036                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
14037                 else
14038                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
14039
14040                 /* In 7.3, result of regproc is already quoted */
14041                 if (fout->remoteVersion >= 70300)
14042                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14043                                                           tginfo->tgfname);
14044                 else
14045                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14046                                                           fmtId(tginfo->tgfname));
14047
14048                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
14049                                                                                   &lentgargs);
14050                 p = tgargs;
14051                 for (findx = 0; findx < tginfo->tgnargs; findx++)
14052                 {
14053                         /* find the embedded null that terminates this trigger argument */
14054                         size_t          tlen = strlen(p);
14055
14056                         if (p + tlen >= tgargs + lentgargs)
14057                         {
14058                                 /* hm, not found before end of bytea value... */
14059                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
14060                                                   tginfo->tgargs,
14061                                                   tginfo->dobj.name,
14062                                                   tbinfo->dobj.name);
14063                                 exit_nicely(1);
14064                         }
14065
14066                         if (findx > 0)
14067                                 appendPQExpBuffer(query, ", ");
14068                         appendStringLiteralAH(query, p, fout);
14069                         p += tlen + 1;
14070                 }
14071                 free(tgargs);
14072                 appendPQExpBuffer(query, ");\n");
14073         }
14074
14075         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
14076         {
14077                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
14078                                                   fmtId(tbinfo->dobj.name));
14079                 switch (tginfo->tgenabled)
14080                 {
14081                         case 'D':
14082                         case 'f':
14083                                 appendPQExpBuffer(query, "DISABLE");
14084                                 break;
14085                         case 'A':
14086                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
14087                                 break;
14088                         case 'R':
14089                                 appendPQExpBuffer(query, "ENABLE REPLICA");
14090                                 break;
14091                         default:
14092                                 appendPQExpBuffer(query, "ENABLE");
14093                                 break;
14094                 }
14095                 appendPQExpBuffer(query, " TRIGGER %s;\n",
14096                                                   fmtId(tginfo->dobj.name));
14097         }
14098
14099         appendPQExpBuffer(labelq, "TRIGGER %s ",
14100                                           fmtId(tginfo->dobj.name));
14101         appendPQExpBuffer(labelq, "ON %s",
14102                                           fmtId(tbinfo->dobj.name));
14103
14104         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
14105                                  tginfo->dobj.name,
14106                                  tbinfo->dobj.namespace->dobj.name,
14107                                  NULL,
14108                                  tbinfo->rolname, false,
14109                                  "TRIGGER", SECTION_POST_DATA,
14110                                  query->data, delqry->data, NULL,
14111                                  NULL, 0,
14112                                  NULL, NULL);
14113
14114         dumpComment(fout, labelq->data,
14115                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14116                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
14117
14118         destroyPQExpBuffer(query);
14119         destroyPQExpBuffer(delqry);
14120         destroyPQExpBuffer(labelq);
14121 }
14122
14123 static void
14124 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
14125 {
14126         PQExpBuffer query;
14127         PQExpBuffer labelq;
14128
14129         query = createPQExpBuffer();
14130         labelq = createPQExpBuffer();
14131
14132         appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
14133         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
14134         appendPQExpBuffer(query, " ON ");
14135         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
14136         appendPQExpBufferStr(query, " ");
14137
14138         if (strcmp("", evtinfo->evttags) != 0)
14139         {
14140                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
14141                 appendPQExpBufferStr(query, evtinfo->evttags);
14142                 appendPQExpBufferStr(query, ") ");
14143         }
14144
14145         appendPQExpBuffer(query, "\n   EXECUTE PROCEDURE ");
14146         appendPQExpBufferStr(query, evtinfo->evtfname);
14147         appendPQExpBuffer(query, "();\n");
14148
14149         if (evtinfo->evtenabled != 'O')
14150         {
14151                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
14152                                                   fmtId(evtinfo->dobj.name));
14153                 switch (evtinfo->evtenabled)
14154                 {
14155                         case 'D':
14156                                 appendPQExpBuffer(query, "DISABLE");
14157                                 break;
14158                         case 'A':
14159                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
14160                                 break;
14161                         case 'R':
14162                                 appendPQExpBuffer(query, "ENABLE REPLICA");
14163                                 break;
14164                         default:
14165                                 appendPQExpBuffer(query, "ENABLE");
14166                                 break;
14167                 }
14168                 appendPQExpBuffer(query, ";\n");
14169         }
14170         appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
14171                                           fmtId(evtinfo->dobj.name));
14172
14173         ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
14174                                  evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
14175                                  "EVENT TRIGGER", SECTION_POST_DATA,
14176                                  query->data, "", NULL, NULL, 0, NULL, NULL);
14177
14178         dumpComment(fout, labelq->data,
14179                                 NULL, NULL,
14180                                 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
14181
14182         destroyPQExpBuffer(query);
14183         destroyPQExpBuffer(labelq);
14184 }
14185
14186 /*
14187  * dumpRule
14188  *              Dump a rule
14189  */
14190 static void
14191 dumpRule(Archive *fout, RuleInfo *rinfo)
14192 {
14193         TableInfo  *tbinfo = rinfo->ruletable;
14194         PQExpBuffer query;
14195         PQExpBuffer cmd;
14196         PQExpBuffer delcmd;
14197         PQExpBuffer labelq;
14198         PGresult   *res;
14199
14200         /* Skip if not to be dumped */
14201         if (!rinfo->dobj.dump || dataOnly)
14202                 return;
14203
14204         /*
14205          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
14206          * we do not want to dump it as a separate object.
14207          */
14208         if (!rinfo->separate)
14209                 return;
14210
14211         /*
14212          * Make sure we are in proper schema.
14213          */
14214         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14215
14216         query = createPQExpBuffer();
14217         cmd = createPQExpBuffer();
14218         delcmd = createPQExpBuffer();
14219         labelq = createPQExpBuffer();
14220
14221         if (fout->remoteVersion >= 70300)
14222         {
14223                 appendPQExpBuffer(query,
14224                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14225                                                   rinfo->dobj.catId.oid);
14226         }
14227         else
14228         {
14229                 /* Rule name was unique before 7.3 ... */
14230                 appendPQExpBuffer(query,
14231                                                   "SELECT pg_get_ruledef('%s') AS definition",
14232                                                   rinfo->dobj.name);
14233         }
14234
14235         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14236
14237         if (PQntuples(res) != 1)
14238         {
14239                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14240                                   rinfo->dobj.name, tbinfo->dobj.name);
14241                 exit_nicely(1);
14242         }
14243
14244         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14245
14246         /*
14247          * Add the command to alter the rules replication firing semantics if it
14248          * differs from the default.
14249          */
14250         if (rinfo->ev_enabled != 'O')
14251         {
14252                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14253                 switch (rinfo->ev_enabled)
14254                 {
14255                         case 'A':
14256                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14257                                                                   fmtId(rinfo->dobj.name));
14258                                 break;
14259                         case 'R':
14260                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14261                                                                   fmtId(rinfo->dobj.name));
14262                                 break;
14263                         case 'D':
14264                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14265                                                                   fmtId(rinfo->dobj.name));
14266                                 break;
14267                 }
14268         }
14269
14270         /*
14271          * Apply view's reloptions when its ON SELECT rule is separate.
14272          */
14273         if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14274         {
14275                 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14276                                                   fmtId(tbinfo->dobj.name),
14277                                                   rinfo->reloptions);
14278         }
14279
14280         /*
14281          * DROP must be fully qualified in case same name appears in pg_catalog
14282          */
14283         appendPQExpBuffer(delcmd, "DROP RULE %s ",
14284                                           fmtId(rinfo->dobj.name));
14285         appendPQExpBuffer(delcmd, "ON %s.",
14286                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14287         appendPQExpBuffer(delcmd, "%s;\n",
14288                                           fmtId(tbinfo->dobj.name));
14289
14290         appendPQExpBuffer(labelq, "RULE %s",
14291                                           fmtId(rinfo->dobj.name));
14292         appendPQExpBuffer(labelq, " ON %s",
14293                                           fmtId(tbinfo->dobj.name));
14294
14295         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14296                                  rinfo->dobj.name,
14297                                  tbinfo->dobj.namespace->dobj.name,
14298                                  NULL,
14299                                  tbinfo->rolname, false,
14300                                  "RULE", SECTION_POST_DATA,
14301                                  cmd->data, delcmd->data, NULL,
14302                                  NULL, 0,
14303                                  NULL, NULL);
14304
14305         /* Dump rule comments */
14306         dumpComment(fout, labelq->data,
14307                                 tbinfo->dobj.namespace->dobj.name,
14308                                 tbinfo->rolname,
14309                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14310
14311         PQclear(res);
14312
14313         destroyPQExpBuffer(query);
14314         destroyPQExpBuffer(cmd);
14315         destroyPQExpBuffer(delcmd);
14316         destroyPQExpBuffer(labelq);
14317 }
14318
14319 /*
14320  * getExtensionMembership --- obtain extension membership data
14321  */
14322 void
14323 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14324                                            int numExtensions)
14325 {
14326         PQExpBuffer query;
14327         PGresult   *res;
14328         int                     ntups,
14329                                 i;
14330         int                     i_classid,
14331                                 i_objid,
14332                                 i_refclassid,
14333                                 i_refobjid;
14334         DumpableObject *dobj,
14335                            *refdobj;
14336
14337         /* Nothing to do if no extensions */
14338         if (numExtensions == 0)
14339                 return;
14340
14341         /* Make sure we are in proper schema */
14342         selectSourceSchema(fout, "pg_catalog");
14343
14344         query = createPQExpBuffer();
14345
14346         /* refclassid constraint is redundant but may speed the search */
14347         appendPQExpBuffer(query, "SELECT "
14348                                           "classid, objid, refclassid, refobjid "
14349                                           "FROM pg_depend "
14350                                           "WHERE refclassid = 'pg_extension'::regclass "
14351                                           "AND deptype = 'e' "
14352                                           "ORDER BY 3,4");
14353
14354         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14355
14356         ntups = PQntuples(res);
14357
14358         i_classid = PQfnumber(res, "classid");
14359         i_objid = PQfnumber(res, "objid");
14360         i_refclassid = PQfnumber(res, "refclassid");
14361         i_refobjid = PQfnumber(res, "refobjid");
14362
14363         /*
14364          * Since we ordered the SELECT by referenced ID, we can expect that
14365          * multiple entries for the same extension will appear together; this
14366          * saves on searches.
14367          */
14368         refdobj = NULL;
14369
14370         for (i = 0; i < ntups; i++)
14371         {
14372                 CatalogId       objId;
14373                 CatalogId       refobjId;
14374
14375                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14376                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14377                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14378                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14379
14380                 if (refdobj == NULL ||
14381                         refdobj->catId.tableoid != refobjId.tableoid ||
14382                         refdobj->catId.oid != refobjId.oid)
14383                         refdobj = findObjectByCatalogId(refobjId);
14384
14385                 /*
14386                  * Failure to find objects mentioned in pg_depend is not unexpected,
14387                  * since for example we don't collect info about TOAST tables.
14388                  */
14389                 if (refdobj == NULL)
14390                 {
14391 #ifdef NOT_USED
14392                         fprintf(stderr, "no referenced object %u %u\n",
14393                                         refobjId.tableoid, refobjId.oid);
14394 #endif
14395                         continue;
14396                 }
14397
14398                 dobj = findObjectByCatalogId(objId);
14399
14400                 if (dobj == NULL)
14401                 {
14402 #ifdef NOT_USED
14403                         fprintf(stderr, "no referencing object %u %u\n",
14404                                         objId.tableoid, objId.oid);
14405 #endif
14406                         continue;
14407                 }
14408
14409                 /* Record dependency so that getDependencies needn't repeat this */
14410                 addObjectDependency(dobj, refdobj->dumpId);
14411
14412                 dobj->ext_member = true;
14413
14414                 /*
14415                  * Normally, mark the member object as not to be dumped.  But in
14416                  * binary upgrades, we still dump the members individually, since the
14417                  * idea is to exactly reproduce the database contents rather than
14418                  * replace the extension contents with something different.
14419                  */
14420                 if (!binary_upgrade)
14421                         dobj->dump = false;
14422                 else
14423                         dobj->dump = refdobj->dump;
14424         }
14425
14426         PQclear(res);
14427
14428         /*
14429          * Now identify extension configuration tables and create TableDataInfo
14430          * objects for them, ensuring their data will be dumped even though the
14431          * tables themselves won't be.
14432          *
14433          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14434          * user data in a configuration table is treated like schema data. This
14435          * seems appropriate since system data in a config table would get
14436          * reloaded by CREATE EXTENSION.
14437          */
14438         for (i = 0; i < numExtensions; i++)
14439         {
14440                 ExtensionInfo *curext = &(extinfo[i]);
14441                 char       *extconfig = curext->extconfig;
14442                 char       *extcondition = curext->extcondition;
14443                 char      **extconfigarray = NULL;
14444                 char      **extconditionarray = NULL;
14445                 int                     nconfigitems;
14446                 int                     nconditionitems;
14447
14448                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14449                 if (!curext->dobj.dump)
14450                         continue;
14451
14452                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14453                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14454                         nconfigitems == nconditionitems)
14455                 {
14456                         int                     j;
14457
14458                         for (j = 0; j < nconfigitems; j++)
14459                         {
14460                                 TableInfo  *configtbl;
14461
14462                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
14463                                 if (configtbl == NULL)
14464                                         continue;
14465
14466                                 /*
14467                                  * Note: config tables are dumped without OIDs regardless of
14468                                  * the --oids setting.  This is because row filtering
14469                                  * conditions aren't compatible with dumping OIDs.
14470                                  */
14471                                 makeTableDataInfo(configtbl, false);
14472                                 if (configtbl->dataObj != NULL)
14473                                 {
14474                                         if (strlen(extconditionarray[j]) > 0)
14475                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14476                                 }
14477                         }
14478                 }
14479                 if (extconfigarray)
14480                         free(extconfigarray);
14481                 if (extconditionarray)
14482                         free(extconditionarray);
14483         }
14484
14485         destroyPQExpBuffer(query);
14486 }
14487
14488 /*
14489  * getDependencies --- obtain available dependency data
14490  */
14491 static void
14492 getDependencies(Archive *fout)
14493 {
14494         PQExpBuffer query;
14495         PGresult   *res;
14496         int                     ntups,
14497                                 i;
14498         int                     i_classid,
14499                                 i_objid,
14500                                 i_refclassid,
14501                                 i_refobjid,
14502                                 i_deptype;
14503         DumpableObject *dobj,
14504                            *refdobj;
14505
14506         /* No dependency info available before 7.3 */
14507         if (fout->remoteVersion < 70300)
14508                 return;
14509
14510         if (g_verbose)
14511                 write_msg(NULL, "reading dependency data\n");
14512
14513         /* Make sure we are in proper schema */
14514         selectSourceSchema(fout, "pg_catalog");
14515
14516         query = createPQExpBuffer();
14517
14518         /*
14519          * PIN dependencies aren't interesting, and EXTENSION dependencies were
14520          * already processed by getExtensionMembership.
14521          */
14522         appendPQExpBuffer(query, "SELECT "
14523                                           "classid, objid, refclassid, refobjid, deptype "
14524                                           "FROM pg_depend "
14525                                           "WHERE deptype != 'p' AND deptype != 'e' "
14526                                           "ORDER BY 1,2");
14527
14528         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14529
14530         ntups = PQntuples(res);
14531
14532         i_classid = PQfnumber(res, "classid");
14533         i_objid = PQfnumber(res, "objid");
14534         i_refclassid = PQfnumber(res, "refclassid");
14535         i_refobjid = PQfnumber(res, "refobjid");
14536         i_deptype = PQfnumber(res, "deptype");
14537
14538         /*
14539          * Since we ordered the SELECT by referencing ID, we can expect that
14540          * multiple entries for the same object will appear together; this saves
14541          * on searches.
14542          */
14543         dobj = NULL;
14544
14545         for (i = 0; i < ntups; i++)
14546         {
14547                 CatalogId       objId;
14548                 CatalogId       refobjId;
14549                 char            deptype;
14550
14551                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14552                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14553                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14554                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14555                 deptype = *(PQgetvalue(res, i, i_deptype));
14556
14557                 if (dobj == NULL ||
14558                         dobj->catId.tableoid != objId.tableoid ||
14559                         dobj->catId.oid != objId.oid)
14560                         dobj = findObjectByCatalogId(objId);
14561
14562                 /*
14563                  * Failure to find objects mentioned in pg_depend is not unexpected,
14564                  * since for example we don't collect info about TOAST tables.
14565                  */
14566                 if (dobj == NULL)
14567                 {
14568 #ifdef NOT_USED
14569                         fprintf(stderr, "no referencing object %u %u\n",
14570                                         objId.tableoid, objId.oid);
14571 #endif
14572                         continue;
14573                 }
14574
14575                 refdobj = findObjectByCatalogId(refobjId);
14576
14577                 if (refdobj == NULL)
14578                 {
14579 #ifdef NOT_USED
14580                         fprintf(stderr, "no referenced object %u %u\n",
14581                                         refobjId.tableoid, refobjId.oid);
14582 #endif
14583                         continue;
14584                 }
14585
14586                 /*
14587                  * Ordinarily, table rowtypes have implicit dependencies on their
14588                  * tables.      However, for a composite type the implicit dependency goes
14589                  * the other way in pg_depend; which is the right thing for DROP but
14590                  * it doesn't produce the dependency ordering we need. So in that one
14591                  * case, we reverse the direction of the dependency.
14592                  */
14593                 if (deptype == 'i' &&
14594                         dobj->objType == DO_TABLE &&
14595                         refdobj->objType == DO_TYPE)
14596                         addObjectDependency(refdobj, dobj->dumpId);
14597                 else
14598                         /* normal case */
14599                         addObjectDependency(dobj, refdobj->dumpId);
14600         }
14601
14602         PQclear(res);
14603
14604         destroyPQExpBuffer(query);
14605 }
14606
14607
14608 /*
14609  * createBoundaryObjects - create dummy DumpableObjects to represent
14610  * dump section boundaries.
14611  */
14612 static DumpableObject *
14613 createBoundaryObjects(void)
14614 {
14615         DumpableObject *dobjs;
14616
14617         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14618
14619         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14620         dobjs[0].catId = nilCatalogId;
14621         AssignDumpId(dobjs + 0);
14622         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14623
14624         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14625         dobjs[1].catId = nilCatalogId;
14626         AssignDumpId(dobjs + 1);
14627         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14628
14629         return dobjs;
14630 }
14631
14632 /*
14633  * addBoundaryDependencies - add dependencies as needed to enforce the dump
14634  * section boundaries.
14635  */
14636 static void
14637 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14638                                                 DumpableObject *boundaryObjs)
14639 {
14640         DumpableObject *preDataBound = boundaryObjs + 0;
14641         DumpableObject *postDataBound = boundaryObjs + 1;
14642         int                     i;
14643
14644         for (i = 0; i < numObjs; i++)
14645         {
14646                 DumpableObject *dobj = dobjs[i];
14647
14648                 /*
14649                  * The classification of object types here must match the SECTION_xxx
14650                  * values assigned during subsequent ArchiveEntry calls!
14651                  */
14652                 switch (dobj->objType)
14653                 {
14654                         case DO_NAMESPACE:
14655                         case DO_EXTENSION:
14656                         case DO_TYPE:
14657                         case DO_SHELL_TYPE:
14658                         case DO_FUNC:
14659                         case DO_AGG:
14660                         case DO_OPERATOR:
14661                         case DO_OPCLASS:
14662                         case DO_OPFAMILY:
14663                         case DO_COLLATION:
14664                         case DO_CONVERSION:
14665                         case DO_TABLE:
14666                         case DO_ATTRDEF:
14667                         case DO_PROCLANG:
14668                         case DO_CAST:
14669                         case DO_DUMMY_TYPE:
14670                         case DO_TSPARSER:
14671                         case DO_TSDICT:
14672                         case DO_TSTEMPLATE:
14673                         case DO_TSCONFIG:
14674                         case DO_FDW:
14675                         case DO_FOREIGN_SERVER:
14676                         case DO_BLOB:
14677                                 /* Pre-data objects: must come before the pre-data boundary */
14678                                 addObjectDependency(preDataBound, dobj->dumpId);
14679                                 break;
14680                         case DO_TABLE_DATA:
14681                         case DO_BLOB_DATA:
14682                                 /* Data objects: must come between the boundaries */
14683                                 addObjectDependency(dobj, preDataBound->dumpId);
14684                                 addObjectDependency(postDataBound, dobj->dumpId);
14685                                 break;
14686                         case DO_INDEX:
14687                         case DO_REFRESH_MATVIEW:
14688                         case DO_TRIGGER:
14689                         case DO_EVENT_TRIGGER:
14690                         case DO_DEFAULT_ACL:
14691                                 /* Post-data objects: must come after the post-data boundary */
14692                                 addObjectDependency(dobj, postDataBound->dumpId);
14693                                 break;
14694                         case DO_RULE:
14695                                 /* Rules are post-data, but only if dumped separately */
14696                                 if (((RuleInfo *) dobj)->separate)
14697                                         addObjectDependency(dobj, postDataBound->dumpId);
14698                                 break;
14699                         case DO_CONSTRAINT:
14700                         case DO_FK_CONSTRAINT:
14701                                 /* Constraints are post-data, but only if dumped separately */
14702                                 if (((ConstraintInfo *) dobj)->separate)
14703                                         addObjectDependency(dobj, postDataBound->dumpId);
14704                                 break;
14705                         case DO_PRE_DATA_BOUNDARY:
14706                                 /* nothing to do */
14707                                 break;
14708                         case DO_POST_DATA_BOUNDARY:
14709                                 /* must come after the pre-data boundary */
14710                                 addObjectDependency(dobj, preDataBound->dumpId);
14711                                 break;
14712                 }
14713         }
14714 }
14715
14716
14717 /*
14718  * BuildArchiveDependencies - create dependency data for archive TOC entries
14719  *
14720  * The raw dependency data obtained by getDependencies() is not terribly
14721  * useful in an archive dump, because in many cases there are dependency
14722  * chains linking through objects that don't appear explicitly in the dump.
14723  * For example, a view will depend on its _RETURN rule while the _RETURN rule
14724  * will depend on other objects --- but the rule will not appear as a separate
14725  * object in the dump.  We need to adjust the view's dependencies to include
14726  * whatever the rule depends on that is included in the dump.
14727  *
14728  * Just to make things more complicated, there are also "special" dependencies
14729  * such as the dependency of a TABLE DATA item on its TABLE, which we must
14730  * not rearrange because pg_restore knows that TABLE DATA only depends on
14731  * its table.  In these cases we must leave the dependencies strictly as-is
14732  * even if they refer to not-to-be-dumped objects.
14733  *
14734  * To handle this, the convention is that "special" dependencies are created
14735  * during ArchiveEntry calls, and an archive TOC item that has any such
14736  * entries will not be touched here.  Otherwise, we recursively search the
14737  * DumpableObject data structures to build the correct dependencies for each
14738  * archive TOC item.
14739  */
14740 static void
14741 BuildArchiveDependencies(Archive *fout)
14742 {
14743         ArchiveHandle *AH = (ArchiveHandle *) fout;
14744         TocEntry   *te;
14745
14746         /* Scan all TOC entries in the archive */
14747         for (te = AH->toc->next; te != AH->toc; te = te->next)
14748         {
14749                 DumpableObject *dobj;
14750                 DumpId     *dependencies;
14751                 int                     nDeps;
14752                 int                     allocDeps;
14753
14754                 /* No need to process entries that will not be dumped */
14755                 if (te->reqs == 0)
14756                         continue;
14757                 /* Ignore entries that already have "special" dependencies */
14758                 if (te->nDeps > 0)
14759                         continue;
14760                 /* Otherwise, look up the item's original DumpableObject, if any */
14761                 dobj = findObjectByDumpId(te->dumpId);
14762                 if (dobj == NULL)
14763                         continue;
14764                 /* No work if it has no dependencies */
14765                 if (dobj->nDeps <= 0)
14766                         continue;
14767                 /* Set up work array */
14768                 allocDeps = 64;
14769                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14770                 nDeps = 0;
14771                 /* Recursively find all dumpable dependencies */
14772                 findDumpableDependencies(AH, dobj,
14773                                                                  &dependencies, &nDeps, &allocDeps);
14774                 /* And save 'em ... */
14775                 if (nDeps > 0)
14776                 {
14777                         dependencies = (DumpId *) pg_realloc(dependencies,
14778                                                                                                  nDeps * sizeof(DumpId));
14779                         te->dependencies = dependencies;
14780                         te->nDeps = nDeps;
14781                 }
14782                 else
14783                         free(dependencies);
14784         }
14785 }
14786
14787 /* Recursive search subroutine for BuildArchiveDependencies */
14788 static void
14789 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14790                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
14791 {
14792         int                     i;
14793
14794         /*
14795          * Ignore section boundary objects: if we search through them, we'll
14796          * report lots of bogus dependencies.
14797          */
14798         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14799                 dobj->objType == DO_POST_DATA_BOUNDARY)
14800                 return;
14801
14802         for (i = 0; i < dobj->nDeps; i++)
14803         {
14804                 DumpId          depid = dobj->dependencies[i];
14805
14806                 if (TocIDRequired(AH, depid) != 0)
14807                 {
14808                         /* Object will be dumped, so just reference it as a dependency */
14809                         if (*nDeps >= *allocDeps)
14810                         {
14811                                 *allocDeps *= 2;
14812                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
14813                                                                                           *allocDeps * sizeof(DumpId));
14814                         }
14815                         (*dependencies)[*nDeps] = depid;
14816                         (*nDeps)++;
14817                 }
14818                 else
14819                 {
14820                         /*
14821                          * Object will not be dumped, so recursively consider its deps.
14822                          * We rely on the assumption that sortDumpableObjects already
14823                          * broke any dependency loops, else we might recurse infinitely.
14824                          */
14825                         DumpableObject *otherdobj = findObjectByDumpId(depid);
14826
14827                         if (otherdobj)
14828                                 findDumpableDependencies(AH, otherdobj,
14829                                                                                  dependencies, nDeps, allocDeps);
14830                 }
14831         }
14832 }
14833
14834
14835 /*
14836  * selectSourceSchema - make the specified schema the active search path
14837  * in the source database.
14838  *
14839  * NB: pg_catalog is explicitly searched after the specified schema;
14840  * so user names are only qualified if they are cross-schema references,
14841  * and system names are only qualified if they conflict with a user name
14842  * in the current schema.
14843  *
14844  * Whenever the selected schema is not pg_catalog, be careful to qualify
14845  * references to system catalogs and types in our emitted commands!
14846  */
14847 static void
14848 selectSourceSchema(Archive *fout, const char *schemaName)
14849 {
14850         static char *curSchemaName = NULL;
14851         PQExpBuffer query;
14852
14853         /* Not relevant if fetching from pre-7.3 DB */
14854         if (fout->remoteVersion < 70300)
14855                 return;
14856         /* Ignore null schema names */
14857         if (schemaName == NULL || *schemaName == '\0')
14858                 return;
14859         /* Optimize away repeated selection of same schema */
14860         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14861                 return;
14862
14863         query = createPQExpBuffer();
14864         appendPQExpBuffer(query, "SET search_path = %s",
14865                                           fmtId(schemaName));
14866         if (strcmp(schemaName, "pg_catalog") != 0)
14867                 appendPQExpBuffer(query, ", pg_catalog");
14868
14869         ExecuteSqlStatement(fout, query->data);
14870
14871         destroyPQExpBuffer(query);
14872         if (curSchemaName)
14873                 free(curSchemaName);
14874         curSchemaName = pg_strdup(schemaName);
14875 }
14876
14877 /*
14878  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14879  * given type name.
14880  *
14881  * NB: in 7.3 and up the result may depend on the currently-selected
14882  * schema; this is why we don't try to cache the names.
14883  */
14884 static char *
14885 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14886 {
14887         char       *result;
14888         PQExpBuffer query;
14889         PGresult   *res;
14890
14891         if (oid == 0)
14892         {
14893                 if ((opts & zeroAsOpaque) != 0)
14894                         return pg_strdup(g_opaque_type);
14895                 else if ((opts & zeroAsAny) != 0)
14896                         return pg_strdup("'any'");
14897                 else if ((opts & zeroAsStar) != 0)
14898                         return pg_strdup("*");
14899                 else if ((opts & zeroAsNone) != 0)
14900                         return pg_strdup("NONE");
14901         }
14902
14903         query = createPQExpBuffer();
14904         if (fout->remoteVersion >= 70300)
14905         {
14906                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14907                                                   oid);
14908         }
14909         else if (fout->remoteVersion >= 70100)
14910         {
14911                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14912                                                   oid);
14913         }
14914         else
14915         {
14916                 appendPQExpBuffer(query, "SELECT typname "
14917                                                   "FROM pg_type "
14918                                                   "WHERE oid = '%u'::oid",
14919                                                   oid);
14920         }
14921
14922         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14923
14924         if (fout->remoteVersion >= 70100)
14925         {
14926                 /* already quoted */
14927                 result = pg_strdup(PQgetvalue(res, 0, 0));
14928         }
14929         else
14930         {
14931                 /* may need to quote it */
14932                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14933         }
14934
14935         PQclear(res);
14936         destroyPQExpBuffer(query);
14937
14938         return result;
14939 }
14940
14941 /*
14942  * myFormatType --- local implementation of format_type for use with 7.0.
14943  */
14944 static char *
14945 myFormatType(const char *typname, int32 typmod)
14946 {
14947         char       *result;
14948         bool            isarray = false;
14949         PQExpBuffer buf = createPQExpBuffer();
14950
14951         /* Handle array types */
14952         if (typname[0] == '_')
14953         {
14954                 isarray = true;
14955                 typname++;
14956         }
14957
14958         /* Show lengths on bpchar and varchar */
14959         if (strcmp(typname, "bpchar") == 0)
14960         {
14961                 int                     len = (typmod - VARHDRSZ);
14962
14963                 appendPQExpBuffer(buf, "character");
14964                 if (len > 1)
14965                         appendPQExpBuffer(buf, "(%d)",
14966                                                           typmod - VARHDRSZ);
14967         }
14968         else if (strcmp(typname, "varchar") == 0)
14969         {
14970                 appendPQExpBuffer(buf, "character varying");
14971                 if (typmod != -1)
14972                         appendPQExpBuffer(buf, "(%d)",
14973                                                           typmod - VARHDRSZ);
14974         }
14975         else if (strcmp(typname, "numeric") == 0)
14976         {
14977                 appendPQExpBuffer(buf, "numeric");
14978                 if (typmod != -1)
14979                 {
14980                         int32           tmp_typmod;
14981                         int                     precision;
14982                         int                     scale;
14983
14984                         tmp_typmod = typmod - VARHDRSZ;
14985                         precision = (tmp_typmod >> 16) & 0xffff;
14986                         scale = tmp_typmod & 0xffff;
14987                         appendPQExpBuffer(buf, "(%d,%d)",
14988                                                           precision, scale);
14989                 }
14990         }
14991
14992         /*
14993          * char is an internal single-byte data type; Let's make sure we force it
14994          * through with quotes. - thomas 1998-12-13
14995          */
14996         else if (strcmp(typname, "char") == 0)
14997                 appendPQExpBuffer(buf, "\"char\"");
14998         else
14999                 appendPQExpBuffer(buf, "%s", fmtId(typname));
15000
15001         /* Append array qualifier for array types */
15002         if (isarray)
15003                 appendPQExpBuffer(buf, "[]");
15004
15005         result = pg_strdup(buf->data);
15006         destroyPQExpBuffer(buf);
15007
15008         return result;
15009 }
15010
15011 /*
15012  * fmtQualifiedId - convert a qualified name to the proper format for
15013  * the source database.
15014  *
15015  * Like fmtId, use the result before calling again.
15016  */
15017 static const char *
15018 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
15019 {
15020         static PQExpBuffer id_return = NULL;
15021
15022         if (id_return)                          /* first time through? */
15023                 resetPQExpBuffer(id_return);
15024         else
15025                 id_return = createPQExpBuffer();
15026
15027         /* Suppress schema name if fetching from pre-7.3 DB */
15028         if (fout->remoteVersion >= 70300 && schema && *schema)
15029         {
15030                 appendPQExpBuffer(id_return, "%s.",
15031                                                   fmtId(schema));
15032         }
15033         appendPQExpBuffer(id_return, "%s",
15034                                           fmtId(id));
15035
15036         return id_return->data;
15037 }
15038
15039 /*
15040  * Return a column list clause for the given relation.
15041  *
15042  * Special case: if there are no undropped columns in the relation, return
15043  * "", not an invalid "()" column list.
15044  */
15045 static const char *
15046 fmtCopyColumnList(const TableInfo *ti)
15047 {
15048         static PQExpBuffer q = NULL;
15049         int                     numatts = ti->numatts;
15050         char      **attnames = ti->attnames;
15051         bool       *attisdropped = ti->attisdropped;
15052         bool            needComma;
15053         int                     i;
15054
15055         if (q)                                          /* first time through? */
15056                 resetPQExpBuffer(q);
15057         else
15058                 q = createPQExpBuffer();
15059
15060         appendPQExpBuffer(q, "(");
15061         needComma = false;
15062         for (i = 0; i < numatts; i++)
15063         {
15064                 if (attisdropped[i])
15065                         continue;
15066                 if (needComma)
15067                         appendPQExpBuffer(q, ", ");
15068                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
15069                 needComma = true;
15070         }
15071
15072         if (!needComma)
15073                 return "";                              /* no undropped columns */
15074
15075         appendPQExpBuffer(q, ")");
15076         return q->data;
15077 }
15078
15079 /*
15080  * Execute an SQL query and verify that we got exactly one row back.
15081  */
15082 static PGresult *
15083 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
15084 {
15085         PGresult   *res;
15086         int                     ntups;
15087
15088         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
15089
15090         /* Expecting a single result only */
15091         ntups = PQntuples(res);
15092         if (ntups != 1)
15093                 exit_horribly(NULL,
15094                                           ngettext("query returned %d row instead of one: %s\n",
15095                                                            "query returned %d rows instead of one: %s\n",
15096                                                            ntups),
15097                                           ntups, query);
15098
15099         return res;
15100 }