]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
WITH CHECK OPTION support for auto-updatable VIEWs
[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 look at
18  *      the currently committed state.  So it is possible to get 'cache
19  *      lookup failed' error if someone performs DDL changes while a dump is
20  *      happening. The window for this sort of thing is from the acquisition
21  *      of the transaction snapshot to getSchemaData() (when pg_dump acquires
22  *      AccessShareLock on every table it intends to dump). It isn't very large,
23  *      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 "pg_backup_utils.h"
63 #include "dumputils.h"
64 #include "parallel.h"
65
66 extern char *optarg;
67 extern int      optind,
68                         opterr;
69
70
71 typedef struct
72 {
73         const char *descr;                      /* comment for an object */
74         Oid                     classoid;               /* object class (catalog OID) */
75         Oid                     objoid;                 /* object OID */
76         int                     objsubid;               /* subobject (table column #) */
77 } CommentItem;
78
79 typedef struct
80 {
81         const char *provider;           /* label provider of this security label */
82         const char *label;                      /* security label for an object */
83         Oid                     classoid;               /* object class (catalog OID) */
84         Oid                     objoid;                 /* object OID */
85         int                     objsubid;               /* subobject (table column #) */
86 } SecLabelItem;
87
88 /* global decls */
89 bool            g_verbose;                      /* User wants verbose narration of our
90                                                                  * activities. */
91
92 /* various user-settable parameters */
93 bool            schemaOnly;
94 bool            dataOnly;
95 int                     dumpSections;           /* bitmask of chosen sections */
96 bool            aclsSkip;
97 const char *lockWaitTimeout;
98
99 /* subquery used to convert user ID (eg, datdba) to user name */
100 static const char *username_subquery;
101
102 /* obsolete as of 7.3: */
103 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
104
105 /*
106  * Object inclusion/exclusion lists
107  *
108  * The string lists record the patterns given by command-line switches,
109  * which we then convert to lists of OIDs of matching objects.
110  */
111 static SimpleStringList schema_include_patterns = {NULL, NULL};
112 static SimpleOidList schema_include_oids = {NULL, NULL};
113 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
114 static SimpleOidList schema_exclude_oids = {NULL, NULL};
115
116 static SimpleStringList table_include_patterns = {NULL, NULL};
117 static SimpleOidList table_include_oids = {NULL, NULL};
118 static SimpleStringList table_exclude_patterns = {NULL, NULL};
119 static SimpleOidList table_exclude_oids = {NULL, NULL};
120 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
121 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
122
123 /* default, if no "inclusion" switches appear, is to dump everything */
124 static bool include_everything = true;
125
126 char            g_opaque_type[10];      /* name for the opaque type */
127
128 /* placeholders for the delimiters for comments */
129 char            g_comment_start[10];
130 char            g_comment_end[10];
131
132 static const CatalogId nilCatalogId = {0, 0};
133
134 /* flags for various command-line long options */
135 static int      binary_upgrade = 0;
136 static int      disable_dollar_quoting = 0;
137 static int      dump_inserts = 0;
138 static int      column_inserts = 0;
139 static int      no_security_labels = 0;
140 static int      no_synchronized_snapshots = 0;
141 static int      no_unlogged_table_data = 0;
142 static int      serializable_deferrable = 0;
143
144
145 static void help(const char *progname);
146 static void setup_connection(Archive *AH, const char *dumpencoding,
147                                  char *use_role);
148 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
149 static void expand_schema_name_patterns(Archive *fout,
150                                                         SimpleStringList *patterns,
151                                                         SimpleOidList *oids);
152 static void expand_table_name_patterns(Archive *fout,
153                                                    SimpleStringList *patterns,
154                                                    SimpleOidList *oids);
155 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
156 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
157 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
158 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
159 static void dumpComment(Archive *fout, const char *target,
160                         const char *namespace, const char *owner,
161                         CatalogId catalogId, int subid, DumpId dumpId);
162 static int findComments(Archive *fout, Oid classoid, Oid objoid,
163                          CommentItem **items);
164 static int      collectComments(Archive *fout, CommentItem **items);
165 static void dumpSecLabel(Archive *fout, const char *target,
166                          const char *namespace, const char *owner,
167                          CatalogId catalogId, int subid, DumpId dumpId);
168 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
169                           SecLabelItem **items);
170 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
171 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
172 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
173 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
174 static void dumpType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
179 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
181 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
182 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
183 static void dumpFunc(Archive *fout, FuncInfo *finfo);
184 static void dumpCast(Archive *fout, CastInfo *cast);
185 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
186 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
187 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
188 static void dumpCollation(Archive *fout, CollInfo *convinfo);
189 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
190 static void dumpRule(Archive *fout, RuleInfo *rinfo);
191 static void dumpAgg(Archive *fout, AggInfo *agginfo);
192 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
193 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
194 static void dumpTable(Archive *fout, TableInfo *tbinfo);
195 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
196 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
197 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
198 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
199 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
200 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
201 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
202 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
203 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
204 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
205 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
206 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
207 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
208 static void dumpUserMappings(Archive *fout,
209                                  const char *servername, const char *namespace,
210                                  const char *owner, CatalogId catalogId, DumpId dumpId);
211 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
212
213 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
214                 const char *type, const char *name, const char *subname,
215                 const char *tag, const char *nspname, const char *owner,
216                 const char *acls);
217
218 static void getDependencies(Archive *fout);
219 static void BuildArchiveDependencies(Archive *fout);
220 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
221                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
222
223 static DumpableObject *createBoundaryObjects(void);
224 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
225                                                 DumpableObject *boundaryObjs);
226
227 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
228 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
229 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
230 static void buildMatViewRefreshDependencies(Archive *fout);
231 static void getTableDataFKConstraints(void);
232 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
233 static char *format_function_arguments_old(Archive *fout,
234                                                           FuncInfo *finfo, int nallargs,
235                                                           char **allargtypes,
236                                                           char **argmodes,
237                                                           char **argnames);
238 static char *format_function_signature(Archive *fout,
239                                                   FuncInfo *finfo, bool honor_quotes);
240 static const char *convertRegProcReference(Archive *fout,
241                                                 const char *proc);
242 static const char *convertOperatorReference(Archive *fout, const char *opr);
243 static const char *convertTSFunction(Archive *fout, Oid funcOid);
244 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
245 static Oid      findLastBuiltinOid_V70(Archive *fout);
246 static void selectSourceSchema(Archive *fout, const char *schemaName);
247 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
248 static char *myFormatType(const char *typname, int32 typmod);
249 static void getBlobs(Archive *fout);
250 static void dumpBlob(Archive *fout, BlobInfo *binfo);
251 static int      dumpBlobs(Archive *fout, void *arg);
252 static void dumpDatabase(Archive *AH);
253 static void dumpEncoding(Archive *AH);
254 static void dumpStdStrings(Archive *AH);
255 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
256                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
257 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
258                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
259 static void binary_upgrade_set_pg_class_oids(Archive *fout,
260                                                                  PQExpBuffer upgrade_buffer,
261                                                                  Oid pg_class_oid, bool is_index);
262 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
263                                                                 DumpableObject *dobj,
264                                                                 const char *objlabel);
265 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
266 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
267 static char *get_synchronized_snapshot(Archive *fout);
268 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
269 static void setupDumpWorker(Archive *AHX, RestoreOptions *ropt);
270
271
272 int
273 main(int argc, char **argv)
274 {
275         int                     c;
276         const char *filename = NULL;
277         const char *format = "p";
278         const char *dbname = NULL;
279         const char *pghost = NULL;
280         const char *pgport = NULL;
281         const char *username = NULL;
282         const char *dumpencoding = NULL;
283         bool            oids = false;
284         TableInfo  *tblinfo;
285         int                     numTables;
286         DumpableObject **dobjs;
287         int                     numObjs;
288         DumpableObject *boundaryObjs;
289         int                     i;
290         int                     numWorkers = 1;
291         enum trivalue prompt_password = TRI_DEFAULT;
292         int                     compressLevel = -1;
293         int                     plainText = 0;
294         int                     outputClean = 0;
295         int                     outputCreateDB = 0;
296         bool            outputBlobs = false;
297         int                     outputNoOwner = 0;
298         char       *outputSuperuser = NULL;
299         char       *use_role = NULL;
300         int                     optindex;
301         RestoreOptions *ropt;
302         ArchiveFormat archiveFormat = archUnknown;
303         ArchiveMode archiveMode;
304         Archive    *fout;                       /* the script file */
305
306         static int      disable_triggers = 0;
307         static int      outputNoTablespaces = 0;
308         static int      use_setsessauth = 0;
309
310         static struct option long_options[] = {
311                 {"data-only", no_argument, NULL, 'a'},
312                 {"blobs", no_argument, NULL, 'b'},
313                 {"clean", no_argument, NULL, 'c'},
314                 {"create", no_argument, NULL, 'C'},
315                 {"dbname", required_argument, NULL, 'd'},
316                 {"file", required_argument, NULL, 'f'},
317                 {"format", required_argument, NULL, 'F'},
318                 {"host", required_argument, NULL, 'h'},
319                 {"ignore-version", no_argument, NULL, 'i'},
320                 {"jobs", 1, NULL, 'j'},
321                 {"no-reconnect", no_argument, NULL, 'R'},
322                 {"oids", no_argument, NULL, 'o'},
323                 {"no-owner", no_argument, NULL, 'O'},
324                 {"port", required_argument, NULL, 'p'},
325                 {"schema", required_argument, NULL, 'n'},
326                 {"exclude-schema", required_argument, NULL, 'N'},
327                 {"schema-only", no_argument, NULL, 's'},
328                 {"superuser", required_argument, NULL, 'S'},
329                 {"table", required_argument, NULL, 't'},
330                 {"exclude-table", required_argument, NULL, 'T'},
331                 {"no-password", no_argument, NULL, 'w'},
332                 {"password", no_argument, NULL, 'W'},
333                 {"username", required_argument, NULL, 'U'},
334                 {"verbose", no_argument, NULL, 'v'},
335                 {"no-privileges", no_argument, NULL, 'x'},
336                 {"no-acl", no_argument, NULL, 'x'},
337                 {"compress", required_argument, NULL, 'Z'},
338                 {"encoding", required_argument, NULL, 'E'},
339                 {"help", no_argument, NULL, '?'},
340                 {"version", no_argument, NULL, 'V'},
341
342                 /*
343                  * the following options don't have an equivalent short option letter
344                  */
345                 {"attribute-inserts", no_argument, &column_inserts, 1},
346                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
347                 {"column-inserts", no_argument, &column_inserts, 1},
348                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
349                 {"disable-triggers", no_argument, &disable_triggers, 1},
350                 {"exclude-table-data", required_argument, NULL, 4},
351                 {"inserts", no_argument, &dump_inserts, 1},
352                 {"lock-wait-timeout", required_argument, NULL, 2},
353                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
354                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
355                 {"role", required_argument, NULL, 3},
356                 {"section", required_argument, NULL, 5},
357                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
358                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
359                 {"no-security-labels", no_argument, &no_security_labels, 1},
360                 {"no-synchronized-snapshots", no_argument, &no_synchronized_snapshots, 1},
361                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
362
363                 {NULL, 0, NULL, 0}
364         };
365
366         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
367
368         /*
369          * Initialize what we need for parallel execution, especially for thread
370          * support on Windows.
371          */
372         init_parallel_dump_utils();
373
374         g_verbose = false;
375
376         strcpy(g_comment_start, "-- ");
377         g_comment_end[0] = '\0';
378         strcpy(g_opaque_type, "opaque");
379
380         dataOnly = schemaOnly = false;
381         dumpSections = DUMP_UNSECTIONED;
382         lockWaitTimeout = NULL;
383
384         progname = get_progname(argv[0]);
385
386         /* Set default options based on progname */
387         if (strcmp(progname, "pg_backup") == 0)
388                 format = "c";
389
390         if (argc > 1)
391         {
392                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
393                 {
394                         help(progname);
395                         exit_nicely(0);
396                 }
397                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
398                 {
399                         puts("pg_dump (PostgreSQL) " PG_VERSION);
400                         exit_nicely(0);
401                 }
402         }
403
404         while ((c = getopt_long(argc, argv, "abcCd:E:f:F:h:ij:K:n:N:oOp:RsS:t:T:U:vwWxZ:",
405                                                         long_options, &optindex)) != -1)
406         {
407                 switch (c)
408                 {
409                         case 'a':                       /* Dump data only */
410                                 dataOnly = true;
411                                 break;
412
413                         case 'b':                       /* Dump blobs */
414                                 outputBlobs = true;
415                                 break;
416
417                         case 'c':                       /* clean (i.e., drop) schema prior to create */
418                                 outputClean = 1;
419                                 break;
420
421                         case 'C':                       /* Create DB */
422                                 outputCreateDB = 1;
423                                 break;
424
425                         case 'd':                       /* database name */
426                                 dbname = pg_strdup(optarg);
427                                 break;
428
429                         case 'E':                       /* Dump encoding */
430                                 dumpencoding = pg_strdup(optarg);
431                                 break;
432
433                         case 'f':
434                                 filename = pg_strdup(optarg);
435                                 break;
436
437                         case 'F':
438                                 format = pg_strdup(optarg);
439                                 break;
440
441                         case 'h':                       /* server host */
442                                 pghost = pg_strdup(optarg);
443                                 break;
444
445                         case 'i':
446                                 /* ignored, deprecated option */
447                                 break;
448
449                         case 'j':                       /* number of dump jobs */
450                                 numWorkers = atoi(optarg);
451                                 break;
452
453                         case 'n':                       /* include schema(s) */
454                                 simple_string_list_append(&schema_include_patterns, optarg);
455                                 include_everything = false;
456                                 break;
457
458                         case 'N':                       /* exclude schema(s) */
459                                 simple_string_list_append(&schema_exclude_patterns, optarg);
460                                 break;
461
462                         case 'o':                       /* Dump oids */
463                                 oids = true;
464                                 break;
465
466                         case 'O':                       /* Don't reconnect to match owner */
467                                 outputNoOwner = 1;
468                                 break;
469
470                         case 'p':                       /* server port */
471                                 pgport = pg_strdup(optarg);
472                                 break;
473
474                         case 'R':
475                                 /* no-op, still accepted for backwards compatibility */
476                                 break;
477
478                         case 's':                       /* dump schema only */
479                                 schemaOnly = true;
480                                 break;
481
482                         case 'S':                       /* Username for superuser in plain text output */
483                                 outputSuperuser = pg_strdup(optarg);
484                                 break;
485
486                         case 't':                       /* include table(s) */
487                                 simple_string_list_append(&table_include_patterns, optarg);
488                                 include_everything = false;
489                                 break;
490
491                         case 'T':                       /* exclude table(s) */
492                                 simple_string_list_append(&table_exclude_patterns, optarg);
493                                 break;
494
495                         case 'U':
496                                 username = pg_strdup(optarg);
497                                 break;
498
499                         case 'v':                       /* verbose */
500                                 g_verbose = true;
501                                 break;
502
503                         case 'w':
504                                 prompt_password = TRI_NO;
505                                 break;
506
507                         case 'W':
508                                 prompt_password = TRI_YES;
509                                 break;
510
511                         case 'x':                       /* skip ACL dump */
512                                 aclsSkip = true;
513                                 break;
514
515                         case 'Z':                       /* Compression Level */
516                                 compressLevel = atoi(optarg);
517                                 break;
518
519                         case 0:
520                                 /* This covers the long options. */
521                                 break;
522
523                         case 2:                         /* lock-wait-timeout */
524                                 lockWaitTimeout = pg_strdup(optarg);
525                                 break;
526
527                         case 3:                         /* SET ROLE */
528                                 use_role = pg_strdup(optarg);
529                                 break;
530
531                         case 4:                         /* exclude table(s) data */
532                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
533                                 break;
534
535                         case 5:                         /* section */
536                                 set_dump_section(optarg, &dumpSections);
537                                 break;
538
539                         default:
540                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
541                                 exit_nicely(1);
542                 }
543         }
544
545         /*
546          * Non-option argument specifies database name as long as it wasn't
547          * already specified with -d / --dbname
548          */
549         if (optind < argc && dbname == NULL)
550                 dbname = argv[optind++];
551
552         /* Complain if any arguments remain */
553         if (optind < argc)
554         {
555                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
556                                 progname, argv[optind]);
557                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
558                                 progname);
559                 exit_nicely(1);
560         }
561
562         /* --column-inserts implies --inserts */
563         if (column_inserts)
564                 dump_inserts = 1;
565
566         if (dataOnly && schemaOnly)
567                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
568
569         if (dataOnly && outputClean)
570                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
571
572         if (dump_inserts && oids)
573         {
574                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
575                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
576                 exit_nicely(1);
577         }
578
579         /* Identify archive format to emit */
580         archiveFormat = parseArchiveFormat(format, &archiveMode);
581
582         /* archiveFormat specific setup */
583         if (archiveFormat == archNull)
584                 plainText = 1;
585
586         /* Custom and directory formats are compressed by default, others not */
587         if (compressLevel == -1)
588         {
589                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
590                         compressLevel = Z_DEFAULT_COMPRESSION;
591                 else
592                         compressLevel = 0;
593         }
594
595         /*
596          * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
597          * parallel jobs because that's the maximum limit for the
598          * WaitForMultipleObjects() call.
599          */
600         if (numWorkers <= 0
601 #ifdef WIN32
602                 || numWorkers > MAXIMUM_WAIT_OBJECTS
603 #endif
604                 )
605                 exit_horribly(NULL, "%s: invalid number of parallel jobs\n", progname);
606
607         /* Parallel backup only in the directory archive format so far */
608         if (archiveFormat != archDirectory && numWorkers > 1)
609                 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
610
611         /* Open the output file */
612         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode,
613                                                  setupDumpWorker);
614
615         /* Register the cleanup hook */
616         on_exit_close_archive(fout);
617
618         if (fout == NULL)
619                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
620
621         /* Let the archiver know how noisy to be */
622         fout->verbose = g_verbose;
623
624         /*
625          * We allow the server to be back to 7.0, and up to any minor release of
626          * our own major version.  (See also version check in pg_dumpall.c.)
627          */
628         fout->minRemoteVersion = 70000;
629         fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
630
631         fout->numWorkers = numWorkers;
632
633         /*
634          * Open the database using the Archiver, so it knows about it. Errors mean
635          * death.
636          */
637         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
638         setup_connection(fout, dumpencoding, use_role);
639
640         /*
641          * Disable security label support if server version < v9.1.x (prevents
642          * access to nonexistent pg_seclabel catalog)
643          */
644         if (fout->remoteVersion < 90100)
645                 no_security_labels = 1;
646
647         /*
648          * When running against 9.0 or later, check if we are in recovery mode,
649          * which means we are on a hot standby.
650          */
651         if (fout->remoteVersion >= 90000)
652         {
653                 PGresult   *res = ExecuteSqlQueryForSingleRow(fout, "SELECT pg_catalog.pg_is_in_recovery()");
654
655                 if (strcmp(PQgetvalue(res, 0, 0), "t") == 0)
656                 {
657                         /*
658                          * On hot standby slaves, never try to dump unlogged table data,
659                          * since it will just throw an error.
660                          */
661                         no_unlogged_table_data = true;
662                 }
663                 PQclear(res);
664         }
665
666         /* Select the appropriate subquery to convert user IDs to names */
667         if (fout->remoteVersion >= 80100)
668                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
669         else if (fout->remoteVersion >= 70300)
670                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
671         else
672                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
673
674         /* check the version for the synchronized snapshots feature */
675         if (numWorkers > 1 && fout->remoteVersion < 90200
676                 && !no_synchronized_snapshots)
677                 exit_horribly(NULL,
678                  "Synchronized snapshots are not supported by this server version.\n"
679                   "Run with --no-synchronized-snapshots instead if you do not need\n"
680                                           "synchronized snapshots.\n");
681
682         /* Find the last built-in OID, if needed */
683         if (fout->remoteVersion < 70300)
684         {
685                 if (fout->remoteVersion >= 70100)
686                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
687                                                                                                   PQdb(GetConnection(fout)));
688                 else
689                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
690                 if (g_verbose)
691                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
692         }
693
694         /* Expand schema selection patterns into OID lists */
695         if (schema_include_patterns.head != NULL)
696         {
697                 expand_schema_name_patterns(fout, &schema_include_patterns,
698                                                                         &schema_include_oids);
699                 if (schema_include_oids.head == NULL)
700                         exit_horribly(NULL, "No matching schemas were found\n");
701         }
702         expand_schema_name_patterns(fout, &schema_exclude_patterns,
703                                                                 &schema_exclude_oids);
704         /* non-matching exclusion patterns aren't an error */
705
706         /* Expand table selection patterns into OID lists */
707         if (table_include_patterns.head != NULL)
708         {
709                 expand_table_name_patterns(fout, &table_include_patterns,
710                                                                    &table_include_oids);
711                 if (table_include_oids.head == NULL)
712                         exit_horribly(NULL, "No matching tables were found\n");
713         }
714         expand_table_name_patterns(fout, &table_exclude_patterns,
715                                                            &table_exclude_oids);
716
717         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
718                                                            &tabledata_exclude_oids);
719
720         /* non-matching exclusion patterns aren't an error */
721
722         /*
723          * Dumping blobs is now default unless we saw an inclusion switch or -s
724          * ... but even if we did see one of these, -b turns it back on.
725          */
726         if (include_everything && !schemaOnly)
727                 outputBlobs = true;
728
729         /*
730          * Now scan the database and create DumpableObject structs for all the
731          * objects we intend to dump.
732          */
733         tblinfo = getSchemaData(fout, &numTables);
734
735         if (fout->remoteVersion < 80400)
736                 guessConstraintInheritance(tblinfo, numTables);
737
738         if (!schemaOnly)
739         {
740                 getTableData(tblinfo, numTables, oids);
741                 buildMatViewRefreshDependencies(fout);
742                 if (dataOnly)
743                         getTableDataFKConstraints();
744         }
745
746         if (outputBlobs)
747                 getBlobs(fout);
748
749         /*
750          * Collect dependency data to assist in ordering the objects.
751          */
752         getDependencies(fout);
753
754         /* Lastly, create dummy objects to represent the section boundaries */
755         boundaryObjs = createBoundaryObjects();
756
757         /* Get pointers to all the known DumpableObjects */
758         getDumpableObjects(&dobjs, &numObjs);
759
760         /*
761          * Add dummy dependencies to enforce the dump section ordering.
762          */
763         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
764
765         /*
766          * Sort the objects into a safe dump order (no forward references).
767          *
768          * In 7.3 or later, we can rely on dependency information to help us
769          * determine a safe order, so the initial sort is mostly for cosmetic
770          * purposes: we sort by name to ensure that logically identical schemas
771          * will dump identically.  Before 7.3 we don't have dependencies and we
772          * use OID ordering as an (unreliable) guide to creation order.
773          */
774         if (fout->remoteVersion >= 70300)
775                 sortDumpableObjectsByTypeName(dobjs, numObjs);
776         else
777                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
778
779         /* If we do a parallel dump, we want the largest tables to go first */
780         if (archiveFormat == archDirectory && numWorkers > 1)
781                 sortDataAndIndexObjectsBySize(dobjs, numObjs);
782
783         sortDumpableObjects(dobjs, numObjs,
784                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
785
786         /*
787          * Create archive TOC entries for all the objects to be dumped, in a safe
788          * order.
789          */
790
791         /* First the special ENCODING and STDSTRINGS entries. */
792         dumpEncoding(fout);
793         dumpStdStrings(fout);
794
795         /* The database item is always next, unless we don't want it at all */
796         if (include_everything && !dataOnly)
797                 dumpDatabase(fout);
798
799         /* Now the rearrangeable objects. */
800         for (i = 0; i < numObjs; i++)
801                 dumpDumpableObject(fout, dobjs[i]);
802
803         /*
804          * Set up options info to ensure we dump what we want.
805          */
806         ropt = NewRestoreOptions();
807         ropt->filename = filename;
808         ropt->dropSchema = outputClean;
809         ropt->dataOnly = dataOnly;
810         ropt->schemaOnly = schemaOnly;
811         ropt->dumpSections = dumpSections;
812         ropt->aclsSkip = aclsSkip;
813         ropt->superuser = outputSuperuser;
814         ropt->createDB = outputCreateDB;
815         ropt->noOwner = outputNoOwner;
816         ropt->noTablespace = outputNoTablespaces;
817         ropt->disable_triggers = disable_triggers;
818         ropt->use_setsessauth = use_setsessauth;
819
820         if (compressLevel == -1)
821                 ropt->compression = 0;
822         else
823                 ropt->compression = compressLevel;
824
825         ropt->suppressDumpWarnings = true;      /* We've already shown them */
826
827         SetArchiveRestoreOptions(fout, ropt);
828
829         /*
830          * The archive's TOC entries are now marked as to which ones will actually
831          * be output, so we can set up their dependency lists properly. This isn't
832          * necessary for plain-text output, though.
833          */
834         if (!plainText)
835                 BuildArchiveDependencies(fout);
836
837         /*
838          * And finally we can do the actual output.
839          *
840          * Note: for non-plain-text output formats, the output file is written
841          * inside CloseArchive().  This is, um, bizarre; but not worth changing
842          * right now.
843          */
844         if (plainText)
845                 RestoreArchive(fout);
846
847         CloseArchive(fout);
848
849         exit_nicely(0);
850 }
851
852
853 static void
854 help(const char *progname)
855 {
856         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
857         printf(_("Usage:\n"));
858         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
859
860         printf(_("\nGeneral options:\n"));
861         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
862         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
863                          "                               plain text (default))\n"));
864         printf(_("  -j, --jobs=NUM               use this many parallel jobs to dump\n"));
865         printf(_("  -v, --verbose                verbose mode\n"));
866         printf(_("  -V, --version                output version information, then exit\n"));
867         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
868         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
869         printf(_("  -?, --help                   show this help, then exit\n"));
870
871         printf(_("\nOptions controlling the output content:\n"));
872         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
873         printf(_("  -b, --blobs                  include large objects in dump\n"));
874         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
875         printf(_("  -C, --create                 include commands to create database in dump\n"));
876         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
877         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
878         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
879         printf(_("  -o, --oids                   include OIDs in dump\n"));
880         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
881                          "                               plain-text format\n"));
882         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
883         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
884         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
885         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
886         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
887         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
888         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
889         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
890         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
891         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
892         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
893         printf(_("  --no-security-labels         do not dump security label assignments\n"));
894         printf(_("  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs\n"));
895         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
896         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
897         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
898         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
899         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
900         printf(_("  --use-set-session-authorization\n"
901                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
902                          "                               ALTER OWNER commands to set ownership\n"));
903
904         printf(_("\nConnection options:\n"));
905         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
906         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
907         printf(_("  -p, --port=PORT          database server port number\n"));
908         printf(_("  -U, --username=NAME      connect as specified database user\n"));
909         printf(_("  -w, --no-password        never prompt for password\n"));
910         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
911         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
912
913         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
914                          "variable value is used.\n\n"));
915         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
916 }
917
918 static void
919 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
920 {
921         PGconn     *conn = GetConnection(AH);
922         const char *std_strings;
923
924         /*
925          * Set the client encoding if requested. If dumpencoding == NULL then
926          * either it hasn't been requested or we're a cloned connection and then
927          * this has already been set in CloneArchive according to the original
928          * connection encoding.
929          */
930         if (dumpencoding)
931         {
932                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
933                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
934                                                   dumpencoding);
935         }
936
937         /*
938          * Get the active encoding and the standard_conforming_strings setting, so
939          * we know how to escape strings.
940          */
941         AH->encoding = PQclientEncoding(conn);
942
943         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
944         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
945
946         /* Set the role if requested */
947         if (!use_role && AH->use_role)
948                 use_role = AH->use_role;
949
950         /* Set the role if requested */
951         if (use_role && AH->remoteVersion >= 80100)
952         {
953                 PQExpBuffer query = createPQExpBuffer();
954
955                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
956                 ExecuteSqlStatement(AH, query->data);
957                 destroyPQExpBuffer(query);
958
959                 /* save this for later use on parallel connections */
960                 if (!AH->use_role)
961                         AH->use_role = strdup(use_role);
962         }
963
964         /* Set the datestyle to ISO to ensure the dump's portability */
965         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
966
967         /* Likewise, avoid using sql_standard intervalstyle */
968         if (AH->remoteVersion >= 80400)
969                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
970
971         /*
972          * If supported, set extra_float_digits so that we can dump float data
973          * exactly (given correctly implemented float I/O code, anyway)
974          */
975         if (AH->remoteVersion >= 90000)
976                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
977         else if (AH->remoteVersion >= 70400)
978                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
979
980         /*
981          * If synchronized scanning is supported, disable it, to prevent
982          * unpredictable changes in row ordering across a dump and reload.
983          */
984         if (AH->remoteVersion >= 80300)
985                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
986
987         /*
988          * Disable timeouts if supported.
989          */
990         if (AH->remoteVersion >= 70300)
991                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
992         if (AH->remoteVersion >= 90300)
993                 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
994
995         /*
996          * Quote all identifiers, if requested.
997          */
998         if (quote_all_identifiers && AH->remoteVersion >= 90100)
999                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1000
1001         /*
1002          * Start transaction-snapshot mode transaction to dump consistent data.
1003          */
1004         ExecuteSqlStatement(AH, "BEGIN");
1005         if (AH->remoteVersion >= 90100)
1006         {
1007                 if (serializable_deferrable)
1008                         ExecuteSqlStatement(AH,
1009                                                                 "SET TRANSACTION ISOLATION LEVEL "
1010                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1011                 else
1012                         ExecuteSqlStatement(AH,
1013                                                                 "SET TRANSACTION ISOLATION LEVEL "
1014                                                                 "REPEATABLE READ, READ ONLY");
1015         }
1016         else if (AH->remoteVersion >= 70400)
1017         {
1018                 /* note: comma was not accepted in SET TRANSACTION before 8.0 */
1019                 ExecuteSqlStatement(AH,
1020                                                         "SET TRANSACTION ISOLATION LEVEL "
1021                                                         "SERIALIZABLE READ ONLY");
1022         }
1023         else
1024                 ExecuteSqlStatement(AH,
1025                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
1026
1027
1028
1029         if (AH->numWorkers > 1 && AH->remoteVersion >= 90200 && !no_synchronized_snapshots)
1030         {
1031                 if (AH->sync_snapshot_id)
1032                 {
1033                         PQExpBuffer query = createPQExpBuffer();
1034
1035                         appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1036                         appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1037                         ExecuteSqlStatement(AH, query->data);
1038                         destroyPQExpBuffer(query);
1039                 }
1040                 else
1041                         AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1042         }
1043 }
1044
1045 static void
1046 setupDumpWorker(Archive *AHX, RestoreOptions *ropt)
1047 {
1048         setup_connection(AHX, NULL, NULL);
1049 }
1050
1051 static char *
1052 get_synchronized_snapshot(Archive *fout)
1053 {
1054         char       *query = "SELECT pg_export_snapshot()";
1055         char       *result;
1056         PGresult   *res;
1057
1058         res = ExecuteSqlQueryForSingleRow(fout, query);
1059         result = strdup(PQgetvalue(res, 0, 0));
1060         PQclear(res);
1061
1062         return result;
1063 }
1064
1065 static ArchiveFormat
1066 parseArchiveFormat(const char *format, ArchiveMode *mode)
1067 {
1068         ArchiveFormat archiveFormat;
1069
1070         *mode = archModeWrite;
1071
1072         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1073         {
1074                 /* This is used by pg_dumpall, and is not documented */
1075                 archiveFormat = archNull;
1076                 *mode = archModeAppend;
1077         }
1078         else if (pg_strcasecmp(format, "c") == 0)
1079                 archiveFormat = archCustom;
1080         else if (pg_strcasecmp(format, "custom") == 0)
1081                 archiveFormat = archCustom;
1082         else if (pg_strcasecmp(format, "d") == 0)
1083                 archiveFormat = archDirectory;
1084         else if (pg_strcasecmp(format, "directory") == 0)
1085                 archiveFormat = archDirectory;
1086         else if (pg_strcasecmp(format, "p") == 0)
1087                 archiveFormat = archNull;
1088         else if (pg_strcasecmp(format, "plain") == 0)
1089                 archiveFormat = archNull;
1090         else if (pg_strcasecmp(format, "t") == 0)
1091                 archiveFormat = archTar;
1092         else if (pg_strcasecmp(format, "tar") == 0)
1093                 archiveFormat = archTar;
1094         else
1095                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1096         return archiveFormat;
1097 }
1098
1099 /*
1100  * Find the OIDs of all schemas matching the given list of patterns,
1101  * and append them to the given OID list.
1102  */
1103 static void
1104 expand_schema_name_patterns(Archive *fout,
1105                                                         SimpleStringList *patterns,
1106                                                         SimpleOidList *oids)
1107 {
1108         PQExpBuffer query;
1109         PGresult   *res;
1110         SimpleStringListCell *cell;
1111         int                     i;
1112
1113         if (patterns->head == NULL)
1114                 return;                                 /* nothing to do */
1115
1116         if (fout->remoteVersion < 70300)
1117                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1118
1119         query = createPQExpBuffer();
1120
1121         /*
1122          * We use UNION ALL rather than UNION; this might sometimes result in
1123          * duplicate entries in the OID list, but we don't care.
1124          */
1125
1126         for (cell = patterns->head; cell; cell = cell->next)
1127         {
1128                 if (cell != patterns->head)
1129                         appendPQExpBuffer(query, "UNION ALL\n");
1130                 appendPQExpBuffer(query,
1131                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1132                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1133                                                           false, NULL, "n.nspname", NULL, NULL);
1134         }
1135
1136         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1137
1138         for (i = 0; i < PQntuples(res); i++)
1139         {
1140                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1141         }
1142
1143         PQclear(res);
1144         destroyPQExpBuffer(query);
1145 }
1146
1147 /*
1148  * Find the OIDs of all tables matching the given list of patterns,
1149  * and append them to the given OID list.
1150  */
1151 static void
1152 expand_table_name_patterns(Archive *fout,
1153                                                    SimpleStringList *patterns, SimpleOidList *oids)
1154 {
1155         PQExpBuffer query;
1156         PGresult   *res;
1157         SimpleStringListCell *cell;
1158         int                     i;
1159
1160         if (patterns->head == NULL)
1161                 return;                                 /* nothing to do */
1162
1163         query = createPQExpBuffer();
1164
1165         /*
1166          * We use UNION ALL rather than UNION; this might sometimes result in
1167          * duplicate entries in the OID list, but we don't care.
1168          */
1169
1170         for (cell = patterns->head; cell; cell = cell->next)
1171         {
1172                 if (cell != patterns->head)
1173                         appendPQExpBuffer(query, "UNION ALL\n");
1174                 appendPQExpBuffer(query,
1175                                                   "SELECT c.oid"
1176                                                   "\nFROM pg_catalog.pg_class c"
1177                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1178                                          "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c')\n",
1179                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1180                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
1181                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1182                                                           false, "n.nspname", "c.relname", NULL,
1183                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1184         }
1185
1186         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1187
1188         for (i = 0; i < PQntuples(res); i++)
1189         {
1190                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1191         }
1192
1193         PQclear(res);
1194         destroyPQExpBuffer(query);
1195 }
1196
1197 /*
1198  * selectDumpableNamespace: policy-setting subroutine
1199  *              Mark a namespace as to be dumped or not
1200  */
1201 static void
1202 selectDumpableNamespace(NamespaceInfo *nsinfo)
1203 {
1204         /*
1205          * If specific tables are being dumped, do not dump any complete
1206          * namespaces. If specific namespaces are being dumped, dump just those
1207          * namespaces. Otherwise, dump all non-system namespaces.
1208          */
1209         if (table_include_oids.head != NULL)
1210                 nsinfo->dobj.dump = false;
1211         else if (schema_include_oids.head != NULL)
1212                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1213                                                                                                    nsinfo->dobj.catId.oid);
1214         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1215                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1216                 nsinfo->dobj.dump = false;
1217         else
1218                 nsinfo->dobj.dump = true;
1219
1220         /*
1221          * In any case, a namespace can be excluded by an exclusion switch
1222          */
1223         if (nsinfo->dobj.dump &&
1224                 simple_oid_list_member(&schema_exclude_oids,
1225                                                            nsinfo->dobj.catId.oid))
1226                 nsinfo->dobj.dump = false;
1227 }
1228
1229 /*
1230  * selectDumpableTable: policy-setting subroutine
1231  *              Mark a table as to be dumped or not
1232  */
1233 static void
1234 selectDumpableTable(TableInfo *tbinfo)
1235 {
1236         /*
1237          * If specific tables are being dumped, dump just those tables; else, dump
1238          * according to the parent namespace's dump flag.
1239          */
1240         if (table_include_oids.head != NULL)
1241                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1242                                                                                                    tbinfo->dobj.catId.oid);
1243         else
1244                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1245
1246         /*
1247          * In any case, a table can be excluded by an exclusion switch
1248          */
1249         if (tbinfo->dobj.dump &&
1250                 simple_oid_list_member(&table_exclude_oids,
1251                                                            tbinfo->dobj.catId.oid))
1252                 tbinfo->dobj.dump = false;
1253 }
1254
1255 /*
1256  * selectDumpableType: policy-setting subroutine
1257  *              Mark a type as to be dumped or not
1258  *
1259  * If it's a table's rowtype or an autogenerated array type, we also apply a
1260  * special type code to facilitate sorting into the desired order.      (We don't
1261  * want to consider those to be ordinary types because that would bring tables
1262  * up into the datatype part of the dump order.)  We still set the object's
1263  * dump flag; that's not going to cause the dummy type to be dumped, but we
1264  * need it so that casts involving such types will be dumped correctly -- see
1265  * dumpCast.  This means the flag should be set the same as for the underlying
1266  * object (the table or base type).
1267  */
1268 static void
1269 selectDumpableType(TypeInfo *tyinfo)
1270 {
1271         /* skip complex types, except for standalone composite types */
1272         if (OidIsValid(tyinfo->typrelid) &&
1273                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1274         {
1275                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1276
1277                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1278                 if (tytable != NULL)
1279                         tyinfo->dobj.dump = tytable->dobj.dump;
1280                 else
1281                         tyinfo->dobj.dump = false;
1282                 return;
1283         }
1284
1285         /* skip auto-generated array types */
1286         if (tyinfo->isArray)
1287         {
1288                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1289
1290                 /*
1291                  * Fall through to set the dump flag; we assume that the subsequent
1292                  * rules will do the same thing as they would for the array's base
1293                  * type.  (We cannot reliably look up the base type here, since
1294                  * getTypes may not have processed it yet.)
1295                  */
1296         }
1297
1298         /* dump only types in dumpable namespaces */
1299         if (!tyinfo->dobj.namespace->dobj.dump)
1300                 tyinfo->dobj.dump = false;
1301
1302         /* skip undefined placeholder types */
1303         else if (!tyinfo->isDefined)
1304                 tyinfo->dobj.dump = false;
1305
1306         else
1307                 tyinfo->dobj.dump = true;
1308 }
1309
1310 /*
1311  * selectDumpableDefaultACL: policy-setting subroutine
1312  *              Mark a default ACL as to be dumped or not
1313  *
1314  * For per-schema default ACLs, dump if the schema is to be dumped.
1315  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1316  * and aclsSkip are checked separately.
1317  */
1318 static void
1319 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1320 {
1321         if (dinfo->dobj.namespace)
1322                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1323         else
1324                 dinfo->dobj.dump = include_everything;
1325 }
1326
1327 /*
1328  * selectDumpableExtension: policy-setting subroutine
1329  *              Mark an extension as to be dumped or not
1330  *
1331  * Normally, we dump all extensions, or none of them if include_everything
1332  * is false (i.e., a --schema or --table switch was given).  However, in
1333  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1334  * assume those will already be installed in the target database.  We identify
1335  * such extensions by their having OIDs in the range reserved for initdb.
1336  */
1337 static void
1338 selectDumpableExtension(ExtensionInfo *extinfo)
1339 {
1340         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1341                 extinfo->dobj.dump = false;
1342         else
1343                 extinfo->dobj.dump = include_everything;
1344 }
1345
1346 /*
1347  * selectDumpableObject: policy-setting subroutine
1348  *              Mark a generic dumpable object as to be dumped or not
1349  *
1350  * Use this only for object types without a special-case routine above.
1351  */
1352 static void
1353 selectDumpableObject(DumpableObject *dobj)
1354 {
1355         /*
1356          * Default policy is to dump if parent namespace is dumpable, or always
1357          * for non-namespace-associated items.
1358          */
1359         if (dobj->namespace)
1360                 dobj->dump = dobj->namespace->dobj.dump;
1361         else
1362                 dobj->dump = true;
1363 }
1364
1365 /*
1366  *      Dump a table's contents for loading using the COPY command
1367  *      - this routine is called by the Archiver when it wants the table
1368  *        to be dumped.
1369  */
1370
1371 static int
1372 dumpTableData_copy(Archive *fout, void *dcontext)
1373 {
1374         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1375         TableInfo  *tbinfo = tdinfo->tdtable;
1376         const char *classname = tbinfo->dobj.name;
1377         const bool      hasoids = tbinfo->hasoids;
1378         const bool      oids = tdinfo->oids;
1379         PQExpBuffer q = createPQExpBuffer();
1380
1381         /*
1382          * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1383          * which uses it already.
1384          */
1385         PQExpBuffer clistBuf = createPQExpBuffer();
1386         PGconn     *conn = GetConnection(fout);
1387         PGresult   *res;
1388         int                     ret;
1389         char       *copybuf;
1390         const char *column_list;
1391
1392         if (g_verbose)
1393                 write_msg(NULL, "dumping contents of table %s\n", classname);
1394
1395         /*
1396          * Make sure we are in proper schema.  We will qualify the table name
1397          * below anyway (in case its name conflicts with a pg_catalog table); but
1398          * this ensures reproducible results in case the table contains regproc,
1399          * regclass, etc columns.
1400          */
1401         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1402
1403         /*
1404          * If possible, specify the column list explicitly so that we have no
1405          * possibility of retrieving data in the wrong column order.  (The default
1406          * column ordering of COPY will not be what we want in certain corner
1407          * cases involving ADD COLUMN and inheritance.)
1408          */
1409         if (fout->remoteVersion >= 70300)
1410                 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1411         else
1412                 column_list = "";               /* can't select columns in COPY */
1413
1414         if (oids && hasoids)
1415         {
1416                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1417                                                   fmtQualifiedId(fout->remoteVersion,
1418                                                                                  tbinfo->dobj.namespace->dobj.name,
1419                                                                                  classname),
1420                                                   column_list);
1421         }
1422         else if (tdinfo->filtercond)
1423         {
1424                 /* Note: this syntax is only supported in 8.2 and up */
1425                 appendPQExpBufferStr(q, "COPY (SELECT ");
1426                 /* klugery to get rid of parens in column list */
1427                 if (strlen(column_list) > 2)
1428                 {
1429                         appendPQExpBufferStr(q, column_list + 1);
1430                         q->data[q->len - 1] = ' ';
1431                 }
1432                 else
1433                         appendPQExpBufferStr(q, "* ");
1434                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1435                                                   fmtQualifiedId(fout->remoteVersion,
1436                                                                                  tbinfo->dobj.namespace->dobj.name,
1437                                                                                  classname),
1438                                                   tdinfo->filtercond);
1439         }
1440         else
1441         {
1442                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1443                                                   fmtQualifiedId(fout->remoteVersion,
1444                                                                                  tbinfo->dobj.namespace->dobj.name,
1445                                                                                  classname),
1446                                                   column_list);
1447         }
1448         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1449         PQclear(res);
1450         destroyPQExpBuffer(clistBuf);
1451
1452         for (;;)
1453         {
1454                 ret = PQgetCopyData(conn, &copybuf, 0);
1455
1456                 if (ret < 0)
1457                         break;                          /* done or error */
1458
1459                 if (copybuf)
1460                 {
1461                         WriteData(fout, copybuf, ret);
1462                         PQfreemem(copybuf);
1463                 }
1464
1465                 /* ----------
1466                  * THROTTLE:
1467                  *
1468                  * There was considerable discussion in late July, 2000 regarding
1469                  * slowing down pg_dump when backing up large tables. Users with both
1470                  * slow & fast (multi-processor) machines experienced performance
1471                  * degradation when doing a backup.
1472                  *
1473                  * Initial attempts based on sleeping for a number of ms for each ms
1474                  * of work were deemed too complex, then a simple 'sleep in each loop'
1475                  * implementation was suggested. The latter failed because the loop
1476                  * was too tight. Finally, the following was implemented:
1477                  *
1478                  * If throttle is non-zero, then
1479                  *              See how long since the last sleep.
1480                  *              Work out how long to sleep (based on ratio).
1481                  *              If sleep is more than 100ms, then
1482                  *                      sleep
1483                  *                      reset timer
1484                  *              EndIf
1485                  * EndIf
1486                  *
1487                  * where the throttle value was the number of ms to sleep per ms of
1488                  * work. The calculation was done in each loop.
1489                  *
1490                  * Most of the hard work is done in the backend, and this solution
1491                  * still did not work particularly well: on slow machines, the ratio
1492                  * was 50:1, and on medium paced machines, 1:1, and on fast
1493                  * multi-processor machines, it had little or no effect, for reasons
1494                  * that were unclear.
1495                  *
1496                  * Further discussion ensued, and the proposal was dropped.
1497                  *
1498                  * For those people who want this feature, it can be implemented using
1499                  * gettimeofday in each loop, calculating the time since last sleep,
1500                  * multiplying that by the sleep ratio, then if the result is more
1501                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1502                  * function to sleep for a subsecond period ie.
1503                  *
1504                  * select(0, NULL, NULL, NULL, &tvi);
1505                  *
1506                  * This will return after the interval specified in the structure tvi.
1507                  * Finally, call gettimeofday again to save the 'last sleep time'.
1508                  * ----------
1509                  */
1510         }
1511         archprintf(fout, "\\.\n\n\n");
1512
1513         if (ret == -2)
1514         {
1515                 /* copy data transfer failed */
1516                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1517                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1518                 write_msg(NULL, "The command was: %s\n", q->data);
1519                 exit_nicely(1);
1520         }
1521
1522         /* Check command status and return to normal libpq state */
1523         res = PQgetResult(conn);
1524         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1525         {
1526                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1527                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1528                 write_msg(NULL, "The command was: %s\n", q->data);
1529                 exit_nicely(1);
1530         }
1531         PQclear(res);
1532
1533         destroyPQExpBuffer(q);
1534         return 1;
1535 }
1536
1537 /*
1538  * Dump table data using INSERT commands.
1539  *
1540  * Caution: when we restore from an archive file direct to database, the
1541  * INSERT commands emitted by this function have to be parsed by
1542  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1543  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1544  */
1545 static int
1546 dumpTableData_insert(Archive *fout, void *dcontext)
1547 {
1548         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1549         TableInfo  *tbinfo = tdinfo->tdtable;
1550         const char *classname = tbinfo->dobj.name;
1551         PQExpBuffer q = createPQExpBuffer();
1552         PGresult   *res;
1553         int                     tuple;
1554         int                     nfields;
1555         int                     field;
1556
1557         /*
1558          * Make sure we are in proper schema.  We will qualify the table name
1559          * below anyway (in case its name conflicts with a pg_catalog table); but
1560          * this ensures reproducible results in case the table contains regproc,
1561          * regclass, etc columns.
1562          */
1563         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1564
1565         if (fout->remoteVersion >= 70100)
1566         {
1567                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1568                                                   "SELECT * FROM ONLY %s",
1569                                                   fmtQualifiedId(fout->remoteVersion,
1570                                                                                  tbinfo->dobj.namespace->dobj.name,
1571                                                                                  classname));
1572         }
1573         else
1574         {
1575                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1576                                                   "SELECT * FROM %s",
1577                                                   fmtQualifiedId(fout->remoteVersion,
1578                                                                                  tbinfo->dobj.namespace->dobj.name,
1579                                                                                  classname));
1580         }
1581         if (tdinfo->filtercond)
1582                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1583
1584         ExecuteSqlStatement(fout, q->data);
1585
1586         while (1)
1587         {
1588                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1589                                                           PGRES_TUPLES_OK);
1590                 nfields = PQnfields(res);
1591                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1592                 {
1593                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1594                         if (nfields == 0)
1595                         {
1596                                 /* corner case for zero-column table */
1597                                 archprintf(fout, "DEFAULT VALUES;\n");
1598                                 continue;
1599                         }
1600                         if (column_inserts)
1601                         {
1602                                 resetPQExpBuffer(q);
1603                                 appendPQExpBuffer(q, "(");
1604                                 for (field = 0; field < nfields; field++)
1605                                 {
1606                                         if (field > 0)
1607                                                 appendPQExpBuffer(q, ", ");
1608                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1609                                 }
1610                                 appendPQExpBuffer(q, ") ");
1611                                 archputs(q->data, fout);
1612                         }
1613                         archprintf(fout, "VALUES (");
1614                         for (field = 0; field < nfields; field++)
1615                         {
1616                                 if (field > 0)
1617                                         archprintf(fout, ", ");
1618                                 if (PQgetisnull(res, tuple, field))
1619                                 {
1620                                         archprintf(fout, "NULL");
1621                                         continue;
1622                                 }
1623
1624                                 /* XXX This code is partially duplicated in ruleutils.c */
1625                                 switch (PQftype(res, field))
1626                                 {
1627                                         case INT2OID:
1628                                         case INT4OID:
1629                                         case INT8OID:
1630                                         case OIDOID:
1631                                         case FLOAT4OID:
1632                                         case FLOAT8OID:
1633                                         case NUMERICOID:
1634                                                 {
1635                                                         /*
1636                                                          * These types are printed without quotes unless
1637                                                          * they contain values that aren't accepted by the
1638                                                          * scanner unquoted (e.g., 'NaN').      Note that
1639                                                          * strtod() and friends might accept NaN, so we
1640                                                          * can't use that to test.
1641                                                          *
1642                                                          * In reality we only need to defend against
1643                                                          * infinity and NaN, so we need not get too crazy
1644                                                          * about pattern matching here.
1645                                                          */
1646                                                         const char *s = PQgetvalue(res, tuple, field);
1647
1648                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1649                                                                 archprintf(fout, "%s", s);
1650                                                         else
1651                                                                 archprintf(fout, "'%s'", s);
1652                                                 }
1653                                                 break;
1654
1655                                         case BITOID:
1656                                         case VARBITOID:
1657                                                 archprintf(fout, "B'%s'",
1658                                                                    PQgetvalue(res, tuple, field));
1659                                                 break;
1660
1661                                         case BOOLOID:
1662                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1663                                                         archprintf(fout, "true");
1664                                                 else
1665                                                         archprintf(fout, "false");
1666                                                 break;
1667
1668                                         default:
1669                                                 /* All other types are printed as string literals. */
1670                                                 resetPQExpBuffer(q);
1671                                                 appendStringLiteralAH(q,
1672                                                                                           PQgetvalue(res, tuple, field),
1673                                                                                           fout);
1674                                                 archputs(q->data, fout);
1675                                                 break;
1676                                 }
1677                         }
1678                         archprintf(fout, ");\n");
1679                 }
1680
1681                 if (PQntuples(res) <= 0)
1682                 {
1683                         PQclear(res);
1684                         break;
1685                 }
1686                 PQclear(res);
1687         }
1688
1689         archprintf(fout, "\n\n");
1690
1691         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1692
1693         destroyPQExpBuffer(q);
1694         return 1;
1695 }
1696
1697
1698 /*
1699  * dumpTableData -
1700  *        dump the contents of a single table
1701  *
1702  * Actually, this just makes an ArchiveEntry for the table contents.
1703  */
1704 static void
1705 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1706 {
1707         TableInfo  *tbinfo = tdinfo->tdtable;
1708         PQExpBuffer copyBuf = createPQExpBuffer();
1709         PQExpBuffer clistBuf = createPQExpBuffer();
1710         DataDumperPtr dumpFn;
1711         char       *copyStmt;
1712
1713         if (!dump_inserts)
1714         {
1715                 /* Dump/restore using COPY */
1716                 dumpFn = dumpTableData_copy;
1717                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1718                 appendPQExpBuffer(copyBuf, "COPY %s ",
1719                                                   fmtId(tbinfo->dobj.name));
1720                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1721                                                   fmtCopyColumnList(tbinfo, clistBuf),
1722                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1723                 copyStmt = copyBuf->data;
1724         }
1725         else
1726         {
1727                 /* Restore using INSERT */
1728                 dumpFn = dumpTableData_insert;
1729                 copyStmt = NULL;
1730         }
1731
1732         /*
1733          * Note: although the TableDataInfo is a full DumpableObject, we treat its
1734          * dependency on its table as "special" and pass it to ArchiveEntry now.
1735          * See comments for BuildArchiveDependencies.
1736          */
1737         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1738                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1739                                  NULL, tbinfo->rolname,
1740                                  false, "TABLE DATA", SECTION_DATA,
1741                                  "", "", copyStmt,
1742                                  &(tbinfo->dobj.dumpId), 1,
1743                                  dumpFn, tdinfo);
1744
1745         destroyPQExpBuffer(copyBuf);
1746         destroyPQExpBuffer(clistBuf);
1747 }
1748
1749 /*
1750  * refreshMatViewData -
1751  *        load or refresh the contents of a single materialized view
1752  *
1753  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
1754  * statement.
1755  */
1756 static void
1757 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
1758 {
1759         TableInfo  *tbinfo = tdinfo->tdtable;
1760         PQExpBuffer q;
1761
1762         /* If the materialized view is not flagged as populated, skip this. */
1763         if (!tbinfo->relispopulated)
1764                 return;
1765
1766         q = createPQExpBuffer();
1767
1768         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
1769                                           fmtId(tbinfo->dobj.name));
1770
1771         ArchiveEntry(fout,
1772                                  tdinfo->dobj.catId,    /* catalog ID */
1773                                  tdinfo->dobj.dumpId,   /* dump ID */
1774                                  tbinfo->dobj.name,             /* Name */
1775                                  tbinfo->dobj.namespace->dobj.name,             /* Namespace */
1776                                  NULL,                  /* Tablespace */
1777                                  tbinfo->rolname,               /* Owner */
1778                                  false,                 /* with oids */
1779                                  "MATERIALIZED VIEW DATA",              /* Desc */
1780                                  SECTION_POST_DATA,             /* Section */
1781                                  q->data,               /* Create */
1782                                  "",                    /* Del */
1783                                  NULL,                  /* Copy */
1784                                  tdinfo->dobj.dependencies,             /* Deps */
1785                                  tdinfo->dobj.nDeps,    /* # Deps */
1786                                  NULL,                  /* Dumper */
1787                                  NULL);                 /* Dumper Arg */
1788
1789         destroyPQExpBuffer(q);
1790 }
1791
1792 /*
1793  * getTableData -
1794  *        set up dumpable objects representing the contents of tables
1795  */
1796 static void
1797 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1798 {
1799         int                     i;
1800
1801         for (i = 0; i < numTables; i++)
1802         {
1803                 if (tblinfo[i].dobj.dump)
1804                         makeTableDataInfo(&(tblinfo[i]), oids);
1805         }
1806 }
1807
1808 /*
1809  * Make a dumpable object for the data of this specific table
1810  *
1811  * Note: we make a TableDataInfo if and only if we are going to dump the
1812  * table data; the "dump" flag in such objects isn't used.
1813  */
1814 static void
1815 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1816 {
1817         TableDataInfo *tdinfo;
1818
1819         /*
1820          * Nothing to do if we already decided to dump the table.  This will
1821          * happen for "config" tables.
1822          */
1823         if (tbinfo->dataObj != NULL)
1824                 return;
1825
1826         /* Skip VIEWs (no data to dump) */
1827         if (tbinfo->relkind == RELKIND_VIEW)
1828                 return;
1829         /* Skip FOREIGN TABLEs (no data to dump) */
1830         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1831                 return;
1832
1833         /* Don't dump data in unlogged tables, if so requested */
1834         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1835                 no_unlogged_table_data)
1836                 return;
1837
1838         /* Check that the data is not explicitly excluded */
1839         if (simple_oid_list_member(&tabledata_exclude_oids,
1840                                                            tbinfo->dobj.catId.oid))
1841                 return;
1842
1843         /* OK, let's dump it */
1844         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1845
1846         if (tbinfo->relkind == RELKIND_MATVIEW)
1847                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
1848         else
1849                 tdinfo->dobj.objType = DO_TABLE_DATA;
1850
1851         /*
1852          * Note: use tableoid 0 so that this object won't be mistaken for
1853          * something that pg_depend entries apply to.
1854          */
1855         tdinfo->dobj.catId.tableoid = 0;
1856         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1857         AssignDumpId(&tdinfo->dobj);
1858         tdinfo->dobj.name = tbinfo->dobj.name;
1859         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1860         tdinfo->tdtable = tbinfo;
1861         tdinfo->oids = oids;
1862         tdinfo->filtercond = NULL;      /* might get set later */
1863         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1864
1865         tbinfo->dataObj = tdinfo;
1866 }
1867
1868 /*
1869  * The refresh for a materialized view must be dependent on the refresh for
1870  * any materialized view that this one is dependent on.
1871  *
1872  * This must be called after all the objects are created, but before they are
1873  * sorted.
1874  */
1875 static void
1876 buildMatViewRefreshDependencies(Archive *fout)
1877 {
1878         PQExpBuffer query;
1879         PGresult   *res;
1880         int                     ntups,
1881                                 i;
1882         int                     i_classid,
1883                                 i_objid,
1884                                 i_refobjid;
1885
1886         /* No Mat Views before 9.3. */
1887         if (fout->remoteVersion < 90300)
1888                 return;
1889
1890         /* Make sure we are in proper schema */
1891         selectSourceSchema(fout, "pg_catalog");
1892
1893         query = createPQExpBuffer();
1894
1895         appendPQExpBuffer(query, "with recursive w as "
1896                                           "( "
1897                                         "select d1.objid, d2.refobjid, c2.relkind as refrelkind "
1898                                           "from pg_depend d1 "
1899                                           "join pg_class c1 on c1.oid = d1.objid "
1900                                           "and c1.relkind = 'm' "
1901                                           "join pg_rewrite r1 on r1.ev_class = d1.objid "
1902                                   "join pg_depend d2 on d2.classid = 'pg_rewrite'::regclass "
1903                                           "and d2.objid = r1.oid "
1904                                           "and d2.refobjid <> d1.objid "
1905                                           "join pg_class c2 on c2.oid = d2.refobjid "
1906                                           "and c2.relkind in ('m','v') "
1907                                           "where d1.classid = 'pg_class'::regclass "
1908                                           "union "
1909                                           "select w.objid, d3.refobjid, c3.relkind "
1910                                           "from w "
1911                                           "join pg_rewrite r3 on r3.ev_class = w.refobjid "
1912                                   "join pg_depend d3 on d3.classid = 'pg_rewrite'::regclass "
1913                                           "and d3.objid = r3.oid "
1914                                           "and d3.refobjid <> w.refobjid "
1915                                           "join pg_class c3 on c3.oid = d3.refobjid "
1916                                           "and c3.relkind in ('m','v') "
1917                                           ") "
1918                           "select 'pg_class'::regclass::oid as classid, objid, refobjid "
1919                                           "from w "
1920                                           "where refrelkind = 'm'");
1921
1922         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1923
1924         ntups = PQntuples(res);
1925
1926         i_classid = PQfnumber(res, "classid");
1927         i_objid = PQfnumber(res, "objid");
1928         i_refobjid = PQfnumber(res, "refobjid");
1929
1930         for (i = 0; i < ntups; i++)
1931         {
1932                 CatalogId       objId;
1933                 CatalogId       refobjId;
1934                 DumpableObject *dobj;
1935                 DumpableObject *refdobj;
1936                 TableInfo  *tbinfo;
1937                 TableInfo  *reftbinfo;
1938
1939                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
1940                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
1941                 refobjId.tableoid = objId.tableoid;
1942                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
1943
1944                 dobj = findObjectByCatalogId(objId);
1945                 if (dobj == NULL)
1946                         continue;
1947
1948                 Assert(dobj->objType == DO_TABLE);
1949                 tbinfo = (TableInfo *) dobj;
1950                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
1951                 dobj = (DumpableObject *) tbinfo->dataObj;
1952                 if (dobj == NULL)
1953                         continue;
1954                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
1955
1956                 refdobj = findObjectByCatalogId(refobjId);
1957                 if (refdobj == NULL)
1958                         continue;
1959
1960                 Assert(refdobj->objType == DO_TABLE);
1961                 reftbinfo = (TableInfo *) refdobj;
1962                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
1963                 refdobj = (DumpableObject *) reftbinfo->dataObj;
1964                 if (refdobj == NULL)
1965                         continue;
1966                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
1967
1968                 addObjectDependency(dobj, refdobj->dumpId);
1969
1970                 if (!reftbinfo->relispopulated)
1971                         tbinfo->relispopulated = false;
1972         }
1973
1974         PQclear(res);
1975
1976         destroyPQExpBuffer(query);
1977 }
1978
1979 /*
1980  * getTableDataFKConstraints -
1981  *        add dump-order dependencies reflecting foreign key constraints
1982  *
1983  * This code is executed only in a data-only dump --- in schema+data dumps
1984  * we handle foreign key issues by not creating the FK constraints until
1985  * after the data is loaded.  In a data-only dump, however, we want to
1986  * order the table data objects in such a way that a table's referenced
1987  * tables are restored first.  (In the presence of circular references or
1988  * self-references this may be impossible; we'll detect and complain about
1989  * that during the dependency sorting step.)
1990  */
1991 static void
1992 getTableDataFKConstraints(void)
1993 {
1994         DumpableObject **dobjs;
1995         int                     numObjs;
1996         int                     i;
1997
1998         /* Search through all the dumpable objects for FK constraints */
1999         getDumpableObjects(&dobjs, &numObjs);
2000         for (i = 0; i < numObjs; i++)
2001         {
2002                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2003                 {
2004                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2005                         TableInfo  *ftable;
2006
2007                         /* Not interesting unless both tables are to be dumped */
2008                         if (cinfo->contable == NULL ||
2009                                 cinfo->contable->dataObj == NULL)
2010                                 continue;
2011                         ftable = findTableByOid(cinfo->confrelid);
2012                         if (ftable == NULL ||
2013                                 ftable->dataObj == NULL)
2014                                 continue;
2015
2016                         /*
2017                          * Okay, make referencing table's TABLE_DATA object depend on the
2018                          * referenced table's TABLE_DATA object.
2019                          */
2020                         addObjectDependency(&cinfo->contable->dataObj->dobj,
2021                                                                 ftable->dataObj->dobj.dumpId);
2022                 }
2023         }
2024         free(dobjs);
2025 }
2026
2027
2028 /*
2029  * guessConstraintInheritance:
2030  *      In pre-8.4 databases, we can't tell for certain which constraints
2031  *      are inherited.  We assume a CHECK constraint is inherited if its name
2032  *      matches the name of any constraint in the parent.  Originally this code
2033  *      tried to compare the expression texts, but that can fail for various
2034  *      reasons --- for example, if the parent and child tables are in different
2035  *      schemas, reverse-listing of function calls may produce different text
2036  *      (schema-qualified or not) depending on search path.
2037  *
2038  *      In 8.4 and up we can rely on the conislocal field to decide which
2039  *      constraints must be dumped; much safer.
2040  *
2041  *      This function assumes all conislocal flags were initialized to TRUE.
2042  *      It clears the flag on anything that seems to be inherited.
2043  */
2044 static void
2045 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2046 {
2047         int                     i,
2048                                 j,
2049                                 k;
2050
2051         for (i = 0; i < numTables; i++)
2052         {
2053                 TableInfo  *tbinfo = &(tblinfo[i]);
2054                 int                     numParents;
2055                 TableInfo **parents;
2056                 TableInfo  *parent;
2057
2058                 /* Sequences and views never have parents */
2059                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2060                         tbinfo->relkind == RELKIND_VIEW)
2061                         continue;
2062
2063                 /* Don't bother computing anything for non-target tables, either */
2064                 if (!tbinfo->dobj.dump)
2065                         continue;
2066
2067                 numParents = tbinfo->numParents;
2068                 parents = tbinfo->parents;
2069
2070                 if (numParents == 0)
2071                         continue;                       /* nothing to see here, move along */
2072
2073                 /* scan for inherited CHECK constraints */
2074                 for (j = 0; j < tbinfo->ncheck; j++)
2075                 {
2076                         ConstraintInfo *constr;
2077
2078                         constr = &(tbinfo->checkexprs[j]);
2079
2080                         for (k = 0; k < numParents; k++)
2081                         {
2082                                 int                     l;
2083
2084                                 parent = parents[k];
2085                                 for (l = 0; l < parent->ncheck; l++)
2086                                 {
2087                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2088
2089                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2090                                         {
2091                                                 constr->conislocal = false;
2092                                                 break;
2093                                         }
2094                                 }
2095                                 if (!constr->conislocal)
2096                                         break;
2097                         }
2098                 }
2099         }
2100 }
2101
2102
2103 /*
2104  * dumpDatabase:
2105  *      dump the database definition
2106  */
2107 static void
2108 dumpDatabase(Archive *fout)
2109 {
2110         PQExpBuffer dbQry = createPQExpBuffer();
2111         PQExpBuffer delQry = createPQExpBuffer();
2112         PQExpBuffer creaQry = createPQExpBuffer();
2113         PGconn     *conn = GetConnection(fout);
2114         PGresult   *res;
2115         int                     i_tableoid,
2116                                 i_oid,
2117                                 i_dba,
2118                                 i_encoding,
2119                                 i_collate,
2120                                 i_ctype,
2121                                 i_frozenxid,
2122                                 i_tablespace;
2123         CatalogId       dbCatId;
2124         DumpId          dbDumpId;
2125         const char *datname,
2126                            *dba,
2127                            *encoding,
2128                            *collate,
2129                            *ctype,
2130                            *tablespace;
2131         uint32          frozenxid;
2132
2133         datname = PQdb(conn);
2134
2135         if (g_verbose)
2136                 write_msg(NULL, "saving database definition\n");
2137
2138         /* Make sure we are in proper schema */
2139         selectSourceSchema(fout, "pg_catalog");
2140
2141         /* Get the database owner and parameters from pg_database */
2142         if (fout->remoteVersion >= 80400)
2143         {
2144                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2145                                                   "(%s datdba) AS dba, "
2146                                                   "pg_encoding_to_char(encoding) AS encoding, "
2147                                                   "datcollate, datctype, datfrozenxid, "
2148                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2149                                           "shobj_description(oid, 'pg_database') AS description "
2150
2151                                                   "FROM pg_database "
2152                                                   "WHERE datname = ",
2153                                                   username_subquery);
2154                 appendStringLiteralAH(dbQry, datname, fout);
2155         }
2156         else if (fout->remoteVersion >= 80200)
2157         {
2158                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2159                                                   "(%s datdba) AS dba, "
2160                                                   "pg_encoding_to_char(encoding) AS encoding, "
2161                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2162                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2163                                           "shobj_description(oid, 'pg_database') AS description "
2164
2165                                                   "FROM pg_database "
2166                                                   "WHERE datname = ",
2167                                                   username_subquery);
2168                 appendStringLiteralAH(dbQry, datname, fout);
2169         }
2170         else if (fout->remoteVersion >= 80000)
2171         {
2172                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2173                                                   "(%s datdba) AS dba, "
2174                                                   "pg_encoding_to_char(encoding) AS encoding, "
2175                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2176                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2177                                                   "FROM pg_database "
2178                                                   "WHERE datname = ",
2179                                                   username_subquery);
2180                 appendStringLiteralAH(dbQry, datname, fout);
2181         }
2182         else if (fout->remoteVersion >= 70100)
2183         {
2184                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2185                                                   "(%s datdba) AS dba, "
2186                                                   "pg_encoding_to_char(encoding) AS encoding, "
2187                                                   "NULL AS datcollate, NULL AS datctype, "
2188                                                   "0 AS datfrozenxid, "
2189                                                   "NULL AS tablespace "
2190                                                   "FROM pg_database "
2191                                                   "WHERE datname = ",
2192                                                   username_subquery);
2193                 appendStringLiteralAH(dbQry, datname, fout);
2194         }
2195         else
2196         {
2197                 appendPQExpBuffer(dbQry, "SELECT "
2198                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
2199                                                   "oid, "
2200                                                   "(%s datdba) AS dba, "
2201                                                   "pg_encoding_to_char(encoding) AS encoding, "
2202                                                   "NULL AS datcollate, NULL AS datctype, "
2203                                                   "0 AS datfrozenxid, "
2204                                                   "NULL AS tablespace "
2205                                                   "FROM pg_database "
2206                                                   "WHERE datname = ",
2207                                                   username_subquery);
2208                 appendStringLiteralAH(dbQry, datname, fout);
2209         }
2210
2211         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2212
2213         i_tableoid = PQfnumber(res, "tableoid");
2214         i_oid = PQfnumber(res, "oid");
2215         i_dba = PQfnumber(res, "dba");
2216         i_encoding = PQfnumber(res, "encoding");
2217         i_collate = PQfnumber(res, "datcollate");
2218         i_ctype = PQfnumber(res, "datctype");
2219         i_frozenxid = PQfnumber(res, "datfrozenxid");
2220         i_tablespace = PQfnumber(res, "tablespace");
2221
2222         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2223         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2224         dba = PQgetvalue(res, 0, i_dba);
2225         encoding = PQgetvalue(res, 0, i_encoding);
2226         collate = PQgetvalue(res, 0, i_collate);
2227         ctype = PQgetvalue(res, 0, i_ctype);
2228         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2229         tablespace = PQgetvalue(res, 0, i_tablespace);
2230
2231         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2232                                           fmtId(datname));
2233         if (strlen(encoding) > 0)
2234         {
2235                 appendPQExpBuffer(creaQry, " ENCODING = ");
2236                 appendStringLiteralAH(creaQry, encoding, fout);
2237         }
2238         if (strlen(collate) > 0)
2239         {
2240                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
2241                 appendStringLiteralAH(creaQry, collate, fout);
2242         }
2243         if (strlen(ctype) > 0)
2244         {
2245                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
2246                 appendStringLiteralAH(creaQry, ctype, fout);
2247         }
2248         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
2249                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2250                                                   fmtId(tablespace));
2251         appendPQExpBuffer(creaQry, ";\n");
2252
2253         if (binary_upgrade)
2254         {
2255                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
2256                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2257                                                   "SET datfrozenxid = '%u'\n"
2258                                                   "WHERE        datname = ",
2259                                                   frozenxid);
2260                 appendStringLiteralAH(creaQry, datname, fout);
2261                 appendPQExpBuffer(creaQry, ";\n");
2262
2263         }
2264
2265         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2266                                           fmtId(datname));
2267
2268         dbDumpId = createDumpId();
2269
2270         ArchiveEntry(fout,
2271                                  dbCatId,               /* catalog ID */
2272                                  dbDumpId,              /* dump ID */
2273                                  datname,               /* Name */
2274                                  NULL,                  /* Namespace */
2275                                  NULL,                  /* Tablespace */
2276                                  dba,                   /* Owner */
2277                                  false,                 /* with oids */
2278                                  "DATABASE",    /* Desc */
2279                                  SECTION_PRE_DATA,              /* Section */
2280                                  creaQry->data, /* Create */
2281                                  delQry->data,  /* Del */
2282                                  NULL,                  /* Copy */
2283                                  NULL,                  /* Deps */
2284                                  0,                             /* # Deps */
2285                                  NULL,                  /* Dumper */
2286                                  NULL);                 /* Dumper Arg */
2287
2288         /*
2289          * pg_largeobject and pg_largeobject_metadata come from the old system
2290          * intact, so set their relfrozenxids.
2291          */
2292         if (binary_upgrade)
2293         {
2294                 PGresult   *lo_res;
2295                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2296                 PQExpBuffer loOutQry = createPQExpBuffer();
2297                 int                     i_relfrozenxid;
2298
2299                 /*
2300                  * pg_largeobject
2301                  */
2302                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2303                                                   "FROM pg_catalog.pg_class\n"
2304                                                   "WHERE oid = %u;\n",
2305                                                   LargeObjectRelationId);
2306
2307                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2308
2309                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2310
2311                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2312                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2313                                                   "SET relfrozenxid = '%u'\n"
2314                                                   "WHERE oid = %u;\n",
2315                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2316                                                   LargeObjectRelationId);
2317                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2318                                          "pg_largeobject", NULL, NULL, "",
2319                                          false, "pg_largeobject", SECTION_PRE_DATA,
2320                                          loOutQry->data, "", NULL,
2321                                          NULL, 0,
2322                                          NULL, NULL);
2323
2324                 PQclear(lo_res);
2325
2326                 /*
2327                  * pg_largeobject_metadata
2328                  */
2329                 if (fout->remoteVersion >= 90000)
2330                 {
2331                         resetPQExpBuffer(loFrozenQry);
2332                         resetPQExpBuffer(loOutQry);
2333
2334                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2335                                                           "FROM pg_catalog.pg_class\n"
2336                                                           "WHERE oid = %u;\n",
2337                                                           LargeObjectMetadataRelationId);
2338
2339                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2340
2341                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2342
2343                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2344                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2345                                                           "SET relfrozenxid = '%u'\n"
2346                                                           "WHERE oid = %u;\n",
2347                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2348                                                           LargeObjectMetadataRelationId);
2349                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2350                                                  "pg_largeobject_metadata", NULL, NULL, "",
2351                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2352                                                  loOutQry->data, "", NULL,
2353                                                  NULL, 0,
2354                                                  NULL, NULL);
2355
2356                         PQclear(lo_res);
2357                 }
2358
2359                 destroyPQExpBuffer(loFrozenQry);
2360                 destroyPQExpBuffer(loOutQry);
2361         }
2362
2363         /* Dump DB comment if any */
2364         if (fout->remoteVersion >= 80200)
2365         {
2366                 /*
2367                  * 8.2 keeps comments on shared objects in a shared table, so we
2368                  * cannot use the dumpComment used for other database objects.
2369                  */
2370                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2371
2372                 if (comment && strlen(comment))
2373                 {
2374                         resetPQExpBuffer(dbQry);
2375
2376                         /*
2377                          * Generates warning when loaded into a differently-named
2378                          * database.
2379                          */
2380                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2381                         appendStringLiteralAH(dbQry, comment, fout);
2382                         appendPQExpBuffer(dbQry, ";\n");
2383
2384                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2385                                                  dba, false, "COMMENT", SECTION_NONE,
2386                                                  dbQry->data, "", NULL,
2387                                                  &dbDumpId, 1, NULL, NULL);
2388                 }
2389         }
2390         else
2391         {
2392                 resetPQExpBuffer(dbQry);
2393                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2394                 dumpComment(fout, dbQry->data, NULL, "",
2395                                         dbCatId, 0, dbDumpId);
2396         }
2397
2398         PQclear(res);
2399
2400         /* Dump shared security label. */
2401         if (!no_security_labels && fout->remoteVersion >= 90200)
2402         {
2403                 PQExpBuffer seclabelQry = createPQExpBuffer();
2404
2405                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2406                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2407                 resetPQExpBuffer(seclabelQry);
2408                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2409                 if (strlen(seclabelQry->data))
2410                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2411                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2412                                                  seclabelQry->data, "", NULL,
2413                                                  &dbDumpId, 1, NULL, NULL);
2414                 destroyPQExpBuffer(seclabelQry);
2415         }
2416
2417         destroyPQExpBuffer(dbQry);
2418         destroyPQExpBuffer(delQry);
2419         destroyPQExpBuffer(creaQry);
2420 }
2421
2422
2423 /*
2424  * dumpEncoding: put the correct encoding into the archive
2425  */
2426 static void
2427 dumpEncoding(Archive *AH)
2428 {
2429         const char *encname = pg_encoding_to_char(AH->encoding);
2430         PQExpBuffer qry = createPQExpBuffer();
2431
2432         if (g_verbose)
2433                 write_msg(NULL, "saving encoding = %s\n", encname);
2434
2435         appendPQExpBuffer(qry, "SET client_encoding = ");
2436         appendStringLiteralAH(qry, encname, AH);
2437         appendPQExpBuffer(qry, ";\n");
2438
2439         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2440                                  "ENCODING", NULL, NULL, "",
2441                                  false, "ENCODING", SECTION_PRE_DATA,
2442                                  qry->data, "", NULL,
2443                                  NULL, 0,
2444                                  NULL, NULL);
2445
2446         destroyPQExpBuffer(qry);
2447 }
2448
2449
2450 /*
2451  * dumpStdStrings: put the correct escape string behavior into the archive
2452  */
2453 static void
2454 dumpStdStrings(Archive *AH)
2455 {
2456         const char *stdstrings = AH->std_strings ? "on" : "off";
2457         PQExpBuffer qry = createPQExpBuffer();
2458
2459         if (g_verbose)
2460                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2461                                   stdstrings);
2462
2463         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2464                                           stdstrings);
2465
2466         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2467                                  "STDSTRINGS", NULL, NULL, "",
2468                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2469                                  qry->data, "", NULL,
2470                                  NULL, 0,
2471                                  NULL, NULL);
2472
2473         destroyPQExpBuffer(qry);
2474 }
2475
2476
2477 /*
2478  * getBlobs:
2479  *      Collect schema-level data about large objects
2480  */
2481 static void
2482 getBlobs(Archive *fout)
2483 {
2484         PQExpBuffer blobQry = createPQExpBuffer();
2485         BlobInfo   *binfo;
2486         DumpableObject *bdata;
2487         PGresult   *res;
2488         int                     ntups;
2489         int                     i;
2490
2491         /* Verbose message */
2492         if (g_verbose)
2493                 write_msg(NULL, "reading large objects\n");
2494
2495         /* Make sure we are in proper schema */
2496         selectSourceSchema(fout, "pg_catalog");
2497
2498         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2499         if (fout->remoteVersion >= 90000)
2500                 appendPQExpBuffer(blobQry,
2501                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2502                                                   " FROM pg_largeobject_metadata",
2503                                                   username_subquery);
2504         else if (fout->remoteVersion >= 70100)
2505                 appendPQExpBuffer(blobQry,
2506                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2507                                                   " FROM pg_largeobject");
2508         else
2509                 appendPQExpBuffer(blobQry,
2510                                                   "SELECT oid, NULL::oid, NULL::oid"
2511                                                   " FROM pg_class WHERE relkind = 'l'");
2512
2513         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2514
2515         ntups = PQntuples(res);
2516         if (ntups > 0)
2517         {
2518                 /*
2519                  * Each large object has its own BLOB archive entry.
2520                  */
2521                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2522
2523                 for (i = 0; i < ntups; i++)
2524                 {
2525                         binfo[i].dobj.objType = DO_BLOB;
2526                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2527                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2528                         AssignDumpId(&binfo[i].dobj);
2529
2530                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2531                         if (!PQgetisnull(res, i, 1))
2532                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2533                         else
2534                                 binfo[i].rolname = "";
2535                         if (!PQgetisnull(res, i, 2))
2536                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2537                         else
2538                                 binfo[i].blobacl = NULL;
2539                 }
2540
2541                 /*
2542                  * If we have any large objects, a "BLOBS" archive entry is needed.
2543                  * This is just a placeholder for sorting; it carries no data now.
2544                  */
2545                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2546                 bdata->objType = DO_BLOB_DATA;
2547                 bdata->catId = nilCatalogId;
2548                 AssignDumpId(bdata);
2549                 bdata->name = pg_strdup("BLOBS");
2550         }
2551
2552         PQclear(res);
2553         destroyPQExpBuffer(blobQry);
2554 }
2555
2556 /*
2557  * dumpBlob
2558  *
2559  * dump the definition (metadata) of the given large object
2560  */
2561 static void
2562 dumpBlob(Archive *fout, BlobInfo *binfo)
2563 {
2564         PQExpBuffer cquery = createPQExpBuffer();
2565         PQExpBuffer dquery = createPQExpBuffer();
2566
2567         appendPQExpBuffer(cquery,
2568                                           "SELECT pg_catalog.lo_create('%s');\n",
2569                                           binfo->dobj.name);
2570
2571         appendPQExpBuffer(dquery,
2572                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2573                                           binfo->dobj.name);
2574
2575         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2576                                  binfo->dobj.name,
2577                                  NULL, NULL,
2578                                  binfo->rolname, false,
2579                                  "BLOB", SECTION_PRE_DATA,
2580                                  cquery->data, dquery->data, NULL,
2581                                  NULL, 0,
2582                                  NULL, NULL);
2583
2584         /* set up tag for comment and/or ACL */
2585         resetPQExpBuffer(cquery);
2586         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2587
2588         /* Dump comment if any */
2589         dumpComment(fout, cquery->data,
2590                                 NULL, binfo->rolname,
2591                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2592
2593         /* Dump security label if any */
2594         dumpSecLabel(fout, cquery->data,
2595                                  NULL, binfo->rolname,
2596                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2597
2598         /* Dump ACL if any */
2599         if (binfo->blobacl)
2600                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2601                                 binfo->dobj.name, NULL, cquery->data,
2602                                 NULL, binfo->rolname, binfo->blobacl);
2603
2604         destroyPQExpBuffer(cquery);
2605         destroyPQExpBuffer(dquery);
2606 }
2607
2608 /*
2609  * dumpBlobs:
2610  *      dump the data contents of all large objects
2611  */
2612 static int
2613 dumpBlobs(Archive *fout, void *arg)
2614 {
2615         const char *blobQry;
2616         const char *blobFetchQry;
2617         PGconn     *conn = GetConnection(fout);
2618         PGresult   *res;
2619         char            buf[LOBBUFSIZE];
2620         int                     ntups;
2621         int                     i;
2622         int                     cnt;
2623
2624         if (g_verbose)
2625                 write_msg(NULL, "saving large objects\n");
2626
2627         /* Make sure we are in proper schema */
2628         selectSourceSchema(fout, "pg_catalog");
2629
2630         /*
2631          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2632          * the already-in-memory dumpable objects instead...
2633          */
2634         if (fout->remoteVersion >= 90000)
2635                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2636         else if (fout->remoteVersion >= 70100)
2637                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2638         else
2639                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2640
2641         ExecuteSqlStatement(fout, blobQry);
2642
2643         /* Command to fetch from cursor */
2644         blobFetchQry = "FETCH 1000 IN bloboid";
2645
2646         do
2647         {
2648                 /* Do a fetch */
2649                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2650
2651                 /* Process the tuples, if any */
2652                 ntups = PQntuples(res);
2653                 for (i = 0; i < ntups; i++)
2654                 {
2655                         Oid                     blobOid;
2656                         int                     loFd;
2657
2658                         blobOid = atooid(PQgetvalue(res, i, 0));
2659                         /* Open the BLOB */
2660                         loFd = lo_open(conn, blobOid, INV_READ);
2661                         if (loFd == -1)
2662                                 exit_horribly(NULL, "could not open large object %u: %s",
2663                                                           blobOid, PQerrorMessage(conn));
2664
2665                         StartBlob(fout, blobOid);
2666
2667                         /* Now read it in chunks, sending data to archive */
2668                         do
2669                         {
2670                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2671                                 if (cnt < 0)
2672                                         exit_horribly(NULL, "error reading large object %u: %s",
2673                                                                   blobOid, PQerrorMessage(conn));
2674
2675                                 WriteData(fout, buf, cnt);
2676                         } while (cnt > 0);
2677
2678                         lo_close(conn, loFd);
2679
2680                         EndBlob(fout, blobOid);
2681                 }
2682
2683                 PQclear(res);
2684         } while (ntups > 0);
2685
2686         return 1;
2687 }
2688
2689 static void
2690 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2691                                                                                  PQExpBuffer upgrade_buffer,
2692                                                                                  Oid pg_type_oid)
2693 {
2694         PQExpBuffer upgrade_query = createPQExpBuffer();
2695         PGresult   *upgrade_res;
2696         Oid                     pg_type_array_oid;
2697
2698         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2699         appendPQExpBuffer(upgrade_buffer,
2700          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2701                                           pg_type_oid);
2702
2703         /* we only support old >= 8.3 for binary upgrades */
2704         appendPQExpBuffer(upgrade_query,
2705                                           "SELECT typarray "
2706                                           "FROM pg_catalog.pg_type "
2707                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2708                                           pg_type_oid);
2709
2710         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2711
2712         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2713
2714         if (OidIsValid(pg_type_array_oid))
2715         {
2716                 appendPQExpBuffer(upgrade_buffer,
2717                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2718                 appendPQExpBuffer(upgrade_buffer,
2719                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2720                                                   pg_type_array_oid);
2721         }
2722
2723         PQclear(upgrade_res);
2724         destroyPQExpBuffer(upgrade_query);
2725 }
2726
2727 static bool
2728 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2729                                                                                 PQExpBuffer upgrade_buffer,
2730                                                                                 Oid pg_rel_oid)
2731 {
2732         PQExpBuffer upgrade_query = createPQExpBuffer();
2733         PGresult   *upgrade_res;
2734         Oid                     pg_type_oid;
2735         bool            toast_set = false;
2736
2737         /* we only support old >= 8.3 for binary upgrades */
2738         appendPQExpBuffer(upgrade_query,
2739                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2740                                           "FROM pg_catalog.pg_class c "
2741                                           "LEFT JOIN pg_catalog.pg_class t ON "
2742                                           "  (c.reltoastrelid = t.oid) "
2743                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2744                                           pg_rel_oid);
2745
2746         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2747
2748         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2749
2750         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2751                                                                                          pg_type_oid);
2752
2753         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2754         {
2755                 /* Toast tables do not have pg_type array rows */
2756                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2757                                                                                         PQfnumber(upgrade_res, "trel")));
2758
2759                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2760                 appendPQExpBuffer(upgrade_buffer,
2761                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2762                                                   pg_type_toast_oid);
2763
2764                 toast_set = true;
2765         }
2766
2767         PQclear(upgrade_res);
2768         destroyPQExpBuffer(upgrade_query);
2769
2770         return toast_set;
2771 }
2772
2773 static void
2774 binary_upgrade_set_pg_class_oids(Archive *fout,
2775                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2776                                                                  bool is_index)
2777 {
2778         PQExpBuffer upgrade_query = createPQExpBuffer();
2779         PGresult   *upgrade_res;
2780         Oid                     pg_class_reltoastrelid;
2781         Oid                     pg_index_indexrelid;
2782
2783         appendPQExpBuffer(upgrade_query,
2784                                           "SELECT c.reltoastrelid, i.indexrelid "
2785                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2786                                           "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
2787                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2788                                           pg_class_oid);
2789
2790         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2791
2792         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2793         pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
2794
2795         appendPQExpBuffer(upgrade_buffer,
2796                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2797
2798         if (!is_index)
2799         {
2800                 appendPQExpBuffer(upgrade_buffer,
2801                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2802                                                   pg_class_oid);
2803                 /* only tables have toast tables, not indexes */
2804                 if (OidIsValid(pg_class_reltoastrelid))
2805                 {
2806                         /*
2807                          * One complexity is that the table definition might not require
2808                          * the creation of a TOAST table, and the TOAST table might have
2809                          * been created long after table creation, when the table was
2810                          * loaded with wide data.  By setting the TOAST oid we force
2811                          * creation of the TOAST heap and TOAST index by the backend so we
2812                          * can cleanly copy the files during binary upgrade.
2813                          */
2814
2815                         appendPQExpBuffer(upgrade_buffer,
2816                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2817                                                           pg_class_reltoastrelid);
2818
2819                         /* every toast table has an index */
2820                         appendPQExpBuffer(upgrade_buffer,
2821                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2822                                                           pg_index_indexrelid);
2823                 }
2824         }
2825         else
2826                 appendPQExpBuffer(upgrade_buffer,
2827                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2828                                                   pg_class_oid);
2829
2830         appendPQExpBuffer(upgrade_buffer, "\n");
2831
2832         PQclear(upgrade_res);
2833         destroyPQExpBuffer(upgrade_query);
2834 }
2835
2836 /*
2837  * If the DumpableObject is a member of an extension, add a suitable
2838  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2839  */
2840 static void
2841 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2842                                                                 DumpableObject *dobj,
2843                                                                 const char *objlabel)
2844 {
2845         DumpableObject *extobj = NULL;
2846         int                     i;
2847
2848         if (!dobj->ext_member)
2849                 return;
2850
2851         /*
2852          * Find the parent extension.  We could avoid this search if we wanted to
2853          * add a link field to DumpableObject, but the space costs of that would
2854          * be considerable.  We assume that member objects could only have a
2855          * direct dependency on their own extension, not any others.
2856          */
2857         for (i = 0; i < dobj->nDeps; i++)
2858         {
2859                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2860                 if (extobj && extobj->objType == DO_EXTENSION)
2861                         break;
2862                 extobj = NULL;
2863         }
2864         if (extobj == NULL)
2865                 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2866
2867         appendPQExpBuffer(upgrade_buffer,
2868           "\n-- For binary upgrade, handle extension membership the hard way\n");
2869         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2870                                           fmtId(extobj->name),
2871                                           objlabel);
2872 }
2873
2874 /*
2875  * getNamespaces:
2876  *        read all namespaces in the system catalogs and return them in the
2877  * NamespaceInfo* structure
2878  *
2879  *      numNamespaces is set to the number of namespaces read in
2880  */
2881 NamespaceInfo *
2882 getNamespaces(Archive *fout, int *numNamespaces)
2883 {
2884         PGresult   *res;
2885         int                     ntups;
2886         int                     i;
2887         PQExpBuffer query;
2888         NamespaceInfo *nsinfo;
2889         int                     i_tableoid;
2890         int                     i_oid;
2891         int                     i_nspname;
2892         int                     i_rolname;
2893         int                     i_nspacl;
2894
2895         /*
2896          * Before 7.3, there are no real namespaces; create two dummy entries, one
2897          * for user stuff and one for system stuff.
2898          */
2899         if (fout->remoteVersion < 70300)
2900         {
2901                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2902
2903                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2904                 nsinfo[0].dobj.catId.tableoid = 0;
2905                 nsinfo[0].dobj.catId.oid = 0;
2906                 AssignDumpId(&nsinfo[0].dobj);
2907                 nsinfo[0].dobj.name = pg_strdup("public");
2908                 nsinfo[0].rolname = pg_strdup("");
2909                 nsinfo[0].nspacl = pg_strdup("");
2910
2911                 selectDumpableNamespace(&nsinfo[0]);
2912
2913                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2914                 nsinfo[1].dobj.catId.tableoid = 0;
2915                 nsinfo[1].dobj.catId.oid = 1;
2916                 AssignDumpId(&nsinfo[1].dobj);
2917                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2918                 nsinfo[1].rolname = pg_strdup("");
2919                 nsinfo[1].nspacl = pg_strdup("");
2920
2921                 selectDumpableNamespace(&nsinfo[1]);
2922
2923                 *numNamespaces = 2;
2924
2925                 return nsinfo;
2926         }
2927
2928         query = createPQExpBuffer();
2929
2930         /* Make sure we are in proper schema */
2931         selectSourceSchema(fout, "pg_catalog");
2932
2933         /*
2934          * we fetch all namespaces including system ones, so that every object we
2935          * read in can be linked to a containing namespace.
2936          */
2937         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2938                                           "(%s nspowner) AS rolname, "
2939                                           "nspacl FROM pg_namespace",
2940                                           username_subquery);
2941
2942         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2943
2944         ntups = PQntuples(res);
2945
2946         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2947
2948         i_tableoid = PQfnumber(res, "tableoid");
2949         i_oid = PQfnumber(res, "oid");
2950         i_nspname = PQfnumber(res, "nspname");
2951         i_rolname = PQfnumber(res, "rolname");
2952         i_nspacl = PQfnumber(res, "nspacl");
2953
2954         for (i = 0; i < ntups; i++)
2955         {
2956                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2957                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2958                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2959                 AssignDumpId(&nsinfo[i].dobj);
2960                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2961                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2962                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2963
2964                 /* Decide whether to dump this namespace */
2965                 selectDumpableNamespace(&nsinfo[i]);
2966
2967                 if (strlen(nsinfo[i].rolname) == 0)
2968                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2969                                           nsinfo[i].dobj.name);
2970         }
2971
2972         PQclear(res);
2973         destroyPQExpBuffer(query);
2974
2975         *numNamespaces = ntups;
2976
2977         return nsinfo;
2978 }
2979
2980 /*
2981  * findNamespace:
2982  *              given a namespace OID and an object OID, look up the info read by
2983  *              getNamespaces
2984  *
2985  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2986  * a system object or not.      In 7.3 and later there is no guessing, and we
2987  * don't use objoid at all.
2988  */
2989 static NamespaceInfo *
2990 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2991 {
2992         NamespaceInfo *nsinfo;
2993
2994         if (fout->remoteVersion >= 70300)
2995         {
2996                 nsinfo = findNamespaceByOid(nsoid);
2997         }
2998         else
2999         {
3000                 /* This code depends on the dummy objects set up by getNamespaces. */
3001                 Oid                     i;
3002
3003                 if (objoid > g_last_builtin_oid)
3004                         i = 0;                          /* user object */
3005                 else
3006                         i = 1;                          /* system object */
3007                 nsinfo = findNamespaceByOid(i);
3008         }
3009
3010         if (nsinfo == NULL)
3011                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
3012
3013         return nsinfo;
3014 }
3015
3016 /*
3017  * getExtensions:
3018  *        read all extensions in the system catalogs and return them in the
3019  * ExtensionInfo* structure
3020  *
3021  *      numExtensions is set to the number of extensions read in
3022  */
3023 ExtensionInfo *
3024 getExtensions(Archive *fout, int *numExtensions)
3025 {
3026         PGresult   *res;
3027         int                     ntups;
3028         int                     i;
3029         PQExpBuffer query;
3030         ExtensionInfo *extinfo;
3031         int                     i_tableoid;
3032         int                     i_oid;
3033         int                     i_extname;
3034         int                     i_nspname;
3035         int                     i_extrelocatable;
3036         int                     i_extversion;
3037         int                     i_extconfig;
3038         int                     i_extcondition;
3039
3040         /*
3041          * Before 9.1, there are no extensions.
3042          */
3043         if (fout->remoteVersion < 90100)
3044         {
3045                 *numExtensions = 0;
3046                 return NULL;
3047         }
3048
3049         query = createPQExpBuffer();
3050
3051         /* Make sure we are in proper schema */
3052         selectSourceSchema(fout, "pg_catalog");
3053
3054         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
3055                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
3056                                           "FROM pg_extension x "
3057                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
3058
3059         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3060
3061         ntups = PQntuples(res);
3062
3063         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
3064
3065         i_tableoid = PQfnumber(res, "tableoid");
3066         i_oid = PQfnumber(res, "oid");
3067         i_extname = PQfnumber(res, "extname");
3068         i_nspname = PQfnumber(res, "nspname");
3069         i_extrelocatable = PQfnumber(res, "extrelocatable");
3070         i_extversion = PQfnumber(res, "extversion");
3071         i_extconfig = PQfnumber(res, "extconfig");
3072         i_extcondition = PQfnumber(res, "extcondition");
3073
3074         for (i = 0; i < ntups; i++)
3075         {
3076                 extinfo[i].dobj.objType = DO_EXTENSION;
3077                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3078                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3079                 AssignDumpId(&extinfo[i].dobj);
3080                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
3081                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
3082                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
3083                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
3084                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
3085                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
3086
3087                 /* Decide whether we want to dump it */
3088                 selectDumpableExtension(&(extinfo[i]));
3089         }
3090
3091         PQclear(res);
3092         destroyPQExpBuffer(query);
3093
3094         *numExtensions = ntups;
3095
3096         return extinfo;
3097 }
3098
3099 /*
3100  * getTypes:
3101  *        read all types in the system catalogs and return them in the
3102  * TypeInfo* structure
3103  *
3104  *      numTypes is set to the number of types read in
3105  *
3106  * NB: this must run after getFuncs() because we assume we can do
3107  * findFuncByOid().
3108  */
3109 TypeInfo *
3110 getTypes(Archive *fout, int *numTypes)
3111 {
3112         PGresult   *res;
3113         int                     ntups;
3114         int                     i;
3115         PQExpBuffer query = createPQExpBuffer();
3116         TypeInfo   *tyinfo;
3117         ShellTypeInfo *stinfo;
3118         int                     i_tableoid;
3119         int                     i_oid;
3120         int                     i_typname;
3121         int                     i_typnamespace;
3122         int                     i_typacl;
3123         int                     i_rolname;
3124         int                     i_typinput;
3125         int                     i_typoutput;
3126         int                     i_typelem;
3127         int                     i_typrelid;
3128         int                     i_typrelkind;
3129         int                     i_typtype;
3130         int                     i_typisdefined;
3131         int                     i_isarray;
3132
3133         /*
3134          * we include even the built-in types because those may be used as array
3135          * elements by user-defined types
3136          *
3137          * we filter out the built-in types when we dump out the types
3138          *
3139          * same approach for undefined (shell) types and array types
3140          *
3141          * Note: as of 8.3 we can reliably detect whether a type is an
3142          * auto-generated array type by checking the element type's typarray.
3143          * (Before that the test is capable of generating false positives.) We
3144          * still check for name beginning with '_', though, so as to avoid the
3145          * cost of the subselect probe for all standard types.  This would have to
3146          * be revisited if the backend ever allows renaming of array types.
3147          */
3148
3149         /* Make sure we are in proper schema */
3150         selectSourceSchema(fout, "pg_catalog");
3151
3152         if (fout->remoteVersion >= 90200)
3153         {
3154                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3155                                                   "typnamespace, typacl, "
3156                                                   "(%s typowner) AS rolname, "
3157                                                   "typinput::oid AS typinput, "
3158                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3159                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3160                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3161                                                   "typtype, typisdefined, "
3162                                                   "typname[0] = '_' AND typelem != 0 AND "
3163                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3164                                                   "FROM pg_type",
3165                                                   username_subquery);
3166         }
3167         else if (fout->remoteVersion >= 80300)
3168         {
3169                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3170                                                   "typnamespace, '{=U}' AS typacl, "
3171                                                   "(%s typowner) AS rolname, "
3172                                                   "typinput::oid AS typinput, "
3173                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3174                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3175                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3176                                                   "typtype, typisdefined, "
3177                                                   "typname[0] = '_' AND typelem != 0 AND "
3178                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3179                                                   "FROM pg_type",
3180                                                   username_subquery);
3181         }
3182         else if (fout->remoteVersion >= 70300)
3183         {
3184                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3185                                                   "typnamespace, '{=U}' AS typacl, "
3186                                                   "(%s typowner) AS rolname, "
3187                                                   "typinput::oid AS typinput, "
3188                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3189                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3190                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3191                                                   "typtype, typisdefined, "
3192                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3193                                                   "FROM pg_type",
3194                                                   username_subquery);
3195         }
3196         else if (fout->remoteVersion >= 70100)
3197         {
3198                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3199                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
3200                                                   "(%s typowner) AS rolname, "
3201                                                   "typinput::oid AS typinput, "
3202                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3203                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3204                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3205                                                   "typtype, typisdefined, "
3206                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3207                                                   "FROM pg_type",
3208                                                   username_subquery);
3209         }
3210         else
3211         {
3212                 appendPQExpBuffer(query, "SELECT "
3213                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
3214                                                   "oid, typname, "
3215                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
3216                                                   "(%s typowner) AS rolname, "
3217                                                   "typinput::oid AS typinput, "
3218                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
3219                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3220                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3221                                                   "typtype, typisdefined, "
3222                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
3223                                                   "FROM pg_type",
3224                                                   username_subquery);
3225         }
3226
3227         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3228
3229         ntups = PQntuples(res);
3230
3231         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3232
3233         i_tableoid = PQfnumber(res, "tableoid");
3234         i_oid = PQfnumber(res, "oid");
3235         i_typname = PQfnumber(res, "typname");
3236         i_typnamespace = PQfnumber(res, "typnamespace");
3237         i_typacl = PQfnumber(res, "typacl");
3238         i_rolname = PQfnumber(res, "rolname");
3239         i_typinput = PQfnumber(res, "typinput");
3240         i_typoutput = PQfnumber(res, "typoutput");
3241         i_typelem = PQfnumber(res, "typelem");
3242         i_typrelid = PQfnumber(res, "typrelid");
3243         i_typrelkind = PQfnumber(res, "typrelkind");
3244         i_typtype = PQfnumber(res, "typtype");
3245         i_typisdefined = PQfnumber(res, "typisdefined");
3246         i_isarray = PQfnumber(res, "isarray");
3247
3248         for (i = 0; i < ntups; i++)
3249         {
3250                 tyinfo[i].dobj.objType = DO_TYPE;
3251                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3252                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3253                 AssignDumpId(&tyinfo[i].dobj);
3254                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3255                 tyinfo[i].dobj.namespace =
3256                         findNamespace(fout,
3257                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
3258                                                   tyinfo[i].dobj.catId.oid);
3259                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3260                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
3261                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3262                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3263                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3264                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3265                 tyinfo[i].shellType = NULL;
3266
3267                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3268                         tyinfo[i].isDefined = true;
3269                 else
3270                         tyinfo[i].isDefined = false;
3271
3272                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3273                         tyinfo[i].isArray = true;
3274                 else
3275                         tyinfo[i].isArray = false;
3276
3277                 /* Decide whether we want to dump it */
3278                 selectDumpableType(&tyinfo[i]);
3279
3280                 /*
3281                  * If it's a domain, fetch info about its constraints, if any
3282                  */
3283                 tyinfo[i].nDomChecks = 0;
3284                 tyinfo[i].domChecks = NULL;
3285                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3286                         getDomainConstraints(fout, &(tyinfo[i]));
3287
3288                 /*
3289                  * If it's a base type, make a DumpableObject representing a shell
3290                  * definition of the type.      We will need to dump that ahead of the I/O
3291                  * functions for the type.      Similarly, range types need a shell
3292                  * definition in case they have a canonicalize function.
3293                  *
3294                  * Note: the shell type doesn't have a catId.  You might think it
3295                  * should copy the base type's catId, but then it might capture the
3296                  * pg_depend entries for the type, which we don't want.
3297                  */
3298                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3299                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
3300                 {
3301                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3302                         stinfo->dobj.objType = DO_SHELL_TYPE;
3303                         stinfo->dobj.catId = nilCatalogId;
3304                         AssignDumpId(&stinfo->dobj);
3305                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3306                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3307                         stinfo->baseType = &(tyinfo[i]);
3308                         tyinfo[i].shellType = stinfo;
3309
3310                         /*
3311                          * Initially mark the shell type as not to be dumped.  We'll only
3312                          * dump it if the I/O or canonicalize functions need to be dumped;
3313                          * this is taken care of while sorting dependencies.
3314                          */
3315                         stinfo->dobj.dump = false;
3316
3317                         /*
3318                          * However, if dumping from pre-7.3, there will be no dependency
3319                          * info so we have to fake it here.  We only need to worry about
3320                          * typinput and typoutput since the other functions only exist
3321                          * post-7.3.
3322                          */
3323                         if (fout->remoteVersion < 70300)
3324                         {
3325                                 Oid                     typinput;
3326                                 Oid                     typoutput;
3327                                 FuncInfo   *funcInfo;
3328
3329                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3330                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3331
3332                                 funcInfo = findFuncByOid(typinput);
3333                                 if (funcInfo && funcInfo->dobj.dump)
3334                                 {
3335                                         /* base type depends on function */
3336                                         addObjectDependency(&tyinfo[i].dobj,
3337                                                                                 funcInfo->dobj.dumpId);
3338                                         /* function depends on shell type */
3339                                         addObjectDependency(&funcInfo->dobj,
3340                                                                                 stinfo->dobj.dumpId);
3341                                         /* mark shell type as to be dumped */
3342                                         stinfo->dobj.dump = true;
3343                                 }
3344
3345                                 funcInfo = findFuncByOid(typoutput);
3346                                 if (funcInfo && funcInfo->dobj.dump)
3347                                 {
3348                                         /* base type depends on function */
3349                                         addObjectDependency(&tyinfo[i].dobj,
3350                                                                                 funcInfo->dobj.dumpId);
3351                                         /* function depends on shell type */
3352                                         addObjectDependency(&funcInfo->dobj,
3353                                                                                 stinfo->dobj.dumpId);
3354                                         /* mark shell type as to be dumped */
3355                                         stinfo->dobj.dump = true;
3356                                 }
3357                         }
3358                 }
3359
3360                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3361                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3362                                           tyinfo[i].dobj.name);
3363         }
3364
3365         *numTypes = ntups;
3366
3367         PQclear(res);
3368
3369         destroyPQExpBuffer(query);
3370
3371         return tyinfo;
3372 }
3373
3374 /*
3375  * getOperators:
3376  *        read all operators in the system catalogs and return them in the
3377  * OprInfo* structure
3378  *
3379  *      numOprs is set to the number of operators read in
3380  */
3381 OprInfo *
3382 getOperators(Archive *fout, int *numOprs)
3383 {
3384         PGresult   *res;
3385         int                     ntups;
3386         int                     i;
3387         PQExpBuffer query = createPQExpBuffer();
3388         OprInfo    *oprinfo;
3389         int                     i_tableoid;
3390         int                     i_oid;
3391         int                     i_oprname;
3392         int                     i_oprnamespace;
3393         int                     i_rolname;
3394         int                     i_oprkind;
3395         int                     i_oprcode;
3396
3397         /*
3398          * find all operators, including builtin operators; we filter out
3399          * system-defined operators at dump-out time.
3400          */
3401
3402         /* Make sure we are in proper schema */
3403         selectSourceSchema(fout, "pg_catalog");
3404
3405         if (fout->remoteVersion >= 70300)
3406         {
3407                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3408                                                   "oprnamespace, "
3409                                                   "(%s oprowner) AS rolname, "
3410                                                   "oprkind, "
3411                                                   "oprcode::oid AS oprcode "
3412                                                   "FROM pg_operator",
3413                                                   username_subquery);
3414         }
3415         else if (fout->remoteVersion >= 70100)
3416         {
3417                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3418                                                   "0::oid AS oprnamespace, "
3419                                                   "(%s oprowner) AS rolname, "
3420                                                   "oprkind, "
3421                                                   "oprcode::oid AS oprcode "
3422                                                   "FROM pg_operator",
3423                                                   username_subquery);
3424         }
3425         else
3426         {
3427                 appendPQExpBuffer(query, "SELECT "
3428                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3429                                                   "oid, oprname, "
3430                                                   "0::oid AS oprnamespace, "
3431                                                   "(%s oprowner) AS rolname, "
3432                                                   "oprkind, "
3433                                                   "oprcode::oid AS oprcode "
3434                                                   "FROM pg_operator",
3435                                                   username_subquery);
3436         }
3437
3438         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3439
3440         ntups = PQntuples(res);
3441         *numOprs = ntups;
3442
3443         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3444
3445         i_tableoid = PQfnumber(res, "tableoid");
3446         i_oid = PQfnumber(res, "oid");
3447         i_oprname = PQfnumber(res, "oprname");
3448         i_oprnamespace = PQfnumber(res, "oprnamespace");
3449         i_rolname = PQfnumber(res, "rolname");
3450         i_oprkind = PQfnumber(res, "oprkind");
3451         i_oprcode = PQfnumber(res, "oprcode");
3452
3453         for (i = 0; i < ntups; i++)
3454         {
3455                 oprinfo[i].dobj.objType = DO_OPERATOR;
3456                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3457                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3458                 AssignDumpId(&oprinfo[i].dobj);
3459                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3460                 oprinfo[i].dobj.namespace =
3461                         findNamespace(fout,
3462                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3463                                                   oprinfo[i].dobj.catId.oid);
3464                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3465                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3466                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3467
3468                 /* Decide whether we want to dump it */
3469                 selectDumpableObject(&(oprinfo[i].dobj));
3470
3471                 if (strlen(oprinfo[i].rolname) == 0)
3472                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3473                                           oprinfo[i].dobj.name);
3474         }
3475
3476         PQclear(res);
3477
3478         destroyPQExpBuffer(query);
3479
3480         return oprinfo;
3481 }
3482
3483 /*
3484  * getCollations:
3485  *        read all collations in the system catalogs and return them in the
3486  * CollInfo* structure
3487  *
3488  *      numCollations is set to the number of collations read in
3489  */
3490 CollInfo *
3491 getCollations(Archive *fout, int *numCollations)
3492 {
3493         PGresult   *res;
3494         int                     ntups;
3495         int                     i;
3496         PQExpBuffer query;
3497         CollInfo   *collinfo;
3498         int                     i_tableoid;
3499         int                     i_oid;
3500         int                     i_collname;
3501         int                     i_collnamespace;
3502         int                     i_rolname;
3503
3504         /* Collations didn't exist pre-9.1 */
3505         if (fout->remoteVersion < 90100)
3506         {
3507                 *numCollations = 0;
3508                 return NULL;
3509         }
3510
3511         query = createPQExpBuffer();
3512
3513         /*
3514          * find all collations, including builtin collations; we filter out
3515          * system-defined collations at dump-out time.
3516          */
3517
3518         /* Make sure we are in proper schema */
3519         selectSourceSchema(fout, "pg_catalog");
3520
3521         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3522                                           "collnamespace, "
3523                                           "(%s collowner) AS rolname "
3524                                           "FROM pg_collation",
3525                                           username_subquery);
3526
3527         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3528
3529         ntups = PQntuples(res);
3530         *numCollations = ntups;
3531
3532         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3533
3534         i_tableoid = PQfnumber(res, "tableoid");
3535         i_oid = PQfnumber(res, "oid");
3536         i_collname = PQfnumber(res, "collname");
3537         i_collnamespace = PQfnumber(res, "collnamespace");
3538         i_rolname = PQfnumber(res, "rolname");
3539
3540         for (i = 0; i < ntups; i++)
3541         {
3542                 collinfo[i].dobj.objType = DO_COLLATION;
3543                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3544                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3545                 AssignDumpId(&collinfo[i].dobj);
3546                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3547                 collinfo[i].dobj.namespace =
3548                         findNamespace(fout,
3549                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3550                                                   collinfo[i].dobj.catId.oid);
3551                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3552
3553                 /* Decide whether we want to dump it */
3554                 selectDumpableObject(&(collinfo[i].dobj));
3555         }
3556
3557         PQclear(res);
3558
3559         destroyPQExpBuffer(query);
3560
3561         return collinfo;
3562 }
3563
3564 /*
3565  * getConversions:
3566  *        read all conversions in the system catalogs and return them in the
3567  * ConvInfo* structure
3568  *
3569  *      numConversions is set to the number of conversions read in
3570  */
3571 ConvInfo *
3572 getConversions(Archive *fout, int *numConversions)
3573 {
3574         PGresult   *res;
3575         int                     ntups;
3576         int                     i;
3577         PQExpBuffer query = createPQExpBuffer();
3578         ConvInfo   *convinfo;
3579         int                     i_tableoid;
3580         int                     i_oid;
3581         int                     i_conname;
3582         int                     i_connamespace;
3583         int                     i_rolname;
3584
3585         /* Conversions didn't exist pre-7.3 */
3586         if (fout->remoteVersion < 70300)
3587         {
3588                 *numConversions = 0;
3589                 return NULL;
3590         }
3591
3592         /*
3593          * find all conversions, including builtin conversions; we filter out
3594          * system-defined conversions at dump-out time.
3595          */
3596
3597         /* Make sure we are in proper schema */
3598         selectSourceSchema(fout, "pg_catalog");
3599
3600         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3601                                           "connamespace, "
3602                                           "(%s conowner) AS rolname "
3603                                           "FROM pg_conversion",
3604                                           username_subquery);
3605
3606         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3607
3608         ntups = PQntuples(res);
3609         *numConversions = ntups;
3610
3611         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3612
3613         i_tableoid = PQfnumber(res, "tableoid");
3614         i_oid = PQfnumber(res, "oid");
3615         i_conname = PQfnumber(res, "conname");
3616         i_connamespace = PQfnumber(res, "connamespace");
3617         i_rolname = PQfnumber(res, "rolname");
3618
3619         for (i = 0; i < ntups; i++)
3620         {
3621                 convinfo[i].dobj.objType = DO_CONVERSION;
3622                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3623                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3624                 AssignDumpId(&convinfo[i].dobj);
3625                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3626                 convinfo[i].dobj.namespace =
3627                         findNamespace(fout,
3628                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3629                                                   convinfo[i].dobj.catId.oid);
3630                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3631
3632                 /* Decide whether we want to dump it */
3633                 selectDumpableObject(&(convinfo[i].dobj));
3634         }
3635
3636         PQclear(res);
3637
3638         destroyPQExpBuffer(query);
3639
3640         return convinfo;
3641 }
3642
3643 /*
3644  * getOpclasses:
3645  *        read all opclasses in the system catalogs and return them in the
3646  * OpclassInfo* structure
3647  *
3648  *      numOpclasses is set to the number of opclasses read in
3649  */
3650 OpclassInfo *
3651 getOpclasses(Archive *fout, int *numOpclasses)
3652 {
3653         PGresult   *res;
3654         int                     ntups;
3655         int                     i;
3656         PQExpBuffer query = createPQExpBuffer();
3657         OpclassInfo *opcinfo;
3658         int                     i_tableoid;
3659         int                     i_oid;
3660         int                     i_opcname;
3661         int                     i_opcnamespace;
3662         int                     i_rolname;
3663
3664         /*
3665          * find all opclasses, including builtin opclasses; we filter out
3666          * system-defined opclasses at dump-out time.
3667          */
3668
3669         /* Make sure we are in proper schema */
3670         selectSourceSchema(fout, "pg_catalog");
3671
3672         if (fout->remoteVersion >= 70300)
3673         {
3674                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3675                                                   "opcnamespace, "
3676                                                   "(%s opcowner) AS rolname "
3677                                                   "FROM pg_opclass",
3678                                                   username_subquery);
3679         }
3680         else if (fout->remoteVersion >= 70100)
3681         {
3682                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3683                                                   "0::oid AS opcnamespace, "
3684                                                   "''::name AS rolname "
3685                                                   "FROM pg_opclass");
3686         }
3687         else
3688         {
3689                 appendPQExpBuffer(query, "SELECT "
3690                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3691                                                   "oid, opcname, "
3692                                                   "0::oid AS opcnamespace, "
3693                                                   "''::name AS rolname "
3694                                                   "FROM pg_opclass");
3695         }
3696
3697         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3698
3699         ntups = PQntuples(res);
3700         *numOpclasses = ntups;
3701
3702         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3703
3704         i_tableoid = PQfnumber(res, "tableoid");
3705         i_oid = PQfnumber(res, "oid");
3706         i_opcname = PQfnumber(res, "opcname");
3707         i_opcnamespace = PQfnumber(res, "opcnamespace");
3708         i_rolname = PQfnumber(res, "rolname");
3709
3710         for (i = 0; i < ntups; i++)
3711         {
3712                 opcinfo[i].dobj.objType = DO_OPCLASS;
3713                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3714                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3715                 AssignDumpId(&opcinfo[i].dobj);
3716                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3717                 opcinfo[i].dobj.namespace =
3718                         findNamespace(fout,
3719                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3720                                                   opcinfo[i].dobj.catId.oid);
3721                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3722
3723                 /* Decide whether we want to dump it */
3724                 selectDumpableObject(&(opcinfo[i].dobj));
3725
3726                 if (fout->remoteVersion >= 70300)
3727                 {
3728                         if (strlen(opcinfo[i].rolname) == 0)
3729                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3730                                                   opcinfo[i].dobj.name);
3731                 }
3732         }
3733
3734         PQclear(res);
3735
3736         destroyPQExpBuffer(query);
3737
3738         return opcinfo;
3739 }
3740
3741 /*
3742  * getOpfamilies:
3743  *        read all opfamilies in the system catalogs and return them in the
3744  * OpfamilyInfo* structure
3745  *
3746  *      numOpfamilies is set to the number of opfamilies read in
3747  */
3748 OpfamilyInfo *
3749 getOpfamilies(Archive *fout, int *numOpfamilies)
3750 {
3751         PGresult   *res;
3752         int                     ntups;
3753         int                     i;
3754         PQExpBuffer query;
3755         OpfamilyInfo *opfinfo;
3756         int                     i_tableoid;
3757         int                     i_oid;
3758         int                     i_opfname;
3759         int                     i_opfnamespace;
3760         int                     i_rolname;
3761
3762         /* Before 8.3, there is no separate concept of opfamilies */
3763         if (fout->remoteVersion < 80300)
3764         {
3765                 *numOpfamilies = 0;
3766                 return NULL;
3767         }
3768
3769         query = createPQExpBuffer();
3770
3771         /*
3772          * find all opfamilies, including builtin opfamilies; we filter out
3773          * system-defined opfamilies at dump-out time.
3774          */
3775
3776         /* Make sure we are in proper schema */
3777         selectSourceSchema(fout, "pg_catalog");
3778
3779         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3780                                           "opfnamespace, "
3781                                           "(%s opfowner) AS rolname "
3782                                           "FROM pg_opfamily",
3783                                           username_subquery);
3784
3785         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3786
3787         ntups = PQntuples(res);
3788         *numOpfamilies = ntups;
3789
3790         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3791
3792         i_tableoid = PQfnumber(res, "tableoid");
3793         i_oid = PQfnumber(res, "oid");
3794         i_opfname = PQfnumber(res, "opfname");
3795         i_opfnamespace = PQfnumber(res, "opfnamespace");
3796         i_rolname = PQfnumber(res, "rolname");
3797
3798         for (i = 0; i < ntups; i++)
3799         {
3800                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3801                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3802                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3803                 AssignDumpId(&opfinfo[i].dobj);
3804                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3805                 opfinfo[i].dobj.namespace =
3806                         findNamespace(fout,
3807                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3808                                                   opfinfo[i].dobj.catId.oid);
3809                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3810
3811                 /* Decide whether we want to dump it */
3812                 selectDumpableObject(&(opfinfo[i].dobj));
3813
3814                 if (fout->remoteVersion >= 70300)
3815                 {
3816                         if (strlen(opfinfo[i].rolname) == 0)
3817                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3818                                                   opfinfo[i].dobj.name);
3819                 }
3820         }
3821
3822         PQclear(res);
3823
3824         destroyPQExpBuffer(query);
3825
3826         return opfinfo;
3827 }
3828
3829 /*
3830  * getAggregates:
3831  *        read all the user-defined aggregates in the system catalogs and
3832  * return them in the AggInfo* structure
3833  *
3834  * numAggs is set to the number of aggregates read in
3835  */
3836 AggInfo *
3837 getAggregates(Archive *fout, int *numAggs)
3838 {
3839         PGresult   *res;
3840         int                     ntups;
3841         int                     i;
3842         PQExpBuffer query = createPQExpBuffer();
3843         AggInfo    *agginfo;
3844         int                     i_tableoid;
3845         int                     i_oid;
3846         int                     i_aggname;
3847         int                     i_aggnamespace;
3848         int                     i_pronargs;
3849         int                     i_proargtypes;
3850         int                     i_rolname;
3851         int                     i_aggacl;
3852         int                     i_proiargs;
3853
3854         /* Make sure we are in proper schema */
3855         selectSourceSchema(fout, "pg_catalog");
3856
3857         /*
3858          * Find all user-defined aggregates.  See comment in getFuncs() for the
3859          * rationale behind the filtering logic.
3860          */
3861
3862         if (fout->remoteVersion >= 80400)
3863         {
3864                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3865                                                   "pronamespace AS aggnamespace, "
3866                                                   "pronargs, proargtypes, "
3867                         "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3868                                                   "(%s proowner) AS rolname, "
3869                                                   "proacl AS aggacl "
3870                                                   "FROM pg_proc p "
3871                                                   "WHERE proisagg AND ("
3872                                                   "pronamespace != "
3873                                                   "(SELECT oid FROM pg_namespace "
3874                                                   "WHERE nspname = 'pg_catalog')",
3875                                                   username_subquery);
3876                 if (binary_upgrade && fout->remoteVersion >= 90100)
3877                         appendPQExpBuffer(query,
3878                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3879                                                           "classid = 'pg_proc'::regclass AND "
3880                                                           "objid = p.oid AND "
3881                                                           "refclassid = 'pg_extension'::regclass AND "
3882                                                           "deptype = 'e')");
3883                 appendPQExpBuffer(query, ")");
3884         }
3885         else if (fout->remoteVersion >= 80200)
3886         {
3887                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3888                                                   "pronamespace AS aggnamespace, "
3889                                                   "pronargs, proargtypes, "
3890                                                   "NULL::text AS proiargs,"
3891                                                   "(%s proowner) AS rolname, "
3892                                                   "proacl AS aggacl "
3893                                                   "FROM pg_proc p "
3894                                                   "WHERE proisagg AND ("
3895                                                   "pronamespace != "
3896                                                   "(SELECT oid FROM pg_namespace "
3897                                                   "WHERE nspname = 'pg_catalog'))",
3898                                                   username_subquery);
3899         }
3900         else if (fout->remoteVersion >= 70300)
3901         {
3902                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3903                                                   "pronamespace AS aggnamespace, "
3904                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3905                                                   "proargtypes, "
3906                                                   "NULL::text AS proiargs, "
3907                                                   "(%s proowner) AS rolname, "
3908                                                   "proacl AS aggacl "
3909                                                   "FROM pg_proc "
3910                                                   "WHERE proisagg "
3911                                                   "AND pronamespace != "
3912                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3913                                                   username_subquery);
3914         }
3915         else if (fout->remoteVersion >= 70100)
3916         {
3917                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3918                                                   "0::oid AS aggnamespace, "
3919                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3920                                                   "aggbasetype AS proargtypes, "
3921                                                   "NULL::text AS proiargs, "
3922                                                   "(%s aggowner) AS rolname, "
3923                                                   "'{=X}' AS aggacl "
3924                                                   "FROM pg_aggregate "
3925                                                   "where oid > '%u'::oid",
3926                                                   username_subquery,
3927                                                   g_last_builtin_oid);
3928         }
3929         else
3930         {
3931                 appendPQExpBuffer(query, "SELECT "
3932                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3933                                                   "oid, aggname, "
3934                                                   "0::oid AS aggnamespace, "
3935                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3936                                                   "aggbasetype AS proargtypes, "
3937                                                   "NULL::text AS proiargs, "
3938                                                   "(%s aggowner) AS rolname, "
3939                                                   "'{=X}' AS aggacl "
3940                                                   "FROM pg_aggregate "
3941                                                   "where oid > '%u'::oid",
3942                                                   username_subquery,
3943                                                   g_last_builtin_oid);
3944         }
3945
3946         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3947
3948         ntups = PQntuples(res);
3949         *numAggs = ntups;
3950
3951         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3952
3953         i_tableoid = PQfnumber(res, "tableoid");
3954         i_oid = PQfnumber(res, "oid");
3955         i_aggname = PQfnumber(res, "aggname");
3956         i_aggnamespace = PQfnumber(res, "aggnamespace");
3957         i_pronargs = PQfnumber(res, "pronargs");
3958         i_proargtypes = PQfnumber(res, "proargtypes");
3959         i_rolname = PQfnumber(res, "rolname");
3960         i_aggacl = PQfnumber(res, "aggacl");
3961         i_proiargs = PQfnumber(res, "proiargs");
3962
3963         for (i = 0; i < ntups; i++)
3964         {
3965                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3966                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3967                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3968                 AssignDumpId(&agginfo[i].aggfn.dobj);
3969                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3970                 agginfo[i].aggfn.dobj.namespace =
3971                         findNamespace(fout,
3972                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3973                                                   agginfo[i].aggfn.dobj.catId.oid);
3974                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3975                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3976                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3977                                           agginfo[i].aggfn.dobj.name);
3978                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3979                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3980                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3981                 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3982                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3983                 if (agginfo[i].aggfn.nargs == 0)
3984                         agginfo[i].aggfn.argtypes = NULL;
3985                 else
3986                 {
3987                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3988                         if (fout->remoteVersion >= 70300)
3989                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3990                                                           agginfo[i].aggfn.argtypes,
3991                                                           agginfo[i].aggfn.nargs);
3992                         else
3993                                 /* it's just aggbasetype */
3994                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3995                 }
3996
3997                 /* Decide whether we want to dump it */
3998                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3999         }
4000
4001         PQclear(res);
4002
4003         destroyPQExpBuffer(query);
4004
4005         return agginfo;
4006 }
4007
4008 /*
4009  * getFuncs:
4010  *        read all the user-defined functions in the system catalogs and
4011  * return them in the FuncInfo* structure
4012  *
4013  * numFuncs is set to the number of functions read in
4014  */
4015 FuncInfo *
4016 getFuncs(Archive *fout, int *numFuncs)
4017 {
4018         PGresult   *res;
4019         int                     ntups;
4020         int                     i;
4021         PQExpBuffer query = createPQExpBuffer();
4022         FuncInfo   *finfo;
4023         int                     i_tableoid;
4024         int                     i_oid;
4025         int                     i_proname;
4026         int                     i_pronamespace;
4027         int                     i_rolname;
4028         int                     i_prolang;
4029         int                     i_pronargs;
4030         int                     i_proargtypes;
4031         int                     i_prorettype;
4032         int                     i_proacl;
4033         int                     i_proiargs;
4034
4035         /* Make sure we are in proper schema */
4036         selectSourceSchema(fout, "pg_catalog");
4037
4038         /*
4039          * Find all user-defined functions.  Normally we can exclude functions in
4040          * pg_catalog, which is worth doing since there are several thousand of
4041          * 'em.  However, there are some extensions that create functions in
4042          * pg_catalog.  In normal dumps we can still ignore those --- but in
4043          * binary-upgrade mode, we must dump the member objects of the extension,
4044          * so be sure to fetch any such functions.
4045          *
4046          * Also, in 9.2 and up, exclude functions that are internally dependent on
4047          * something else, since presumably those will be created as a result of
4048          * creating the something else.  This currently only acts to suppress
4049          * constructor functions for range types.  Note that this is OK only
4050          * because the constructors don't have any dependencies the range type
4051          * doesn't have; otherwise we might not get creation ordering correct.
4052          */
4053
4054         if (fout->remoteVersion >= 80400)
4055         {
4056                 appendPQExpBuffer(query,
4057                                                   "SELECT tableoid, oid, proname, prolang, "
4058                                                   "pronargs, proargtypes, prorettype, proacl, "
4059                                                   "pronamespace, "
4060                         "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
4061                                                   "(%s proowner) AS rolname "
4062                                                   "FROM pg_proc p "
4063                                                   "WHERE NOT proisagg AND ("
4064                                                   "pronamespace != "
4065                                                   "(SELECT oid FROM pg_namespace "
4066                                                   "WHERE nspname = 'pg_catalog')",
4067                                                   username_subquery);
4068                 if (fout->remoteVersion >= 90200)
4069                         appendPQExpBuffer(query,
4070                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
4071                                                           "WHERE classid = 'pg_proc'::regclass AND "
4072                                                           "objid = p.oid AND deptype = 'i')");
4073                 if (binary_upgrade && fout->remoteVersion >= 90100)
4074                         appendPQExpBuffer(query,
4075                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
4076                                                           "classid = 'pg_proc'::regclass AND "
4077                                                           "objid = p.oid AND "
4078                                                           "refclassid = 'pg_extension'::regclass AND "
4079                                                           "deptype = 'e')");
4080                 appendPQExpBuffer(query, ")");
4081         }
4082         else if (fout->remoteVersion >= 70300)
4083         {
4084                 appendPQExpBuffer(query,
4085                                                   "SELECT tableoid, oid, proname, prolang, "
4086                                                   "pronargs, proargtypes, prorettype, proacl, "
4087                                                   "pronamespace, "
4088                                                   "NULL::text AS proiargs,"
4089                                                   "(%s proowner) AS rolname "
4090                                                   "FROM pg_proc p "
4091                                                   "WHERE NOT proisagg AND ("
4092                                                   "pronamespace != "
4093                                                   "(SELECT oid FROM pg_namespace "
4094                                                   "WHERE nspname = 'pg_catalog'))",
4095                                                   username_subquery);
4096         }
4097         else if (fout->remoteVersion >= 70100)
4098         {
4099                 appendPQExpBuffer(query,
4100                                                   "SELECT tableoid, oid, proname, prolang, "
4101                                                   "pronargs, proargtypes, prorettype, "
4102                                                   "'{=X}' AS proacl, "
4103                                                   "0::oid AS pronamespace, "
4104                                                   "NULL::text AS proiargs,"
4105                                                   "(%s proowner) AS rolname "
4106                                                   "FROM pg_proc "
4107                                                   "WHERE pg_proc.oid > '%u'::oid",
4108                                                   username_subquery,
4109                                                   g_last_builtin_oid);
4110         }
4111         else
4112         {
4113                 appendPQExpBuffer(query,
4114                                                   "SELECT "
4115                                                   "(SELECT oid FROM pg_class "
4116                                                   " WHERE relname = 'pg_proc') AS tableoid, "
4117                                                   "oid, proname, prolang, "
4118                                                   "pronargs, proargtypes, prorettype, "
4119                                                   "'{=X}' AS proacl, "
4120                                                   "0::oid AS pronamespace, "
4121                                                   "NULL::text AS proiargs,"
4122                                                   "(%s proowner) AS rolname "
4123                                                   "FROM pg_proc "
4124                                                   "where pg_proc.oid > '%u'::oid",
4125                                                   username_subquery,
4126                                                   g_last_builtin_oid);
4127         }
4128
4129         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4130
4131         ntups = PQntuples(res);
4132
4133         *numFuncs = ntups;
4134
4135         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
4136
4137         i_tableoid = PQfnumber(res, "tableoid");
4138         i_oid = PQfnumber(res, "oid");
4139         i_proname = PQfnumber(res, "proname");
4140         i_pronamespace = PQfnumber(res, "pronamespace");
4141         i_rolname = PQfnumber(res, "rolname");
4142         i_prolang = PQfnumber(res, "prolang");
4143         i_pronargs = PQfnumber(res, "pronargs");
4144         i_proargtypes = PQfnumber(res, "proargtypes");
4145         i_prorettype = PQfnumber(res, "prorettype");
4146         i_proacl = PQfnumber(res, "proacl");
4147         i_proiargs = PQfnumber(res, "proiargs");
4148
4149         for (i = 0; i < ntups; i++)
4150         {
4151                 finfo[i].dobj.objType = DO_FUNC;
4152                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4153                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4154                 AssignDumpId(&finfo[i].dobj);
4155                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
4156                 finfo[i].dobj.namespace =
4157                         findNamespace(fout,
4158                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
4159                                                   finfo[i].dobj.catId.oid);
4160                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4161                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
4162                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
4163                 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
4164                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
4165                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
4166                 if (finfo[i].nargs == 0)
4167                         finfo[i].argtypes = NULL;
4168                 else
4169                 {
4170                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
4171                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
4172                                                   finfo[i].argtypes, finfo[i].nargs);
4173                 }
4174
4175                 /* Decide whether we want to dump it */
4176                 selectDumpableObject(&(finfo[i].dobj));
4177
4178                 if (strlen(finfo[i].rolname) == 0)
4179                         write_msg(NULL,
4180                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
4181                                           finfo[i].dobj.name);
4182         }
4183
4184         PQclear(res);
4185
4186         destroyPQExpBuffer(query);
4187
4188         return finfo;
4189 }
4190
4191 /*
4192  * getTables
4193  *        read all the user-defined tables (no indexes, no catalogs)
4194  * in the system catalogs return them in the TableInfo* structure
4195  *
4196  * numTables is set to the number of tables read in
4197  */
4198 TableInfo *
4199 getTables(Archive *fout, int *numTables)
4200 {
4201         PGresult   *res;
4202         int                     ntups;
4203         int                     i;
4204         PQExpBuffer query = createPQExpBuffer();
4205         TableInfo  *tblinfo;
4206         int                     i_reltableoid;
4207         int                     i_reloid;
4208         int                     i_relname;
4209         int                     i_relnamespace;
4210         int                     i_relkind;
4211         int                     i_relacl;
4212         int                     i_rolname;
4213         int                     i_relchecks;
4214         int                     i_relhastriggers;
4215         int                     i_relhasindex;
4216         int                     i_relhasrules;
4217         int                     i_relhasoids;
4218         int                     i_relfrozenxid;
4219         int                     i_toastoid;
4220         int                     i_toastfrozenxid;
4221         int                     i_relpersistence;
4222         int                     i_relispopulated;
4223         int                     i_owning_tab;
4224         int                     i_owning_col;
4225         int                     i_reltablespace;
4226         int                     i_reloptions;
4227         int                     i_checkoption;
4228         int                     i_toastreloptions;
4229         int                     i_reloftype;
4230         int                     i_relpages;
4231
4232         /* Make sure we are in proper schema */
4233         selectSourceSchema(fout, "pg_catalog");
4234
4235         /*
4236          * Find all the tables and table-like objects.
4237          *
4238          * We include system catalogs, so that we can work if a user table is
4239          * defined to inherit from a system catalog (pretty weird, but...)
4240          *
4241          * We ignore relations that are not ordinary tables, sequences, views,
4242          * materialized views, composite types, or foreign tables.
4243          *
4244          * Composite-type table entries won't be dumped as such, but we have to
4245          * make a DumpableObject for them so that we can track dependencies of the
4246          * composite type (pg_depend entries for columns of the composite type
4247          * link to the pg_class entry not the pg_type entry).
4248          *
4249          * Note: in this phase we should collect only a minimal amount of
4250          * information about each table, basically just enough to decide if it is
4251          * interesting. We must fetch all tables in this phase because otherwise
4252          * we cannot correctly identify inherited columns, owned sequences, etc.
4253          */
4254
4255         if (fout->remoteVersion >= 90300)
4256         {
4257                 /*
4258                  * Left join to pick up dependency info linking sequences to their
4259                  * owning column, if any (note this dependency is AUTO as of 8.2)
4260                  */
4261                 appendPQExpBuffer(query,
4262                                                   "SELECT c.tableoid, c.oid, c.relname, "
4263                                                   "c.relacl, c.relkind, c.relnamespace, "
4264                                                   "(%s c.relowner) AS rolname, "
4265                                                   "c.relchecks, c.relhastriggers, "
4266                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4267                                                   "c.relfrozenxid, tc.oid AS toid, "
4268                                                   "tc.relfrozenxid AS tfrozenxid, "
4269                                                   "c.relpersistence, c.relispopulated, "
4270                                                   "c.relpages, "
4271                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4272                                                   "d.refobjid AS owning_tab, "
4273                                                   "d.refobjsubid AS owning_col, "
4274                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4275                                                 "array_to_string(array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded'), ', ') AS reloptions, "
4276                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
4277                                                            "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
4278                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4279                                                   "FROM pg_class c "
4280                                                   "LEFT JOIN pg_depend d ON "
4281                                                   "(c.relkind = '%c' AND "
4282                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4283                                                   "d.objsubid = 0 AND "
4284                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4285                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4286                                    "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4287                                                   "ORDER BY c.oid",
4288                                                   username_subquery,
4289                                                   RELKIND_SEQUENCE,
4290                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4291                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4292                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4293         }
4294         else if (fout->remoteVersion >= 90100)
4295         {
4296                 /*
4297                  * Left join to pick up dependency info linking sequences to their
4298                  * owning column, if any (note this dependency is AUTO as of 8.2)
4299                  */
4300                 appendPQExpBuffer(query,
4301                                                   "SELECT c.tableoid, c.oid, c.relname, "
4302                                                   "c.relacl, c.relkind, c.relnamespace, "
4303                                                   "(%s c.relowner) AS rolname, "
4304                                                   "c.relchecks, c.relhastriggers, "
4305                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4306                                                   "c.relfrozenxid, tc.oid AS toid, "
4307                                                   "tc.relfrozenxid AS tfrozenxid, "
4308                                                   "c.relpersistence, 't' as relispopulated, "
4309                                                   "c.relpages, "
4310                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4311                                                   "d.refobjid AS owning_tab, "
4312                                                   "d.refobjsubid AS owning_col, "
4313                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4314                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4315                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4316                                                   "FROM pg_class c "
4317                                                   "LEFT JOIN pg_depend d ON "
4318                                                   "(c.relkind = '%c' AND "
4319                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4320                                                   "d.objsubid = 0 AND "
4321                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4322                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4323                                    "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4324                                                   "ORDER BY c.oid",
4325                                                   username_subquery,
4326                                                   RELKIND_SEQUENCE,
4327                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4328                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4329                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4330         }
4331         else if (fout->remoteVersion >= 90000)
4332         {
4333                 /*
4334                  * Left join to pick up dependency info linking sequences to their
4335                  * owning column, if any (note this dependency is AUTO as of 8.2)
4336                  */
4337                 appendPQExpBuffer(query,
4338                                                   "SELECT c.tableoid, c.oid, c.relname, "
4339                                                   "c.relacl, c.relkind, c.relnamespace, "
4340                                                   "(%s c.relowner) AS rolname, "
4341                                                   "c.relchecks, c.relhastriggers, "
4342                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4343                                                   "c.relfrozenxid, tc.oid AS toid, "
4344                                                   "tc.relfrozenxid AS tfrozenxid, "
4345                                                   "'p' AS relpersistence, 't' as relispopulated, "
4346                                                   "c.relpages, "
4347                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4348                                                   "d.refobjid AS owning_tab, "
4349                                                   "d.refobjsubid AS owning_col, "
4350                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4351                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4352                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4353                                                   "FROM pg_class c "
4354                                                   "LEFT JOIN pg_depend d ON "
4355                                                   "(c.relkind = '%c' AND "
4356                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4357                                                   "d.objsubid = 0 AND "
4358                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4359                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4360                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4361                                                   "ORDER BY c.oid",
4362                                                   username_subquery,
4363                                                   RELKIND_SEQUENCE,
4364                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4365                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4366         }
4367         else if (fout->remoteVersion >= 80400)
4368         {
4369                 /*
4370                  * Left join to pick up dependency info linking sequences to their
4371                  * owning column, if any (note this dependency is AUTO as of 8.2)
4372                  */
4373                 appendPQExpBuffer(query,
4374                                                   "SELECT c.tableoid, c.oid, c.relname, "
4375                                                   "c.relacl, c.relkind, c.relnamespace, "
4376                                                   "(%s c.relowner) AS rolname, "
4377                                                   "c.relchecks, c.relhastriggers, "
4378                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4379                                                   "c.relfrozenxid, tc.oid AS toid, "
4380                                                   "tc.relfrozenxid AS tfrozenxid, "
4381                                                   "'p' AS relpersistence, 't' as relispopulated, "
4382                                                   "c.relpages, "
4383                                                   "NULL AS reloftype, "
4384                                                   "d.refobjid AS owning_tab, "
4385                                                   "d.refobjsubid AS owning_col, "
4386                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4387                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4388                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4389                                                   "FROM pg_class c "
4390                                                   "LEFT JOIN pg_depend d ON "
4391                                                   "(c.relkind = '%c' AND "
4392                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4393                                                   "d.objsubid = 0 AND "
4394                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4395                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4396                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4397                                                   "ORDER BY c.oid",
4398                                                   username_subquery,
4399                                                   RELKIND_SEQUENCE,
4400                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4401                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4402         }
4403         else if (fout->remoteVersion >= 80200)
4404         {
4405                 /*
4406                  * Left join to pick up dependency info linking sequences to their
4407                  * owning column, if any (note this dependency is AUTO as of 8.2)
4408                  */
4409                 appendPQExpBuffer(query,
4410                                                   "SELECT c.tableoid, c.oid, c.relname, "
4411                                                   "c.relacl, c.relkind, c.relnamespace, "
4412                                                   "(%s c.relowner) AS rolname, "
4413                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4414                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4415                                                   "c.relfrozenxid, tc.oid AS toid, "
4416                                                   "tc.relfrozenxid AS tfrozenxid, "
4417                                                   "'p' AS relpersistence, 't' as relispopulated, "
4418                                                   "c.relpages, "
4419                                                   "NULL AS reloftype, "
4420                                                   "d.refobjid AS owning_tab, "
4421                                                   "d.refobjsubid AS owning_col, "
4422                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4423                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4424                                                   "NULL AS toast_reloptions "
4425                                                   "FROM pg_class c "
4426                                                   "LEFT JOIN pg_depend d ON "
4427                                                   "(c.relkind = '%c' AND "
4428                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4429                                                   "d.objsubid = 0 AND "
4430                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4431                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4432                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4433                                                   "ORDER BY c.oid",
4434                                                   username_subquery,
4435                                                   RELKIND_SEQUENCE,
4436                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4437                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4438         }
4439         else if (fout->remoteVersion >= 80000)
4440         {
4441                 /*
4442                  * Left join to pick up dependency info linking sequences to their
4443                  * owning column, if any
4444                  */
4445                 appendPQExpBuffer(query,
4446                                                   "SELECT c.tableoid, c.oid, relname, "
4447                                                   "relacl, relkind, relnamespace, "
4448                                                   "(%s relowner) AS rolname, "
4449                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4450                                                   "relhasindex, relhasrules, relhasoids, "
4451                                                   "0 AS relfrozenxid, "
4452                                                   "0 AS toid, "
4453                                                   "0 AS tfrozenxid, "
4454                                                   "'p' AS relpersistence, 't' as relispopulated, "
4455                                                   "relpages, "
4456                                                   "NULL AS reloftype, "
4457                                                   "d.refobjid AS owning_tab, "
4458                                                   "d.refobjsubid AS owning_col, "
4459                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4460                                                   "NULL AS reloptions, "
4461                                                   "NULL AS toast_reloptions "
4462                                                   "FROM pg_class c "
4463                                                   "LEFT JOIN pg_depend d ON "
4464                                                   "(c.relkind = '%c' AND "
4465                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4466                                                   "d.objsubid = 0 AND "
4467                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4468                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4469                                                   "ORDER BY c.oid",
4470                                                   username_subquery,
4471                                                   RELKIND_SEQUENCE,
4472                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4473                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4474         }
4475         else if (fout->remoteVersion >= 70300)
4476         {
4477                 /*
4478                  * Left join to pick up dependency info linking sequences to their
4479                  * owning column, if any
4480                  */
4481                 appendPQExpBuffer(query,
4482                                                   "SELECT c.tableoid, c.oid, relname, "
4483                                                   "relacl, relkind, relnamespace, "
4484                                                   "(%s relowner) AS rolname, "
4485                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4486                                                   "relhasindex, relhasrules, relhasoids, "
4487                                                   "0 AS relfrozenxid, "
4488                                                   "0 AS toid, "
4489                                                   "0 AS tfrozenxid, "
4490                                                   "'p' AS relpersistence, 't' as relispopulated, "
4491                                                   "relpages, "
4492                                                   "NULL AS reloftype, "
4493                                                   "d.refobjid AS owning_tab, "
4494                                                   "d.refobjsubid AS owning_col, "
4495                                                   "NULL AS reltablespace, "
4496                                                   "NULL AS reloptions, "
4497                                                   "NULL AS toast_reloptions "
4498                                                   "FROM pg_class c "
4499                                                   "LEFT JOIN pg_depend d ON "
4500                                                   "(c.relkind = '%c' AND "
4501                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4502                                                   "d.objsubid = 0 AND "
4503                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4504                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4505                                                   "ORDER BY c.oid",
4506                                                   username_subquery,
4507                                                   RELKIND_SEQUENCE,
4508                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4509                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4510         }
4511         else if (fout->remoteVersion >= 70200)
4512         {
4513                 appendPQExpBuffer(query,
4514                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4515                                                   "0::oid AS relnamespace, "
4516                                                   "(%s relowner) AS rolname, "
4517                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4518                                                   "relhasindex, relhasrules, relhasoids, "
4519                                                   "0 AS relfrozenxid, "
4520                                                   "0 AS toid, "
4521                                                   "0 AS tfrozenxid, "
4522                                                   "'p' AS relpersistence, 't' as relispopulated, "
4523                                                   "relpages, "
4524                                                   "NULL AS reloftype, "
4525                                                   "NULL::oid AS owning_tab, "
4526                                                   "NULL::int4 AS owning_col, "
4527                                                   "NULL AS reltablespace, "
4528                                                   "NULL AS reloptions, "
4529                                                   "NULL AS toast_reloptions "
4530                                                   "FROM pg_class "
4531                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4532                                                   "ORDER BY oid",
4533                                                   username_subquery,
4534                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4535         }
4536         else if (fout->remoteVersion >= 70100)
4537         {
4538                 /* all tables have oids in 7.1 */
4539                 appendPQExpBuffer(query,
4540                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4541                                                   "0::oid AS relnamespace, "
4542                                                   "(%s relowner) AS rolname, "
4543                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4544                                                   "relhasindex, relhasrules, "
4545                                                   "'t'::bool AS relhasoids, "
4546                                                   "0 AS relfrozenxid, "
4547                                                   "0 AS toid, "
4548                                                   "0 AS tfrozenxid, "
4549                                                   "'p' AS relpersistence, 't' as relispopulated, "
4550                                                   "relpages, "
4551                                                   "NULL AS reloftype, "
4552                                                   "NULL::oid AS owning_tab, "
4553                                                   "NULL::int4 AS owning_col, "
4554                                                   "NULL AS reltablespace, "
4555                                                   "NULL AS reloptions, "
4556                                                   "NULL AS toast_reloptions "
4557                                                   "FROM pg_class "
4558                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4559                                                   "ORDER BY oid",
4560                                                   username_subquery,
4561                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4562         }
4563         else
4564         {
4565                 /*
4566                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4567                  * have a view by looking for a rule in pg_rewrite.
4568                  */
4569                 appendPQExpBuffer(query,
4570                                                   "SELECT "
4571                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4572                                                   "oid, relname, relacl, "
4573                                                   "CASE WHEN relhasrules and relkind = 'r' "
4574                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4575                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4576                                                   "THEN '%c'::\"char\" "
4577                                                   "ELSE relkind END AS relkind,"
4578                                                   "0::oid AS relnamespace, "
4579                                                   "(%s relowner) AS rolname, "
4580                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4581                                                   "relhasindex, relhasrules, "
4582                                                   "'t'::bool AS relhasoids, "
4583                                                   "0 as relfrozenxid, "
4584                                                   "0 AS toid, "
4585                                                   "0 AS tfrozenxid, "
4586                                                   "'p' AS relpersistence, 't' as relispopulated, "
4587                                                   "0 AS relpages, "
4588                                                   "NULL AS reloftype, "
4589                                                   "NULL::oid AS owning_tab, "
4590                                                   "NULL::int4 AS owning_col, "
4591                                                   "NULL AS reltablespace, "
4592                                                   "NULL AS reloptions, "
4593                                                   "NULL AS toast_reloptions "
4594                                                   "FROM pg_class c "
4595                                                   "WHERE relkind IN ('%c', '%c') "
4596                                                   "ORDER BY oid",
4597                                                   RELKIND_VIEW,
4598                                                   username_subquery,
4599                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4600         }
4601
4602         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4603
4604         ntups = PQntuples(res);
4605
4606         *numTables = ntups;
4607
4608         /*
4609          * Extract data from result and lock dumpable tables.  We do the locking
4610          * before anything else, to minimize the window wherein a table could
4611          * disappear under us.
4612          *
4613          * Note that we have to save info about all tables here, even when dumping
4614          * only one, because we don't yet know which tables might be inheritance
4615          * ancestors of the target table.
4616          */
4617         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4618
4619         i_reltableoid = PQfnumber(res, "tableoid");
4620         i_reloid = PQfnumber(res, "oid");
4621         i_relname = PQfnumber(res, "relname");
4622         i_relnamespace = PQfnumber(res, "relnamespace");
4623         i_relacl = PQfnumber(res, "relacl");
4624         i_relkind = PQfnumber(res, "relkind");
4625         i_rolname = PQfnumber(res, "rolname");
4626         i_relchecks = PQfnumber(res, "relchecks");
4627         i_relhastriggers = PQfnumber(res, "relhastriggers");
4628         i_relhasindex = PQfnumber(res, "relhasindex");
4629         i_relhasrules = PQfnumber(res, "relhasrules");
4630         i_relhasoids = PQfnumber(res, "relhasoids");
4631         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4632         i_toastoid = PQfnumber(res, "toid");
4633         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4634         i_relpersistence = PQfnumber(res, "relpersistence");
4635         i_relispopulated = PQfnumber(res, "relispopulated");
4636         i_relpages = PQfnumber(res, "relpages");
4637         i_owning_tab = PQfnumber(res, "owning_tab");
4638         i_owning_col = PQfnumber(res, "owning_col");
4639         i_reltablespace = PQfnumber(res, "reltablespace");
4640         i_reloptions = PQfnumber(res, "reloptions");
4641         i_checkoption = PQfnumber(res, "checkoption");
4642         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4643         i_reloftype = PQfnumber(res, "reloftype");
4644
4645         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4646         {
4647                 /*
4648                  * Arrange to fail instead of waiting forever for a table lock.
4649                  *
4650                  * NB: this coding assumes that the only queries issued within the
4651                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4652                  * applied to other things too.
4653                  */
4654                 resetPQExpBuffer(query);
4655                 appendPQExpBuffer(query, "SET statement_timeout = ");
4656                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4657                 ExecuteSqlStatement(fout, query->data);
4658         }
4659
4660         for (i = 0; i < ntups; i++)
4661         {
4662                 tblinfo[i].dobj.objType = DO_TABLE;
4663                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4664                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4665                 AssignDumpId(&tblinfo[i].dobj);
4666                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4667                 tblinfo[i].dobj.namespace =
4668                         findNamespace(fout,
4669                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4670                                                   tblinfo[i].dobj.catId.oid);
4671                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4672                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4673                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4674                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4675                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4676                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4677                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4678                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4679                 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
4680                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
4681                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4682                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4683                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4684                 if (PQgetisnull(res, i, i_reloftype))
4685                         tblinfo[i].reloftype = NULL;
4686                 else
4687                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4688                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4689                 if (PQgetisnull(res, i, i_owning_tab))
4690                 {
4691                         tblinfo[i].owning_tab = InvalidOid;
4692                         tblinfo[i].owning_col = 0;
4693                 }
4694                 else
4695                 {
4696                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4697                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4698                 }
4699                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4700                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4701                 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
4702                         tblinfo[i].checkoption = NULL;
4703                 else
4704                         tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
4705                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4706
4707                 /* other fields were zeroed above */
4708
4709                 /*
4710                  * Decide whether we want to dump this table.
4711                  */
4712                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4713                         tblinfo[i].dobj.dump = false;
4714                 else
4715                         selectDumpableTable(&tblinfo[i]);
4716                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4717
4718                 /*
4719                  * Read-lock target tables to make sure they aren't DROPPED or altered
4720                  * in schema before we get around to dumping them.
4721                  *
4722                  * Note that we don't explicitly lock parents of the target tables; we
4723                  * assume our lock on the child is enough to prevent schema
4724                  * alterations to parent tables.
4725                  *
4726                  * NOTE: it'd be kinda nice to lock other relations too, not only
4727                  * plain tables, but the backend doesn't presently allow that.
4728                  */
4729                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4730                 {
4731                         resetPQExpBuffer(query);
4732                         appendPQExpBuffer(query,
4733                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4734                                                           fmtQualifiedId(fout->remoteVersion,
4735                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4736                                                                                          tblinfo[i].dobj.name));
4737                         ExecuteSqlStatement(fout, query->data);
4738                 }
4739
4740                 /* Emit notice if join for owner failed */
4741                 if (strlen(tblinfo[i].rolname) == 0)
4742                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4743                                           tblinfo[i].dobj.name);
4744         }
4745
4746         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4747         {
4748                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4749         }
4750
4751         PQclear(res);
4752
4753         destroyPQExpBuffer(query);
4754
4755         return tblinfo;
4756 }
4757
4758 /*
4759  * getOwnedSeqs
4760  *        identify owned sequences and mark them as dumpable if owning table is
4761  *
4762  * We used to do this in getTables(), but it's better to do it after the
4763  * index used by findTableByOid() has been set up.
4764  */
4765 void
4766 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4767 {
4768         int                     i;
4769
4770         /*
4771          * Force sequences that are "owned" by table columns to be dumped whenever
4772          * their owning table is being dumped.
4773          */
4774         for (i = 0; i < numTables; i++)
4775         {
4776                 TableInfo  *seqinfo = &tblinfo[i];
4777                 TableInfo  *owning_tab;
4778
4779                 if (!OidIsValid(seqinfo->owning_tab))
4780                         continue;                       /* not an owned sequence */
4781                 if (seqinfo->dobj.dump)
4782                         continue;                       /* no need to search */
4783                 owning_tab = findTableByOid(seqinfo->owning_tab);
4784                 if (owning_tab && owning_tab->dobj.dump)
4785                 {
4786                         seqinfo->interesting = true;
4787                         seqinfo->dobj.dump = true;
4788                 }
4789         }
4790 }
4791
4792 /*
4793  * getInherits
4794  *        read all the inheritance information
4795  * from the system catalogs return them in the InhInfo* structure
4796  *
4797  * numInherits is set to the number of pairs read in
4798  */
4799 InhInfo *
4800 getInherits(Archive *fout, int *numInherits)
4801 {
4802         PGresult   *res;
4803         int                     ntups;
4804         int                     i;
4805         PQExpBuffer query = createPQExpBuffer();
4806         InhInfo    *inhinfo;
4807
4808         int                     i_inhrelid;
4809         int                     i_inhparent;
4810
4811         /* Make sure we are in proper schema */
4812         selectSourceSchema(fout, "pg_catalog");
4813
4814         /* find all the inheritance information */
4815
4816         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4817
4818         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4819
4820         ntups = PQntuples(res);
4821
4822         *numInherits = ntups;
4823
4824         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4825
4826         i_inhrelid = PQfnumber(res, "inhrelid");
4827         i_inhparent = PQfnumber(res, "inhparent");
4828
4829         for (i = 0; i < ntups; i++)
4830         {
4831                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4832                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4833         }
4834
4835         PQclear(res);
4836
4837         destroyPQExpBuffer(query);
4838
4839         return inhinfo;
4840 }
4841
4842 /*
4843  * getIndexes
4844  *        get information about every index on a dumpable table
4845  *
4846  * Note: index data is not returned directly to the caller, but it
4847  * does get entered into the DumpableObject tables.
4848  */
4849 void
4850 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4851 {
4852         int                     i,
4853                                 j;
4854         PQExpBuffer query = createPQExpBuffer();
4855         PGresult   *res;
4856         IndxInfo   *indxinfo;
4857         ConstraintInfo *constrinfo;
4858         int                     i_tableoid,
4859                                 i_oid,
4860                                 i_indexname,
4861                                 i_indexdef,
4862                                 i_indnkeys,
4863                                 i_indkey,
4864                                 i_indisclustered,
4865                                 i_contype,
4866                                 i_conname,
4867                                 i_condeferrable,
4868                                 i_condeferred,
4869                                 i_contableoid,
4870                                 i_conoid,
4871                                 i_condef,
4872                                 i_tablespace,
4873                                 i_options,
4874                                 i_relpages;
4875         int                     ntups;
4876
4877         for (i = 0; i < numTables; i++)
4878         {
4879                 TableInfo  *tbinfo = &tblinfo[i];
4880
4881                 /* Only plain tables and materialized views have indexes. */
4882                 if (tbinfo->relkind != RELKIND_RELATION &&
4883                         tbinfo->relkind != RELKIND_MATVIEW)
4884                         continue;
4885                 if (!tbinfo->hasindex)
4886                         continue;
4887
4888                 /* Ignore indexes of tables not to be dumped */
4889                 if (!tbinfo->dobj.dump)
4890                         continue;
4891
4892                 if (g_verbose)
4893                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4894                                           tbinfo->dobj.name);
4895
4896                 /* Make sure we are in proper schema so indexdef is right */
4897                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4898
4899                 /*
4900                  * The point of the messy-looking outer join is to find a constraint
4901                  * that is related by an internal dependency link to the index. If we
4902                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4903                  * assume an index won't have more than one internal dependency.
4904                  *
4905                  * As of 9.0 we don't need to look at pg_depend but can check for a
4906                  * match to pg_constraint.conindid.  The check on conrelid is
4907                  * redundant but useful because that column is indexed while conindid
4908                  * is not.
4909                  */
4910                 resetPQExpBuffer(query);
4911                 if (fout->remoteVersion >= 90000)
4912                 {
4913                         /*
4914                          * the test on indisready is necessary in 9.2, and harmless in
4915                          * earlier/later versions
4916                          */
4917                         appendPQExpBuffer(query,
4918                                                           "SELECT t.tableoid, t.oid, "
4919                                                           "t.relname AS indexname, "
4920                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4921                                                           "t.relnatts AS indnkeys, "
4922                                                           "i.indkey, i.indisclustered, "
4923                                                           "t.relpages, "
4924                                                           "c.contype, c.conname, "
4925                                                           "c.condeferrable, c.condeferred, "
4926                                                           "c.tableoid AS contableoid, "
4927                                                           "c.oid AS conoid, "
4928                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4929                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4930                                                         "array_to_string(t.reloptions, ', ') AS options "
4931                                                           "FROM pg_catalog.pg_index i "
4932                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4933                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4934                                                           "ON (i.indrelid = c.conrelid AND "
4935                                                           "i.indexrelid = c.conindid AND "
4936                                                           "c.contype IN ('p','u','x')) "
4937                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4938                                                           "AND i.indisvalid AND i.indisready "
4939                                                           "ORDER BY indexname",
4940                                                           tbinfo->dobj.catId.oid);
4941                 }
4942                 else if (fout->remoteVersion >= 80200)
4943                 {
4944                         appendPQExpBuffer(query,
4945                                                           "SELECT t.tableoid, t.oid, "
4946                                                           "t.relname AS indexname, "
4947                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4948                                                           "t.relnatts AS indnkeys, "
4949                                                           "i.indkey, i.indisclustered, "
4950                                                           "t.relpages, "
4951                                                           "c.contype, c.conname, "
4952                                                           "c.condeferrable, c.condeferred, "
4953                                                           "c.tableoid AS contableoid, "
4954                                                           "c.oid AS conoid, "
4955                                                           "null AS condef, "
4956                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4957                                                         "array_to_string(t.reloptions, ', ') AS options "
4958                                                           "FROM pg_catalog.pg_index i "
4959                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4960                                                           "LEFT JOIN pg_catalog.pg_depend d "
4961                                                           "ON (d.classid = t.tableoid "
4962                                                           "AND d.objid = t.oid "
4963                                                           "AND d.deptype = 'i') "
4964                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4965                                                           "ON (d.refclassid = c.tableoid "
4966                                                           "AND d.refobjid = c.oid) "
4967                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4968                                                           "AND i.indisvalid "
4969                                                           "ORDER BY indexname",
4970                                                           tbinfo->dobj.catId.oid);
4971                 }
4972                 else if (fout->remoteVersion >= 80000)
4973                 {
4974                         appendPQExpBuffer(query,
4975                                                           "SELECT t.tableoid, t.oid, "
4976                                                           "t.relname AS indexname, "
4977                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4978                                                           "t.relnatts AS indnkeys, "
4979                                                           "i.indkey, i.indisclustered, "
4980                                                           "t.relpages, "
4981                                                           "c.contype, c.conname, "
4982                                                           "c.condeferrable, c.condeferred, "
4983                                                           "c.tableoid AS contableoid, "
4984                                                           "c.oid AS conoid, "
4985                                                           "null AS condef, "
4986                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4987                                                           "null AS options "
4988                                                           "FROM pg_catalog.pg_index i "
4989                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4990                                                           "LEFT JOIN pg_catalog.pg_depend d "
4991                                                           "ON (d.classid = t.tableoid "
4992                                                           "AND d.objid = t.oid "
4993                                                           "AND d.deptype = 'i') "
4994                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4995                                                           "ON (d.refclassid = c.tableoid "
4996                                                           "AND d.refobjid = c.oid) "
4997                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4998                                                           "ORDER BY indexname",
4999                                                           tbinfo->dobj.catId.oid);
5000                 }
5001                 else if (fout->remoteVersion >= 70300)
5002                 {
5003                         appendPQExpBuffer(query,
5004                                                           "SELECT t.tableoid, t.oid, "
5005                                                           "t.relname AS indexname, "
5006                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
5007                                                           "t.relnatts AS indnkeys, "
5008                                                           "i.indkey, i.indisclustered, "
5009                                                           "t.relpages, "
5010                                                           "c.contype, c.conname, "
5011                                                           "c.condeferrable, c.condeferred, "
5012                                                           "c.tableoid AS contableoid, "
5013                                                           "c.oid AS conoid, "
5014                                                           "null AS condef, "
5015                                                           "NULL AS tablespace, "
5016                                                           "null AS options "
5017                                                           "FROM pg_catalog.pg_index i "
5018                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
5019                                                           "LEFT JOIN pg_catalog.pg_depend d "
5020                                                           "ON (d.classid = t.tableoid "
5021                                                           "AND d.objid = t.oid "
5022                                                           "AND d.deptype = 'i') "
5023                                                           "LEFT JOIN pg_catalog.pg_constraint c "
5024                                                           "ON (d.refclassid = c.tableoid "
5025                                                           "AND d.refobjid = c.oid) "
5026                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
5027                                                           "ORDER BY indexname",
5028                                                           tbinfo->dobj.catId.oid);
5029                 }
5030                 else if (fout->remoteVersion >= 70100)
5031                 {
5032                         appendPQExpBuffer(query,
5033                                                           "SELECT t.tableoid, t.oid, "
5034                                                           "t.relname AS indexname, "
5035                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
5036                                                           "t.relnatts AS indnkeys, "
5037                                                           "i.indkey, false AS indisclustered, "
5038                                                           "t.relpages, "
5039                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
5040                                                           "ELSE '0'::char END AS contype, "
5041                                                           "t.relname AS conname, "
5042                                                           "false AS condeferrable, "
5043                                                           "false AS condeferred, "
5044                                                           "0::oid AS contableoid, "
5045                                                           "t.oid AS conoid, "
5046                                                           "null AS condef, "
5047                                                           "NULL AS tablespace, "
5048                                                           "null AS options "
5049                                                           "FROM pg_index i, pg_class t "
5050                                                           "WHERE t.oid = i.indexrelid "
5051                                                           "AND i.indrelid = '%u'::oid "
5052                                                           "ORDER BY indexname",
5053                                                           tbinfo->dobj.catId.oid);
5054                 }
5055                 else
5056                 {
5057                         appendPQExpBuffer(query,
5058                                                           "SELECT "
5059                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
5060                                                           "t.oid, "
5061                                                           "t.relname AS indexname, "
5062                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
5063                                                           "t.relnatts AS indnkeys, "
5064                                                           "i.indkey, false AS indisclustered, "
5065                                                           "t.relpages, "
5066                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
5067                                                           "ELSE '0'::char END AS contype, "
5068                                                           "t.relname AS conname, "
5069                                                           "false AS condeferrable, "
5070                                                           "false AS condeferred, "
5071                                                           "0::oid AS contableoid, "
5072                                                           "t.oid AS conoid, "
5073                                                           "null AS condef, "
5074                                                           "NULL AS tablespace, "
5075                                                           "null AS options "
5076                                                           "FROM pg_index i, pg_class t "
5077                                                           "WHERE t.oid = i.indexrelid "
5078                                                           "AND i.indrelid = '%u'::oid "
5079                                                           "ORDER BY indexname",
5080                                                           tbinfo->dobj.catId.oid);
5081                 }
5082
5083                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5084
5085                 ntups = PQntuples(res);
5086
5087                 i_tableoid = PQfnumber(res, "tableoid");
5088                 i_oid = PQfnumber(res, "oid");
5089                 i_indexname = PQfnumber(res, "indexname");
5090                 i_indexdef = PQfnumber(res, "indexdef");
5091                 i_indnkeys = PQfnumber(res, "indnkeys");
5092                 i_indkey = PQfnumber(res, "indkey");
5093                 i_indisclustered = PQfnumber(res, "indisclustered");
5094                 i_relpages = PQfnumber(res, "relpages");
5095                 i_contype = PQfnumber(res, "contype");
5096                 i_conname = PQfnumber(res, "conname");
5097                 i_condeferrable = PQfnumber(res, "condeferrable");
5098                 i_condeferred = PQfnumber(res, "condeferred");
5099                 i_contableoid = PQfnumber(res, "contableoid");
5100                 i_conoid = PQfnumber(res, "conoid");
5101                 i_condef = PQfnumber(res, "condef");
5102                 i_tablespace = PQfnumber(res, "tablespace");
5103                 i_options = PQfnumber(res, "options");
5104
5105                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
5106                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5107
5108                 for (j = 0; j < ntups; j++)
5109                 {
5110                         char            contype;
5111
5112                         indxinfo[j].dobj.objType = DO_INDEX;
5113                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5114                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5115                         AssignDumpId(&indxinfo[j].dobj);
5116                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
5117                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5118                         indxinfo[j].indextable = tbinfo;
5119                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
5120                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
5121                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
5122                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
5123
5124                         /*
5125                          * In pre-7.4 releases, indkeys may contain more entries than
5126                          * indnkeys says (since indnkeys will be 1 for a functional
5127                          * index).      We don't actually care about this case since we don't
5128                          * examine indkeys except for indexes associated with PRIMARY and
5129                          * UNIQUE constraints, which are never functional indexes. But we
5130                          * have to allocate enough space to keep parseOidArray from
5131                          * complaining.
5132                          */
5133                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
5134                         parseOidArray(PQgetvalue(res, j, i_indkey),
5135                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
5136                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
5137                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
5138                         contype = *(PQgetvalue(res, j, i_contype));
5139
5140                         if (contype == 'p' || contype == 'u' || contype == 'x')
5141                         {
5142                                 /*
5143                                  * If we found a constraint matching the index, create an
5144                                  * entry for it.
5145                                  *
5146                                  * In a pre-7.3 database, we take this path iff the index was
5147                                  * marked indisprimary.
5148                                  */
5149                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
5150                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5151                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5152                                 AssignDumpId(&constrinfo[j].dobj);
5153                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5154                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5155                                 constrinfo[j].contable = tbinfo;
5156                                 constrinfo[j].condomain = NULL;
5157                                 constrinfo[j].contype = contype;
5158                                 if (contype == 'x')
5159                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5160                                 else
5161                                         constrinfo[j].condef = NULL;
5162                                 constrinfo[j].confrelid = InvalidOid;
5163                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
5164                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
5165                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
5166                                 constrinfo[j].conislocal = true;
5167                                 constrinfo[j].separate = true;
5168
5169                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
5170
5171                                 /* If pre-7.3 DB, better make sure table comes first */
5172                                 addObjectDependency(&constrinfo[j].dobj,
5173                                                                         tbinfo->dobj.dumpId);
5174                         }
5175                         else
5176                         {
5177                                 /* Plain secondary index */
5178                                 indxinfo[j].indexconstraint = 0;
5179                         }
5180                 }
5181
5182                 PQclear(res);
5183         }
5184
5185         destroyPQExpBuffer(query);
5186 }
5187
5188 /*
5189  * getConstraints
5190  *
5191  * Get info about constraints on dumpable tables.
5192  *
5193  * Currently handles foreign keys only.
5194  * Unique and primary key constraints are handled with indexes,
5195  * while check constraints are processed in getTableAttrs().
5196  */
5197 void
5198 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
5199 {
5200         int                     i,
5201                                 j;
5202         ConstraintInfo *constrinfo;
5203         PQExpBuffer query;
5204         PGresult   *res;
5205         int                     i_contableoid,
5206                                 i_conoid,
5207                                 i_conname,
5208                                 i_confrelid,
5209                                 i_condef;
5210         int                     ntups;
5211
5212         /* pg_constraint was created in 7.3, so nothing to do if older */
5213         if (fout->remoteVersion < 70300)
5214                 return;
5215
5216         query = createPQExpBuffer();
5217
5218         for (i = 0; i < numTables; i++)
5219         {
5220                 TableInfo  *tbinfo = &tblinfo[i];
5221
5222                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5223                         continue;
5224
5225                 if (g_verbose)
5226                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
5227                                           tbinfo->dobj.name);
5228
5229                 /*
5230                  * select table schema to ensure constraint expr is qualified if
5231                  * needed
5232                  */
5233                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5234
5235                 resetPQExpBuffer(query);
5236                 appendPQExpBuffer(query,
5237                                                   "SELECT tableoid, oid, conname, confrelid, "
5238                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
5239                                                   "FROM pg_catalog.pg_constraint "
5240                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5241                                                   "AND contype = 'f'",
5242                                                   tbinfo->dobj.catId.oid);
5243                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5244
5245                 ntups = PQntuples(res);
5246
5247                 i_contableoid = PQfnumber(res, "tableoid");
5248                 i_conoid = PQfnumber(res, "oid");
5249                 i_conname = PQfnumber(res, "conname");
5250                 i_confrelid = PQfnumber(res, "confrelid");
5251                 i_condef = PQfnumber(res, "condef");
5252
5253                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5254
5255                 for (j = 0; j < ntups; j++)
5256                 {
5257                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
5258                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5259                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5260                         AssignDumpId(&constrinfo[j].dobj);
5261                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5262                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5263                         constrinfo[j].contable = tbinfo;
5264                         constrinfo[j].condomain = NULL;
5265                         constrinfo[j].contype = 'f';
5266                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5267                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
5268                         constrinfo[j].conindex = 0;
5269                         constrinfo[j].condeferrable = false;
5270                         constrinfo[j].condeferred = false;
5271                         constrinfo[j].conislocal = true;
5272                         constrinfo[j].separate = true;
5273                 }
5274
5275                 PQclear(res);
5276         }
5277
5278         destroyPQExpBuffer(query);
5279 }
5280
5281 /*
5282  * getDomainConstraints
5283  *
5284  * Get info about constraints on a domain.
5285  */
5286 static void
5287 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
5288 {
5289         int                     i;
5290         ConstraintInfo *constrinfo;
5291         PQExpBuffer query;
5292         PGresult   *res;
5293         int                     i_tableoid,
5294                                 i_oid,
5295                                 i_conname,
5296                                 i_consrc;
5297         int                     ntups;
5298
5299         /* pg_constraint was created in 7.3, so nothing to do if older */
5300         if (fout->remoteVersion < 70300)
5301                 return;
5302
5303         /*
5304          * select appropriate schema to ensure names in constraint are properly
5305          * qualified
5306          */
5307         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
5308
5309         query = createPQExpBuffer();
5310
5311         if (fout->remoteVersion >= 90100)
5312                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5313                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5314                                                   "convalidated "
5315                                                   "FROM pg_catalog.pg_constraint "
5316                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5317                                                   "ORDER BY conname",
5318                                                   tyinfo->dobj.catId.oid);
5319
5320         else if (fout->remoteVersion >= 70400)
5321                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5322                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5323                                                   "true as convalidated "
5324                                                   "FROM pg_catalog.pg_constraint "
5325                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5326                                                   "ORDER BY conname",
5327                                                   tyinfo->dobj.catId.oid);
5328         else
5329                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5330                                                   "'CHECK (' || consrc || ')' AS consrc, "
5331                                                   "true as convalidated "
5332                                                   "FROM pg_catalog.pg_constraint "
5333                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5334                                                   "ORDER BY conname",
5335                                                   tyinfo->dobj.catId.oid);
5336
5337         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5338
5339         ntups = PQntuples(res);
5340
5341         i_tableoid = PQfnumber(res, "tableoid");
5342         i_oid = PQfnumber(res, "oid");
5343         i_conname = PQfnumber(res, "conname");
5344         i_consrc = PQfnumber(res, "consrc");
5345
5346         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5347
5348         tyinfo->nDomChecks = ntups;
5349         tyinfo->domChecks = constrinfo;
5350
5351         for (i = 0; i < ntups; i++)
5352         {
5353                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
5354
5355                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5356                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5357                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5358                 AssignDumpId(&constrinfo[i].dobj);
5359                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5360                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5361                 constrinfo[i].contable = NULL;
5362                 constrinfo[i].condomain = tyinfo;
5363                 constrinfo[i].contype = 'c';
5364                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5365                 constrinfo[i].confrelid = InvalidOid;
5366                 constrinfo[i].conindex = 0;
5367                 constrinfo[i].condeferrable = false;
5368                 constrinfo[i].condeferred = false;
5369                 constrinfo[i].conislocal = true;
5370
5371                 constrinfo[i].separate = !validated;
5372
5373                 /*
5374                  * Make the domain depend on the constraint, ensuring it won't be
5375                  * output till any constraint dependencies are OK.      If the constraint
5376                  * has not been validated, it's going to be dumped after the domain
5377                  * anyway, so this doesn't matter.
5378                  */
5379                 if (validated)
5380                         addObjectDependency(&tyinfo->dobj,
5381                                                                 constrinfo[i].dobj.dumpId);
5382         }
5383
5384         PQclear(res);
5385
5386         destroyPQExpBuffer(query);
5387 }
5388
5389 /*
5390  * getRules
5391  *        get basic information about every rule in the system
5392  *
5393  * numRules is set to the number of rules read in
5394  */
5395 RuleInfo *
5396 getRules(Archive *fout, int *numRules)
5397 {
5398         PGresult   *res;
5399         int                     ntups;
5400         int                     i;
5401         PQExpBuffer query = createPQExpBuffer();
5402         RuleInfo   *ruleinfo;
5403         int                     i_tableoid;
5404         int                     i_oid;
5405         int                     i_rulename;
5406         int                     i_ruletable;
5407         int                     i_ev_type;
5408         int                     i_is_instead;
5409         int                     i_ev_enabled;
5410
5411         /* Make sure we are in proper schema */
5412         selectSourceSchema(fout, "pg_catalog");
5413
5414         if (fout->remoteVersion >= 80300)
5415         {
5416                 appendPQExpBuffer(query, "SELECT "
5417                                                   "tableoid, oid, rulename, "
5418                                                   "ev_class AS ruletable, ev_type, is_instead, "
5419                                                   "ev_enabled "
5420                                                   "FROM pg_rewrite "
5421                                                   "ORDER BY oid");
5422         }
5423         else if (fout->remoteVersion >= 70100)
5424         {
5425                 appendPQExpBuffer(query, "SELECT "
5426                                                   "tableoid, oid, rulename, "
5427                                                   "ev_class AS ruletable, ev_type, is_instead, "
5428                                                   "'O'::char AS ev_enabled "
5429                                                   "FROM pg_rewrite "
5430                                                   "ORDER BY oid");
5431         }
5432         else
5433         {
5434                 appendPQExpBuffer(query, "SELECT "
5435                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5436                                                   "oid, rulename, "
5437                                                   "ev_class AS ruletable, ev_type, is_instead, "
5438                                                   "'O'::char AS ev_enabled "
5439                                                   "FROM pg_rewrite "
5440                                                   "ORDER BY oid");
5441         }
5442
5443         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5444
5445         ntups = PQntuples(res);
5446
5447         *numRules = ntups;
5448
5449         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5450
5451         i_tableoid = PQfnumber(res, "tableoid");
5452         i_oid = PQfnumber(res, "oid");
5453         i_rulename = PQfnumber(res, "rulename");
5454         i_ruletable = PQfnumber(res, "ruletable");
5455         i_ev_type = PQfnumber(res, "ev_type");
5456         i_is_instead = PQfnumber(res, "is_instead");
5457         i_ev_enabled = PQfnumber(res, "ev_enabled");
5458
5459         for (i = 0; i < ntups; i++)
5460         {
5461                 Oid                     ruletableoid;
5462
5463                 ruleinfo[i].dobj.objType = DO_RULE;
5464                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5465                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5466                 AssignDumpId(&ruleinfo[i].dobj);
5467                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5468                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5469                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5470                 if (ruleinfo[i].ruletable == NULL)
5471                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5472                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5473                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5474                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5475                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5476                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5477                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5478                 if (ruleinfo[i].ruletable)
5479                 {
5480                         /*
5481                          * If the table is a view or materialized view, force its ON
5482                          * SELECT rule to be sorted before the view itself --- this
5483                          * ensures that any dependencies for the rule affect the table's
5484                          * positioning. Other rules are forced to appear after their
5485                          * table.
5486                          */
5487                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
5488                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
5489                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5490                         {
5491                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5492                                                                         ruleinfo[i].dobj.dumpId);
5493                                 /* We'll merge the rule into CREATE VIEW, if possible */
5494                                 ruleinfo[i].separate = false;
5495                         }
5496                         else
5497                         {
5498                                 addObjectDependency(&ruleinfo[i].dobj,
5499                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5500                                 ruleinfo[i].separate = true;
5501                         }
5502                 }
5503                 else
5504                         ruleinfo[i].separate = true;
5505
5506                 /*
5507                  * If we're forced to break a dependency loop by dumping a view as a
5508                  * table and separate _RETURN rule, we'll move the view's reloptions
5509                  * to the rule.  (This is necessary because tables and views have
5510                  * different valid reloptions, so we can't apply the options until the
5511                  * backend knows it's a view.)  Otherwise the rule's reloptions stay
5512                  * NULL.
5513                  */
5514                 ruleinfo[i].reloptions = NULL;
5515         }
5516
5517         PQclear(res);
5518
5519         destroyPQExpBuffer(query);
5520
5521         return ruleinfo;
5522 }
5523
5524 /*
5525  * getTriggers
5526  *        get information about every trigger on a dumpable table
5527  *
5528  * Note: trigger data is not returned directly to the caller, but it
5529  * does get entered into the DumpableObject tables.
5530  */
5531 void
5532 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5533 {
5534         int                     i,
5535                                 j;
5536         PQExpBuffer query = createPQExpBuffer();
5537         PGresult   *res;
5538         TriggerInfo *tginfo;
5539         int                     i_tableoid,
5540                                 i_oid,
5541                                 i_tgname,
5542                                 i_tgfname,
5543                                 i_tgtype,
5544                                 i_tgnargs,
5545                                 i_tgargs,
5546                                 i_tgisconstraint,
5547                                 i_tgconstrname,
5548                                 i_tgconstrrelid,
5549                                 i_tgconstrrelname,
5550                                 i_tgenabled,
5551                                 i_tgdeferrable,
5552                                 i_tginitdeferred,
5553                                 i_tgdef;
5554         int                     ntups;
5555
5556         for (i = 0; i < numTables; i++)
5557         {
5558                 TableInfo  *tbinfo = &tblinfo[i];
5559
5560                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5561                         continue;
5562
5563                 if (g_verbose)
5564                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5565                                           tbinfo->dobj.name);
5566
5567                 /*
5568                  * select table schema to ensure regproc name is qualified if needed
5569                  */
5570                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5571
5572                 resetPQExpBuffer(query);
5573                 if (fout->remoteVersion >= 90000)
5574                 {
5575                         /*
5576                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5577                          * could result in non-forward-compatible dumps of WHEN clauses
5578                          * due to under-parenthesization.
5579                          */
5580                         appendPQExpBuffer(query,
5581                                                           "SELECT tgname, "
5582                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5583                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5584                                                           "tgenabled, tableoid, oid "
5585                                                           "FROM pg_catalog.pg_trigger t "
5586                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5587                                                           "AND NOT tgisinternal",
5588                                                           tbinfo->dobj.catId.oid);
5589                 }
5590                 else if (fout->remoteVersion >= 80300)
5591                 {
5592                         /*
5593                          * We ignore triggers that are tied to a foreign-key constraint
5594                          */
5595                         appendPQExpBuffer(query,
5596                                                           "SELECT tgname, "
5597                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5598                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5599                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5600                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5601                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5602                                                           "FROM pg_catalog.pg_trigger t "
5603                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5604                                                           "AND tgconstraint = 0",
5605                                                           tbinfo->dobj.catId.oid);
5606                 }
5607                 else if (fout->remoteVersion >= 70300)
5608                 {
5609                         /*
5610                          * We ignore triggers that are tied to a foreign-key constraint,
5611                          * but in these versions we have to grovel through pg_constraint
5612                          * to find out
5613                          */
5614                         appendPQExpBuffer(query,
5615                                                           "SELECT tgname, "
5616                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5617                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5618                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5619                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5620                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5621                                                           "FROM pg_catalog.pg_trigger t "
5622                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5623                                                           "AND (NOT tgisconstraint "
5624                                                           " OR NOT EXISTS"
5625                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5626                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5627                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5628                                                           tbinfo->dobj.catId.oid);
5629                 }
5630                 else if (fout->remoteVersion >= 70100)
5631                 {
5632                         appendPQExpBuffer(query,
5633                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5634                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5635                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5636                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5637                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5638                                                           "             AS tgconstrrelname "
5639                                                           "FROM pg_trigger "
5640                                                           "WHERE tgrelid = '%u'::oid",
5641                                                           tbinfo->dobj.catId.oid);
5642                 }
5643                 else
5644                 {
5645                         appendPQExpBuffer(query,
5646                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5647                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5648                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5649                                                           "tgconstrrelid, tginitdeferred, "
5650                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5651                                                           "oid, "
5652                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5653                                                           "             AS tgconstrrelname "
5654                                                           "FROM pg_trigger "
5655                                                           "WHERE tgrelid = '%u'::oid",
5656                                                           tbinfo->dobj.catId.oid);
5657                 }
5658                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5659
5660                 ntups = PQntuples(res);
5661
5662                 i_tableoid = PQfnumber(res, "tableoid");
5663                 i_oid = PQfnumber(res, "oid");
5664                 i_tgname = PQfnumber(res, "tgname");
5665                 i_tgfname = PQfnumber(res, "tgfname");
5666                 i_tgtype = PQfnumber(res, "tgtype");
5667                 i_tgnargs = PQfnumber(res, "tgnargs");
5668                 i_tgargs = PQfnumber(res, "tgargs");
5669                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5670                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5671                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5672                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5673                 i_tgenabled = PQfnumber(res, "tgenabled");
5674                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5675                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5676                 i_tgdef = PQfnumber(res, "tgdef");
5677
5678                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5679
5680                 for (j = 0; j < ntups; j++)
5681                 {
5682                         tginfo[j].dobj.objType = DO_TRIGGER;
5683                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5684                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5685                         AssignDumpId(&tginfo[j].dobj);
5686                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5687                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5688                         tginfo[j].tgtable = tbinfo;
5689                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5690                         if (i_tgdef >= 0)
5691                         {
5692                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5693
5694                                 /* remaining fields are not valid if we have tgdef */
5695                                 tginfo[j].tgfname = NULL;
5696                                 tginfo[j].tgtype = 0;
5697                                 tginfo[j].tgnargs = 0;
5698                                 tginfo[j].tgargs = NULL;
5699                                 tginfo[j].tgisconstraint = false;
5700                                 tginfo[j].tgdeferrable = false;
5701                                 tginfo[j].tginitdeferred = false;
5702                                 tginfo[j].tgconstrname = NULL;
5703                                 tginfo[j].tgconstrrelid = InvalidOid;
5704                                 tginfo[j].tgconstrrelname = NULL;
5705                         }
5706                         else
5707                         {
5708                                 tginfo[j].tgdef = NULL;
5709
5710                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5711                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5712                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5713                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5714                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5715                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5716                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5717
5718                                 if (tginfo[j].tgisconstraint)
5719                                 {
5720                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5721                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5722                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5723                                         {
5724                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5725                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5726                                                                                   tginfo[j].dobj.name,
5727                                                                                   tbinfo->dobj.name,
5728                                                                                   tginfo[j].tgconstrrelid);
5729                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5730                                         }
5731                                         else
5732                                                 tginfo[j].tgconstrrelname = NULL;
5733                                 }
5734                                 else
5735                                 {
5736                                         tginfo[j].tgconstrname = NULL;
5737                                         tginfo[j].tgconstrrelid = InvalidOid;
5738                                         tginfo[j].tgconstrrelname = NULL;
5739                                 }
5740                         }
5741                 }
5742
5743                 PQclear(res);
5744         }
5745
5746         destroyPQExpBuffer(query);
5747 }
5748
5749 /*
5750  * getEventTriggers
5751  *        get information about event triggers
5752  */
5753 EventTriggerInfo *
5754 getEventTriggers(Archive *fout, int *numEventTriggers)
5755 {
5756         int                     i;
5757         PQExpBuffer query;
5758         PGresult   *res;
5759         EventTriggerInfo *evtinfo;
5760         int                     i_tableoid,
5761                                 i_oid,
5762                                 i_evtname,
5763                                 i_evtevent,
5764                                 i_evtowner,
5765                                 i_evttags,
5766                                 i_evtfname,
5767                                 i_evtenabled;
5768         int                     ntups;
5769
5770         /* Before 9.3, there are no event triggers */
5771         if (fout->remoteVersion < 90300)
5772         {
5773                 *numEventTriggers = 0;
5774                 return NULL;
5775         }
5776
5777         query = createPQExpBuffer();
5778
5779         /* Make sure we are in proper schema */
5780         selectSourceSchema(fout, "pg_catalog");
5781
5782         appendPQExpBuffer(query,
5783                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5784                                           "evtevent, (%s evtowner) AS evtowner, "
5785                                           "array_to_string(array("
5786                                           "select quote_literal(x) "
5787                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
5788                                           "e.evtfoid::regproc as evtfname "
5789                                           "FROM pg_event_trigger e "
5790                                           "ORDER BY e.oid",
5791                                           username_subquery);
5792
5793         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5794
5795         ntups = PQntuples(res);
5796
5797         *numEventTriggers = ntups;
5798
5799         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5800
5801         i_tableoid = PQfnumber(res, "tableoid");
5802         i_oid = PQfnumber(res, "oid");
5803         i_evtname = PQfnumber(res, "evtname");
5804         i_evtevent = PQfnumber(res, "evtevent");
5805         i_evtowner = PQfnumber(res, "evtowner");
5806         i_evttags = PQfnumber(res, "evttags");
5807         i_evtfname = PQfnumber(res, "evtfname");
5808         i_evtenabled = PQfnumber(res, "evtenabled");
5809
5810         for (i = 0; i < ntups; i++)
5811         {
5812                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5813                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5814                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5815                 AssignDumpId(&evtinfo[i].dobj);
5816                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5817                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5818                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5819                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5820                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5821                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5822                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5823         }
5824
5825         PQclear(res);
5826
5827         destroyPQExpBuffer(query);
5828
5829         return evtinfo;
5830 }
5831
5832 /*
5833  * getProcLangs
5834  *        get basic information about every procedural language in the system
5835  *
5836  * numProcLangs is set to the number of langs read in
5837  *
5838  * NB: this must run after getFuncs() because we assume we can do
5839  * findFuncByOid().
5840  */
5841 ProcLangInfo *
5842 getProcLangs(Archive *fout, int *numProcLangs)
5843 {
5844         PGresult   *res;
5845         int                     ntups;
5846         int                     i;
5847         PQExpBuffer query = createPQExpBuffer();
5848         ProcLangInfo *planginfo;
5849         int                     i_tableoid;
5850         int                     i_oid;
5851         int                     i_lanname;
5852         int                     i_lanpltrusted;
5853         int                     i_lanplcallfoid;
5854         int                     i_laninline;
5855         int                     i_lanvalidator;
5856         int                     i_lanacl;
5857         int                     i_lanowner;
5858
5859         /* Make sure we are in proper schema */
5860         selectSourceSchema(fout, "pg_catalog");
5861
5862         if (fout->remoteVersion >= 90000)
5863         {
5864                 /* pg_language has a laninline column */
5865                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5866                                                   "lanname, lanpltrusted, lanplcallfoid, "
5867                                                   "laninline, lanvalidator,  lanacl, "
5868                                                   "(%s lanowner) AS lanowner "
5869                                                   "FROM pg_language "
5870                                                   "WHERE lanispl "
5871                                                   "ORDER BY oid",
5872                                                   username_subquery);
5873         }
5874         else if (fout->remoteVersion >= 80300)
5875         {
5876                 /* pg_language has a lanowner column */
5877                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5878                                                   "lanname, lanpltrusted, lanplcallfoid, "
5879                                                   "lanvalidator,  lanacl, "
5880                                                   "(%s lanowner) AS lanowner "
5881                                                   "FROM pg_language "
5882                                                   "WHERE lanispl "
5883                                                   "ORDER BY oid",
5884                                                   username_subquery);
5885         }
5886         else if (fout->remoteVersion >= 80100)
5887         {
5888                 /* Languages are owned by the bootstrap superuser, OID 10 */
5889                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5890                                                   "(%s '10') AS lanowner "
5891                                                   "FROM pg_language "
5892                                                   "WHERE lanispl "
5893                                                   "ORDER BY oid",
5894                                                   username_subquery);
5895         }
5896         else if (fout->remoteVersion >= 70400)
5897         {
5898                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5899                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5900                                                   "(%s '1') AS lanowner "
5901                                                   "FROM pg_language "
5902                                                   "WHERE lanispl "
5903                                                   "ORDER BY oid",
5904                                                   username_subquery);
5905         }
5906         else if (fout->remoteVersion >= 70100)
5907         {
5908                 /* No clear notion of an owner at all before 7.4 ... */
5909                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5910                                                   "WHERE lanispl "
5911                                                   "ORDER BY oid");
5912         }
5913         else
5914         {
5915                 appendPQExpBuffer(query, "SELECT "
5916                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5917                                                   "oid, * FROM pg_language "
5918                                                   "WHERE lanispl "
5919                                                   "ORDER BY oid");
5920         }
5921
5922         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5923
5924         ntups = PQntuples(res);
5925
5926         *numProcLangs = ntups;
5927
5928         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5929
5930         i_tableoid = PQfnumber(res, "tableoid");
5931         i_oid = PQfnumber(res, "oid");
5932         i_lanname = PQfnumber(res, "lanname");
5933         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5934         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5935         /* these may fail and return -1: */
5936         i_laninline = PQfnumber(res, "laninline");
5937         i_lanvalidator = PQfnumber(res, "lanvalidator");
5938         i_lanacl = PQfnumber(res, "lanacl");
5939         i_lanowner = PQfnumber(res, "lanowner");
5940
5941         for (i = 0; i < ntups; i++)
5942         {
5943                 planginfo[i].dobj.objType = DO_PROCLANG;
5944                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5945                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5946                 AssignDumpId(&planginfo[i].dobj);
5947
5948                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5949                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5950                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5951                 if (i_laninline >= 0)
5952                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5953                 else
5954                         planginfo[i].laninline = InvalidOid;
5955                 if (i_lanvalidator >= 0)
5956                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5957                 else
5958                         planginfo[i].lanvalidator = InvalidOid;
5959                 if (i_lanacl >= 0)
5960                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5961                 else
5962                         planginfo[i].lanacl = pg_strdup("{=U}");
5963                 if (i_lanowner >= 0)
5964                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5965                 else
5966                         planginfo[i].lanowner = pg_strdup("");
5967
5968                 if (fout->remoteVersion < 70300)
5969                 {
5970                         /*
5971                          * We need to make a dependency to ensure the function will be
5972                          * dumped first.  (In 7.3 and later the regular dependency
5973                          * mechanism will handle this for us.)
5974                          */
5975                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5976
5977                         if (funcInfo)
5978                                 addObjectDependency(&planginfo[i].dobj,
5979                                                                         funcInfo->dobj.dumpId);
5980                 }
5981         }
5982
5983         PQclear(res);
5984
5985         destroyPQExpBuffer(query);
5986
5987         return planginfo;
5988 }
5989
5990 /*
5991  * getCasts
5992  *        get basic information about every cast in the system
5993  *
5994  * numCasts is set to the number of casts read in
5995  */
5996 CastInfo *
5997 getCasts(Archive *fout, int *numCasts)
5998 {
5999         PGresult   *res;
6000         int                     ntups;
6001         int                     i;
6002         PQExpBuffer query = createPQExpBuffer();
6003         CastInfo   *castinfo;
6004         int                     i_tableoid;
6005         int                     i_oid;
6006         int                     i_castsource;
6007         int                     i_casttarget;
6008         int                     i_castfunc;
6009         int                     i_castcontext;
6010         int                     i_castmethod;
6011
6012         /* Make sure we are in proper schema */
6013         selectSourceSchema(fout, "pg_catalog");
6014
6015         if (fout->remoteVersion >= 80400)
6016         {
6017                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6018                                                   "castsource, casttarget, castfunc, castcontext, "
6019                                                   "castmethod "
6020                                                   "FROM pg_cast ORDER BY 3,4");
6021         }
6022         else if (fout->remoteVersion >= 70300)
6023         {
6024                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6025                                                   "castsource, casttarget, castfunc, castcontext, "
6026                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
6027                                                   "FROM pg_cast ORDER BY 3,4");
6028         }
6029         else
6030         {
6031                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
6032                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
6033                                                   "p.oid AS castfunc, 'e' AS castcontext, "
6034                                                   "'f' AS castmethod "
6035                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
6036                                                   "WHERE p.pronargs = 1 AND "
6037                                                   "p.proargtypes[0] = t1.oid AND "
6038                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
6039                                                   "ORDER BY 3,4");
6040         }
6041
6042         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6043
6044         ntups = PQntuples(res);
6045
6046         *numCasts = ntups;
6047
6048         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
6049
6050         i_tableoid = PQfnumber(res, "tableoid");
6051         i_oid = PQfnumber(res, "oid");
6052         i_castsource = PQfnumber(res, "castsource");
6053         i_casttarget = PQfnumber(res, "casttarget");
6054         i_castfunc = PQfnumber(res, "castfunc");
6055         i_castcontext = PQfnumber(res, "castcontext");
6056         i_castmethod = PQfnumber(res, "castmethod");
6057
6058         for (i = 0; i < ntups; i++)
6059         {
6060                 PQExpBufferData namebuf;
6061                 TypeInfo   *sTypeInfo;
6062                 TypeInfo   *tTypeInfo;
6063
6064                 castinfo[i].dobj.objType = DO_CAST;
6065                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6066                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6067                 AssignDumpId(&castinfo[i].dobj);
6068                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
6069                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
6070                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
6071                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
6072                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
6073
6074                 /*
6075                  * Try to name cast as concatenation of typnames.  This is only used
6076                  * for purposes of sorting.  If we fail to find either type, the name
6077                  * will be an empty string.
6078                  */
6079                 initPQExpBuffer(&namebuf);
6080                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
6081                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
6082                 if (sTypeInfo && tTypeInfo)
6083                         appendPQExpBuffer(&namebuf, "%s %s",
6084                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
6085                 castinfo[i].dobj.name = namebuf.data;
6086
6087                 if (OidIsValid(castinfo[i].castfunc))
6088                 {
6089                         /*
6090                          * We need to make a dependency to ensure the function will be
6091                          * dumped first.  (In 7.3 and later the regular dependency
6092                          * mechanism will handle this for us.)
6093                          */
6094                         FuncInfo   *funcInfo;
6095
6096                         funcInfo = findFuncByOid(castinfo[i].castfunc);
6097                         if (funcInfo)
6098                                 addObjectDependency(&castinfo[i].dobj,
6099                                                                         funcInfo->dobj.dumpId);
6100                 }
6101         }
6102
6103         PQclear(res);
6104
6105         destroyPQExpBuffer(query);
6106
6107         return castinfo;
6108 }
6109
6110 /*
6111  * getTableAttrs -
6112  *        for each interesting table, read info about its attributes
6113  *        (names, types, default values, CHECK constraints, etc)
6114  *
6115  * This is implemented in a very inefficient way right now, looping
6116  * through the tblinfo and doing a join per table to find the attrs and their
6117  * types.  However, because we want type names and so forth to be named
6118  * relative to the schema of each table, we couldn't do it in just one
6119  * query.  (Maybe one query per schema?)
6120  *
6121  *      modifies tblinfo
6122  */
6123 void
6124 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
6125 {
6126         int                     i,
6127                                 j;
6128         PQExpBuffer q = createPQExpBuffer();
6129         int                     i_attnum;
6130         int                     i_attname;
6131         int                     i_atttypname;
6132         int                     i_atttypmod;
6133         int                     i_attstattarget;
6134         int                     i_attstorage;
6135         int                     i_typstorage;
6136         int                     i_attnotnull;
6137         int                     i_atthasdef;
6138         int                     i_attisdropped;
6139         int                     i_attlen;
6140         int                     i_attalign;
6141         int                     i_attislocal;
6142         int                     i_attoptions;
6143         int                     i_attcollation;
6144         int                     i_attfdwoptions;
6145         PGresult   *res;
6146         int                     ntups;
6147         bool            hasdefaults;
6148
6149         for (i = 0; i < numTables; i++)
6150         {
6151                 TableInfo  *tbinfo = &tblinfo[i];
6152
6153                 /* Don't bother to collect info for sequences */
6154                 if (tbinfo->relkind == RELKIND_SEQUENCE)
6155                         continue;
6156
6157                 /* Don't bother with uninteresting tables, either */
6158                 if (!tbinfo->interesting)
6159                         continue;
6160
6161                 /*
6162                  * Make sure we are in proper schema for this table; this allows
6163                  * correct retrieval of formatted type names and default exprs
6164                  */
6165                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6166
6167                 /* find all the user attributes and their types */
6168
6169                 /*
6170                  * we must read the attribute names in attribute number order! because
6171                  * we will use the attnum to index into the attnames array later.  We
6172                  * actually ask to order by "attrelid, attnum" because (at least up to
6173                  * 7.3) the planner is not smart enough to realize it needn't re-sort
6174                  * the output of an indexscan on pg_attribute_relid_attnum_index.
6175                  */
6176                 if (g_verbose)
6177                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
6178                                           tbinfo->dobj.name);
6179
6180                 resetPQExpBuffer(q);
6181
6182                 if (fout->remoteVersion >= 90200)
6183                 {
6184                         /*
6185                          * attfdwoptions is new in 9.2.
6186                          */
6187                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6188                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6189                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6190                                                           "a.attlen, a.attalign, a.attislocal, "
6191                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6192                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6193                                                           "CASE WHEN a.attcollation <> t.typcollation "
6194                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
6195                                                           "pg_catalog.array_to_string(ARRAY("
6196                                                           "SELECT pg_catalog.quote_ident(option_name) || "
6197                                                           "' ' || pg_catalog.quote_literal(option_value) "
6198                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
6199                                                           "ORDER BY option_name"
6200                                                           "), E',\n    ') AS attfdwoptions "
6201                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6202                                                           "ON a.atttypid = t.oid "
6203                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6204                                                           "AND a.attnum > 0::pg_catalog.int2 "
6205                                                           "ORDER BY a.attrelid, a.attnum",
6206                                                           tbinfo->dobj.catId.oid);
6207                 }
6208                 else if (fout->remoteVersion >= 90100)
6209                 {
6210                         /*
6211                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
6212                          * clauses for attributes whose collation is different from their
6213                          * type's default, we use a CASE here to suppress uninteresting
6214                          * attcollations cheaply.
6215                          */
6216                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6217                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6218                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6219                                                           "a.attlen, a.attalign, a.attislocal, "
6220                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6221                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6222                                                           "CASE WHEN a.attcollation <> t.typcollation "
6223                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
6224                                                           "NULL AS attfdwoptions "
6225                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6226                                                           "ON a.atttypid = t.oid "
6227                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6228                                                           "AND a.attnum > 0::pg_catalog.int2 "
6229                                                           "ORDER BY a.attrelid, a.attnum",
6230                                                           tbinfo->dobj.catId.oid);
6231                 }
6232                 else if (fout->remoteVersion >= 90000)
6233                 {
6234                         /* attoptions is new in 9.0 */
6235                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6236                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6237                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6238                                                           "a.attlen, a.attalign, a.attislocal, "
6239                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6240                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6241                                                           "0 AS attcollation, "
6242                                                           "NULL AS attfdwoptions "
6243                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6244                                                           "ON a.atttypid = t.oid "
6245                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6246                                                           "AND a.attnum > 0::pg_catalog.int2 "
6247                                                           "ORDER BY a.attrelid, a.attnum",
6248                                                           tbinfo->dobj.catId.oid);
6249                 }
6250                 else if (fout->remoteVersion >= 70300)
6251                 {
6252                         /* need left join here to not fail on dropped columns ... */
6253                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6254                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6255                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6256                                                           "a.attlen, a.attalign, a.attislocal, "
6257                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6258                                                           "'' AS attoptions, 0 AS attcollation, "
6259                                                           "NULL AS attfdwoptions "
6260                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6261                                                           "ON a.atttypid = t.oid "
6262                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6263                                                           "AND a.attnum > 0::pg_catalog.int2 "
6264                                                           "ORDER BY a.attrelid, a.attnum",
6265                                                           tbinfo->dobj.catId.oid);
6266                 }
6267                 else if (fout->remoteVersion >= 70100)
6268                 {
6269                         /*
6270                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
6271                          * we don't dump it because we can't tell whether it's been
6272                          * explicitly set or was just a default.
6273                          *
6274                          * attislocal doesn't exist before 7.3, either; in older databases
6275                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
6276                          */
6277                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6278                                                           "-1 AS attstattarget, a.attstorage, "
6279                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
6280                                                           "false AS attisdropped, a.attlen, "
6281                                                           "a.attalign, true AS attislocal, "
6282                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
6283                                                           "'' AS attoptions, 0 AS attcollation, "
6284                                                           "NULL AS attfdwoptions "
6285                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
6286                                                           "ON a.atttypid = t.oid "
6287                                                           "WHERE a.attrelid = '%u'::oid "
6288                                                           "AND a.attnum > 0::int2 "
6289                                                           "ORDER BY a.attrelid, a.attnum",
6290                                                           tbinfo->dobj.catId.oid);
6291                 }
6292                 else
6293                 {
6294                         /* format_type not available before 7.1 */
6295                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
6296                                                           "-1 AS attstattarget, "
6297                                                           "attstorage, attstorage AS typstorage, "
6298                                                           "attnotnull, atthasdef, false AS attisdropped, "
6299                                                           "attlen, attalign, "
6300                                                           "true AS attislocal, "
6301                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
6302                                                           "'' AS attoptions, 0 AS attcollation, "
6303                                                           "NULL AS attfdwoptions "
6304                                                           "FROM pg_attribute a "
6305                                                           "WHERE attrelid = '%u'::oid "
6306                                                           "AND attnum > 0::int2 "
6307                                                           "ORDER BY attrelid, attnum",
6308                                                           tbinfo->dobj.catId.oid);
6309                 }
6310
6311                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6312
6313                 ntups = PQntuples(res);
6314
6315                 i_attnum = PQfnumber(res, "attnum");
6316                 i_attname = PQfnumber(res, "attname");
6317                 i_atttypname = PQfnumber(res, "atttypname");
6318                 i_atttypmod = PQfnumber(res, "atttypmod");
6319                 i_attstattarget = PQfnumber(res, "attstattarget");
6320                 i_attstorage = PQfnumber(res, "attstorage");
6321                 i_typstorage = PQfnumber(res, "typstorage");
6322                 i_attnotnull = PQfnumber(res, "attnotnull");
6323                 i_atthasdef = PQfnumber(res, "atthasdef");
6324                 i_attisdropped = PQfnumber(res, "attisdropped");
6325                 i_attlen = PQfnumber(res, "attlen");
6326                 i_attalign = PQfnumber(res, "attalign");
6327                 i_attislocal = PQfnumber(res, "attislocal");
6328                 i_attoptions = PQfnumber(res, "attoptions");
6329                 i_attcollation = PQfnumber(res, "attcollation");
6330                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
6331
6332                 tbinfo->numatts = ntups;
6333                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
6334                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
6335                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
6336                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
6337                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
6338                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
6339                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
6340                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
6341                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
6342                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
6343                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
6344                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
6345                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
6346                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
6347                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
6348                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
6349                 hasdefaults = false;
6350
6351                 for (j = 0; j < ntups; j++)
6352                 {
6353                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
6354                                 exit_horribly(NULL,
6355                                                           "invalid column numbering in table \"%s\"\n",
6356                                                           tbinfo->dobj.name);
6357                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6358                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6359                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6360                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6361                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6362                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6363                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6364                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6365                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6366                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6367                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6368                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6369                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6370                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6371                         tbinfo->attrdefs[j] = NULL; /* fix below */
6372                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6373                                 hasdefaults = true;
6374                         /* these flags will be set in flagInhAttrs() */
6375                         tbinfo->inhNotNull[j] = false;
6376                 }
6377
6378                 PQclear(res);
6379
6380                 /*
6381                  * Get info about column defaults
6382                  */
6383                 if (hasdefaults)
6384                 {
6385                         AttrDefInfo *attrdefs;
6386                         int                     numDefaults;
6387
6388                         if (g_verbose)
6389                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6390                                                   tbinfo->dobj.name);
6391
6392                         resetPQExpBuffer(q);
6393                         if (fout->remoteVersion >= 70300)
6394                         {
6395                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6396                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6397                                                                   "FROM pg_catalog.pg_attrdef "
6398                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
6399                                                                   tbinfo->dobj.catId.oid);
6400                         }
6401                         else if (fout->remoteVersion >= 70200)
6402                         {
6403                                 /* 7.2 did not have OIDs in pg_attrdef */
6404                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6405                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
6406                                                                   "FROM pg_attrdef "
6407                                                                   "WHERE adrelid = '%u'::oid",
6408                                                                   tbinfo->dobj.catId.oid);
6409                         }
6410                         else if (fout->remoteVersion >= 70100)
6411                         {
6412                                 /* no pg_get_expr, so must rely on adsrc */
6413                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6414                                                                   "FROM pg_attrdef "
6415                                                                   "WHERE adrelid = '%u'::oid",
6416                                                                   tbinfo->dobj.catId.oid);
6417                         }
6418                         else
6419                         {
6420                                 /* no pg_get_expr, no tableoid either */
6421                                 appendPQExpBuffer(q, "SELECT "
6422                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6423                                                                   "oid, adnum, adsrc "
6424                                                                   "FROM pg_attrdef "
6425                                                                   "WHERE adrelid = '%u'::oid",
6426                                                                   tbinfo->dobj.catId.oid);
6427                         }
6428                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6429
6430                         numDefaults = PQntuples(res);
6431                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6432
6433                         for (j = 0; j < numDefaults; j++)
6434                         {
6435                                 int                     adnum;
6436
6437                                 adnum = atoi(PQgetvalue(res, j, 2));
6438
6439                                 if (adnum <= 0 || adnum > ntups)
6440                                         exit_horribly(NULL,
6441                                                                   "invalid adnum value %d for table \"%s\"\n",
6442                                                                   adnum, tbinfo->dobj.name);
6443
6444                                 /*
6445                                  * dropped columns shouldn't have defaults, but just in case,
6446                                  * ignore 'em
6447                                  */
6448                                 if (tbinfo->attisdropped[adnum - 1])
6449                                         continue;
6450
6451                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
6452                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6453                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6454                                 AssignDumpId(&attrdefs[j].dobj);
6455                                 attrdefs[j].adtable = tbinfo;
6456                                 attrdefs[j].adnum = adnum;
6457                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6458
6459                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6460                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6461
6462                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6463
6464                                 /*
6465                                  * Defaults on a VIEW must always be dumped as separate ALTER
6466                                  * TABLE commands.      Defaults on regular tables are dumped as
6467                                  * part of the CREATE TABLE if possible, which it won't be if
6468                                  * the column is not going to be emitted explicitly.
6469                                  */
6470                                 if (tbinfo->relkind == RELKIND_VIEW)
6471                                 {
6472                                         attrdefs[j].separate = true;
6473                                         /* needed in case pre-7.3 DB: */
6474                                         addObjectDependency(&attrdefs[j].dobj,
6475                                                                                 tbinfo->dobj.dumpId);
6476                                 }
6477                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6478                                 {
6479                                         /* column will be suppressed, print default separately */
6480                                         attrdefs[j].separate = true;
6481                                         /* needed in case pre-7.3 DB: */
6482                                         addObjectDependency(&attrdefs[j].dobj,
6483                                                                                 tbinfo->dobj.dumpId);
6484                                 }
6485                                 else
6486                                 {
6487                                         attrdefs[j].separate = false;
6488
6489                                         /*
6490                                          * Mark the default as needing to appear before the table,
6491                                          * so that any dependencies it has must be emitted before
6492                                          * the CREATE TABLE.  If this is not possible, we'll
6493                                          * change to "separate" mode while sorting dependencies.
6494                                          */
6495                                         addObjectDependency(&tbinfo->dobj,
6496                                                                                 attrdefs[j].dobj.dumpId);
6497                                 }
6498
6499                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6500                         }
6501                         PQclear(res);
6502                 }
6503
6504                 /*
6505                  * Get info about table CHECK constraints
6506                  */
6507                 if (tbinfo->ncheck > 0)
6508                 {
6509                         ConstraintInfo *constrs;
6510                         int                     numConstrs;
6511
6512                         if (g_verbose)
6513                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6514                                                   tbinfo->dobj.name);
6515
6516                         resetPQExpBuffer(q);
6517                         if (fout->remoteVersion >= 90200)
6518                         {
6519                                 /*
6520                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
6521                                  * but it wasn't ever false for check constraints until 9.2).
6522                                  */
6523                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6524                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6525                                                                   "conislocal, convalidated "
6526                                                                   "FROM pg_catalog.pg_constraint "
6527                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6528                                                                   "   AND contype = 'c' "
6529                                                                   "ORDER BY conname",
6530                                                                   tbinfo->dobj.catId.oid);
6531                         }
6532                         else if (fout->remoteVersion >= 80400)
6533                         {
6534                                 /* conislocal is new in 8.4 */
6535                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6536                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6537                                                                   "conislocal, true AS convalidated "
6538                                                                   "FROM pg_catalog.pg_constraint "
6539                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6540                                                                   "   AND contype = 'c' "
6541                                                                   "ORDER BY conname",
6542                                                                   tbinfo->dobj.catId.oid);
6543                         }
6544                         else if (fout->remoteVersion >= 70400)
6545                         {
6546                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6547                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6548                                                                   "true AS conislocal, true AS convalidated "
6549                                                                   "FROM pg_catalog.pg_constraint "
6550                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6551                                                                   "   AND contype = 'c' "
6552                                                                   "ORDER BY conname",
6553                                                                   tbinfo->dobj.catId.oid);
6554                         }
6555                         else if (fout->remoteVersion >= 70300)
6556                         {
6557                                 /* no pg_get_constraintdef, must use consrc */
6558                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6559                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6560                                                                   "true AS conislocal, true AS convalidated "
6561                                                                   "FROM pg_catalog.pg_constraint "
6562                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6563                                                                   "   AND contype = 'c' "
6564                                                                   "ORDER BY conname",
6565                                                                   tbinfo->dobj.catId.oid);
6566                         }
6567                         else if (fout->remoteVersion >= 70200)
6568                         {
6569                                 /* 7.2 did not have OIDs in pg_relcheck */
6570                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6571                                                                   "rcname AS conname, "
6572                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6573                                                                   "true AS conislocal, true AS convalidated "
6574                                                                   "FROM pg_relcheck "
6575                                                                   "WHERE rcrelid = '%u'::oid "
6576                                                                   "ORDER BY rcname",
6577                                                                   tbinfo->dobj.catId.oid);
6578                         }
6579                         else if (fout->remoteVersion >= 70100)
6580                         {
6581                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6582                                                                   "rcname AS conname, "
6583                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6584                                                                   "true AS conislocal, true AS convalidated "
6585                                                                   "FROM pg_relcheck "
6586                                                                   "WHERE rcrelid = '%u'::oid "
6587                                                                   "ORDER BY rcname",
6588                                                                   tbinfo->dobj.catId.oid);
6589                         }
6590                         else
6591                         {
6592                                 /* no tableoid in 7.0 */
6593                                 appendPQExpBuffer(q, "SELECT "
6594                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6595                                                                   "oid, rcname AS conname, "
6596                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6597                                                                   "true AS conislocal, true AS convalidated "
6598                                                                   "FROM pg_relcheck "
6599                                                                   "WHERE rcrelid = '%u'::oid "
6600                                                                   "ORDER BY rcname",
6601                                                                   tbinfo->dobj.catId.oid);
6602                         }
6603                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6604
6605                         numConstrs = PQntuples(res);
6606                         if (numConstrs != tbinfo->ncheck)
6607                         {
6608                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6609                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6610                                                                                  tbinfo->ncheck),
6611                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6612                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6613                                 exit_nicely(1);
6614                         }
6615
6616                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6617                         tbinfo->checkexprs = constrs;
6618
6619                         for (j = 0; j < numConstrs; j++)
6620                         {
6621                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6622
6623                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6624                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6625                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6626                                 AssignDumpId(&constrs[j].dobj);
6627                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6628                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6629                                 constrs[j].contable = tbinfo;
6630                                 constrs[j].condomain = NULL;
6631                                 constrs[j].contype = 'c';
6632                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6633                                 constrs[j].confrelid = InvalidOid;
6634                                 constrs[j].conindex = 0;
6635                                 constrs[j].condeferrable = false;
6636                                 constrs[j].condeferred = false;
6637                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6638
6639                                 /*
6640                                  * An unvalidated constraint needs to be dumped separately, so
6641                                  * that potentially-violating existing data is loaded before
6642                                  * the constraint.
6643                                  */
6644                                 constrs[j].separate = !validated;
6645
6646                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6647
6648                                 /*
6649                                  * Mark the constraint as needing to appear before the table
6650                                  * --- this is so that any other dependencies of the
6651                                  * constraint will be emitted before we try to create the
6652                                  * table.  If the constraint is to be dumped separately, it
6653                                  * will be dumped after data is loaded anyway, so don't do it.
6654                                  * (There's an automatic dependency in the opposite direction
6655                                  * anyway, so don't need to add one manually here.)
6656                                  */
6657                                 if (!constrs[j].separate)
6658                                         addObjectDependency(&tbinfo->dobj,
6659                                                                                 constrs[j].dobj.dumpId);
6660
6661                                 /*
6662                                  * If the constraint is inherited, this will be detected later
6663                                  * (in pre-8.4 databases).      We also detect later if the
6664                                  * constraint must be split out from the table definition.
6665                                  */
6666                         }
6667                         PQclear(res);
6668                 }
6669         }
6670
6671         destroyPQExpBuffer(q);
6672 }
6673
6674 /*
6675  * Test whether a column should be printed as part of table's CREATE TABLE.
6676  * Column number is zero-based.
6677  *
6678  * Normally this is always true, but it's false for dropped columns, as well
6679  * as those that were inherited without any local definition.  (If we print
6680  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6681  * However, in binary_upgrade mode, we must print all such columns anyway and
6682  * fix the attislocal/attisdropped state later, so as to keep control of the
6683  * physical column order.
6684  *
6685  * This function exists because there are scattered nonobvious places that
6686  * must be kept in sync with this decision.
6687  */
6688 bool
6689 shouldPrintColumn(TableInfo *tbinfo, int colno)
6690 {
6691         if (binary_upgrade)
6692                 return true;
6693         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6694 }
6695
6696
6697 /*
6698  * getTSParsers:
6699  *        read all text search parsers in the system catalogs and return them
6700  *        in the TSParserInfo* structure
6701  *
6702  *      numTSParsers is set to the number of parsers read in
6703  */
6704 TSParserInfo *
6705 getTSParsers(Archive *fout, int *numTSParsers)
6706 {
6707         PGresult   *res;
6708         int                     ntups;
6709         int                     i;
6710         PQExpBuffer query;
6711         TSParserInfo *prsinfo;
6712         int                     i_tableoid;
6713         int                     i_oid;
6714         int                     i_prsname;
6715         int                     i_prsnamespace;
6716         int                     i_prsstart;
6717         int                     i_prstoken;
6718         int                     i_prsend;
6719         int                     i_prsheadline;
6720         int                     i_prslextype;
6721
6722         /* Before 8.3, there is no built-in text search support */
6723         if (fout->remoteVersion < 80300)
6724         {
6725                 *numTSParsers = 0;
6726                 return NULL;
6727         }
6728
6729         query = createPQExpBuffer();
6730
6731         /*
6732          * find all text search objects, including builtin ones; we filter out
6733          * system-defined objects at dump-out time.
6734          */
6735
6736         /* Make sure we are in proper schema */
6737         selectSourceSchema(fout, "pg_catalog");
6738
6739         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6740                                           "prsstart::oid, prstoken::oid, "
6741                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6742                                           "FROM pg_ts_parser");
6743
6744         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6745
6746         ntups = PQntuples(res);
6747         *numTSParsers = ntups;
6748
6749         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6750
6751         i_tableoid = PQfnumber(res, "tableoid");
6752         i_oid = PQfnumber(res, "oid");
6753         i_prsname = PQfnumber(res, "prsname");
6754         i_prsnamespace = PQfnumber(res, "prsnamespace");
6755         i_prsstart = PQfnumber(res, "prsstart");
6756         i_prstoken = PQfnumber(res, "prstoken");
6757         i_prsend = PQfnumber(res, "prsend");
6758         i_prsheadline = PQfnumber(res, "prsheadline");
6759         i_prslextype = PQfnumber(res, "prslextype");
6760
6761         for (i = 0; i < ntups; i++)
6762         {
6763                 prsinfo[i].dobj.objType = DO_TSPARSER;
6764                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6765                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6766                 AssignDumpId(&prsinfo[i].dobj);
6767                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6768                 prsinfo[i].dobj.namespace =
6769                         findNamespace(fout,
6770                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6771                                                   prsinfo[i].dobj.catId.oid);
6772                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6773                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6774                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6775                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6776                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6777
6778                 /* Decide whether we want to dump it */
6779                 selectDumpableObject(&(prsinfo[i].dobj));
6780         }
6781
6782         PQclear(res);
6783
6784         destroyPQExpBuffer(query);
6785
6786         return prsinfo;
6787 }
6788
6789 /*
6790  * getTSDictionaries:
6791  *        read all text search dictionaries in the system catalogs and return them
6792  *        in the TSDictInfo* structure
6793  *
6794  *      numTSDicts is set to the number of dictionaries read in
6795  */
6796 TSDictInfo *
6797 getTSDictionaries(Archive *fout, int *numTSDicts)
6798 {
6799         PGresult   *res;
6800         int                     ntups;
6801         int                     i;
6802         PQExpBuffer query;
6803         TSDictInfo *dictinfo;
6804         int                     i_tableoid;
6805         int                     i_oid;
6806         int                     i_dictname;
6807         int                     i_dictnamespace;
6808         int                     i_rolname;
6809         int                     i_dicttemplate;
6810         int                     i_dictinitoption;
6811
6812         /* Before 8.3, there is no built-in text search support */
6813         if (fout->remoteVersion < 80300)
6814         {
6815                 *numTSDicts = 0;
6816                 return NULL;
6817         }
6818
6819         query = createPQExpBuffer();
6820
6821         /* Make sure we are in proper schema */
6822         selectSourceSchema(fout, "pg_catalog");
6823
6824         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6825                                           "dictnamespace, (%s dictowner) AS rolname, "
6826                                           "dicttemplate, dictinitoption "
6827                                           "FROM pg_ts_dict",
6828                                           username_subquery);
6829
6830         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6831
6832         ntups = PQntuples(res);
6833         *numTSDicts = ntups;
6834
6835         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6836
6837         i_tableoid = PQfnumber(res, "tableoid");
6838         i_oid = PQfnumber(res, "oid");
6839         i_dictname = PQfnumber(res, "dictname");
6840         i_dictnamespace = PQfnumber(res, "dictnamespace");
6841         i_rolname = PQfnumber(res, "rolname");
6842         i_dictinitoption = PQfnumber(res, "dictinitoption");
6843         i_dicttemplate = PQfnumber(res, "dicttemplate");
6844
6845         for (i = 0; i < ntups; i++)
6846         {
6847                 dictinfo[i].dobj.objType = DO_TSDICT;
6848                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6849                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6850                 AssignDumpId(&dictinfo[i].dobj);
6851                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6852                 dictinfo[i].dobj.namespace =
6853                         findNamespace(fout,
6854                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6855                                                   dictinfo[i].dobj.catId.oid);
6856                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6857                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6858                 if (PQgetisnull(res, i, i_dictinitoption))
6859                         dictinfo[i].dictinitoption = NULL;
6860                 else
6861                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6862
6863                 /* Decide whether we want to dump it */
6864                 selectDumpableObject(&(dictinfo[i].dobj));
6865         }
6866
6867         PQclear(res);
6868
6869         destroyPQExpBuffer(query);
6870
6871         return dictinfo;
6872 }
6873
6874 /*
6875  * getTSTemplates:
6876  *        read all text search templates in the system catalogs and return them
6877  *        in the TSTemplateInfo* structure
6878  *
6879  *      numTSTemplates is set to the number of templates read in
6880  */
6881 TSTemplateInfo *
6882 getTSTemplates(Archive *fout, int *numTSTemplates)
6883 {
6884         PGresult   *res;
6885         int                     ntups;
6886         int                     i;
6887         PQExpBuffer query;
6888         TSTemplateInfo *tmplinfo;
6889         int                     i_tableoid;
6890         int                     i_oid;
6891         int                     i_tmplname;
6892         int                     i_tmplnamespace;
6893         int                     i_tmplinit;
6894         int                     i_tmpllexize;
6895
6896         /* Before 8.3, there is no built-in text search support */
6897         if (fout->remoteVersion < 80300)
6898         {
6899                 *numTSTemplates = 0;
6900                 return NULL;
6901         }
6902
6903         query = createPQExpBuffer();
6904
6905         /* Make sure we are in proper schema */
6906         selectSourceSchema(fout, "pg_catalog");
6907
6908         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6909                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6910                                           "FROM pg_ts_template");
6911
6912         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6913
6914         ntups = PQntuples(res);
6915         *numTSTemplates = ntups;
6916
6917         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6918
6919         i_tableoid = PQfnumber(res, "tableoid");
6920         i_oid = PQfnumber(res, "oid");
6921         i_tmplname = PQfnumber(res, "tmplname");
6922         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6923         i_tmplinit = PQfnumber(res, "tmplinit");
6924         i_tmpllexize = PQfnumber(res, "tmpllexize");
6925
6926         for (i = 0; i < ntups; i++)
6927         {
6928                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6929                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6930                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6931                 AssignDumpId(&tmplinfo[i].dobj);
6932                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6933                 tmplinfo[i].dobj.namespace =
6934                         findNamespace(fout,
6935                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6936                                                   tmplinfo[i].dobj.catId.oid);
6937                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6938                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6939
6940                 /* Decide whether we want to dump it */
6941                 selectDumpableObject(&(tmplinfo[i].dobj));
6942         }
6943
6944         PQclear(res);
6945
6946         destroyPQExpBuffer(query);
6947
6948         return tmplinfo;
6949 }
6950
6951 /*
6952  * getTSConfigurations:
6953  *        read all text search configurations in the system catalogs and return
6954  *        them in the TSConfigInfo* structure
6955  *
6956  *      numTSConfigs is set to the number of configurations read in
6957  */
6958 TSConfigInfo *
6959 getTSConfigurations(Archive *fout, int *numTSConfigs)
6960 {
6961         PGresult   *res;
6962         int                     ntups;
6963         int                     i;
6964         PQExpBuffer query;
6965         TSConfigInfo *cfginfo;
6966         int                     i_tableoid;
6967         int                     i_oid;
6968         int                     i_cfgname;
6969         int                     i_cfgnamespace;
6970         int                     i_rolname;
6971         int                     i_cfgparser;
6972
6973         /* Before 8.3, there is no built-in text search support */
6974         if (fout->remoteVersion < 80300)
6975         {
6976                 *numTSConfigs = 0;
6977                 return NULL;
6978         }
6979
6980         query = createPQExpBuffer();
6981
6982         /* Make sure we are in proper schema */
6983         selectSourceSchema(fout, "pg_catalog");
6984
6985         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6986                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6987                                           "FROM pg_ts_config",
6988                                           username_subquery);
6989
6990         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6991
6992         ntups = PQntuples(res);
6993         *numTSConfigs = ntups;
6994
6995         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6996
6997         i_tableoid = PQfnumber(res, "tableoid");
6998         i_oid = PQfnumber(res, "oid");
6999         i_cfgname = PQfnumber(res, "cfgname");
7000         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
7001         i_rolname = PQfnumber(res, "rolname");
7002         i_cfgparser = PQfnumber(res, "cfgparser");
7003
7004         for (i = 0; i < ntups; i++)
7005         {
7006                 cfginfo[i].dobj.objType = DO_TSCONFIG;
7007                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7008                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7009                 AssignDumpId(&cfginfo[i].dobj);
7010                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
7011                 cfginfo[i].dobj.namespace =
7012                         findNamespace(fout,
7013                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
7014                                                   cfginfo[i].dobj.catId.oid);
7015                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7016                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
7017
7018                 /* Decide whether we want to dump it */
7019                 selectDumpableObject(&(cfginfo[i].dobj));
7020         }
7021
7022         PQclear(res);
7023
7024         destroyPQExpBuffer(query);
7025
7026         return cfginfo;
7027 }
7028
7029 /*
7030  * getForeignDataWrappers:
7031  *        read all foreign-data wrappers in the system catalogs and return
7032  *        them in the FdwInfo* structure
7033  *
7034  *      numForeignDataWrappers is set to the number of fdws read in
7035  */
7036 FdwInfo *
7037 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
7038 {
7039         PGresult   *res;
7040         int                     ntups;
7041         int                     i;
7042         PQExpBuffer query = createPQExpBuffer();
7043         FdwInfo    *fdwinfo;
7044         int                     i_tableoid;
7045         int                     i_oid;
7046         int                     i_fdwname;
7047         int                     i_rolname;
7048         int                     i_fdwhandler;
7049         int                     i_fdwvalidator;
7050         int                     i_fdwacl;
7051         int                     i_fdwoptions;
7052
7053         /* Before 8.4, there are no foreign-data wrappers */
7054         if (fout->remoteVersion < 80400)
7055         {
7056                 *numForeignDataWrappers = 0;
7057                 return NULL;
7058         }
7059
7060         /* Make sure we are in proper schema */
7061         selectSourceSchema(fout, "pg_catalog");
7062
7063         if (fout->remoteVersion >= 90100)
7064         {
7065                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7066                                                   "(%s fdwowner) AS rolname, "
7067                                                   "fdwhandler::pg_catalog.regproc, "
7068                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
7069                                                   "array_to_string(ARRAY("
7070                                                   "SELECT quote_ident(option_name) || ' ' || "
7071                                                   "quote_literal(option_value) "
7072                                                   "FROM pg_options_to_table(fdwoptions) "
7073                                                   "ORDER BY option_name"
7074                                                   "), E',\n    ') AS fdwoptions "
7075                                                   "FROM pg_foreign_data_wrapper",
7076                                                   username_subquery);
7077         }
7078         else
7079         {
7080                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7081                                                   "(%s fdwowner) AS rolname, "
7082                                                   "'-' AS fdwhandler, "
7083                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
7084                                                   "array_to_string(ARRAY("
7085                                                   "SELECT quote_ident(option_name) || ' ' || "
7086                                                   "quote_literal(option_value) "
7087                                                   "FROM pg_options_to_table(fdwoptions) "
7088                                                   "ORDER BY option_name"
7089                                                   "), E',\n    ') AS fdwoptions "
7090                                                   "FROM pg_foreign_data_wrapper",
7091                                                   username_subquery);
7092         }
7093
7094         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7095
7096         ntups = PQntuples(res);
7097         *numForeignDataWrappers = ntups;
7098
7099         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
7100
7101         i_tableoid = PQfnumber(res, "tableoid");
7102         i_oid = PQfnumber(res, "oid");
7103         i_fdwname = PQfnumber(res, "fdwname");
7104         i_rolname = PQfnumber(res, "rolname");
7105         i_fdwhandler = PQfnumber(res, "fdwhandler");
7106         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
7107         i_fdwacl = PQfnumber(res, "fdwacl");
7108         i_fdwoptions = PQfnumber(res, "fdwoptions");
7109
7110         for (i = 0; i < ntups; i++)
7111         {
7112                 fdwinfo[i].dobj.objType = DO_FDW;
7113                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7114                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7115                 AssignDumpId(&fdwinfo[i].dobj);
7116                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
7117                 fdwinfo[i].dobj.namespace = NULL;
7118                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7119                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
7120                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
7121                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
7122                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
7123
7124                 /* Decide whether we want to dump it */
7125                 selectDumpableObject(&(fdwinfo[i].dobj));
7126         }
7127
7128         PQclear(res);
7129
7130         destroyPQExpBuffer(query);
7131
7132         return fdwinfo;
7133 }
7134
7135 /*
7136  * getForeignServers:
7137  *        read all foreign servers in the system catalogs and return
7138  *        them in the ForeignServerInfo * structure
7139  *
7140  *      numForeignServers is set to the number of servers read in
7141  */
7142 ForeignServerInfo *
7143 getForeignServers(Archive *fout, int *numForeignServers)
7144 {
7145         PGresult   *res;
7146         int                     ntups;
7147         int                     i;
7148         PQExpBuffer query = createPQExpBuffer();
7149         ForeignServerInfo *srvinfo;
7150         int                     i_tableoid;
7151         int                     i_oid;
7152         int                     i_srvname;
7153         int                     i_rolname;
7154         int                     i_srvfdw;
7155         int                     i_srvtype;
7156         int                     i_srvversion;
7157         int                     i_srvacl;
7158         int                     i_srvoptions;
7159
7160         /* Before 8.4, there are no foreign servers */
7161         if (fout->remoteVersion < 80400)
7162         {
7163                 *numForeignServers = 0;
7164                 return NULL;
7165         }
7166
7167         /* Make sure we are in proper schema */
7168         selectSourceSchema(fout, "pg_catalog");
7169
7170         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
7171                                           "(%s srvowner) AS rolname, "
7172                                           "srvfdw, srvtype, srvversion, srvacl,"
7173                                           "array_to_string(ARRAY("
7174                                           "SELECT quote_ident(option_name) || ' ' || "
7175                                           "quote_literal(option_value) "
7176                                           "FROM pg_options_to_table(srvoptions) "
7177                                           "ORDER BY option_name"
7178                                           "), E',\n    ') AS srvoptions "
7179                                           "FROM pg_foreign_server",
7180                                           username_subquery);
7181
7182         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7183
7184         ntups = PQntuples(res);
7185         *numForeignServers = ntups;
7186
7187         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
7188
7189         i_tableoid = PQfnumber(res, "tableoid");
7190         i_oid = PQfnumber(res, "oid");
7191         i_srvname = PQfnumber(res, "srvname");
7192         i_rolname = PQfnumber(res, "rolname");
7193         i_srvfdw = PQfnumber(res, "srvfdw");
7194         i_srvtype = PQfnumber(res, "srvtype");
7195         i_srvversion = PQfnumber(res, "srvversion");
7196         i_srvacl = PQfnumber(res, "srvacl");
7197         i_srvoptions = PQfnumber(res, "srvoptions");
7198
7199         for (i = 0; i < ntups; i++)
7200         {
7201                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
7202                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7203                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7204                 AssignDumpId(&srvinfo[i].dobj);
7205                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
7206                 srvinfo[i].dobj.namespace = NULL;
7207                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7208                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
7209                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
7210                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
7211                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
7212                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
7213
7214                 /* Decide whether we want to dump it */
7215                 selectDumpableObject(&(srvinfo[i].dobj));
7216         }
7217
7218         PQclear(res);
7219
7220         destroyPQExpBuffer(query);
7221
7222         return srvinfo;
7223 }
7224
7225 /*
7226  * getDefaultACLs:
7227  *        read all default ACL information in the system catalogs and return
7228  *        them in the DefaultACLInfo structure
7229  *
7230  *      numDefaultACLs is set to the number of ACLs read in
7231  */
7232 DefaultACLInfo *
7233 getDefaultACLs(Archive *fout, int *numDefaultACLs)
7234 {
7235         DefaultACLInfo *daclinfo;
7236         PQExpBuffer query;
7237         PGresult   *res;
7238         int                     i_oid;
7239         int                     i_tableoid;
7240         int                     i_defaclrole;
7241         int                     i_defaclnamespace;
7242         int                     i_defaclobjtype;
7243         int                     i_defaclacl;
7244         int                     i,
7245                                 ntups;
7246
7247         if (fout->remoteVersion < 90000)
7248         {
7249                 *numDefaultACLs = 0;
7250                 return NULL;
7251         }
7252
7253         query = createPQExpBuffer();
7254
7255         /* Make sure we are in proper schema */
7256         selectSourceSchema(fout, "pg_catalog");
7257
7258         appendPQExpBuffer(query, "SELECT oid, tableoid, "
7259                                           "(%s defaclrole) AS defaclrole, "
7260                                           "defaclnamespace, "
7261                                           "defaclobjtype, "
7262                                           "defaclacl "
7263                                           "FROM pg_default_acl",
7264                                           username_subquery);
7265
7266         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7267
7268         ntups = PQntuples(res);
7269         *numDefaultACLs = ntups;
7270
7271         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
7272
7273         i_oid = PQfnumber(res, "oid");
7274         i_tableoid = PQfnumber(res, "tableoid");
7275         i_defaclrole = PQfnumber(res, "defaclrole");
7276         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
7277         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
7278         i_defaclacl = PQfnumber(res, "defaclacl");
7279
7280         for (i = 0; i < ntups; i++)
7281         {
7282                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
7283
7284                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
7285                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7286                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7287                 AssignDumpId(&daclinfo[i].dobj);
7288                 /* cheesy ... is it worth coming up with a better object name? */
7289                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
7290
7291                 if (nspid != InvalidOid)
7292                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
7293                                                                                                  daclinfo[i].dobj.catId.oid);
7294                 else
7295                         daclinfo[i].dobj.namespace = NULL;
7296
7297                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
7298                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
7299                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
7300
7301                 /* Decide whether we want to dump it */
7302                 selectDumpableDefaultACL(&(daclinfo[i]));
7303         }
7304
7305         PQclear(res);
7306
7307         destroyPQExpBuffer(query);
7308
7309         return daclinfo;
7310 }
7311
7312 /*
7313  * dumpComment --
7314  *
7315  * This routine is used to dump any comments associated with the
7316  * object handed to this routine. The routine takes a constant character
7317  * string for the target part of the comment-creation command, plus
7318  * the namespace and owner of the object (for labeling the ArchiveEntry),
7319  * plus catalog ID and subid which are the lookup key for pg_description,
7320  * plus the dump ID for the object (for setting a dependency).
7321  * If a matching pg_description entry is found, it is dumped.
7322  *
7323  * Note: although this routine takes a dumpId for dependency purposes,
7324  * that purpose is just to mark the dependency in the emitted dump file
7325  * for possible future use by pg_restore.  We do NOT use it for determining
7326  * ordering of the comment in the dump file, because this routine is called
7327  * after dependency sorting occurs.  This routine should be called just after
7328  * calling ArchiveEntry() for the specified object.
7329  */
7330 static void
7331 dumpComment(Archive *fout, const char *target,
7332                         const char *namespace, const char *owner,
7333                         CatalogId catalogId, int subid, DumpId dumpId)
7334 {
7335         CommentItem *comments;
7336         int                     ncomments;
7337
7338         /* Comments are schema not data ... except blob comments are data */
7339         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
7340         {
7341                 if (dataOnly)
7342                         return;
7343         }
7344         else
7345         {
7346                 if (schemaOnly)
7347                         return;
7348         }
7349
7350         /* Search for comments associated with catalogId, using table */
7351         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
7352                                                          &comments);
7353
7354         /* Is there one matching the subid? */
7355         while (ncomments > 0)
7356         {
7357                 if (comments->objsubid == subid)
7358                         break;
7359                 comments++;
7360                 ncomments--;
7361         }
7362
7363         /* If a comment exists, build COMMENT ON statement */
7364         if (ncomments > 0)
7365         {
7366                 PQExpBuffer query = createPQExpBuffer();
7367
7368                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7369                 appendStringLiteralAH(query, comments->descr, fout);
7370                 appendPQExpBuffer(query, ";\n");
7371
7372                 /*
7373                  * We mark comments as SECTION_NONE because they really belong in the
7374                  * same section as their parent, whether that is pre-data or
7375                  * post-data.
7376                  */
7377                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7378                                          target, namespace, NULL, owner,
7379                                          false, "COMMENT", SECTION_NONE,
7380                                          query->data, "", NULL,
7381                                          &(dumpId), 1,
7382                                          NULL, NULL);
7383
7384                 destroyPQExpBuffer(query);
7385         }
7386 }
7387
7388 /*
7389  * dumpTableComment --
7390  *
7391  * As above, but dump comments for both the specified table (or view)
7392  * and its columns.
7393  */
7394 static void
7395 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7396                                  const char *reltypename)
7397 {
7398         CommentItem *comments;
7399         int                     ncomments;
7400         PQExpBuffer query;
7401         PQExpBuffer target;
7402
7403         /* Comments are SCHEMA not data */
7404         if (dataOnly)
7405                 return;
7406
7407         /* Search for comments associated with relation, using table */
7408         ncomments = findComments(fout,
7409                                                          tbinfo->dobj.catId.tableoid,
7410                                                          tbinfo->dobj.catId.oid,
7411                                                          &comments);
7412
7413         /* If comments exist, build COMMENT ON statements */
7414         if (ncomments <= 0)
7415                 return;
7416
7417         query = createPQExpBuffer();
7418         target = createPQExpBuffer();
7419
7420         while (ncomments > 0)
7421         {
7422                 const char *descr = comments->descr;
7423                 int                     objsubid = comments->objsubid;
7424
7425                 if (objsubid == 0)
7426                 {
7427                         resetPQExpBuffer(target);
7428                         appendPQExpBuffer(target, "%s %s", reltypename,
7429                                                           fmtId(tbinfo->dobj.name));
7430
7431                         resetPQExpBuffer(query);
7432                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7433                         appendStringLiteralAH(query, descr, fout);
7434                         appendPQExpBuffer(query, ";\n");
7435
7436                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7437                                                  target->data,
7438                                                  tbinfo->dobj.namespace->dobj.name,
7439                                                  NULL, tbinfo->rolname,
7440                                                  false, "COMMENT", SECTION_NONE,
7441                                                  query->data, "", NULL,
7442                                                  &(tbinfo->dobj.dumpId), 1,
7443                                                  NULL, NULL);
7444                 }
7445                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7446                 {
7447                         resetPQExpBuffer(target);
7448                         appendPQExpBuffer(target, "COLUMN %s.",
7449                                                           fmtId(tbinfo->dobj.name));
7450                         appendPQExpBuffer(target, "%s",
7451                                                           fmtId(tbinfo->attnames[objsubid - 1]));
7452
7453                         resetPQExpBuffer(query);
7454                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7455                         appendStringLiteralAH(query, descr, fout);
7456                         appendPQExpBuffer(query, ";\n");
7457
7458                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7459                                                  target->data,
7460                                                  tbinfo->dobj.namespace->dobj.name,
7461                                                  NULL, tbinfo->rolname,
7462                                                  false, "COMMENT", SECTION_NONE,
7463                                                  query->data, "", NULL,
7464                                                  &(tbinfo->dobj.dumpId), 1,
7465                                                  NULL, NULL);
7466                 }
7467
7468                 comments++;
7469                 ncomments--;
7470         }
7471
7472         destroyPQExpBuffer(query);
7473         destroyPQExpBuffer(target);
7474 }
7475
7476 /*
7477  * findComments --
7478  *
7479  * Find the comment(s), if any, associated with the given object.  All the
7480  * objsubid values associated with the given classoid/objoid are found with
7481  * one search.
7482  */
7483 static int
7484 findComments(Archive *fout, Oid classoid, Oid objoid,
7485                          CommentItem **items)
7486 {
7487         /* static storage for table of comments */
7488         static CommentItem *comments = NULL;
7489         static int      ncomments = -1;
7490
7491         CommentItem *middle = NULL;
7492         CommentItem *low;
7493         CommentItem *high;
7494         int                     nmatch;
7495
7496         /* Get comments if we didn't already */
7497         if (ncomments < 0)
7498                 ncomments = collectComments(fout, &comments);
7499
7500         /*
7501          * Pre-7.2, pg_description does not contain classoid, so collectComments
7502          * just stores a zero.  If there's a collision on object OID, well, you
7503          * get duplicate comments.
7504          */
7505         if (fout->remoteVersion < 70200)
7506                 classoid = 0;
7507
7508         /*
7509          * Do binary search to find some item matching the object.
7510          */
7511         low = &comments[0];
7512         high = &comments[ncomments - 1];
7513         while (low <= high)
7514         {
7515                 middle = low + (high - low) / 2;
7516
7517                 if (classoid < middle->classoid)
7518                         high = middle - 1;
7519                 else if (classoid > middle->classoid)
7520                         low = middle + 1;
7521                 else if (objoid < middle->objoid)
7522                         high = middle - 1;
7523                 else if (objoid > middle->objoid)
7524                         low = middle + 1;
7525                 else
7526                         break;                          /* found a match */
7527         }
7528
7529         if (low > high)                         /* no matches */
7530         {
7531                 *items = NULL;
7532                 return 0;
7533         }
7534
7535         /*
7536          * Now determine how many items match the object.  The search loop
7537          * invariant still holds: only items between low and high inclusive could
7538          * match.
7539          */
7540         nmatch = 1;
7541         while (middle > low)
7542         {
7543                 if (classoid != middle[-1].classoid ||
7544                         objoid != middle[-1].objoid)
7545                         break;
7546                 middle--;
7547                 nmatch++;
7548         }
7549
7550         *items = middle;
7551
7552         middle += nmatch;
7553         while (middle <= high)
7554         {
7555                 if (classoid != middle->classoid ||
7556                         objoid != middle->objoid)
7557                         break;
7558                 middle++;
7559                 nmatch++;
7560         }
7561
7562         return nmatch;
7563 }
7564
7565 /*
7566  * collectComments --
7567  *
7568  * Construct a table of all comments available for database objects.
7569  * We used to do per-object queries for the comments, but it's much faster
7570  * to pull them all over at once, and on most databases the memory cost
7571  * isn't high.
7572  *
7573  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7574  */
7575 static int
7576 collectComments(Archive *fout, CommentItem **items)
7577 {
7578         PGresult   *res;
7579         PQExpBuffer query;
7580         int                     i_description;
7581         int                     i_classoid;
7582         int                     i_objoid;
7583         int                     i_objsubid;
7584         int                     ntups;
7585         int                     i;
7586         CommentItem *comments;
7587
7588         /*
7589          * Note we do NOT change source schema here; preserve the caller's
7590          * setting, instead.
7591          */
7592
7593         query = createPQExpBuffer();
7594
7595         if (fout->remoteVersion >= 70300)
7596         {
7597                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7598                                                   "FROM pg_catalog.pg_description "
7599                                                   "ORDER BY classoid, objoid, objsubid");
7600         }
7601         else if (fout->remoteVersion >= 70200)
7602         {
7603                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7604                                                   "FROM pg_description "
7605                                                   "ORDER BY classoid, objoid, objsubid");
7606         }
7607         else
7608         {
7609                 /* Note: this will fail to find attribute comments in pre-7.2... */
7610                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7611                                                   "FROM pg_description "
7612                                                   "ORDER BY objoid");
7613         }
7614
7615         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7616
7617         /* Construct lookup table containing OIDs in numeric form */
7618
7619         i_description = PQfnumber(res, "description");
7620         i_classoid = PQfnumber(res, "classoid");
7621         i_objoid = PQfnumber(res, "objoid");
7622         i_objsubid = PQfnumber(res, "objsubid");
7623
7624         ntups = PQntuples(res);
7625
7626         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7627
7628         for (i = 0; i < ntups; i++)
7629         {
7630                 comments[i].descr = PQgetvalue(res, i, i_description);
7631                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7632                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7633                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7634         }
7635
7636         /* Do NOT free the PGresult since we are keeping pointers into it */
7637         destroyPQExpBuffer(query);
7638
7639         *items = comments;
7640         return ntups;
7641 }
7642
7643 /*
7644  * dumpDumpableObject
7645  *
7646  * This routine and its subsidiaries are responsible for creating
7647  * ArchiveEntries (TOC objects) for each object to be dumped.
7648  */
7649 static void
7650 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7651 {
7652         switch (dobj->objType)
7653         {
7654                 case DO_NAMESPACE:
7655                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7656                         break;
7657                 case DO_EXTENSION:
7658                         dumpExtension(fout, (ExtensionInfo *) dobj);
7659                         break;
7660                 case DO_TYPE:
7661                         dumpType(fout, (TypeInfo *) dobj);
7662                         break;
7663                 case DO_SHELL_TYPE:
7664                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7665                         break;
7666                 case DO_FUNC:
7667                         dumpFunc(fout, (FuncInfo *) dobj);
7668                         break;
7669                 case DO_AGG:
7670                         dumpAgg(fout, (AggInfo *) dobj);
7671                         break;
7672                 case DO_OPERATOR:
7673                         dumpOpr(fout, (OprInfo *) dobj);
7674                         break;
7675                 case DO_OPCLASS:
7676                         dumpOpclass(fout, (OpclassInfo *) dobj);
7677                         break;
7678                 case DO_OPFAMILY:
7679                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7680                         break;
7681                 case DO_COLLATION:
7682                         dumpCollation(fout, (CollInfo *) dobj);
7683                         break;
7684                 case DO_CONVERSION:
7685                         dumpConversion(fout, (ConvInfo *) dobj);
7686                         break;
7687                 case DO_TABLE:
7688                         dumpTable(fout, (TableInfo *) dobj);
7689                         break;
7690                 case DO_ATTRDEF:
7691                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7692                         break;
7693                 case DO_INDEX:
7694                         dumpIndex(fout, (IndxInfo *) dobj);
7695                         break;
7696                 case DO_REFRESH_MATVIEW:
7697                         refreshMatViewData(fout, (TableDataInfo *) dobj);
7698                         break;
7699                 case DO_RULE:
7700                         dumpRule(fout, (RuleInfo *) dobj);
7701                         break;
7702                 case DO_TRIGGER:
7703                         dumpTrigger(fout, (TriggerInfo *) dobj);
7704                         break;
7705                 case DO_EVENT_TRIGGER:
7706                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7707                         break;
7708                 case DO_CONSTRAINT:
7709                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7710                         break;
7711                 case DO_FK_CONSTRAINT:
7712                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7713                         break;
7714                 case DO_PROCLANG:
7715                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7716                         break;
7717                 case DO_CAST:
7718                         dumpCast(fout, (CastInfo *) dobj);
7719                         break;
7720                 case DO_TABLE_DATA:
7721                         if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7722                                 dumpSequenceData(fout, (TableDataInfo *) dobj);
7723                         else
7724                                 dumpTableData(fout, (TableDataInfo *) dobj);
7725                         break;
7726                 case DO_DUMMY_TYPE:
7727                         /* table rowtypes and array types are never dumped separately */
7728                         break;
7729                 case DO_TSPARSER:
7730                         dumpTSParser(fout, (TSParserInfo *) dobj);
7731                         break;
7732                 case DO_TSDICT:
7733                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7734                         break;
7735                 case DO_TSTEMPLATE:
7736                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7737                         break;
7738                 case DO_TSCONFIG:
7739                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7740                         break;
7741                 case DO_FDW:
7742                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7743                         break;
7744                 case DO_FOREIGN_SERVER:
7745                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7746                         break;
7747                 case DO_DEFAULT_ACL:
7748                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7749                         break;
7750                 case DO_BLOB:
7751                         dumpBlob(fout, (BlobInfo *) dobj);
7752                         break;
7753                 case DO_BLOB_DATA:
7754                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7755                                                  dobj->name, NULL, NULL, "",
7756                                                  false, "BLOBS", SECTION_DATA,
7757                                                  "", "", NULL,
7758                                                  NULL, 0,
7759                                                  dumpBlobs, NULL);
7760                         break;
7761                 case DO_PRE_DATA_BOUNDARY:
7762                 case DO_POST_DATA_BOUNDARY:
7763                         /* never dumped, nothing to do */
7764                         break;
7765         }
7766 }
7767
7768 /*
7769  * dumpNamespace
7770  *        writes out to fout the queries to recreate a user-defined namespace
7771  */
7772 static void
7773 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7774 {
7775         PQExpBuffer q;
7776         PQExpBuffer delq;
7777         PQExpBuffer labelq;
7778         char       *qnspname;
7779
7780         /* Skip if not to be dumped */
7781         if (!nspinfo->dobj.dump || dataOnly)
7782                 return;
7783
7784         /* don't dump dummy namespace from pre-7.3 source */
7785         if (strlen(nspinfo->dobj.name) == 0)
7786                 return;
7787
7788         q = createPQExpBuffer();
7789         delq = createPQExpBuffer();
7790         labelq = createPQExpBuffer();
7791
7792         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7793
7794         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7795
7796         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7797
7798         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7799
7800         if (binary_upgrade)
7801                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7802
7803         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7804                                  nspinfo->dobj.name,
7805                                  NULL, NULL,
7806                                  nspinfo->rolname,
7807                                  false, "SCHEMA", SECTION_PRE_DATA,
7808                                  q->data, delq->data, NULL,
7809                                  NULL, 0,
7810                                  NULL, NULL);
7811
7812         /* Dump Schema Comments and Security Labels */
7813         dumpComment(fout, labelq->data,
7814                                 NULL, nspinfo->rolname,
7815                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7816         dumpSecLabel(fout, labelq->data,
7817                                  NULL, nspinfo->rolname,
7818                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7819
7820         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7821                         qnspname, NULL, nspinfo->dobj.name, NULL,
7822                         nspinfo->rolname, nspinfo->nspacl);
7823
7824         free(qnspname);
7825
7826         destroyPQExpBuffer(q);
7827         destroyPQExpBuffer(delq);
7828         destroyPQExpBuffer(labelq);
7829 }
7830
7831 /*
7832  * dumpExtension
7833  *        writes out to fout the queries to recreate an extension
7834  */
7835 static void
7836 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7837 {
7838         PQExpBuffer q;
7839         PQExpBuffer delq;
7840         PQExpBuffer labelq;
7841         char       *qextname;
7842
7843         /* Skip if not to be dumped */
7844         if (!extinfo->dobj.dump || dataOnly)
7845                 return;
7846
7847         q = createPQExpBuffer();
7848         delq = createPQExpBuffer();
7849         labelq = createPQExpBuffer();
7850
7851         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7852
7853         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7854
7855         if (!binary_upgrade)
7856         {
7857                 /*
7858                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7859                  * problem if the extension already exists in the target database;
7860                  * this is essential for installed-by-default extensions such as
7861                  * plpgsql.
7862                  *
7863                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7864                  * built-in extensions based on their OIDs; see
7865                  * selectDumpableExtension.
7866                  */
7867                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7868                                                   qextname, fmtId(extinfo->namespace));
7869         }
7870         else
7871         {
7872                 int                     i;
7873                 int                     n;
7874
7875                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7876
7877                 /*
7878                  * We unconditionally create the extension, so we must drop it if it
7879                  * exists.      This could happen if the user deleted 'plpgsql' and then
7880                  * readded it, causing its oid to be greater than FirstNormalObjectId.
7881                  * The FirstNormalObjectId test was kept to avoid repeatedly dropping
7882                  * and recreating extensions like 'plpgsql'.
7883                  */
7884                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7885
7886                 appendPQExpBuffer(q,
7887                                                   "SELECT binary_upgrade.create_empty_extension(");
7888                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7889                 appendPQExpBuffer(q, ", ");
7890                 appendStringLiteralAH(q, extinfo->namespace, fout);
7891                 appendPQExpBuffer(q, ", ");
7892                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7893                 appendStringLiteralAH(q, extinfo->extversion, fout);
7894                 appendPQExpBuffer(q, ", ");
7895
7896                 /*
7897                  * Note that we're pushing extconfig (an OID array) back into
7898                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7899                  * preserved in binary upgrade.
7900                  */
7901                 if (strlen(extinfo->extconfig) > 2)
7902                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7903                 else
7904                         appendPQExpBuffer(q, "NULL");
7905                 appendPQExpBuffer(q, ", ");
7906                 if (strlen(extinfo->extcondition) > 2)
7907                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7908                 else
7909                         appendPQExpBuffer(q, "NULL");
7910                 appendPQExpBuffer(q, ", ");
7911                 appendPQExpBuffer(q, "ARRAY[");
7912                 n = 0;
7913                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7914                 {
7915                         DumpableObject *extobj;
7916
7917                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7918                         if (extobj && extobj->objType == DO_EXTENSION)
7919                         {
7920                                 if (n++ > 0)
7921                                         appendPQExpBuffer(q, ",");
7922                                 appendStringLiteralAH(q, extobj->name, fout);
7923                         }
7924                 }
7925                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7926                 appendPQExpBuffer(q, ");\n");
7927         }
7928
7929         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7930
7931         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7932                                  extinfo->dobj.name,
7933                                  NULL, NULL,
7934                                  "",
7935                                  false, "EXTENSION", SECTION_PRE_DATA,
7936                                  q->data, delq->data, NULL,
7937                                  NULL, 0,
7938                                  NULL, NULL);
7939
7940         /* Dump Extension Comments and Security Labels */
7941         dumpComment(fout, labelq->data,
7942                                 NULL, "",
7943                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7944         dumpSecLabel(fout, labelq->data,
7945                                  NULL, "",
7946                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7947
7948         free(qextname);
7949
7950         destroyPQExpBuffer(q);
7951         destroyPQExpBuffer(delq);
7952         destroyPQExpBuffer(labelq);
7953 }
7954
7955 /*
7956  * dumpType
7957  *        writes out to fout the queries to recreate a user-defined type
7958  */
7959 static void
7960 dumpType(Archive *fout, TypeInfo *tyinfo)
7961 {
7962         /* Skip if not to be dumped */
7963         if (!tyinfo->dobj.dump || dataOnly)
7964                 return;
7965
7966         /* Dump out in proper style */
7967         if (tyinfo->typtype == TYPTYPE_BASE)
7968                 dumpBaseType(fout, tyinfo);
7969         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7970                 dumpDomain(fout, tyinfo);
7971         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7972                 dumpCompositeType(fout, tyinfo);
7973         else if (tyinfo->typtype == TYPTYPE_ENUM)
7974                 dumpEnumType(fout, tyinfo);
7975         else if (tyinfo->typtype == TYPTYPE_RANGE)
7976                 dumpRangeType(fout, tyinfo);
7977         else
7978                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7979                                   tyinfo->dobj.name);
7980 }
7981
7982 /*
7983  * dumpEnumType
7984  *        writes out to fout the queries to recreate a user-defined enum type
7985  */
7986 static void
7987 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7988 {
7989         PQExpBuffer q = createPQExpBuffer();
7990         PQExpBuffer delq = createPQExpBuffer();
7991         PQExpBuffer labelq = createPQExpBuffer();
7992         PQExpBuffer query = createPQExpBuffer();
7993         PGresult   *res;
7994         int                     num,
7995                                 i;
7996         Oid                     enum_oid;
7997         char       *qtypname;
7998         char       *label;
7999
8000         /* Set proper schema search path */
8001         selectSourceSchema(fout, "pg_catalog");
8002
8003         if (fout->remoteVersion >= 90100)
8004                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
8005                                                   "FROM pg_catalog.pg_enum "
8006                                                   "WHERE enumtypid = '%u'"
8007                                                   "ORDER BY enumsortorder",
8008                                                   tyinfo->dobj.catId.oid);
8009         else
8010                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
8011                                                   "FROM pg_catalog.pg_enum "
8012                                                   "WHERE enumtypid = '%u'"
8013                                                   "ORDER BY oid",
8014                                                   tyinfo->dobj.catId.oid);
8015
8016         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8017
8018         num = PQntuples(res);
8019
8020         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8021
8022         /*
8023          * DROP must be fully qualified in case same name appears in pg_catalog.
8024          * CASCADE shouldn't be required here as for normal types since the I/O
8025          * functions are generic and do not get dropped.
8026          */
8027         appendPQExpBuffer(delq, "DROP TYPE %s.",
8028                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8029         appendPQExpBuffer(delq, "%s;\n",
8030                                           qtypname);
8031
8032         if (binary_upgrade)
8033                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8034                                                                                                  tyinfo->dobj.catId.oid);
8035
8036         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
8037                                           qtypname);
8038
8039         if (!binary_upgrade)
8040         {
8041                 /* Labels with server-assigned oids */
8042                 for (i = 0; i < num; i++)
8043                 {
8044                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8045                         if (i > 0)
8046                                 appendPQExpBuffer(q, ",");
8047                         appendPQExpBuffer(q, "\n    ");
8048                         appendStringLiteralAH(q, label, fout);
8049                 }
8050         }
8051
8052         appendPQExpBuffer(q, "\n);\n");
8053
8054         if (binary_upgrade)
8055         {
8056                 /* Labels with dump-assigned (preserved) oids */
8057                 for (i = 0; i < num; i++)
8058                 {
8059                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
8060                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8061
8062                         if (i == 0)
8063                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
8064                         appendPQExpBuffer(q,
8065                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
8066                                                           enum_oid);
8067                         appendPQExpBuffer(q, "ALTER TYPE %s.",
8068                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8069                         appendPQExpBuffer(q, "%s ADD VALUE ",
8070                                                           qtypname);
8071                         appendStringLiteralAH(q, label, fout);
8072                         appendPQExpBuffer(q, ";\n\n");
8073                 }
8074         }
8075
8076         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8077
8078         if (binary_upgrade)
8079                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8080
8081         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8082                                  tyinfo->dobj.name,
8083                                  tyinfo->dobj.namespace->dobj.name,
8084                                  NULL,
8085                                  tyinfo->rolname, false,
8086                                  "TYPE", SECTION_PRE_DATA,
8087                                  q->data, delq->data, NULL,
8088                                  NULL, 0,
8089                                  NULL, NULL);
8090
8091         /* Dump Type Comments and Security Labels */
8092         dumpComment(fout, labelq->data,
8093                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8094                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8095         dumpSecLabel(fout, labelq->data,
8096                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8097                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8098
8099         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8100                         qtypname, NULL, tyinfo->dobj.name,
8101                         tyinfo->dobj.namespace->dobj.name,
8102                         tyinfo->rolname, tyinfo->typacl);
8103
8104         PQclear(res);
8105         destroyPQExpBuffer(q);
8106         destroyPQExpBuffer(delq);
8107         destroyPQExpBuffer(labelq);
8108         destroyPQExpBuffer(query);
8109 }
8110
8111 /*
8112  * dumpRangeType
8113  *        writes out to fout the queries to recreate a user-defined range type
8114  */
8115 static void
8116 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
8117 {
8118         PQExpBuffer q = createPQExpBuffer();
8119         PQExpBuffer delq = createPQExpBuffer();
8120         PQExpBuffer labelq = createPQExpBuffer();
8121         PQExpBuffer query = createPQExpBuffer();
8122         PGresult   *res;
8123         Oid                     collationOid;
8124         char       *qtypname;
8125         char       *procname;
8126
8127         /*
8128          * select appropriate schema to ensure names in CREATE are properly
8129          * qualified
8130          */
8131         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8132
8133         appendPQExpBuffer(query,
8134                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
8135                                           "opc.opcname AS opcname, "
8136                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
8137                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
8138                                           "opc.opcdefault, "
8139                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
8140                                           "     ELSE rngcollation END AS collation, "
8141                                           "rngcanonical, rngsubdiff "
8142                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
8143                                           "     pg_catalog.pg_opclass opc "
8144                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
8145                                           "rngtypid = '%u'",
8146                                           tyinfo->dobj.catId.oid);
8147
8148         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8149
8150         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8151
8152         /*
8153          * DROP must be fully qualified in case same name appears in pg_catalog.
8154          * CASCADE shouldn't be required here as for normal types since the I/O
8155          * functions are generic and do not get dropped.
8156          */
8157         appendPQExpBuffer(delq, "DROP TYPE %s.",
8158                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8159         appendPQExpBuffer(delq, "%s;\n",
8160                                           qtypname);
8161
8162         if (binary_upgrade)
8163                 binary_upgrade_set_type_oids_by_type_oid(fout,
8164                                                                                                  q, tyinfo->dobj.catId.oid);
8165
8166         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
8167                                           qtypname);
8168
8169         appendPQExpBuffer(q, "\n    subtype = %s",
8170                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
8171
8172         /* print subtype_opclass only if not default for subtype */
8173         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
8174         {
8175                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
8176                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
8177
8178                 /* always schema-qualify, don't try to be smart */
8179                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
8180                                                   fmtId(nspname));
8181                 appendPQExpBuffer(q, "%s", fmtId(opcname));
8182         }
8183
8184         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
8185         if (OidIsValid(collationOid))
8186         {
8187                 CollInfo   *coll = findCollationByOid(collationOid);
8188
8189                 if (coll)
8190                 {
8191                         /* always schema-qualify, don't try to be smart */
8192                         appendPQExpBuffer(q, ",\n    collation = %s.",
8193                                                           fmtId(coll->dobj.namespace->dobj.name));
8194                         appendPQExpBuffer(q, "%s",
8195                                                           fmtId(coll->dobj.name));
8196                 }
8197         }
8198
8199         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
8200         if (strcmp(procname, "-") != 0)
8201                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
8202
8203         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
8204         if (strcmp(procname, "-") != 0)
8205                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
8206
8207         appendPQExpBuffer(q, "\n);\n");
8208
8209         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8210
8211         if (binary_upgrade)
8212                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8213
8214         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8215                                  tyinfo->dobj.name,
8216                                  tyinfo->dobj.namespace->dobj.name,
8217                                  NULL,
8218                                  tyinfo->rolname, false,
8219                                  "TYPE", SECTION_PRE_DATA,
8220                                  q->data, delq->data, NULL,
8221                                  NULL, 0,
8222                                  NULL, NULL);
8223
8224         /* Dump Type Comments and Security Labels */
8225         dumpComment(fout, labelq->data,
8226                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8227                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8228         dumpSecLabel(fout, labelq->data,
8229                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8230                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8231
8232         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8233                         qtypname, NULL, tyinfo->dobj.name,
8234                         tyinfo->dobj.namespace->dobj.name,
8235                         tyinfo->rolname, tyinfo->typacl);
8236
8237         PQclear(res);
8238         destroyPQExpBuffer(q);
8239         destroyPQExpBuffer(delq);
8240         destroyPQExpBuffer(labelq);
8241         destroyPQExpBuffer(query);
8242 }
8243
8244 /*
8245  * dumpBaseType
8246  *        writes out to fout the queries to recreate a user-defined base type
8247  */
8248 static void
8249 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
8250 {
8251         PQExpBuffer q = createPQExpBuffer();
8252         PQExpBuffer delq = createPQExpBuffer();
8253         PQExpBuffer labelq = createPQExpBuffer();
8254         PQExpBuffer query = createPQExpBuffer();
8255         PGresult   *res;
8256         char       *qtypname;
8257         char       *typlen;
8258         char       *typinput;
8259         char       *typoutput;
8260         char       *typreceive;
8261         char       *typsend;
8262         char       *typmodin;
8263         char       *typmodout;
8264         char       *typanalyze;
8265         Oid                     typreceiveoid;
8266         Oid                     typsendoid;
8267         Oid                     typmodinoid;
8268         Oid                     typmodoutoid;
8269         Oid                     typanalyzeoid;
8270         char       *typcategory;
8271         char       *typispreferred;
8272         char       *typdelim;
8273         char       *typbyval;
8274         char       *typalign;
8275         char       *typstorage;
8276         char       *typcollatable;
8277         char       *typdefault;
8278         bool            typdefault_is_literal = false;
8279
8280         /* Set proper schema search path so regproc references list correctly */
8281         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8282
8283         /* Fetch type-specific details */
8284         if (fout->remoteVersion >= 90100)
8285         {
8286                 appendPQExpBuffer(query, "SELECT typlen, "
8287                                                   "typinput, typoutput, typreceive, typsend, "
8288                                                   "typmodin, typmodout, typanalyze, "
8289                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8290                                                   "typsend::pg_catalog.oid AS typsendoid, "
8291                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8292                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8293                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8294                                                   "typcategory, typispreferred, "
8295                                                   "typdelim, typbyval, typalign, typstorage, "
8296                                                   "(typcollation <> 0) AS typcollatable, "
8297                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8298                                                   "FROM pg_catalog.pg_type "
8299                                                   "WHERE oid = '%u'::pg_catalog.oid",
8300                                                   tyinfo->dobj.catId.oid);
8301         }
8302         else if (fout->remoteVersion >= 80400)
8303         {
8304                 appendPQExpBuffer(query, "SELECT typlen, "
8305                                                   "typinput, typoutput, typreceive, typsend, "
8306                                                   "typmodin, typmodout, typanalyze, "
8307                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8308                                                   "typsend::pg_catalog.oid AS typsendoid, "
8309                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8310                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8311                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8312                                                   "typcategory, typispreferred, "
8313                                                   "typdelim, typbyval, typalign, typstorage, "
8314                                                   "false AS typcollatable, "
8315                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8316                                                   "FROM pg_catalog.pg_type "
8317                                                   "WHERE oid = '%u'::pg_catalog.oid",
8318                                                   tyinfo->dobj.catId.oid);
8319         }
8320         else if (fout->remoteVersion >= 80300)
8321         {
8322                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
8323                 appendPQExpBuffer(query, "SELECT typlen, "
8324                                                   "typinput, typoutput, typreceive, typsend, "
8325                                                   "typmodin, typmodout, typanalyze, "
8326                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8327                                                   "typsend::pg_catalog.oid AS typsendoid, "
8328                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8329                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8330                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8331                                                   "'U' AS typcategory, false AS typispreferred, "
8332                                                   "typdelim, typbyval, typalign, typstorage, "
8333                                                   "false AS typcollatable, "
8334                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8335                                                   "FROM pg_catalog.pg_type "
8336                                                   "WHERE oid = '%u'::pg_catalog.oid",
8337                                                   tyinfo->dobj.catId.oid);
8338         }
8339         else if (fout->remoteVersion >= 80000)
8340         {
8341                 appendPQExpBuffer(query, "SELECT typlen, "
8342                                                   "typinput, typoutput, typreceive, typsend, "
8343                                                   "'-' AS typmodin, '-' AS typmodout, "
8344                                                   "typanalyze, "
8345                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8346                                                   "typsend::pg_catalog.oid AS typsendoid, "
8347                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8348                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8349                                                   "'U' AS typcategory, false AS typispreferred, "
8350                                                   "typdelim, typbyval, typalign, typstorage, "
8351                                                   "false AS typcollatable, "
8352                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8353                                                   "FROM pg_catalog.pg_type "
8354                                                   "WHERE oid = '%u'::pg_catalog.oid",
8355                                                   tyinfo->dobj.catId.oid);
8356         }
8357         else if (fout->remoteVersion >= 70400)
8358         {
8359                 appendPQExpBuffer(query, "SELECT typlen, "
8360                                                   "typinput, typoutput, typreceive, typsend, "
8361                                                   "'-' AS typmodin, '-' AS typmodout, "
8362                                                   "'-' AS typanalyze, "
8363                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8364                                                   "typsend::pg_catalog.oid AS typsendoid, "
8365                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8366                                                   "0 AS typanalyzeoid, "
8367                                                   "'U' AS typcategory, false AS typispreferred, "
8368                                                   "typdelim, typbyval, typalign, typstorage, "
8369                                                   "false AS typcollatable, "
8370                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8371                                                   "FROM pg_catalog.pg_type "
8372                                                   "WHERE oid = '%u'::pg_catalog.oid",
8373                                                   tyinfo->dobj.catId.oid);
8374         }
8375         else if (fout->remoteVersion >= 70300)
8376         {
8377                 appendPQExpBuffer(query, "SELECT typlen, "
8378                                                   "typinput, typoutput, "
8379                                                   "'-' AS typreceive, '-' AS typsend, "
8380                                                   "'-' AS typmodin, '-' AS typmodout, "
8381                                                   "'-' AS typanalyze, "
8382                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8383                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8384                                                   "0 AS typanalyzeoid, "
8385                                                   "'U' AS typcategory, false AS typispreferred, "
8386                                                   "typdelim, typbyval, typalign, typstorage, "
8387                                                   "false AS typcollatable, "
8388                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8389                                                   "FROM pg_catalog.pg_type "
8390                                                   "WHERE oid = '%u'::pg_catalog.oid",
8391                                                   tyinfo->dobj.catId.oid);
8392         }
8393         else if (fout->remoteVersion >= 70200)
8394         {
8395                 /*
8396                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
8397                  * ignore them because they are not right.
8398                  */
8399                 appendPQExpBuffer(query, "SELECT typlen, "
8400                                                   "typinput, typoutput, "
8401                                                   "'-' AS typreceive, '-' AS typsend, "
8402                                                   "'-' AS typmodin, '-' AS typmodout, "
8403                                                   "'-' AS typanalyze, "
8404                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8405                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8406                                                   "0 AS typanalyzeoid, "
8407                                                   "'U' AS typcategory, false AS typispreferred, "
8408                                                   "typdelim, typbyval, typalign, typstorage, "
8409                                                   "false AS typcollatable, "
8410                                                   "NULL AS typdefaultbin, typdefault "
8411                                                   "FROM pg_type "
8412                                                   "WHERE oid = '%u'::oid",
8413                                                   tyinfo->dobj.catId.oid);
8414         }
8415         else if (fout->remoteVersion >= 70100)
8416         {
8417                 /*
8418                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
8419                  * representation.
8420                  */
8421                 appendPQExpBuffer(query, "SELECT typlen, "
8422                                                   "typinput, typoutput, "
8423                                                   "'-' AS typreceive, '-' AS typsend, "
8424                                                   "'-' AS typmodin, '-' AS typmodout, "
8425                                                   "'-' AS typanalyze, "
8426                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8427                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8428                                                   "0 AS typanalyzeoid, "
8429                                                   "'U' AS typcategory, false AS typispreferred, "
8430                                                   "typdelim, typbyval, typalign, typstorage, "
8431                                                   "false AS typcollatable, "
8432                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8433                                                   "FROM pg_type "
8434                                                   "WHERE oid = '%u'::oid",
8435                                                   tyinfo->dobj.catId.oid);
8436         }
8437         else
8438         {
8439                 appendPQExpBuffer(query, "SELECT typlen, "
8440                                                   "typinput, typoutput, "
8441                                                   "'-' AS typreceive, '-' AS typsend, "
8442                                                   "'-' AS typmodin, '-' AS typmodout, "
8443                                                   "'-' AS typanalyze, "
8444                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8445                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8446                                                   "0 AS typanalyzeoid, "
8447                                                   "'U' AS typcategory, false AS typispreferred, "
8448                                                   "typdelim, typbyval, typalign, "
8449                                                   "'p'::char AS typstorage, "
8450                                                   "false AS typcollatable, "
8451                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8452                                                   "FROM pg_type "
8453                                                   "WHERE oid = '%u'::oid",
8454                                                   tyinfo->dobj.catId.oid);
8455         }
8456
8457         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8458
8459         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8460         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8461         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8462         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8463         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8464         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8465         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8466         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8467         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8468         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8469         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8470         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8471         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8472         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8473         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8474         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8475         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8476         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8477         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8478         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8479         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8480                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8481         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8482         {
8483                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8484                 typdefault_is_literal = true;   /* it needs quotes */
8485         }
8486         else
8487                 typdefault = NULL;
8488
8489         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8490
8491         /*
8492          * DROP must be fully qualified in case same name appears in pg_catalog.
8493          * The reason we include CASCADE is that the circular dependency between
8494          * the type and its I/O functions makes it impossible to drop the type any
8495          * other way.
8496          */
8497         appendPQExpBuffer(delq, "DROP TYPE %s.",
8498                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8499         appendPQExpBuffer(delq, "%s CASCADE;\n",
8500                                           qtypname);
8501
8502         /* We might already have a shell type, but setting pg_type_oid is harmless */
8503         if (binary_upgrade)
8504                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8505                                                                                                  tyinfo->dobj.catId.oid);
8506
8507         appendPQExpBuffer(q,
8508                                           "CREATE TYPE %s (\n"
8509                                           "    INTERNALLENGTH = %s",
8510                                           qtypname,
8511                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8512
8513         if (fout->remoteVersion >= 70300)
8514         {
8515                 /* regproc result is correctly quoted as of 7.3 */
8516                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
8517                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
8518                 if (OidIsValid(typreceiveoid))
8519                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
8520                 if (OidIsValid(typsendoid))
8521                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
8522                 if (OidIsValid(typmodinoid))
8523                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
8524                 if (OidIsValid(typmodoutoid))
8525                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
8526                 if (OidIsValid(typanalyzeoid))
8527                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
8528         }
8529         else
8530         {
8531                 /* regproc delivers an unquoted name before 7.3 */
8532                 /* cannot combine these because fmtId uses static result area */
8533                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
8534                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
8535                 /* receive/send/typmodin/typmodout/analyze need not be printed */
8536         }
8537
8538         if (strcmp(typcollatable, "t") == 0)
8539                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
8540
8541         if (typdefault != NULL)
8542         {
8543                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
8544                 if (typdefault_is_literal)
8545                         appendStringLiteralAH(q, typdefault, fout);
8546                 else
8547                         appendPQExpBufferStr(q, typdefault);
8548         }
8549
8550         if (OidIsValid(tyinfo->typelem))
8551         {
8552                 char       *elemType;
8553
8554                 /* reselect schema in case changed by function dump */
8555                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8556                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8557                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8558                 free(elemType);
8559         }
8560
8561         if (strcmp(typcategory, "U") != 0)
8562         {
8563                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8564                 appendStringLiteralAH(q, typcategory, fout);
8565         }
8566
8567         if (strcmp(typispreferred, "t") == 0)
8568                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8569
8570         if (typdelim && strcmp(typdelim, ",") != 0)
8571         {
8572                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8573                 appendStringLiteralAH(q, typdelim, fout);
8574         }
8575
8576         if (strcmp(typalign, "c") == 0)
8577                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8578         else if (strcmp(typalign, "s") == 0)
8579                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8580         else if (strcmp(typalign, "i") == 0)
8581                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8582         else if (strcmp(typalign, "d") == 0)
8583                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8584
8585         if (strcmp(typstorage, "p") == 0)
8586                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8587         else if (strcmp(typstorage, "e") == 0)
8588                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8589         else if (strcmp(typstorage, "x") == 0)
8590                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8591         else if (strcmp(typstorage, "m") == 0)
8592                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8593
8594         if (strcmp(typbyval, "t") == 0)
8595                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8596
8597         appendPQExpBuffer(q, "\n);\n");
8598
8599         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8600
8601         if (binary_upgrade)
8602                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8603
8604         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8605                                  tyinfo->dobj.name,
8606                                  tyinfo->dobj.namespace->dobj.name,
8607                                  NULL,
8608                                  tyinfo->rolname, false,
8609                                  "TYPE", SECTION_PRE_DATA,
8610                                  q->data, delq->data, NULL,
8611                                  NULL, 0,
8612                                  NULL, NULL);
8613
8614         /* Dump Type Comments and Security Labels */
8615         dumpComment(fout, labelq->data,
8616                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8617                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8618         dumpSecLabel(fout, labelq->data,
8619                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8620                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8621
8622         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8623                         qtypname, NULL, tyinfo->dobj.name,
8624                         tyinfo->dobj.namespace->dobj.name,
8625                         tyinfo->rolname, tyinfo->typacl);
8626
8627         PQclear(res);
8628         destroyPQExpBuffer(q);
8629         destroyPQExpBuffer(delq);
8630         destroyPQExpBuffer(labelq);
8631         destroyPQExpBuffer(query);
8632 }
8633
8634 /*
8635  * dumpDomain
8636  *        writes out to fout the queries to recreate a user-defined domain
8637  */
8638 static void
8639 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8640 {
8641         PQExpBuffer q = createPQExpBuffer();
8642         PQExpBuffer delq = createPQExpBuffer();
8643         PQExpBuffer labelq = createPQExpBuffer();
8644         PQExpBuffer query = createPQExpBuffer();
8645         PGresult   *res;
8646         int                     i;
8647         char       *qtypname;
8648         char       *typnotnull;
8649         char       *typdefn;
8650         char       *typdefault;
8651         Oid                     typcollation;
8652         bool            typdefault_is_literal = false;
8653
8654         /* Set proper schema search path so type references list correctly */
8655         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8656
8657         /* Fetch domain specific details */
8658         if (fout->remoteVersion >= 90100)
8659         {
8660                 /* typcollation is new in 9.1 */
8661                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8662                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8663                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8664                                                   "t.typdefault, "
8665                                                   "CASE WHEN t.typcollation <> u.typcollation "
8666                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8667                                                   "FROM pg_catalog.pg_type t "
8668                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8669                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8670                                                   tyinfo->dobj.catId.oid);
8671         }
8672         else
8673         {
8674                 /* We assume here that remoteVersion must be at least 70300 */
8675                 appendPQExpBuffer(query, "SELECT typnotnull, "
8676                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8677                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8678                                                   "typdefault, 0 AS typcollation "
8679                                                   "FROM pg_catalog.pg_type "
8680                                                   "WHERE oid = '%u'::pg_catalog.oid",
8681                                                   tyinfo->dobj.catId.oid);
8682         }
8683
8684         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8685
8686         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8687         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8688         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8689                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8690         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8691         {
8692                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8693                 typdefault_is_literal = true;   /* it needs quotes */
8694         }
8695         else
8696                 typdefault = NULL;
8697         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8698
8699         if (binary_upgrade)
8700                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8701                                                                                                  tyinfo->dobj.catId.oid);
8702
8703         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8704
8705         appendPQExpBuffer(q,
8706                                           "CREATE DOMAIN %s AS %s",
8707                                           qtypname,
8708                                           typdefn);
8709
8710         /* Print collation only if different from base type's collation */
8711         if (OidIsValid(typcollation))
8712         {
8713                 CollInfo   *coll;
8714
8715                 coll = findCollationByOid(typcollation);
8716                 if (coll)
8717                 {
8718                         /* always schema-qualify, don't try to be smart */
8719                         appendPQExpBuffer(q, " COLLATE %s.",
8720                                                           fmtId(coll->dobj.namespace->dobj.name));
8721                         appendPQExpBuffer(q, "%s",
8722                                                           fmtId(coll->dobj.name));
8723                 }
8724         }
8725
8726         if (typnotnull[0] == 't')
8727                 appendPQExpBuffer(q, " NOT NULL");
8728
8729         if (typdefault != NULL)
8730         {
8731                 appendPQExpBuffer(q, " DEFAULT ");
8732                 if (typdefault_is_literal)
8733                         appendStringLiteralAH(q, typdefault, fout);
8734                 else
8735                         appendPQExpBufferStr(q, typdefault);
8736         }
8737
8738         PQclear(res);
8739
8740         /*
8741          * Add any CHECK constraints for the domain
8742          */
8743         for (i = 0; i < tyinfo->nDomChecks; i++)
8744         {
8745                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8746
8747                 if (!domcheck->separate)
8748                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8749                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8750         }
8751
8752         appendPQExpBuffer(q, ";\n");
8753
8754         /*
8755          * DROP must be fully qualified in case same name appears in pg_catalog
8756          */
8757         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8758                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8759         appendPQExpBuffer(delq, "%s;\n",
8760                                           qtypname);
8761
8762         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8763
8764         if (binary_upgrade)
8765                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8766
8767         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8768                                  tyinfo->dobj.name,
8769                                  tyinfo->dobj.namespace->dobj.name,
8770                                  NULL,
8771                                  tyinfo->rolname, false,
8772                                  "DOMAIN", SECTION_PRE_DATA,
8773                                  q->data, delq->data, NULL,
8774                                  NULL, 0,
8775                                  NULL, NULL);
8776
8777         /* Dump Domain Comments and Security Labels */
8778         dumpComment(fout, labelq->data,
8779                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8780                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8781         dumpSecLabel(fout, labelq->data,
8782                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8783                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8784
8785         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8786                         qtypname, NULL, tyinfo->dobj.name,
8787                         tyinfo->dobj.namespace->dobj.name,
8788                         tyinfo->rolname, tyinfo->typacl);
8789
8790         destroyPQExpBuffer(q);
8791         destroyPQExpBuffer(delq);
8792         destroyPQExpBuffer(labelq);
8793         destroyPQExpBuffer(query);
8794 }
8795
8796 /*
8797  * dumpCompositeType
8798  *        writes out to fout the queries to recreate a user-defined stand-alone
8799  *        composite type
8800  */
8801 static void
8802 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8803 {
8804         PQExpBuffer q = createPQExpBuffer();
8805         PQExpBuffer dropped = createPQExpBuffer();
8806         PQExpBuffer delq = createPQExpBuffer();
8807         PQExpBuffer labelq = createPQExpBuffer();
8808         PQExpBuffer query = createPQExpBuffer();
8809         PGresult   *res;
8810         char       *qtypname;
8811         int                     ntups;
8812         int                     i_attname;
8813         int                     i_atttypdefn;
8814         int                     i_attlen;
8815         int                     i_attalign;
8816         int                     i_attisdropped;
8817         int                     i_attcollation;
8818         int                     i_typrelid;
8819         int                     i;
8820         int                     actual_atts;
8821
8822         /* Set proper schema search path so type references list correctly */
8823         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8824
8825         /* Fetch type specific details */
8826         if (fout->remoteVersion >= 90100)
8827         {
8828                 /*
8829                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8830                  * clauses for attributes whose collation is different from their
8831                  * type's default, we use a CASE here to suppress uninteresting
8832                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8833                  * collation does not matter for those.
8834                  */
8835                 appendPQExpBuffer(query, "SELECT a.attname, "
8836                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8837                                                   "a.attlen, a.attalign, a.attisdropped, "
8838                                                   "CASE WHEN a.attcollation <> at.typcollation "
8839                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8840                                                   "ct.typrelid "
8841                                                   "FROM pg_catalog.pg_type ct "
8842                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8843                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8844                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8845                                                   "ORDER BY a.attnum ",
8846                                                   tyinfo->dobj.catId.oid);
8847         }
8848         else
8849         {
8850                 /*
8851                  * We assume here that remoteVersion must be at least 70300.  Since
8852                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8853                  * always be false.
8854                  */
8855                 appendPQExpBuffer(query, "SELECT a.attname, "
8856                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8857                                                   "a.attlen, a.attalign, a.attisdropped, "
8858                                                   "0 AS attcollation, "
8859                                                   "ct.typrelid "
8860                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8861                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8862                                                   "AND a.attrelid = ct.typrelid "
8863                                                   "ORDER BY a.attnum ",
8864                                                   tyinfo->dobj.catId.oid);
8865         }
8866
8867         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8868
8869         ntups = PQntuples(res);
8870
8871         i_attname = PQfnumber(res, "attname");
8872         i_atttypdefn = PQfnumber(res, "atttypdefn");
8873         i_attlen = PQfnumber(res, "attlen");
8874         i_attalign = PQfnumber(res, "attalign");
8875         i_attisdropped = PQfnumber(res, "attisdropped");
8876         i_attcollation = PQfnumber(res, "attcollation");
8877         i_typrelid = PQfnumber(res, "typrelid");
8878
8879         if (binary_upgrade)
8880         {
8881                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8882
8883                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8884                                                                                                  tyinfo->dobj.catId.oid);
8885                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8886         }
8887
8888         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8889
8890         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8891                                           qtypname);
8892
8893         actual_atts = 0;
8894         for (i = 0; i < ntups; i++)
8895         {
8896                 char       *attname;
8897                 char       *atttypdefn;
8898                 char       *attlen;
8899                 char       *attalign;
8900                 bool            attisdropped;
8901                 Oid                     attcollation;
8902
8903                 attname = PQgetvalue(res, i, i_attname);
8904                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8905                 attlen = PQgetvalue(res, i, i_attlen);
8906                 attalign = PQgetvalue(res, i, i_attalign);
8907                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8908                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8909
8910                 if (attisdropped && !binary_upgrade)
8911                         continue;
8912
8913                 /* Format properly if not first attr */
8914                 if (actual_atts++ > 0)
8915                         appendPQExpBuffer(q, ",");
8916                 appendPQExpBuffer(q, "\n\t");
8917
8918                 if (!attisdropped)
8919                 {
8920                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8921
8922                         /* Add collation if not default for the column type */
8923                         if (OidIsValid(attcollation))
8924                         {
8925                                 CollInfo   *coll;
8926
8927                                 coll = findCollationByOid(attcollation);
8928                                 if (coll)
8929                                 {
8930                                         /* always schema-qualify, don't try to be smart */
8931                                         appendPQExpBuffer(q, " COLLATE %s.",
8932                                                                           fmtId(coll->dobj.namespace->dobj.name));
8933                                         appendPQExpBuffer(q, "%s",
8934                                                                           fmtId(coll->dobj.name));
8935                                 }
8936                         }
8937                 }
8938                 else
8939                 {
8940                         /*
8941                          * This is a dropped attribute and we're in binary_upgrade mode.
8942                          * Insert a placeholder for it in the CREATE TYPE command, and set
8943                          * length and alignment with direct UPDATE to the catalogs
8944                          * afterwards. See similar code in dumpTableSchema().
8945                          */
8946                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8947
8948                         /* stash separately for insertion after the CREATE TYPE */
8949                         appendPQExpBuffer(dropped,
8950                                           "\n-- For binary upgrade, recreate dropped column.\n");
8951                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8952                                                           "SET attlen = %s, "
8953                                                           "attalign = '%s', attbyval = false\n"
8954                                                           "WHERE attname = ", attlen, attalign);
8955                         appendStringLiteralAH(dropped, attname, fout);
8956                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8957                         appendStringLiteralAH(dropped, qtypname, fout);
8958                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8959
8960                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8961                                                           qtypname);
8962                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8963                                                           fmtId(attname));
8964                 }
8965         }
8966         appendPQExpBuffer(q, "\n);\n");
8967         appendPQExpBufferStr(q, dropped->data);
8968
8969         /*
8970          * DROP must be fully qualified in case same name appears in pg_catalog
8971          */
8972         appendPQExpBuffer(delq, "DROP TYPE %s.",
8973                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8974         appendPQExpBuffer(delq, "%s;\n",
8975                                           qtypname);
8976
8977         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8978
8979         if (binary_upgrade)
8980                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8981
8982         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8983                                  tyinfo->dobj.name,
8984                                  tyinfo->dobj.namespace->dobj.name,
8985                                  NULL,
8986                                  tyinfo->rolname, false,
8987                                  "TYPE", SECTION_PRE_DATA,
8988                                  q->data, delq->data, NULL,
8989                                  NULL, 0,
8990                                  NULL, NULL);
8991
8992
8993         /* Dump Type Comments and Security Labels */
8994         dumpComment(fout, labelq->data,
8995                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8996                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8997         dumpSecLabel(fout, labelq->data,
8998                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8999                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9000
9001         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
9002                         qtypname, NULL, tyinfo->dobj.name,
9003                         tyinfo->dobj.namespace->dobj.name,
9004                         tyinfo->rolname, tyinfo->typacl);
9005
9006         PQclear(res);
9007         destroyPQExpBuffer(q);
9008         destroyPQExpBuffer(dropped);
9009         destroyPQExpBuffer(delq);
9010         destroyPQExpBuffer(labelq);
9011         destroyPQExpBuffer(query);
9012
9013         /* Dump any per-column comments */
9014         dumpCompositeTypeColComments(fout, tyinfo);
9015 }
9016
9017 /*
9018  * dumpCompositeTypeColComments
9019  *        writes out to fout the queries to recreate comments on the columns of
9020  *        a user-defined stand-alone composite type
9021  */
9022 static void
9023 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
9024 {
9025         CommentItem *comments;
9026         int                     ncomments;
9027         PGresult   *res;
9028         PQExpBuffer query;
9029         PQExpBuffer target;
9030         Oid                     pgClassOid;
9031         int                     i;
9032         int                     ntups;
9033         int                     i_attname;
9034         int                     i_attnum;
9035
9036         query = createPQExpBuffer();
9037
9038         /* We assume here that remoteVersion must be at least 70300 */
9039         appendPQExpBuffer(query,
9040                                           "SELECT c.tableoid, a.attname, a.attnum "
9041                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
9042                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
9043                                           "  AND NOT a.attisdropped "
9044                                           "ORDER BY a.attnum ",
9045                                           tyinfo->typrelid);
9046
9047         /* Fetch column attnames */
9048         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9049
9050         ntups = PQntuples(res);
9051         if (ntups < 1)
9052         {
9053                 PQclear(res);
9054                 destroyPQExpBuffer(query);
9055                 return;
9056         }
9057
9058         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
9059
9060         /* Search for comments associated with type's pg_class OID */
9061         ncomments = findComments(fout,
9062                                                          pgClassOid,
9063                                                          tyinfo->typrelid,
9064                                                          &comments);
9065
9066         /* If no comments exist, we're done */
9067         if (ncomments <= 0)
9068         {
9069                 PQclear(res);
9070                 destroyPQExpBuffer(query);
9071                 return;
9072         }
9073
9074         /* Build COMMENT ON statements */
9075         target = createPQExpBuffer();
9076
9077         i_attnum = PQfnumber(res, "attnum");
9078         i_attname = PQfnumber(res, "attname");
9079         while (ncomments > 0)
9080         {
9081                 const char *attname;
9082
9083                 attname = NULL;
9084                 for (i = 0; i < ntups; i++)
9085                 {
9086                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
9087                         {
9088                                 attname = PQgetvalue(res, i, i_attname);
9089                                 break;
9090                         }
9091                 }
9092                 if (attname)                    /* just in case we don't find it */
9093                 {
9094                         const char *descr = comments->descr;
9095
9096                         resetPQExpBuffer(target);
9097                         appendPQExpBuffer(target, "COLUMN %s.",
9098                                                           fmtId(tyinfo->dobj.name));
9099                         appendPQExpBuffer(target, "%s",
9100                                                           fmtId(attname));
9101
9102                         resetPQExpBuffer(query);
9103                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9104                         appendStringLiteralAH(query, descr, fout);
9105                         appendPQExpBuffer(query, ";\n");
9106
9107                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9108                                                  target->data,
9109                                                  tyinfo->dobj.namespace->dobj.name,
9110                                                  NULL, tyinfo->rolname,
9111                                                  false, "COMMENT", SECTION_NONE,
9112                                                  query->data, "", NULL,
9113                                                  &(tyinfo->dobj.dumpId), 1,
9114                                                  NULL, NULL);
9115                 }
9116
9117                 comments++;
9118                 ncomments--;
9119         }
9120
9121         PQclear(res);
9122         destroyPQExpBuffer(query);
9123         destroyPQExpBuffer(target);
9124 }
9125
9126 /*
9127  * dumpShellType
9128  *        writes out to fout the queries to create a shell type
9129  *
9130  * We dump a shell definition in advance of the I/O functions for the type.
9131  */
9132 static void
9133 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
9134 {
9135         PQExpBuffer q;
9136
9137         /* Skip if not to be dumped */
9138         if (!stinfo->dobj.dump || dataOnly)
9139                 return;
9140
9141         q = createPQExpBuffer();
9142
9143         /*
9144          * Note the lack of a DROP command for the shell type; any required DROP
9145          * is driven off the base type entry, instead.  This interacts with
9146          * _printTocEntry()'s use of the presence of a DROP command to decide
9147          * whether an entry needs an ALTER OWNER command.  We don't want to alter
9148          * the shell type's owner immediately on creation; that should happen only
9149          * after it's filled in, otherwise the backend complains.
9150          */
9151
9152         if (binary_upgrade)
9153                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
9154                                                                                    stinfo->baseType->dobj.catId.oid);
9155
9156         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
9157                                           fmtId(stinfo->dobj.name));
9158
9159         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
9160                                  stinfo->dobj.name,
9161                                  stinfo->dobj.namespace->dobj.name,
9162                                  NULL,
9163                                  stinfo->baseType->rolname, false,
9164                                  "SHELL TYPE", SECTION_PRE_DATA,
9165                                  q->data, "", NULL,
9166                                  NULL, 0,
9167                                  NULL, NULL);
9168
9169         destroyPQExpBuffer(q);
9170 }
9171
9172 /*
9173  * Determine whether we want to dump definitions for procedural languages.
9174  * Since the languages themselves don't have schemas, we can't rely on
9175  * the normal schema-based selection mechanism.  We choose to dump them
9176  * whenever neither --schema nor --table was given.  (Before 8.1, we used
9177  * the dump flag of the PL's call handler function, but in 8.1 this will
9178  * probably always be false since call handlers are created in pg_catalog.)
9179  *
9180  * For some backwards compatibility with the older behavior, we forcibly
9181  * dump a PL if its handler function (and validator if any) are in a
9182  * dumpable namespace.  That case is not checked here.
9183  *
9184  * Also, if the PL belongs to an extension, we do not use this heuristic.
9185  * That case isn't checked here either.
9186  */
9187 static bool
9188 shouldDumpProcLangs(void)
9189 {
9190         if (!include_everything)
9191                 return false;
9192         /* And they're schema not data */
9193         if (dataOnly)
9194                 return false;
9195         return true;
9196 }
9197
9198 /*
9199  * dumpProcLang
9200  *                writes out to fout the queries to recreate a user-defined
9201  *                procedural language
9202  */
9203 static void
9204 dumpProcLang(Archive *fout, ProcLangInfo *plang)
9205 {
9206         PQExpBuffer defqry;
9207         PQExpBuffer delqry;
9208         PQExpBuffer labelq;
9209         bool            useParams;
9210         char       *qlanname;
9211         char       *lanschema;
9212         FuncInfo   *funcInfo;
9213         FuncInfo   *inlineInfo = NULL;
9214         FuncInfo   *validatorInfo = NULL;
9215
9216         /* Skip if not to be dumped */
9217         if (!plang->dobj.dump || dataOnly)
9218                 return;
9219
9220         /*
9221          * Try to find the support function(s).  It is not an error if we don't
9222          * find them --- if the functions are in the pg_catalog schema, as is
9223          * standard in 8.1 and up, then we won't have loaded them. (In this case
9224          * we will emit a parameterless CREATE LANGUAGE command, which will
9225          * require PL template knowledge in the backend to reload.)
9226          */
9227
9228         funcInfo = findFuncByOid(plang->lanplcallfoid);
9229         if (funcInfo != NULL && !funcInfo->dobj.dump)
9230                 funcInfo = NULL;                /* treat not-dumped same as not-found */
9231
9232         if (OidIsValid(plang->laninline))
9233         {
9234                 inlineInfo = findFuncByOid(plang->laninline);
9235                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
9236                         inlineInfo = NULL;
9237         }
9238
9239         if (OidIsValid(plang->lanvalidator))
9240         {
9241                 validatorInfo = findFuncByOid(plang->lanvalidator);
9242                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
9243                         validatorInfo = NULL;
9244         }
9245
9246         /*
9247          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
9248          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
9249          * dump it.
9250          *
9251          * However, for a language that belongs to an extension, we must not use
9252          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
9253          * told to (via dobj.dump).  Generally the support functions will belong
9254          * to the same extension and so have the same dump flags ... if they
9255          * don't, this might not work terribly nicely.
9256          */
9257         useParams = (funcInfo != NULL &&
9258                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
9259                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
9260
9261         if (!plang->dobj.ext_member)
9262         {
9263                 if (!useParams && !shouldDumpProcLangs())
9264                         return;
9265         }
9266
9267         defqry = createPQExpBuffer();
9268         delqry = createPQExpBuffer();
9269         labelq = createPQExpBuffer();
9270
9271         qlanname = pg_strdup(fmtId(plang->dobj.name));
9272
9273         /*
9274          * If dumping a HANDLER clause, treat the language as being in the handler
9275          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
9276          * it doesn't really have a schema.
9277          */
9278         if (useParams)
9279                 lanschema = funcInfo->dobj.namespace->dobj.name;
9280         else
9281                 lanschema = NULL;
9282
9283         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
9284                                           qlanname);
9285
9286         if (useParams)
9287         {
9288                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
9289                                                   plang->lanpltrusted ? "TRUSTED " : "",
9290                                                   qlanname);
9291                 appendPQExpBuffer(defqry, " HANDLER %s",
9292                                                   fmtId(funcInfo->dobj.name));
9293                 if (OidIsValid(plang->laninline))
9294                 {
9295                         appendPQExpBuffer(defqry, " INLINE ");
9296                         /* Cope with possibility that inline is in different schema */
9297                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
9298                                 appendPQExpBuffer(defqry, "%s.",
9299                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
9300                         appendPQExpBuffer(defqry, "%s",
9301                                                           fmtId(inlineInfo->dobj.name));
9302                 }
9303                 if (OidIsValid(plang->lanvalidator))
9304                 {
9305                         appendPQExpBuffer(defqry, " VALIDATOR ");
9306                         /* Cope with possibility that validator is in different schema */
9307                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
9308                                 appendPQExpBuffer(defqry, "%s.",
9309                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
9310                         appendPQExpBuffer(defqry, "%s",
9311                                                           fmtId(validatorInfo->dobj.name));
9312                 }
9313         }
9314         else
9315         {
9316                 /*
9317                  * If not dumping parameters, then use CREATE OR REPLACE so that the
9318                  * command will not fail if the language is preinstalled in the target
9319                  * database.  We restrict the use of REPLACE to this case so as to
9320                  * eliminate the risk of replacing a language with incompatible
9321                  * parameter settings: this command will only succeed at all if there
9322                  * is a pg_pltemplate entry, and if there is one, the existing entry
9323                  * must match it too.
9324                  */
9325                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
9326                                                   qlanname);
9327         }
9328         appendPQExpBuffer(defqry, ";\n");
9329
9330         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
9331
9332         if (binary_upgrade)
9333                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
9334
9335         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
9336                                  plang->dobj.name,
9337                                  lanschema, NULL, plang->lanowner,
9338                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
9339                                  defqry->data, delqry->data, NULL,
9340                                  NULL, 0,
9341                                  NULL, NULL);
9342
9343         /* Dump Proc Lang Comments and Security Labels */
9344         dumpComment(fout, labelq->data,
9345                                 NULL, "",
9346                                 plang->dobj.catId, 0, plang->dobj.dumpId);
9347         dumpSecLabel(fout, labelq->data,
9348                                  NULL, "",
9349                                  plang->dobj.catId, 0, plang->dobj.dumpId);
9350
9351         if (plang->lanpltrusted)
9352                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
9353                                 qlanname, NULL, plang->dobj.name,
9354                                 lanschema,
9355                                 plang->lanowner, plang->lanacl);
9356
9357         free(qlanname);
9358
9359         destroyPQExpBuffer(defqry);
9360         destroyPQExpBuffer(delqry);
9361         destroyPQExpBuffer(labelq);
9362 }
9363
9364 /*
9365  * format_function_arguments: generate function name and argument list
9366  *
9367  * This is used when we can rely on pg_get_function_arguments to format
9368  * the argument list.
9369  */
9370 static char *
9371 format_function_arguments(FuncInfo *finfo, char *funcargs)
9372 {
9373         PQExpBufferData fn;
9374
9375         initPQExpBuffer(&fn);
9376         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9377         return fn.data;
9378 }
9379
9380 /*
9381  * format_function_arguments_old: generate function name and argument list
9382  *
9383  * The argument type names are qualified if needed.  The function name
9384  * is never qualified.
9385  *
9386  * This is used only with pre-8.4 servers, so we aren't expecting to see
9387  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9388  *
9389  * Any or all of allargtypes, argmodes, argnames may be NULL.
9390  */
9391 static char *
9392 format_function_arguments_old(Archive *fout,
9393                                                           FuncInfo *finfo, int nallargs,
9394                                                           char **allargtypes,
9395                                                           char **argmodes,
9396                                                           char **argnames)
9397 {
9398         PQExpBufferData fn;
9399         int                     j;
9400
9401         initPQExpBuffer(&fn);
9402         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9403         for (j = 0; j < nallargs; j++)
9404         {
9405                 Oid                     typid;
9406                 char       *typname;
9407                 const char *argmode;
9408                 const char *argname;
9409
9410                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9411                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9412
9413                 if (argmodes)
9414                 {
9415                         switch (argmodes[j][0])
9416                         {
9417                                 case PROARGMODE_IN:
9418                                         argmode = "";
9419                                         break;
9420                                 case PROARGMODE_OUT:
9421                                         argmode = "OUT ";
9422                                         break;
9423                                 case PROARGMODE_INOUT:
9424                                         argmode = "INOUT ";
9425                                         break;
9426                                 default:
9427                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9428                                         argmode = "";
9429                                         break;
9430                         }
9431                 }
9432                 else
9433                         argmode = "";
9434
9435                 argname = argnames ? argnames[j] : (char *) NULL;
9436                 if (argname && argname[0] == '\0')
9437                         argname = NULL;
9438
9439                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9440                                                   (j > 0) ? ", " : "",
9441                                                   argmode,
9442                                                   argname ? fmtId(argname) : "",
9443                                                   argname ? " " : "",
9444                                                   typname);
9445                 free(typname);
9446         }
9447         appendPQExpBuffer(&fn, ")");
9448         return fn.data;
9449 }
9450
9451 /*
9452  * format_function_signature: generate function name and argument list
9453  *
9454  * This is like format_function_arguments_old except that only a minimal
9455  * list of input argument types is generated; this is sufficient to
9456  * reference the function, but not to define it.
9457  *
9458  * If honor_quotes is false then the function name is never quoted.
9459  * This is appropriate for use in TOC tags, but not in SQL commands.
9460  */
9461 static char *
9462 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9463 {
9464         PQExpBufferData fn;
9465         int                     j;
9466
9467         initPQExpBuffer(&fn);
9468         if (honor_quotes)
9469                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9470         else
9471                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9472         for (j = 0; j < finfo->nargs; j++)
9473         {
9474                 char       *typname;
9475
9476                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9477                                                                            zeroAsOpaque);
9478
9479                 appendPQExpBuffer(&fn, "%s%s",
9480                                                   (j > 0) ? ", " : "",
9481                                                   typname);
9482                 free(typname);
9483         }
9484         appendPQExpBuffer(&fn, ")");
9485         return fn.data;
9486 }
9487
9488
9489 /*
9490  * dumpFunc:
9491  *        dump out one function
9492  */
9493 static void
9494 dumpFunc(Archive *fout, FuncInfo *finfo)
9495 {
9496         PQExpBuffer query;
9497         PQExpBuffer q;
9498         PQExpBuffer delqry;
9499         PQExpBuffer labelq;
9500         PQExpBuffer asPart;
9501         PGresult   *res;
9502         char       *funcsig;            /* identity signature */
9503         char       *funcfullsig;        /* full signature */
9504         char       *funcsig_tag;
9505         char       *proretset;
9506         char       *prosrc;
9507         char       *probin;
9508         char       *funcargs;
9509         char       *funciargs;
9510         char       *funcresult;
9511         char       *proallargtypes;
9512         char       *proargmodes;
9513         char       *proargnames;
9514         char       *proiswindow;
9515         char       *provolatile;
9516         char       *proisstrict;
9517         char       *prosecdef;
9518         char       *proleakproof;
9519         char       *proconfig;
9520         char       *procost;
9521         char       *prorows;
9522         char       *lanname;
9523         char       *rettypename;
9524         int                     nallargs;
9525         char      **allargtypes = NULL;
9526         char      **argmodes = NULL;
9527         char      **argnames = NULL;
9528         char      **configitems = NULL;
9529         int                     nconfigitems = 0;
9530         int                     i;
9531
9532         /* Skip if not to be dumped */
9533         if (!finfo->dobj.dump || dataOnly)
9534                 return;
9535
9536         query = createPQExpBuffer();
9537         q = createPQExpBuffer();
9538         delqry = createPQExpBuffer();
9539         labelq = createPQExpBuffer();
9540         asPart = createPQExpBuffer();
9541
9542         /* Set proper schema search path so type references list correctly */
9543         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9544
9545         /* Fetch function-specific details */
9546         if (fout->remoteVersion >= 90200)
9547         {
9548                 /*
9549                  * proleakproof was added at v9.2
9550                  */
9551                 appendPQExpBuffer(query,
9552                                                   "SELECT proretset, prosrc, probin, "
9553                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9554                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9555                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9556                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9557                                                   "proleakproof, proconfig, procost, prorows, "
9558                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9559                                                   "FROM pg_catalog.pg_proc "
9560                                                   "WHERE oid = '%u'::pg_catalog.oid",
9561                                                   finfo->dobj.catId.oid);
9562         }
9563         else if (fout->remoteVersion >= 80400)
9564         {
9565                 /*
9566                  * In 8.4 and up we rely on pg_get_function_arguments and
9567                  * pg_get_function_result instead of examining proallargtypes etc.
9568                  */
9569                 appendPQExpBuffer(query,
9570                                                   "SELECT proretset, prosrc, probin, "
9571                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9572                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9573                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9574                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9575                                                   "false AS proleakproof, "
9576                                                   " proconfig, procost, prorows, "
9577                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9578                                                   "FROM pg_catalog.pg_proc "
9579                                                   "WHERE oid = '%u'::pg_catalog.oid",
9580                                                   finfo->dobj.catId.oid);
9581         }
9582         else if (fout->remoteVersion >= 80300)
9583         {
9584                 appendPQExpBuffer(query,
9585                                                   "SELECT proretset, prosrc, probin, "
9586                                                   "proallargtypes, proargmodes, proargnames, "
9587                                                   "false AS proiswindow, "
9588                                                   "provolatile, proisstrict, prosecdef, "
9589                                                   "false AS proleakproof, "
9590                                                   "proconfig, procost, prorows, "
9591                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9592                                                   "FROM pg_catalog.pg_proc "
9593                                                   "WHERE oid = '%u'::pg_catalog.oid",
9594                                                   finfo->dobj.catId.oid);
9595         }
9596         else if (fout->remoteVersion >= 80100)
9597         {
9598                 appendPQExpBuffer(query,
9599                                                   "SELECT proretset, prosrc, probin, "
9600                                                   "proallargtypes, proargmodes, proargnames, "
9601                                                   "false AS proiswindow, "
9602                                                   "provolatile, proisstrict, prosecdef, "
9603                                                   "false AS proleakproof, "
9604                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9605                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9606                                                   "FROM pg_catalog.pg_proc "
9607                                                   "WHERE oid = '%u'::pg_catalog.oid",
9608                                                   finfo->dobj.catId.oid);
9609         }
9610         else if (fout->remoteVersion >= 80000)
9611         {
9612                 appendPQExpBuffer(query,
9613                                                   "SELECT proretset, prosrc, probin, "
9614                                                   "null AS proallargtypes, "
9615                                                   "null AS proargmodes, "
9616                                                   "proargnames, "
9617                                                   "false AS proiswindow, "
9618                                                   "provolatile, proisstrict, prosecdef, "
9619                                                   "false AS proleakproof, "
9620                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9621                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9622                                                   "FROM pg_catalog.pg_proc "
9623                                                   "WHERE oid = '%u'::pg_catalog.oid",
9624                                                   finfo->dobj.catId.oid);
9625         }
9626         else if (fout->remoteVersion >= 70300)
9627         {
9628                 appendPQExpBuffer(query,
9629                                                   "SELECT proretset, prosrc, probin, "
9630                                                   "null AS proallargtypes, "
9631                                                   "null AS proargmodes, "
9632                                                   "null AS proargnames, "
9633                                                   "false AS proiswindow, "
9634                                                   "provolatile, proisstrict, prosecdef, "
9635                                                   "false AS proleakproof, "
9636                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9637                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9638                                                   "FROM pg_catalog.pg_proc "
9639                                                   "WHERE oid = '%u'::pg_catalog.oid",
9640                                                   finfo->dobj.catId.oid);
9641         }
9642         else if (fout->remoteVersion >= 70100)
9643         {
9644                 appendPQExpBuffer(query,
9645                                                   "SELECT proretset, prosrc, probin, "
9646                                                   "null AS proallargtypes, "
9647                                                   "null AS proargmodes, "
9648                                                   "null AS proargnames, "
9649                                                   "false AS proiswindow, "
9650                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9651                                                   "proisstrict, "
9652                                                   "false AS prosecdef, "
9653                                                   "false AS proleakproof, "
9654                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9655                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9656                                                   "FROM pg_proc "
9657                                                   "WHERE oid = '%u'::oid",
9658                                                   finfo->dobj.catId.oid);
9659         }
9660         else
9661         {
9662                 appendPQExpBuffer(query,
9663                                                   "SELECT proretset, prosrc, probin, "
9664                                                   "null AS proallargtypes, "
9665                                                   "null AS proargmodes, "
9666                                                   "null AS proargnames, "
9667                                                   "false AS proiswindow, "
9668                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9669                                                   "false AS proisstrict, "
9670                                                   "false AS prosecdef, "
9671                                                   "false AS proleakproof, "
9672                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9673                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9674                                                   "FROM pg_proc "
9675                                                   "WHERE oid = '%u'::oid",
9676                                                   finfo->dobj.catId.oid);
9677         }
9678
9679         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9680
9681         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9682         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9683         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9684         if (fout->remoteVersion >= 80400)
9685         {
9686                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9687                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9688                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9689                 proallargtypes = proargmodes = proargnames = NULL;
9690         }
9691         else
9692         {
9693                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9694                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9695                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9696                 funcargs = funciargs = funcresult = NULL;
9697         }
9698         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9699         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9700         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9701         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9702         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9703         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9704         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9705         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9706         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9707
9708         /*
9709          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9710          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9711          * versions would set it to "-".  There are no known cases in which prosrc
9712          * is unused, so the tests below for "-" are probably useless.
9713          */
9714         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9715         {
9716                 appendPQExpBuffer(asPart, "AS ");
9717                 appendStringLiteralAH(asPart, probin, fout);
9718                 if (strcmp(prosrc, "-") != 0)
9719                 {
9720                         appendPQExpBuffer(asPart, ", ");
9721
9722                         /*
9723                          * where we have bin, use dollar quoting if allowed and src
9724                          * contains quote or backslash; else use regular quoting.
9725                          */
9726                         if (disable_dollar_quoting ||
9727                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9728                                 appendStringLiteralAH(asPart, prosrc, fout);
9729                         else
9730                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9731                 }
9732         }
9733         else
9734         {
9735                 if (strcmp(prosrc, "-") != 0)
9736                 {
9737                         appendPQExpBuffer(asPart, "AS ");
9738                         /* with no bin, dollar quote src unconditionally if allowed */
9739                         if (disable_dollar_quoting)
9740                                 appendStringLiteralAH(asPart, prosrc, fout);
9741                         else
9742                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9743                 }
9744         }
9745
9746         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9747
9748         if (proallargtypes && *proallargtypes)
9749         {
9750                 int                     nitems = 0;
9751
9752                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9753                         nitems < finfo->nargs)
9754                 {
9755                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9756                         if (allargtypes)
9757                                 free(allargtypes);
9758                         allargtypes = NULL;
9759                 }
9760                 else
9761                         nallargs = nitems;
9762         }
9763
9764         if (proargmodes && *proargmodes)
9765         {
9766                 int                     nitems = 0;
9767
9768                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9769                         nitems != nallargs)
9770                 {
9771                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9772                         if (argmodes)
9773                                 free(argmodes);
9774                         argmodes = NULL;
9775                 }
9776         }
9777
9778         if (proargnames && *proargnames)
9779         {
9780                 int                     nitems = 0;
9781
9782                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9783                         nitems != nallargs)
9784                 {
9785                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9786                         if (argnames)
9787                                 free(argnames);
9788                         argnames = NULL;
9789                 }
9790         }
9791
9792         if (proconfig && *proconfig)
9793         {
9794                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9795                 {
9796                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9797                         if (configitems)
9798                                 free(configitems);
9799                         configitems = NULL;
9800                         nconfigitems = 0;
9801                 }
9802         }
9803
9804         if (funcargs)
9805         {
9806                 /* 8.4 or later; we rely on server-side code for most of the work */
9807                 funcfullsig = format_function_arguments(finfo, funcargs);
9808                 funcsig = format_function_arguments(finfo, funciargs);
9809         }
9810         else
9811         {
9812                 /* pre-8.4, do it ourselves */
9813                 funcsig = format_function_arguments_old(fout,
9814                                                                                                 finfo, nallargs, allargtypes,
9815                                                                                                 argmodes, argnames);
9816                 funcfullsig = funcsig;
9817         }
9818
9819         funcsig_tag = format_function_signature(fout, finfo, false);
9820
9821         /*
9822          * DROP must be fully qualified in case same name appears in pg_catalog
9823          */
9824         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9825                                           fmtId(finfo->dobj.namespace->dobj.name),
9826                                           funcsig);
9827
9828         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9829         if (funcresult)
9830                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9831         else
9832         {
9833                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9834                                                                                    zeroAsOpaque);
9835                 appendPQExpBuffer(q, "RETURNS %s%s",
9836                                                   (proretset[0] == 't') ? "SETOF " : "",
9837                                                   rettypename);
9838                 free(rettypename);
9839         }
9840
9841         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9842
9843         if (proiswindow[0] == 't')
9844                 appendPQExpBuffer(q, " WINDOW");
9845
9846         if (provolatile[0] != PROVOLATILE_VOLATILE)
9847         {
9848                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9849                         appendPQExpBuffer(q, " IMMUTABLE");
9850                 else if (provolatile[0] == PROVOLATILE_STABLE)
9851                         appendPQExpBuffer(q, " STABLE");
9852                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9853                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9854                                                   finfo->dobj.name);
9855         }
9856
9857         if (proisstrict[0] == 't')
9858                 appendPQExpBuffer(q, " STRICT");
9859
9860         if (prosecdef[0] == 't')
9861                 appendPQExpBuffer(q, " SECURITY DEFINER");
9862
9863         if (proleakproof[0] == 't')
9864                 appendPQExpBuffer(q, " LEAKPROOF");
9865
9866         /*
9867          * COST and ROWS are emitted only if present and not default, so as not to
9868          * break backwards-compatibility of the dump without need.      Keep this code
9869          * in sync with the defaults in functioncmds.c.
9870          */
9871         if (strcmp(procost, "0") != 0)
9872         {
9873                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9874                 {
9875                         /* default cost is 1 */
9876                         if (strcmp(procost, "1") != 0)
9877                                 appendPQExpBuffer(q, " COST %s", procost);
9878                 }
9879                 else
9880                 {
9881                         /* default cost is 100 */
9882                         if (strcmp(procost, "100") != 0)
9883                                 appendPQExpBuffer(q, " COST %s", procost);
9884                 }
9885         }
9886         if (proretset[0] == 't' &&
9887                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9888                 appendPQExpBuffer(q, " ROWS %s", prorows);
9889
9890         for (i = 0; i < nconfigitems; i++)
9891         {
9892                 /* we feel free to scribble on configitems[] here */
9893                 char       *configitem = configitems[i];
9894                 char       *pos;
9895
9896                 pos = strchr(configitem, '=');
9897                 if (pos == NULL)
9898                         continue;
9899                 *pos++ = '\0';
9900                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9901
9902                 /*
9903                  * Some GUC variable names are 'LIST' type and hence must not be
9904                  * quoted.
9905                  */
9906                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9907                         || pg_strcasecmp(configitem, "search_path") == 0)
9908                         appendPQExpBuffer(q, "%s", pos);
9909                 else
9910                         appendStringLiteralAH(q, pos, fout);
9911         }
9912
9913         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9914
9915         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9916
9917         if (binary_upgrade)
9918                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9919
9920         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9921                                  funcsig_tag,
9922                                  finfo->dobj.namespace->dobj.name,
9923                                  NULL,
9924                                  finfo->rolname, false,
9925                                  "FUNCTION", SECTION_PRE_DATA,
9926                                  q->data, delqry->data, NULL,
9927                                  NULL, 0,
9928                                  NULL, NULL);
9929
9930         /* Dump Function Comments and Security Labels */
9931         dumpComment(fout, labelq->data,
9932                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9933                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9934         dumpSecLabel(fout, labelq->data,
9935                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9936                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9937
9938         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9939                         funcsig, NULL, funcsig_tag,
9940                         finfo->dobj.namespace->dobj.name,
9941                         finfo->rolname, finfo->proacl);
9942
9943         PQclear(res);
9944
9945         destroyPQExpBuffer(query);
9946         destroyPQExpBuffer(q);
9947         destroyPQExpBuffer(delqry);
9948         destroyPQExpBuffer(labelq);
9949         destroyPQExpBuffer(asPart);
9950         free(funcsig);
9951         free(funcsig_tag);
9952         if (allargtypes)
9953                 free(allargtypes);
9954         if (argmodes)
9955                 free(argmodes);
9956         if (argnames)
9957                 free(argnames);
9958         if (configitems)
9959                 free(configitems);
9960 }
9961
9962
9963 /*
9964  * Dump a user-defined cast
9965  */
9966 static void
9967 dumpCast(Archive *fout, CastInfo *cast)
9968 {
9969         PQExpBuffer defqry;
9970         PQExpBuffer delqry;
9971         PQExpBuffer labelq;
9972         FuncInfo   *funcInfo = NULL;
9973
9974         /* Skip if not to be dumped */
9975         if (!cast->dobj.dump || dataOnly)
9976                 return;
9977
9978         /* Cannot dump if we don't have the cast function's info */
9979         if (OidIsValid(cast->castfunc))
9980         {
9981                 funcInfo = findFuncByOid(cast->castfunc);
9982                 if (funcInfo == NULL)
9983                         return;
9984         }
9985
9986         /*
9987          * As per discussion we dump casts if one or more of the underlying
9988          * objects (the conversion function and the two data types) are not
9989          * builtin AND if all of the non-builtin objects are included in the dump.
9990          * Builtin meaning, the namespace name does not start with "pg_".
9991          *
9992          * However, for a cast that belongs to an extension, we must not use this
9993          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9994          */
9995         if (!cast->dobj.ext_member)
9996         {
9997                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9998                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9999
10000                 if (sourceInfo == NULL || targetInfo == NULL)
10001                         return;
10002
10003                 /*
10004                  * Skip this cast if all objects are from pg_
10005                  */
10006                 if ((funcInfo == NULL ||
10007                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
10008                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
10009                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
10010                         return;
10011
10012                 /*
10013                  * Skip cast if function isn't from pg_ and is not to be dumped.
10014                  */
10015                 if (funcInfo &&
10016                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10017                         !funcInfo->dobj.dump)
10018                         return;
10019
10020                 /*
10021                  * Same for the source type
10022                  */
10023                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10024                         !sourceInfo->dobj.dump)
10025                         return;
10026
10027                 /*
10028                  * and the target type.
10029                  */
10030                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10031                         !targetInfo->dobj.dump)
10032                         return;
10033         }
10034
10035         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
10036         selectSourceSchema(fout, "pg_catalog");
10037
10038         defqry = createPQExpBuffer();
10039         delqry = createPQExpBuffer();
10040         labelq = createPQExpBuffer();
10041
10042         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
10043                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10044                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10045
10046         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
10047                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10048                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10049
10050         switch (cast->castmethod)
10051         {
10052                 case COERCION_METHOD_BINARY:
10053                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
10054                         break;
10055                 case COERCION_METHOD_INOUT:
10056                         appendPQExpBuffer(defqry, "WITH INOUT");
10057                         break;
10058                 case COERCION_METHOD_FUNCTION:
10059                         if (funcInfo)
10060                         {
10061                                 char       *fsig = format_function_signature(fout, funcInfo, true);
10062
10063                                 /*
10064                                  * Always qualify the function name, in case it is not in
10065                                  * pg_catalog schema (format_function_signature won't qualify
10066                                  * it).
10067                                  */
10068                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
10069                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
10070                                 free(fsig);
10071                         }
10072                         else
10073                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
10074                         break;
10075                 default:
10076                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
10077         }
10078
10079         if (cast->castcontext == 'a')
10080                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
10081         else if (cast->castcontext == 'i')
10082                 appendPQExpBuffer(defqry, " AS IMPLICIT");
10083         appendPQExpBuffer(defqry, ";\n");
10084
10085         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
10086                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10087                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10088
10089         if (binary_upgrade)
10090                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
10091
10092         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
10093                                  labelq->data,
10094                                  "pg_catalog", NULL, "",
10095                                  false, "CAST", SECTION_PRE_DATA,
10096                                  defqry->data, delqry->data, NULL,
10097                                  NULL, 0,
10098                                  NULL, NULL);
10099
10100         /* Dump Cast Comments */
10101         dumpComment(fout, labelq->data,
10102                                 NULL, "",
10103                                 cast->dobj.catId, 0, cast->dobj.dumpId);
10104
10105         destroyPQExpBuffer(defqry);
10106         destroyPQExpBuffer(delqry);
10107         destroyPQExpBuffer(labelq);
10108 }
10109
10110 /*
10111  * dumpOpr
10112  *        write out a single operator definition
10113  */
10114 static void
10115 dumpOpr(Archive *fout, OprInfo *oprinfo)
10116 {
10117         PQExpBuffer query;
10118         PQExpBuffer q;
10119         PQExpBuffer delq;
10120         PQExpBuffer labelq;
10121         PQExpBuffer oprid;
10122         PQExpBuffer details;
10123         const char *name;
10124         PGresult   *res;
10125         int                     i_oprkind;
10126         int                     i_oprcode;
10127         int                     i_oprleft;
10128         int                     i_oprright;
10129         int                     i_oprcom;
10130         int                     i_oprnegate;
10131         int                     i_oprrest;
10132         int                     i_oprjoin;
10133         int                     i_oprcanmerge;
10134         int                     i_oprcanhash;
10135         char       *oprkind;
10136         char       *oprcode;
10137         char       *oprleft;
10138         char       *oprright;
10139         char       *oprcom;
10140         char       *oprnegate;
10141         char       *oprrest;
10142         char       *oprjoin;
10143         char       *oprcanmerge;
10144         char       *oprcanhash;
10145
10146         /* Skip if not to be dumped */
10147         if (!oprinfo->dobj.dump || dataOnly)
10148                 return;
10149
10150         /*
10151          * some operators are invalid because they were the result of user
10152          * defining operators before commutators exist
10153          */
10154         if (!OidIsValid(oprinfo->oprcode))
10155                 return;
10156
10157         query = createPQExpBuffer();
10158         q = createPQExpBuffer();
10159         delq = createPQExpBuffer();
10160         labelq = createPQExpBuffer();
10161         oprid = createPQExpBuffer();
10162         details = createPQExpBuffer();
10163
10164         /* Make sure we are in proper schema so regoperator works correctly */
10165         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
10166
10167         if (fout->remoteVersion >= 80300)
10168         {
10169                 appendPQExpBuffer(query, "SELECT oprkind, "
10170                                                   "oprcode::pg_catalog.regprocedure, "
10171                                                   "oprleft::pg_catalog.regtype, "
10172                                                   "oprright::pg_catalog.regtype, "
10173                                                   "oprcom::pg_catalog.regoperator, "
10174                                                   "oprnegate::pg_catalog.regoperator, "
10175                                                   "oprrest::pg_catalog.regprocedure, "
10176                                                   "oprjoin::pg_catalog.regprocedure, "
10177                                                   "oprcanmerge, oprcanhash "
10178                                                   "FROM pg_catalog.pg_operator "
10179                                                   "WHERE oid = '%u'::pg_catalog.oid",
10180                                                   oprinfo->dobj.catId.oid);
10181         }
10182         else if (fout->remoteVersion >= 70300)
10183         {
10184                 appendPQExpBuffer(query, "SELECT oprkind, "
10185                                                   "oprcode::pg_catalog.regprocedure, "
10186                                                   "oprleft::pg_catalog.regtype, "
10187                                                   "oprright::pg_catalog.regtype, "
10188                                                   "oprcom::pg_catalog.regoperator, "
10189                                                   "oprnegate::pg_catalog.regoperator, "
10190                                                   "oprrest::pg_catalog.regprocedure, "
10191                                                   "oprjoin::pg_catalog.regprocedure, "
10192                                                   "(oprlsortop != 0) AS oprcanmerge, "
10193                                                   "oprcanhash "
10194                                                   "FROM pg_catalog.pg_operator "
10195                                                   "WHERE oid = '%u'::pg_catalog.oid",
10196                                                   oprinfo->dobj.catId.oid);
10197         }
10198         else if (fout->remoteVersion >= 70100)
10199         {
10200                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10201                                                   "CASE WHEN oprleft = 0 THEN '-' "
10202                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
10203                                                   "CASE WHEN oprright = 0 THEN '-' "
10204                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
10205                                                   "oprcom, oprnegate, oprrest, oprjoin, "
10206                                                   "(oprlsortop != 0) AS oprcanmerge, "
10207                                                   "oprcanhash "
10208                                                   "FROM pg_operator "
10209                                                   "WHERE oid = '%u'::oid",
10210                                                   oprinfo->dobj.catId.oid);
10211         }
10212         else
10213         {
10214                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10215                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
10216                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
10217                                                   "CASE WHEN oprright = 0 THEN '-'::name "
10218                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
10219                                                   "oprcom, oprnegate, oprrest, oprjoin, "
10220                                                   "(oprlsortop != 0) AS oprcanmerge, "
10221                                                   "oprcanhash "
10222                                                   "FROM pg_operator "
10223                                                   "WHERE oid = '%u'::oid",
10224                                                   oprinfo->dobj.catId.oid);
10225         }
10226
10227         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10228
10229         i_oprkind = PQfnumber(res, "oprkind");
10230         i_oprcode = PQfnumber(res, "oprcode");
10231         i_oprleft = PQfnumber(res, "oprleft");
10232         i_oprright = PQfnumber(res, "oprright");
10233         i_oprcom = PQfnumber(res, "oprcom");
10234         i_oprnegate = PQfnumber(res, "oprnegate");
10235         i_oprrest = PQfnumber(res, "oprrest");
10236         i_oprjoin = PQfnumber(res, "oprjoin");
10237         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
10238         i_oprcanhash = PQfnumber(res, "oprcanhash");
10239
10240         oprkind = PQgetvalue(res, 0, i_oprkind);
10241         oprcode = PQgetvalue(res, 0, i_oprcode);
10242         oprleft = PQgetvalue(res, 0, i_oprleft);
10243         oprright = PQgetvalue(res, 0, i_oprright);
10244         oprcom = PQgetvalue(res, 0, i_oprcom);
10245         oprnegate = PQgetvalue(res, 0, i_oprnegate);
10246         oprrest = PQgetvalue(res, 0, i_oprrest);
10247         oprjoin = PQgetvalue(res, 0, i_oprjoin);
10248         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
10249         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
10250
10251         appendPQExpBuffer(details, "    PROCEDURE = %s",
10252                                           convertRegProcReference(fout, oprcode));
10253
10254         appendPQExpBuffer(oprid, "%s (",
10255                                           oprinfo->dobj.name);
10256
10257         /*
10258          * right unary means there's a left arg and left unary means there's a
10259          * right arg
10260          */
10261         if (strcmp(oprkind, "r") == 0 ||
10262                 strcmp(oprkind, "b") == 0)
10263         {
10264                 if (fout->remoteVersion >= 70100)
10265                         name = oprleft;
10266                 else
10267                         name = fmtId(oprleft);
10268                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
10269                 appendPQExpBuffer(oprid, "%s", name);
10270         }
10271         else
10272                 appendPQExpBuffer(oprid, "NONE");
10273
10274         if (strcmp(oprkind, "l") == 0 ||
10275                 strcmp(oprkind, "b") == 0)
10276         {
10277                 if (fout->remoteVersion >= 70100)
10278                         name = oprright;
10279                 else
10280                         name = fmtId(oprright);
10281                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
10282                 appendPQExpBuffer(oprid, ", %s)", name);
10283         }
10284         else
10285                 appendPQExpBuffer(oprid, ", NONE)");
10286
10287         name = convertOperatorReference(fout, oprcom);
10288         if (name)
10289                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
10290
10291         name = convertOperatorReference(fout, oprnegate);
10292         if (name)
10293                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
10294
10295         if (strcmp(oprcanmerge, "t") == 0)
10296                 appendPQExpBuffer(details, ",\n    MERGES");
10297
10298         if (strcmp(oprcanhash, "t") == 0)
10299                 appendPQExpBuffer(details, ",\n    HASHES");
10300
10301         name = convertRegProcReference(fout, oprrest);
10302         if (name)
10303                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
10304
10305         name = convertRegProcReference(fout, oprjoin);
10306         if (name)
10307                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
10308
10309         /*
10310          * DROP must be fully qualified in case same name appears in pg_catalog
10311          */
10312         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
10313                                           fmtId(oprinfo->dobj.namespace->dobj.name),
10314                                           oprid->data);
10315
10316         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
10317                                           oprinfo->dobj.name, details->data);
10318
10319         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
10320
10321         if (binary_upgrade)
10322                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
10323
10324         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
10325                                  oprinfo->dobj.name,
10326                                  oprinfo->dobj.namespace->dobj.name,
10327                                  NULL,
10328                                  oprinfo->rolname,
10329                                  false, "OPERATOR", SECTION_PRE_DATA,
10330                                  q->data, delq->data, NULL,
10331                                  NULL, 0,
10332                                  NULL, NULL);
10333
10334         /* Dump Operator Comments */
10335         dumpComment(fout, labelq->data,
10336                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
10337                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
10338
10339         PQclear(res);
10340
10341         destroyPQExpBuffer(query);
10342         destroyPQExpBuffer(q);
10343         destroyPQExpBuffer(delq);
10344         destroyPQExpBuffer(labelq);
10345         destroyPQExpBuffer(oprid);
10346         destroyPQExpBuffer(details);
10347 }
10348
10349 /*
10350  * Convert a function reference obtained from pg_operator
10351  *
10352  * Returns what to print, or NULL if function references is InvalidOid
10353  *
10354  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
10355  * argument-types part.  In prior versions, the input is a REGPROC display.
10356  */
10357 static const char *
10358 convertRegProcReference(Archive *fout, const char *proc)
10359 {
10360         /* In all cases "-" means a null reference */
10361         if (strcmp(proc, "-") == 0)
10362                 return NULL;
10363
10364         if (fout->remoteVersion >= 70300)
10365         {
10366                 char       *name;
10367                 char       *paren;
10368                 bool            inquote;
10369
10370                 name = pg_strdup(proc);
10371                 /* find non-double-quoted left paren */
10372                 inquote = false;
10373                 for (paren = name; *paren; paren++)
10374                 {
10375                         if (*paren == '(' && !inquote)
10376                         {
10377                                 *paren = '\0';
10378                                 break;
10379                         }
10380                         if (*paren == '"')
10381                                 inquote = !inquote;
10382                 }
10383                 return name;
10384         }
10385
10386         /* REGPROC before 7.3 does not quote its result */
10387         return fmtId(proc);
10388 }
10389
10390 /*
10391  * Convert an operator cross-reference obtained from pg_operator
10392  *
10393  * Returns what to print, or NULL to print nothing
10394  *
10395  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10396  * argument-types part, and add OPERATOR() decoration if the name is
10397  * schema-qualified.  In older versions, the input is just a numeric OID,
10398  * which we search our operator list for.
10399  */
10400 static const char *
10401 convertOperatorReference(Archive *fout, const char *opr)
10402 {
10403         OprInfo    *oprInfo;
10404
10405         /* In all cases "0" means a null reference */
10406         if (strcmp(opr, "0") == 0)
10407                 return NULL;
10408
10409         if (fout->remoteVersion >= 70300)
10410         {
10411                 char       *name;
10412                 char       *oname;
10413                 char       *ptr;
10414                 bool            inquote;
10415                 bool            sawdot;
10416
10417                 name = pg_strdup(opr);
10418                 /* find non-double-quoted left paren, and check for non-quoted dot */
10419                 inquote = false;
10420                 sawdot = false;
10421                 for (ptr = name; *ptr; ptr++)
10422                 {
10423                         if (*ptr == '"')
10424                                 inquote = !inquote;
10425                         else if (*ptr == '.' && !inquote)
10426                                 sawdot = true;
10427                         else if (*ptr == '(' && !inquote)
10428                         {
10429                                 *ptr = '\0';
10430                                 break;
10431                         }
10432                 }
10433                 /* If not schema-qualified, don't need to add OPERATOR() */
10434                 if (!sawdot)
10435                         return name;
10436                 oname = pg_malloc(strlen(name) + 11);
10437                 sprintf(oname, "OPERATOR(%s)", name);
10438                 free(name);
10439                 return oname;
10440         }
10441
10442         oprInfo = findOprByOid(atooid(opr));
10443         if (oprInfo == NULL)
10444         {
10445                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10446                                   opr);
10447                 return NULL;
10448         }
10449         return oprInfo->dobj.name;
10450 }
10451
10452 /*
10453  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10454  *
10455  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10456  * argument lists of these functions are predetermined.  Note that the
10457  * caller should ensure we are in the proper schema, because the results
10458  * are search path dependent!
10459  */
10460 static const char *
10461 convertTSFunction(Archive *fout, Oid funcOid)
10462 {
10463         char       *result;
10464         char            query[128];
10465         PGresult   *res;
10466
10467         snprintf(query, sizeof(query),
10468                          "SELECT '%u'::pg_catalog.regproc", funcOid);
10469         res = ExecuteSqlQueryForSingleRow(fout, query);
10470
10471         result = pg_strdup(PQgetvalue(res, 0, 0));
10472
10473         PQclear(res);
10474
10475         return result;
10476 }
10477
10478
10479 /*
10480  * dumpOpclass
10481  *        write out a single operator class definition
10482  */
10483 static void
10484 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10485 {
10486         PQExpBuffer query;
10487         PQExpBuffer q;
10488         PQExpBuffer delq;
10489         PQExpBuffer labelq;
10490         PGresult   *res;
10491         int                     ntups;
10492         int                     i_opcintype;
10493         int                     i_opckeytype;
10494         int                     i_opcdefault;
10495         int                     i_opcfamily;
10496         int                     i_opcfamilyname;
10497         int                     i_opcfamilynsp;
10498         int                     i_amname;
10499         int                     i_amopstrategy;
10500         int                     i_amopreqcheck;
10501         int                     i_amopopr;
10502         int                     i_sortfamily;
10503         int                     i_sortfamilynsp;
10504         int                     i_amprocnum;
10505         int                     i_amproc;
10506         int                     i_amproclefttype;
10507         int                     i_amprocrighttype;
10508         char       *opcintype;
10509         char       *opckeytype;
10510         char       *opcdefault;
10511         char       *opcfamily;
10512         char       *opcfamilyname;
10513         char       *opcfamilynsp;
10514         char       *amname;
10515         char       *amopstrategy;
10516         char       *amopreqcheck;
10517         char       *amopopr;
10518         char       *sortfamily;
10519         char       *sortfamilynsp;
10520         char       *amprocnum;
10521         char       *amproc;
10522         char       *amproclefttype;
10523         char       *amprocrighttype;
10524         bool            needComma;
10525         int                     i;
10526
10527         /* Skip if not to be dumped */
10528         if (!opcinfo->dobj.dump || dataOnly)
10529                 return;
10530
10531         /*
10532          * XXX currently we do not implement dumping of operator classes from
10533          * pre-7.3 databases.  This could be done but it seems not worth the
10534          * trouble.
10535          */
10536         if (fout->remoteVersion < 70300)
10537                 return;
10538
10539         query = createPQExpBuffer();
10540         q = createPQExpBuffer();
10541         delq = createPQExpBuffer();
10542         labelq = createPQExpBuffer();
10543
10544         /* Make sure we are in proper schema so regoperator works correctly */
10545         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10546
10547         /* Get additional fields from the pg_opclass row */
10548         if (fout->remoteVersion >= 80300)
10549         {
10550                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10551                                                   "opckeytype::pg_catalog.regtype, "
10552                                                   "opcdefault, opcfamily, "
10553                                                   "opfname AS opcfamilyname, "
10554                                                   "nspname AS opcfamilynsp, "
10555                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10556                                                   "FROM pg_catalog.pg_opclass c "
10557                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10558                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10559                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
10560                                                   opcinfo->dobj.catId.oid);
10561         }
10562         else
10563         {
10564                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10565                                                   "opckeytype::pg_catalog.regtype, "
10566                                                   "opcdefault, NULL AS opcfamily, "
10567                                                   "NULL AS opcfamilyname, "
10568                                                   "NULL AS opcfamilynsp, "
10569                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10570                                                   "FROM pg_catalog.pg_opclass "
10571                                                   "WHERE oid = '%u'::pg_catalog.oid",
10572                                                   opcinfo->dobj.catId.oid);
10573         }
10574
10575         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10576
10577         i_opcintype = PQfnumber(res, "opcintype");
10578         i_opckeytype = PQfnumber(res, "opckeytype");
10579         i_opcdefault = PQfnumber(res, "opcdefault");
10580         i_opcfamily = PQfnumber(res, "opcfamily");
10581         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10582         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10583         i_amname = PQfnumber(res, "amname");
10584
10585         opcintype = PQgetvalue(res, 0, i_opcintype);
10586         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10587         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10588         /* opcfamily will still be needed after we PQclear res */
10589         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10590         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10591         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10592         /* amname will still be needed after we PQclear res */
10593         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10594
10595         /*
10596          * DROP must be fully qualified in case same name appears in pg_catalog
10597          */
10598         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10599                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10600         appendPQExpBuffer(delq, ".%s",
10601                                           fmtId(opcinfo->dobj.name));
10602         appendPQExpBuffer(delq, " USING %s;\n",
10603                                           fmtId(amname));
10604
10605         /* Build the fixed portion of the CREATE command */
10606         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10607                                           fmtId(opcinfo->dobj.name));
10608         if (strcmp(opcdefault, "t") == 0)
10609                 appendPQExpBuffer(q, "DEFAULT ");
10610         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10611                                           opcintype,
10612                                           fmtId(amname));
10613         if (strlen(opcfamilyname) > 0 &&
10614                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10615                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10616         {
10617                 appendPQExpBuffer(q, " FAMILY ");
10618                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10619                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10620                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10621         }
10622         appendPQExpBuffer(q, " AS\n    ");
10623
10624         needComma = false;
10625
10626         if (strcmp(opckeytype, "-") != 0)
10627         {
10628                 appendPQExpBuffer(q, "STORAGE %s",
10629                                                   opckeytype);
10630                 needComma = true;
10631         }
10632
10633         PQclear(res);
10634
10635         /*
10636          * Now fetch and print the OPERATOR entries (pg_amop rows).
10637          *
10638          * Print only those opfamily members that are tied to the opclass by
10639          * pg_depend entries.
10640          *
10641          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10642          * older server's opclass in which it is used.  This is to avoid
10643          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10644          * older server and then reload into that old version.  This can go away
10645          * once 8.3 is so old as to not be of interest to anyone.
10646          */
10647         resetPQExpBuffer(query);
10648
10649         if (fout->remoteVersion >= 90100)
10650         {
10651                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10652                                                   "amopopr::pg_catalog.regoperator, "
10653                                                   "opfname AS sortfamily, "
10654                                                   "nspname AS sortfamilynsp "
10655                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10656                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10657                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10658                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10659                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10660                                                   "AND refobjid = '%u'::pg_catalog.oid "
10661                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10662                                                   "ORDER BY amopstrategy",
10663                                                   opcinfo->dobj.catId.oid,
10664                                                   opcfamily);
10665         }
10666         else if (fout->remoteVersion >= 80400)
10667         {
10668                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10669                                                   "amopopr::pg_catalog.regoperator, "
10670                                                   "NULL AS sortfamily, "
10671                                                   "NULL AS sortfamilynsp "
10672                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10673                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10674                                                   "AND refobjid = '%u'::pg_catalog.oid "
10675                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10676                                                   "AND objid = ao.oid "
10677                                                   "ORDER BY amopstrategy",
10678                                                   opcinfo->dobj.catId.oid);
10679         }
10680         else if (fout->remoteVersion >= 80300)
10681         {
10682                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10683                                                   "amopopr::pg_catalog.regoperator, "
10684                                                   "NULL AS sortfamily, "
10685                                                   "NULL AS sortfamilynsp "
10686                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10687                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10688                                                   "AND refobjid = '%u'::pg_catalog.oid "
10689                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10690                                                   "AND objid = ao.oid "
10691                                                   "ORDER BY amopstrategy",
10692                                                   opcinfo->dobj.catId.oid);
10693         }
10694         else
10695         {
10696                 /*
10697                  * Here, we print all entries since there are no opfamilies and hence
10698                  * no loose operators to worry about.
10699                  */
10700                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10701                                                   "amopopr::pg_catalog.regoperator, "
10702                                                   "NULL AS sortfamily, "
10703                                                   "NULL AS sortfamilynsp "
10704                                                   "FROM pg_catalog.pg_amop "
10705                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10706                                                   "ORDER BY amopstrategy",
10707                                                   opcinfo->dobj.catId.oid);
10708         }
10709
10710         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10711
10712         ntups = PQntuples(res);
10713
10714         i_amopstrategy = PQfnumber(res, "amopstrategy");
10715         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10716         i_amopopr = PQfnumber(res, "amopopr");
10717         i_sortfamily = PQfnumber(res, "sortfamily");
10718         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10719
10720         for (i = 0; i < ntups; i++)
10721         {
10722                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10723                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10724                 amopopr = PQgetvalue(res, i, i_amopopr);
10725                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10726                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10727
10728                 if (needComma)
10729                         appendPQExpBuffer(q, " ,\n    ");
10730
10731                 appendPQExpBuffer(q, "OPERATOR %s %s",
10732                                                   amopstrategy, amopopr);
10733
10734                 if (strlen(sortfamily) > 0)
10735                 {
10736                         appendPQExpBuffer(q, " FOR ORDER BY ");
10737                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10738                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10739                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10740                 }
10741
10742                 if (strcmp(amopreqcheck, "t") == 0)
10743                         appendPQExpBuffer(q, " RECHECK");
10744
10745                 needComma = true;
10746         }
10747
10748         PQclear(res);
10749
10750         /*
10751          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10752          *
10753          * Print only those opfamily members that are tied to the opclass by
10754          * pg_depend entries.
10755          *
10756          * We print the amproclefttype/amprocrighttype even though in most cases
10757          * the backend could deduce the right values, because of the corner case
10758          * of a btree sort support function for a cross-type comparison.  That's
10759          * only allowed in 9.2 and later, but for simplicity print them in all
10760          * versions that have the columns.
10761          */
10762         resetPQExpBuffer(query);
10763
10764         if (fout->remoteVersion >= 80300)
10765         {
10766                 appendPQExpBuffer(query, "SELECT amprocnum, "
10767                                                   "amproc::pg_catalog.regprocedure, "
10768                                                   "amproclefttype::pg_catalog.regtype, "
10769                                                   "amprocrighttype::pg_catalog.regtype "
10770                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10771                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10772                                                   "AND refobjid = '%u'::pg_catalog.oid "
10773                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10774                                                   "AND objid = ap.oid "
10775                                                   "ORDER BY amprocnum",
10776                                                   opcinfo->dobj.catId.oid);
10777         }
10778         else
10779         {
10780                 appendPQExpBuffer(query, "SELECT amprocnum, "
10781                                                   "amproc::pg_catalog.regprocedure, "
10782                                                   "'' AS amproclefttype, "
10783                                                   "'' AS amprocrighttype "
10784                                                   "FROM pg_catalog.pg_amproc "
10785                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10786                                                   "ORDER BY amprocnum",
10787                                                   opcinfo->dobj.catId.oid);
10788         }
10789
10790         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10791
10792         ntups = PQntuples(res);
10793
10794         i_amprocnum = PQfnumber(res, "amprocnum");
10795         i_amproc = PQfnumber(res, "amproc");
10796         i_amproclefttype = PQfnumber(res, "amproclefttype");
10797         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10798
10799         for (i = 0; i < ntups; i++)
10800         {
10801                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10802                 amproc = PQgetvalue(res, i, i_amproc);
10803                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10804                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10805
10806                 if (needComma)
10807                         appendPQExpBuffer(q, " ,\n    ");
10808
10809                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10810
10811                 if (*amproclefttype && *amprocrighttype)
10812                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10813
10814                 appendPQExpBuffer(q, " %s", amproc);
10815
10816                 needComma = true;
10817         }
10818
10819         PQclear(res);
10820
10821         appendPQExpBuffer(q, ";\n");
10822
10823         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10824                                           fmtId(opcinfo->dobj.name));
10825         appendPQExpBuffer(labelq, " USING %s",
10826                                           fmtId(amname));
10827
10828         if (binary_upgrade)
10829                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10830
10831         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10832                                  opcinfo->dobj.name,
10833                                  opcinfo->dobj.namespace->dobj.name,
10834                                  NULL,
10835                                  opcinfo->rolname,
10836                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10837                                  q->data, delq->data, NULL,
10838                                  NULL, 0,
10839                                  NULL, NULL);
10840
10841         /* Dump Operator Class Comments */
10842         dumpComment(fout, labelq->data,
10843                                 NULL, opcinfo->rolname,
10844                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10845
10846         free(amname);
10847         destroyPQExpBuffer(query);
10848         destroyPQExpBuffer(q);
10849         destroyPQExpBuffer(delq);
10850         destroyPQExpBuffer(labelq);
10851 }
10852
10853 /*
10854  * dumpOpfamily
10855  *        write out a single operator family definition
10856  *
10857  * Note: this also dumps any "loose" operator members that aren't bound to a
10858  * specific opclass within the opfamily.
10859  */
10860 static void
10861 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10862 {
10863         PQExpBuffer query;
10864         PQExpBuffer q;
10865         PQExpBuffer delq;
10866         PQExpBuffer labelq;
10867         PGresult   *res;
10868         PGresult   *res_ops;
10869         PGresult   *res_procs;
10870         int                     ntups;
10871         int                     i_amname;
10872         int                     i_amopstrategy;
10873         int                     i_amopreqcheck;
10874         int                     i_amopopr;
10875         int                     i_sortfamily;
10876         int                     i_sortfamilynsp;
10877         int                     i_amprocnum;
10878         int                     i_amproc;
10879         int                     i_amproclefttype;
10880         int                     i_amprocrighttype;
10881         char       *amname;
10882         char       *amopstrategy;
10883         char       *amopreqcheck;
10884         char       *amopopr;
10885         char       *sortfamily;
10886         char       *sortfamilynsp;
10887         char       *amprocnum;
10888         char       *amproc;
10889         char       *amproclefttype;
10890         char       *amprocrighttype;
10891         bool            needComma;
10892         int                     i;
10893
10894         /* Skip if not to be dumped */
10895         if (!opfinfo->dobj.dump || dataOnly)
10896                 return;
10897
10898         /*
10899          * We want to dump the opfamily only if (1) it contains "loose" operators
10900          * or functions, or (2) it contains an opclass with a different name or
10901          * owner.  Otherwise it's sufficient to let it be created during creation
10902          * of the contained opclass, and not dumping it improves portability of
10903          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10904          * that first.
10905          */
10906
10907         query = createPQExpBuffer();
10908         q = createPQExpBuffer();
10909         delq = createPQExpBuffer();
10910         labelq = createPQExpBuffer();
10911
10912         /* Make sure we are in proper schema so regoperator works correctly */
10913         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10914
10915         /*
10916          * Fetch only those opfamily members that are tied directly to the
10917          * opfamily by pg_depend entries.
10918          *
10919          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10920          * older server's opclass in which it is used.  This is to avoid
10921          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10922          * older server and then reload into that old version.  This can go away
10923          * once 8.3 is so old as to not be of interest to anyone.
10924          */
10925         if (fout->remoteVersion >= 90100)
10926         {
10927                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10928                                                   "amopopr::pg_catalog.regoperator, "
10929                                                   "opfname AS sortfamily, "
10930                                                   "nspname AS sortfamilynsp "
10931                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10932                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10933                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10934                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10935                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10936                                                   "AND refobjid = '%u'::pg_catalog.oid "
10937                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10938                                                   "ORDER BY amopstrategy",
10939                                                   opfinfo->dobj.catId.oid,
10940                                                   opfinfo->dobj.catId.oid);
10941         }
10942         else if (fout->remoteVersion >= 80400)
10943         {
10944                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10945                                                   "amopopr::pg_catalog.regoperator, "
10946                                                   "NULL AS sortfamily, "
10947                                                   "NULL AS sortfamilynsp "
10948                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10949                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10950                                                   "AND refobjid = '%u'::pg_catalog.oid "
10951                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10952                                                   "AND objid = ao.oid "
10953                                                   "ORDER BY amopstrategy",
10954                                                   opfinfo->dobj.catId.oid);
10955         }
10956         else
10957         {
10958                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10959                                                   "amopopr::pg_catalog.regoperator, "
10960                                                   "NULL AS sortfamily, "
10961                                                   "NULL AS sortfamilynsp "
10962                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10963                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10964                                                   "AND refobjid = '%u'::pg_catalog.oid "
10965                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10966                                                   "AND objid = ao.oid "
10967                                                   "ORDER BY amopstrategy",
10968                                                   opfinfo->dobj.catId.oid);
10969         }
10970
10971         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10972
10973         resetPQExpBuffer(query);
10974
10975         appendPQExpBuffer(query, "SELECT amprocnum, "
10976                                           "amproc::pg_catalog.regprocedure, "
10977                                           "amproclefttype::pg_catalog.regtype, "
10978                                           "amprocrighttype::pg_catalog.regtype "
10979                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10980                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10981                                           "AND refobjid = '%u'::pg_catalog.oid "
10982                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10983                                           "AND objid = ap.oid "
10984                                           "ORDER BY amprocnum",
10985                                           opfinfo->dobj.catId.oid);
10986
10987         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10988
10989         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10990         {
10991                 /* No loose members, so check contained opclasses */
10992                 resetPQExpBuffer(query);
10993
10994                 appendPQExpBuffer(query, "SELECT 1 "
10995                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10996                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10997                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10998                                                   "AND refobjid = f.oid "
10999                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
11000                                                   "AND objid = c.oid "
11001                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
11002                                                   "LIMIT 1",
11003                                                   opfinfo->dobj.catId.oid);
11004
11005                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11006
11007                 if (PQntuples(res) == 0)
11008                 {
11009                         /* no need to dump it, so bail out */
11010                         PQclear(res);
11011                         PQclear(res_ops);
11012                         PQclear(res_procs);
11013                         destroyPQExpBuffer(query);
11014                         destroyPQExpBuffer(q);
11015                         destroyPQExpBuffer(delq);
11016                         destroyPQExpBuffer(labelq);
11017                         return;
11018                 }
11019
11020                 PQclear(res);
11021         }
11022
11023         /* Get additional fields from the pg_opfamily row */
11024         resetPQExpBuffer(query);
11025
11026         appendPQExpBuffer(query, "SELECT "
11027          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
11028                                           "FROM pg_catalog.pg_opfamily "
11029                                           "WHERE oid = '%u'::pg_catalog.oid",
11030                                           opfinfo->dobj.catId.oid);
11031
11032         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11033
11034         i_amname = PQfnumber(res, "amname");
11035
11036         /* amname will still be needed after we PQclear res */
11037         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
11038
11039         /*
11040          * DROP must be fully qualified in case same name appears in pg_catalog
11041          */
11042         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
11043                                           fmtId(opfinfo->dobj.namespace->dobj.name));
11044         appendPQExpBuffer(delq, ".%s",
11045                                           fmtId(opfinfo->dobj.name));
11046         appendPQExpBuffer(delq, " USING %s;\n",
11047                                           fmtId(amname));
11048
11049         /* Build the fixed portion of the CREATE command */
11050         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
11051                                           fmtId(opfinfo->dobj.name));
11052         appendPQExpBuffer(q, " USING %s;\n",
11053                                           fmtId(amname));
11054
11055         PQclear(res);
11056
11057         /* Do we need an ALTER to add loose members? */
11058         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
11059         {
11060                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
11061                                                   fmtId(opfinfo->dobj.name));
11062                 appendPQExpBuffer(q, " USING %s ADD\n    ",
11063                                                   fmtId(amname));
11064
11065                 needComma = false;
11066
11067                 /*
11068                  * Now fetch and print the OPERATOR entries (pg_amop rows).
11069                  */
11070                 ntups = PQntuples(res_ops);
11071
11072                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
11073                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
11074                 i_amopopr = PQfnumber(res_ops, "amopopr");
11075                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
11076                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
11077
11078                 for (i = 0; i < ntups; i++)
11079                 {
11080                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
11081                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
11082                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
11083                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
11084                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
11085
11086                         if (needComma)
11087                                 appendPQExpBuffer(q, " ,\n    ");
11088
11089                         appendPQExpBuffer(q, "OPERATOR %s %s",
11090                                                           amopstrategy, amopopr);
11091
11092                         if (strlen(sortfamily) > 0)
11093                         {
11094                                 appendPQExpBuffer(q, " FOR ORDER BY ");
11095                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
11096                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
11097                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
11098                         }
11099
11100                         if (strcmp(amopreqcheck, "t") == 0)
11101                                 appendPQExpBuffer(q, " RECHECK");
11102
11103                         needComma = true;
11104                 }
11105
11106                 /*
11107                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
11108                  */
11109                 ntups = PQntuples(res_procs);
11110
11111                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
11112                 i_amproc = PQfnumber(res_procs, "amproc");
11113                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
11114                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
11115
11116                 for (i = 0; i < ntups; i++)
11117                 {
11118                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
11119                         amproc = PQgetvalue(res_procs, i, i_amproc);
11120                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
11121                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
11122
11123                         if (needComma)
11124                                 appendPQExpBuffer(q, " ,\n    ");
11125
11126                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
11127                                                           amprocnum, amproclefttype, amprocrighttype,
11128                                                           amproc);
11129
11130                         needComma = true;
11131                 }
11132
11133                 appendPQExpBuffer(q, ";\n");
11134         }
11135
11136         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
11137                                           fmtId(opfinfo->dobj.name));
11138         appendPQExpBuffer(labelq, " USING %s",
11139                                           fmtId(amname));
11140
11141         if (binary_upgrade)
11142                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
11143
11144         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
11145                                  opfinfo->dobj.name,
11146                                  opfinfo->dobj.namespace->dobj.name,
11147                                  NULL,
11148                                  opfinfo->rolname,
11149                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
11150                                  q->data, delq->data, NULL,
11151                                  NULL, 0,
11152                                  NULL, NULL);
11153
11154         /* Dump Operator Family Comments */
11155         dumpComment(fout, labelq->data,
11156                                 NULL, opfinfo->rolname,
11157                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
11158
11159         free(amname);
11160         PQclear(res_ops);
11161         PQclear(res_procs);
11162         destroyPQExpBuffer(query);
11163         destroyPQExpBuffer(q);
11164         destroyPQExpBuffer(delq);
11165         destroyPQExpBuffer(labelq);
11166 }
11167
11168 /*
11169  * dumpCollation
11170  *        write out a single collation definition
11171  */
11172 static void
11173 dumpCollation(Archive *fout, CollInfo *collinfo)
11174 {
11175         PQExpBuffer query;
11176         PQExpBuffer q;
11177         PQExpBuffer delq;
11178         PQExpBuffer labelq;
11179         PGresult   *res;
11180         int                     i_collcollate;
11181         int                     i_collctype;
11182         const char *collcollate;
11183         const char *collctype;
11184
11185         /* Skip if not to be dumped */
11186         if (!collinfo->dobj.dump || dataOnly)
11187                 return;
11188
11189         query = createPQExpBuffer();
11190         q = createPQExpBuffer();
11191         delq = createPQExpBuffer();
11192         labelq = createPQExpBuffer();
11193
11194         /* Make sure we are in proper schema */
11195         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
11196
11197         /* Get conversion-specific details */
11198         appendPQExpBuffer(query, "SELECT "
11199                                           "collcollate, "
11200                                           "collctype "
11201                                           "FROM pg_catalog.pg_collation c "
11202                                           "WHERE c.oid = '%u'::pg_catalog.oid",
11203                                           collinfo->dobj.catId.oid);
11204
11205         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11206
11207         i_collcollate = PQfnumber(res, "collcollate");
11208         i_collctype = PQfnumber(res, "collctype");
11209
11210         collcollate = PQgetvalue(res, 0, i_collcollate);
11211         collctype = PQgetvalue(res, 0, i_collctype);
11212
11213         /*
11214          * DROP must be fully qualified in case same name appears in pg_catalog
11215          */
11216         appendPQExpBuffer(delq, "DROP COLLATION %s",
11217                                           fmtId(collinfo->dobj.namespace->dobj.name));
11218         appendPQExpBuffer(delq, ".%s;\n",
11219                                           fmtId(collinfo->dobj.name));
11220
11221         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
11222                                           fmtId(collinfo->dobj.name));
11223         appendStringLiteralAH(q, collcollate, fout);
11224         appendPQExpBuffer(q, ", lc_ctype = ");
11225         appendStringLiteralAH(q, collctype, fout);
11226         appendPQExpBuffer(q, ");\n");
11227
11228         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
11229
11230         if (binary_upgrade)
11231                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
11232
11233         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
11234                                  collinfo->dobj.name,
11235                                  collinfo->dobj.namespace->dobj.name,
11236                                  NULL,
11237                                  collinfo->rolname,
11238                                  false, "COLLATION", SECTION_PRE_DATA,
11239                                  q->data, delq->data, NULL,
11240                                  NULL, 0,
11241                                  NULL, NULL);
11242
11243         /* Dump Collation Comments */
11244         dumpComment(fout, labelq->data,
11245                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
11246                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
11247
11248         PQclear(res);
11249
11250         destroyPQExpBuffer(query);
11251         destroyPQExpBuffer(q);
11252         destroyPQExpBuffer(delq);
11253         destroyPQExpBuffer(labelq);
11254 }
11255
11256 /*
11257  * dumpConversion
11258  *        write out a single conversion definition
11259  */
11260 static void
11261 dumpConversion(Archive *fout, ConvInfo *convinfo)
11262 {
11263         PQExpBuffer query;
11264         PQExpBuffer q;
11265         PQExpBuffer delq;
11266         PQExpBuffer labelq;
11267         PGresult   *res;
11268         int                     i_conforencoding;
11269         int                     i_contoencoding;
11270         int                     i_conproc;
11271         int                     i_condefault;
11272         const char *conforencoding;
11273         const char *contoencoding;
11274         const char *conproc;
11275         bool            condefault;
11276
11277         /* Skip if not to be dumped */
11278         if (!convinfo->dobj.dump || dataOnly)
11279                 return;
11280
11281         query = createPQExpBuffer();
11282         q = createPQExpBuffer();
11283         delq = createPQExpBuffer();
11284         labelq = createPQExpBuffer();
11285
11286         /* Make sure we are in proper schema */
11287         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
11288
11289         /* Get conversion-specific details */
11290         appendPQExpBuffer(query, "SELECT "
11291                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
11292                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
11293                                           "conproc, condefault "
11294                                           "FROM pg_catalog.pg_conversion c "
11295                                           "WHERE c.oid = '%u'::pg_catalog.oid",
11296                                           convinfo->dobj.catId.oid);
11297
11298         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11299
11300         i_conforencoding = PQfnumber(res, "conforencoding");
11301         i_contoencoding = PQfnumber(res, "contoencoding");
11302         i_conproc = PQfnumber(res, "conproc");
11303         i_condefault = PQfnumber(res, "condefault");
11304
11305         conforencoding = PQgetvalue(res, 0, i_conforencoding);
11306         contoencoding = PQgetvalue(res, 0, i_contoencoding);
11307         conproc = PQgetvalue(res, 0, i_conproc);
11308         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
11309
11310         /*
11311          * DROP must be fully qualified in case same name appears in pg_catalog
11312          */
11313         appendPQExpBuffer(delq, "DROP CONVERSION %s",
11314                                           fmtId(convinfo->dobj.namespace->dobj.name));
11315         appendPQExpBuffer(delq, ".%s;\n",
11316                                           fmtId(convinfo->dobj.name));
11317
11318         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
11319                                           (condefault) ? "DEFAULT " : "",
11320                                           fmtId(convinfo->dobj.name));
11321         appendStringLiteralAH(q, conforencoding, fout);
11322         appendPQExpBuffer(q, " TO ");
11323         appendStringLiteralAH(q, contoencoding, fout);
11324         /* regproc is automatically quoted in 7.3 and above */
11325         appendPQExpBuffer(q, " FROM %s;\n", conproc);
11326
11327         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
11328
11329         if (binary_upgrade)
11330                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
11331
11332         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
11333                                  convinfo->dobj.name,
11334                                  convinfo->dobj.namespace->dobj.name,
11335                                  NULL,
11336                                  convinfo->rolname,
11337                                  false, "CONVERSION", SECTION_PRE_DATA,
11338                                  q->data, delq->data, NULL,
11339                                  NULL, 0,
11340                                  NULL, NULL);
11341
11342         /* Dump Conversion Comments */
11343         dumpComment(fout, labelq->data,
11344                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
11345                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
11346
11347         PQclear(res);
11348
11349         destroyPQExpBuffer(query);
11350         destroyPQExpBuffer(q);
11351         destroyPQExpBuffer(delq);
11352         destroyPQExpBuffer(labelq);
11353 }
11354
11355 /*
11356  * format_aggregate_signature: generate aggregate name and argument list
11357  *
11358  * The argument type names are qualified if needed.  The aggregate name
11359  * is never qualified.
11360  */
11361 static char *
11362 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11363 {
11364         PQExpBufferData buf;
11365         int                     j;
11366
11367         initPQExpBuffer(&buf);
11368         if (honor_quotes)
11369                 appendPQExpBuffer(&buf, "%s",
11370                                                   fmtId(agginfo->aggfn.dobj.name));
11371         else
11372                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11373
11374         if (agginfo->aggfn.nargs == 0)
11375                 appendPQExpBuffer(&buf, "(*)");
11376         else
11377         {
11378                 appendPQExpBuffer(&buf, "(");
11379                 for (j = 0; j < agginfo->aggfn.nargs; j++)
11380                 {
11381                         char       *typname;
11382
11383                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11384                                                                                    zeroAsOpaque);
11385
11386                         appendPQExpBuffer(&buf, "%s%s",
11387                                                           (j > 0) ? ", " : "",
11388                                                           typname);
11389                         free(typname);
11390                 }
11391                 appendPQExpBuffer(&buf, ")");
11392         }
11393         return buf.data;
11394 }
11395
11396 /*
11397  * dumpAgg
11398  *        write out a single aggregate definition
11399  */
11400 static void
11401 dumpAgg(Archive *fout, AggInfo *agginfo)
11402 {
11403         PQExpBuffer query;
11404         PQExpBuffer q;
11405         PQExpBuffer delq;
11406         PQExpBuffer labelq;
11407         PQExpBuffer details;
11408         char       *aggsig;
11409         char       *aggsig_tag;
11410         PGresult   *res;
11411         int                     i_aggtransfn;
11412         int                     i_aggfinalfn;
11413         int                     i_aggsortop;
11414         int                     i_aggtranstype;
11415         int                     i_agginitval;
11416         int                     i_convertok;
11417         const char *aggtransfn;
11418         const char *aggfinalfn;
11419         const char *aggsortop;
11420         const char *aggtranstype;
11421         const char *agginitval;
11422         bool            convertok;
11423
11424         /* Skip if not to be dumped */
11425         if (!agginfo->aggfn.dobj.dump || dataOnly)
11426                 return;
11427
11428         query = createPQExpBuffer();
11429         q = createPQExpBuffer();
11430         delq = createPQExpBuffer();
11431         labelq = createPQExpBuffer();
11432         details = createPQExpBuffer();
11433
11434         /* Make sure we are in proper schema */
11435         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11436
11437         /* Get aggregate-specific details */
11438         if (fout->remoteVersion >= 80100)
11439         {
11440                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11441                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11442                                                   "aggsortop::pg_catalog.regoperator, "
11443                                                   "agginitval, "
11444                                                   "'t'::boolean AS convertok "
11445                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11446                                                   "WHERE a.aggfnoid = p.oid "
11447                                                   "AND p.oid = '%u'::pg_catalog.oid",
11448                                                   agginfo->aggfn.dobj.catId.oid);
11449         }
11450         else if (fout->remoteVersion >= 70300)
11451         {
11452                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11453                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11454                                                   "0 AS aggsortop, "
11455                                                   "agginitval, "
11456                                                   "'t'::boolean AS convertok "
11457                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11458                                                   "WHERE a.aggfnoid = p.oid "
11459                                                   "AND p.oid = '%u'::pg_catalog.oid",
11460                                                   agginfo->aggfn.dobj.catId.oid);
11461         }
11462         else if (fout->remoteVersion >= 70100)
11463         {
11464                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11465                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
11466                                                   "0 AS aggsortop, "
11467                                                   "agginitval, "
11468                                                   "'t'::boolean AS convertok "
11469                                                   "FROM pg_aggregate "
11470                                                   "WHERE oid = '%u'::oid",
11471                                                   agginfo->aggfn.dobj.catId.oid);
11472         }
11473         else
11474         {
11475                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11476                                                   "aggfinalfn, "
11477                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11478                                                   "0 AS aggsortop, "
11479                                                   "agginitval1 AS agginitval, "
11480                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11481                                                   "FROM pg_aggregate "
11482                                                   "WHERE oid = '%u'::oid",
11483                                                   agginfo->aggfn.dobj.catId.oid);
11484         }
11485
11486         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11487
11488         i_aggtransfn = PQfnumber(res, "aggtransfn");
11489         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11490         i_aggsortop = PQfnumber(res, "aggsortop");
11491         i_aggtranstype = PQfnumber(res, "aggtranstype");
11492         i_agginitval = PQfnumber(res, "agginitval");
11493         i_convertok = PQfnumber(res, "convertok");
11494
11495         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11496         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11497         aggsortop = PQgetvalue(res, 0, i_aggsortop);
11498         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11499         agginitval = PQgetvalue(res, 0, i_agginitval);
11500         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11501
11502         aggsig = format_aggregate_signature(agginfo, fout, true);
11503         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11504
11505         if (!convertok)
11506         {
11507                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11508                                   aggsig);
11509                 return;
11510         }
11511
11512         if (fout->remoteVersion >= 70300)
11513         {
11514                 /* If using 7.3's regproc or regtype, data is already quoted */
11515                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11516                                                   aggtransfn,
11517                                                   aggtranstype);
11518         }
11519         else if (fout->remoteVersion >= 70100)
11520         {
11521                 /* format_type quotes, regproc does not */
11522                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11523                                                   fmtId(aggtransfn),
11524                                                   aggtranstype);
11525         }
11526         else
11527         {
11528                 /* need quotes all around */
11529                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
11530                                                   fmtId(aggtransfn));
11531                 appendPQExpBuffer(details, "    STYPE = %s",
11532                                                   fmtId(aggtranstype));
11533         }
11534
11535         if (!PQgetisnull(res, 0, i_agginitval))
11536         {
11537                 appendPQExpBuffer(details, ",\n    INITCOND = ");
11538                 appendStringLiteralAH(details, agginitval, fout);
11539         }
11540
11541         if (strcmp(aggfinalfn, "-") != 0)
11542         {
11543                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
11544                                                   aggfinalfn);
11545         }
11546
11547         aggsortop = convertOperatorReference(fout, aggsortop);
11548         if (aggsortop)
11549         {
11550                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
11551                                                   aggsortop);
11552         }
11553
11554         /*
11555          * DROP must be fully qualified in case same name appears in pg_catalog
11556          */
11557         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11558                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11559                                           aggsig);
11560
11561         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11562                                           aggsig, details->data);
11563
11564         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11565
11566         if (binary_upgrade)
11567                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11568
11569         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11570                                  aggsig_tag,
11571                                  agginfo->aggfn.dobj.namespace->dobj.name,
11572                                  NULL,
11573                                  agginfo->aggfn.rolname,
11574                                  false, "AGGREGATE", SECTION_PRE_DATA,
11575                                  q->data, delq->data, NULL,
11576                                  NULL, 0,
11577                                  NULL, NULL);
11578
11579         /* Dump Aggregate Comments */
11580         dumpComment(fout, labelq->data,
11581                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11582                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11583         dumpSecLabel(fout, labelq->data,
11584                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11585                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11586
11587         /*
11588          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11589          * command look like a function's GRANT; in particular this affects the
11590          * syntax for zero-argument aggregates.
11591          */
11592         free(aggsig);
11593         free(aggsig_tag);
11594
11595         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11596         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11597
11598         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11599                         "FUNCTION",
11600                         aggsig, NULL, aggsig_tag,
11601                         agginfo->aggfn.dobj.namespace->dobj.name,
11602                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11603
11604         free(aggsig);
11605         free(aggsig_tag);
11606
11607         PQclear(res);
11608
11609         destroyPQExpBuffer(query);
11610         destroyPQExpBuffer(q);
11611         destroyPQExpBuffer(delq);
11612         destroyPQExpBuffer(labelq);
11613         destroyPQExpBuffer(details);
11614 }
11615
11616 /*
11617  * dumpTSParser
11618  *        write out a single text search parser
11619  */
11620 static void
11621 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11622 {
11623         PQExpBuffer q;
11624         PQExpBuffer delq;
11625         PQExpBuffer labelq;
11626
11627         /* Skip if not to be dumped */
11628         if (!prsinfo->dobj.dump || dataOnly)
11629                 return;
11630
11631         q = createPQExpBuffer();
11632         delq = createPQExpBuffer();
11633         labelq = createPQExpBuffer();
11634
11635         /* Make sure we are in proper schema */
11636         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11637
11638         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11639                                           fmtId(prsinfo->dobj.name));
11640
11641         appendPQExpBuffer(q, "    START = %s,\n",
11642                                           convertTSFunction(fout, prsinfo->prsstart));
11643         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11644                                           convertTSFunction(fout, prsinfo->prstoken));
11645         appendPQExpBuffer(q, "    END = %s,\n",
11646                                           convertTSFunction(fout, prsinfo->prsend));
11647         if (prsinfo->prsheadline != InvalidOid)
11648                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11649                                                   convertTSFunction(fout, prsinfo->prsheadline));
11650         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11651                                           convertTSFunction(fout, prsinfo->prslextype));
11652
11653         /*
11654          * DROP must be fully qualified in case same name appears in pg_catalog
11655          */
11656         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11657                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11658         appendPQExpBuffer(delq, ".%s;\n",
11659                                           fmtId(prsinfo->dobj.name));
11660
11661         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11662                                           fmtId(prsinfo->dobj.name));
11663
11664         if (binary_upgrade)
11665                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11666
11667         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11668                                  prsinfo->dobj.name,
11669                                  prsinfo->dobj.namespace->dobj.name,
11670                                  NULL,
11671                                  "",
11672                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11673                                  q->data, delq->data, NULL,
11674                                  NULL, 0,
11675                                  NULL, NULL);
11676
11677         /* Dump Parser Comments */
11678         dumpComment(fout, labelq->data,
11679                                 NULL, "",
11680                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11681
11682         destroyPQExpBuffer(q);
11683         destroyPQExpBuffer(delq);
11684         destroyPQExpBuffer(labelq);
11685 }
11686
11687 /*
11688  * dumpTSDictionary
11689  *        write out a single text search dictionary
11690  */
11691 static void
11692 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11693 {
11694         PQExpBuffer q;
11695         PQExpBuffer delq;
11696         PQExpBuffer labelq;
11697         PQExpBuffer query;
11698         PGresult   *res;
11699         char       *nspname;
11700         char       *tmplname;
11701
11702         /* Skip if not to be dumped */
11703         if (!dictinfo->dobj.dump || dataOnly)
11704                 return;
11705
11706         q = createPQExpBuffer();
11707         delq = createPQExpBuffer();
11708         labelq = createPQExpBuffer();
11709         query = createPQExpBuffer();
11710
11711         /* Fetch name and namespace of the dictionary's template */
11712         selectSourceSchema(fout, "pg_catalog");
11713         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11714                                           "FROM pg_ts_template p, pg_namespace n "
11715                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11716                                           dictinfo->dicttemplate);
11717         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11718         nspname = PQgetvalue(res, 0, 0);
11719         tmplname = PQgetvalue(res, 0, 1);
11720
11721         /* Make sure we are in proper schema */
11722         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11723
11724         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11725                                           fmtId(dictinfo->dobj.name));
11726
11727         appendPQExpBuffer(q, "    TEMPLATE = ");
11728         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11729                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11730         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11731
11732         PQclear(res);
11733
11734         /* the dictinitoption can be dumped straight into the command */
11735         if (dictinfo->dictinitoption)
11736                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11737
11738         appendPQExpBuffer(q, " );\n");
11739
11740         /*
11741          * DROP must be fully qualified in case same name appears in pg_catalog
11742          */
11743         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11744                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11745         appendPQExpBuffer(delq, ".%s;\n",
11746                                           fmtId(dictinfo->dobj.name));
11747
11748         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11749                                           fmtId(dictinfo->dobj.name));
11750
11751         if (binary_upgrade)
11752                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11753
11754         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11755                                  dictinfo->dobj.name,
11756                                  dictinfo->dobj.namespace->dobj.name,
11757                                  NULL,
11758                                  dictinfo->rolname,
11759                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11760                                  q->data, delq->data, NULL,
11761                                  NULL, 0,
11762                                  NULL, NULL);
11763
11764         /* Dump Dictionary Comments */
11765         dumpComment(fout, labelq->data,
11766                                 NULL, dictinfo->rolname,
11767                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11768
11769         destroyPQExpBuffer(q);
11770         destroyPQExpBuffer(delq);
11771         destroyPQExpBuffer(labelq);
11772         destroyPQExpBuffer(query);
11773 }
11774
11775 /*
11776  * dumpTSTemplate
11777  *        write out a single text search template
11778  */
11779 static void
11780 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11781 {
11782         PQExpBuffer q;
11783         PQExpBuffer delq;
11784         PQExpBuffer labelq;
11785
11786         /* Skip if not to be dumped */
11787         if (!tmplinfo->dobj.dump || dataOnly)
11788                 return;
11789
11790         q = createPQExpBuffer();
11791         delq = createPQExpBuffer();
11792         labelq = createPQExpBuffer();
11793
11794         /* Make sure we are in proper schema */
11795         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11796
11797         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11798                                           fmtId(tmplinfo->dobj.name));
11799
11800         if (tmplinfo->tmplinit != InvalidOid)
11801                 appendPQExpBuffer(q, "    INIT = %s,\n",
11802                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11803         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11804                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11805
11806         /*
11807          * DROP must be fully qualified in case same name appears in pg_catalog
11808          */
11809         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11810                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11811         appendPQExpBuffer(delq, ".%s;\n",
11812                                           fmtId(tmplinfo->dobj.name));
11813
11814         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11815                                           fmtId(tmplinfo->dobj.name));
11816
11817         if (binary_upgrade)
11818                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11819
11820         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11821                                  tmplinfo->dobj.name,
11822                                  tmplinfo->dobj.namespace->dobj.name,
11823                                  NULL,
11824                                  "",
11825                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11826                                  q->data, delq->data, NULL,
11827                                  NULL, 0,
11828                                  NULL, NULL);
11829
11830         /* Dump Template Comments */
11831         dumpComment(fout, labelq->data,
11832                                 NULL, "",
11833                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11834
11835         destroyPQExpBuffer(q);
11836         destroyPQExpBuffer(delq);
11837         destroyPQExpBuffer(labelq);
11838 }
11839
11840 /*
11841  * dumpTSConfig
11842  *        write out a single text search configuration
11843  */
11844 static void
11845 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11846 {
11847         PQExpBuffer q;
11848         PQExpBuffer delq;
11849         PQExpBuffer labelq;
11850         PQExpBuffer query;
11851         PGresult   *res;
11852         char       *nspname;
11853         char       *prsname;
11854         int                     ntups,
11855                                 i;
11856         int                     i_tokenname;
11857         int                     i_dictname;
11858
11859         /* Skip if not to be dumped */
11860         if (!cfginfo->dobj.dump || dataOnly)
11861                 return;
11862
11863         q = createPQExpBuffer();
11864         delq = createPQExpBuffer();
11865         labelq = createPQExpBuffer();
11866         query = createPQExpBuffer();
11867
11868         /* Fetch name and namespace of the config's parser */
11869         selectSourceSchema(fout, "pg_catalog");
11870         appendPQExpBuffer(query, "SELECT nspname, prsname "
11871                                           "FROM pg_ts_parser p, pg_namespace n "
11872                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11873                                           cfginfo->cfgparser);
11874         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11875         nspname = PQgetvalue(res, 0, 0);
11876         prsname = PQgetvalue(res, 0, 1);
11877
11878         /* Make sure we are in proper schema */
11879         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11880
11881         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11882                                           fmtId(cfginfo->dobj.name));
11883
11884         appendPQExpBuffer(q, "    PARSER = ");
11885         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11886                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11887         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11888
11889         PQclear(res);
11890
11891         resetPQExpBuffer(query);
11892         appendPQExpBuffer(query,
11893                                           "SELECT \n"
11894                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11895                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11896                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11897                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11898                                           "WHERE m.mapcfg = '%u' \n"
11899                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11900                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11901
11902         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11903         ntups = PQntuples(res);
11904
11905         i_tokenname = PQfnumber(res, "tokenname");
11906         i_dictname = PQfnumber(res, "dictname");
11907
11908         for (i = 0; i < ntups; i++)
11909         {
11910                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11911                 char       *dictname = PQgetvalue(res, i, i_dictname);
11912
11913                 if (i == 0 ||
11914                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11915                 {
11916                         /* starting a new token type, so start a new command */
11917                         if (i > 0)
11918                                 appendPQExpBuffer(q, ";\n");
11919                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11920                                                           fmtId(cfginfo->dobj.name));
11921                         /* tokenname needs quoting, dictname does NOT */
11922                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11923                                                           fmtId(tokenname), dictname);
11924                 }
11925                 else
11926                         appendPQExpBuffer(q, ", %s", dictname);
11927         }
11928
11929         if (ntups > 0)
11930                 appendPQExpBuffer(q, ";\n");
11931
11932         PQclear(res);
11933
11934         /*
11935          * DROP must be fully qualified in case same name appears in pg_catalog
11936          */
11937         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11938                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11939         appendPQExpBuffer(delq, ".%s;\n",
11940                                           fmtId(cfginfo->dobj.name));
11941
11942         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11943                                           fmtId(cfginfo->dobj.name));
11944
11945         if (binary_upgrade)
11946                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11947
11948         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11949                                  cfginfo->dobj.name,
11950                                  cfginfo->dobj.namespace->dobj.name,
11951                                  NULL,
11952                                  cfginfo->rolname,
11953                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11954                                  q->data, delq->data, NULL,
11955                                  NULL, 0,
11956                                  NULL, NULL);
11957
11958         /* Dump Configuration Comments */
11959         dumpComment(fout, labelq->data,
11960                                 NULL, cfginfo->rolname,
11961                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11962
11963         destroyPQExpBuffer(q);
11964         destroyPQExpBuffer(delq);
11965         destroyPQExpBuffer(labelq);
11966         destroyPQExpBuffer(query);
11967 }
11968
11969 /*
11970  * dumpForeignDataWrapper
11971  *        write out a single foreign-data wrapper definition
11972  */
11973 static void
11974 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11975 {
11976         PQExpBuffer q;
11977         PQExpBuffer delq;
11978         PQExpBuffer labelq;
11979         char       *qfdwname;
11980
11981         /* Skip if not to be dumped */
11982         if (!fdwinfo->dobj.dump || dataOnly)
11983                 return;
11984
11985         /*
11986          * FDWs that belong to an extension are dumped based on their "dump"
11987          * field. Otherwise omit them if we are only dumping some specific object.
11988          */
11989         if (!fdwinfo->dobj.ext_member)
11990                 if (!include_everything)
11991                         return;
11992
11993         q = createPQExpBuffer();
11994         delq = createPQExpBuffer();
11995         labelq = createPQExpBuffer();
11996
11997         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11998
11999         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
12000                                           qfdwname);
12001
12002         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
12003                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
12004
12005         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
12006                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
12007
12008         if (strlen(fdwinfo->fdwoptions) > 0)
12009                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
12010
12011         appendPQExpBuffer(q, ";\n");
12012
12013         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
12014                                           qfdwname);
12015
12016         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
12017                                           qfdwname);
12018
12019         if (binary_upgrade)
12020                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
12021
12022         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12023                                  fdwinfo->dobj.name,
12024                                  NULL,
12025                                  NULL,
12026                                  fdwinfo->rolname,
12027                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
12028                                  q->data, delq->data, NULL,
12029                                  NULL, 0,
12030                                  NULL, NULL);
12031
12032         /* Handle the ACL */
12033         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12034                         "FOREIGN DATA WRAPPER",
12035                         qfdwname, NULL, fdwinfo->dobj.name,
12036                         NULL, fdwinfo->rolname,
12037                         fdwinfo->fdwacl);
12038
12039         /* Dump Foreign Data Wrapper Comments */
12040         dumpComment(fout, labelq->data,
12041                                 NULL, fdwinfo->rolname,
12042                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
12043
12044         free(qfdwname);
12045
12046         destroyPQExpBuffer(q);
12047         destroyPQExpBuffer(delq);
12048         destroyPQExpBuffer(labelq);
12049 }
12050
12051 /*
12052  * dumpForeignServer
12053  *        write out a foreign server definition
12054  */
12055 static void
12056 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
12057 {
12058         PQExpBuffer q;
12059         PQExpBuffer delq;
12060         PQExpBuffer labelq;
12061         PQExpBuffer query;
12062         PGresult   *res;
12063         char       *qsrvname;
12064         char       *fdwname;
12065
12066         /* Skip if not to be dumped */
12067         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
12068                 return;
12069
12070         q = createPQExpBuffer();
12071         delq = createPQExpBuffer();
12072         labelq = createPQExpBuffer();
12073         query = createPQExpBuffer();
12074
12075         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
12076
12077         /* look up the foreign-data wrapper */
12078         selectSourceSchema(fout, "pg_catalog");
12079         appendPQExpBuffer(query, "SELECT fdwname "
12080                                           "FROM pg_foreign_data_wrapper w "
12081                                           "WHERE w.oid = '%u'",
12082                                           srvinfo->srvfdw);
12083         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12084         fdwname = PQgetvalue(res, 0, 0);
12085
12086         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
12087         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
12088         {
12089                 appendPQExpBuffer(q, " TYPE ");
12090                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
12091         }
12092         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
12093         {
12094                 appendPQExpBuffer(q, " VERSION ");
12095                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
12096         }
12097
12098         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
12099         appendPQExpBuffer(q, "%s", fmtId(fdwname));
12100
12101         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
12102                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
12103
12104         appendPQExpBuffer(q, ";\n");
12105
12106         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
12107                                           qsrvname);
12108
12109         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
12110
12111         if (binary_upgrade)
12112                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
12113
12114         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12115                                  srvinfo->dobj.name,
12116                                  NULL,
12117                                  NULL,
12118                                  srvinfo->rolname,
12119                                  false, "SERVER", SECTION_PRE_DATA,
12120                                  q->data, delq->data, NULL,
12121                                  NULL, 0,
12122                                  NULL, NULL);
12123
12124         /* Handle the ACL */
12125         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12126                         "FOREIGN SERVER",
12127                         qsrvname, NULL, srvinfo->dobj.name,
12128                         NULL, srvinfo->rolname,
12129                         srvinfo->srvacl);
12130
12131         /* Dump user mappings */
12132         dumpUserMappings(fout,
12133                                          srvinfo->dobj.name, NULL,
12134                                          srvinfo->rolname,
12135                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
12136
12137         /* Dump Foreign Server Comments */
12138         dumpComment(fout, labelq->data,
12139                                 NULL, srvinfo->rolname,
12140                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
12141
12142         free(qsrvname);
12143
12144         destroyPQExpBuffer(q);
12145         destroyPQExpBuffer(delq);
12146         destroyPQExpBuffer(labelq);
12147 }
12148
12149 /*
12150  * dumpUserMappings
12151  *
12152  * This routine is used to dump any user mappings associated with the
12153  * server handed to this routine. Should be called after ArchiveEntry()
12154  * for the server.
12155  */
12156 static void
12157 dumpUserMappings(Archive *fout,
12158                                  const char *servername, const char *namespace,
12159                                  const char *owner,
12160                                  CatalogId catalogId, DumpId dumpId)
12161 {
12162         PQExpBuffer q;
12163         PQExpBuffer delq;
12164         PQExpBuffer query;
12165         PQExpBuffer tag;
12166         PGresult   *res;
12167         int                     ntups;
12168         int                     i_usename;
12169         int                     i_umoptions;
12170         int                     i;
12171
12172         q = createPQExpBuffer();
12173         tag = createPQExpBuffer();
12174         delq = createPQExpBuffer();
12175         query = createPQExpBuffer();
12176
12177         /*
12178          * We read from the publicly accessible view pg_user_mappings, so as not
12179          * to fail if run by a non-superuser.  Note that the view will show
12180          * umoptions as null if the user hasn't got privileges for the associated
12181          * server; this means that pg_dump will dump such a mapping, but with no
12182          * OPTIONS clause.      A possible alternative is to skip such mappings
12183          * altogether, but it's not clear that that's an improvement.
12184          */
12185         selectSourceSchema(fout, "pg_catalog");
12186
12187         appendPQExpBuffer(query,
12188                                           "SELECT usename, "
12189                                           "array_to_string(ARRAY("
12190                                           "SELECT quote_ident(option_name) || ' ' || "
12191                                           "quote_literal(option_value) "
12192                                           "FROM pg_options_to_table(umoptions) "
12193                                           "ORDER BY option_name"
12194                                           "), E',\n    ') AS umoptions "
12195                                           "FROM pg_user_mappings "
12196                                           "WHERE srvid = '%u' "
12197                                           "ORDER BY usename",
12198                                           catalogId.oid);
12199
12200         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12201
12202         ntups = PQntuples(res);
12203         i_usename = PQfnumber(res, "usename");
12204         i_umoptions = PQfnumber(res, "umoptions");
12205
12206         for (i = 0; i < ntups; i++)
12207         {
12208                 char       *usename;
12209                 char       *umoptions;
12210
12211                 usename = PQgetvalue(res, i, i_usename);
12212                 umoptions = PQgetvalue(res, i, i_umoptions);
12213
12214                 resetPQExpBuffer(q);
12215                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
12216                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
12217
12218                 if (umoptions && strlen(umoptions) > 0)
12219                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
12220
12221                 appendPQExpBuffer(q, ";\n");
12222
12223                 resetPQExpBuffer(delq);
12224                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
12225                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
12226
12227                 resetPQExpBuffer(tag);
12228                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
12229                                                   usename, servername);
12230
12231                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12232                                          tag->data,
12233                                          namespace,
12234                                          NULL,
12235                                          owner, false,
12236                                          "USER MAPPING", SECTION_PRE_DATA,
12237                                          q->data, delq->data, NULL,
12238                                          &dumpId, 1,
12239                                          NULL, NULL);
12240         }
12241
12242         PQclear(res);
12243
12244         destroyPQExpBuffer(query);
12245         destroyPQExpBuffer(delq);
12246         destroyPQExpBuffer(q);
12247 }
12248
12249 /*
12250  * Write out default privileges information
12251  */
12252 static void
12253 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
12254 {
12255         PQExpBuffer q;
12256         PQExpBuffer tag;
12257         const char *type;
12258
12259         /* Skip if not to be dumped */
12260         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
12261                 return;
12262
12263         q = createPQExpBuffer();
12264         tag = createPQExpBuffer();
12265
12266         switch (daclinfo->defaclobjtype)
12267         {
12268                 case DEFACLOBJ_RELATION:
12269                         type = "TABLES";
12270                         break;
12271                 case DEFACLOBJ_SEQUENCE:
12272                         type = "SEQUENCES";
12273                         break;
12274                 case DEFACLOBJ_FUNCTION:
12275                         type = "FUNCTIONS";
12276                         break;
12277                 case DEFACLOBJ_TYPE:
12278                         type = "TYPES";
12279                         break;
12280                 default:
12281                         /* shouldn't get here */
12282                         exit_horribly(NULL,
12283                                           "unrecognized object type in default privileges: %d\n",
12284                                                   (int) daclinfo->defaclobjtype);
12285                         type = "";                      /* keep compiler quiet */
12286         }
12287
12288         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
12289
12290         /* build the actual command(s) for this tuple */
12291         if (!buildDefaultACLCommands(type,
12292                                                                  daclinfo->dobj.namespace != NULL ?
12293                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
12294                                                                  daclinfo->defaclacl,
12295                                                                  daclinfo->defaclrole,
12296                                                                  fout->remoteVersion,
12297                                                                  q))
12298                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
12299                                           daclinfo->defaclacl);
12300
12301         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
12302                                  tag->data,
12303            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
12304                                  NULL,
12305                                  daclinfo->defaclrole,
12306                                  false, "DEFAULT ACL", SECTION_POST_DATA,
12307                                  q->data, "", NULL,
12308                                  NULL, 0,
12309                                  NULL, NULL);
12310
12311         destroyPQExpBuffer(tag);
12312         destroyPQExpBuffer(q);
12313 }
12314
12315 /*----------
12316  * Write out grant/revoke information
12317  *
12318  * 'objCatId' is the catalog ID of the underlying object.
12319  * 'objDumpId' is the dump ID of the underlying object.
12320  * 'type' must be one of
12321  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
12322  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
12323  * 'name' is the formatted name of the object.  Must be quoted etc. already.
12324  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
12325  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12326  * 'nspname' is the namespace the object is in (NULL if none).
12327  * 'owner' is the owner, NULL if there is no owner (for languages).
12328  * 'acls' is the string read out of the fooacl system catalog field;
12329  *              it will be parsed here.
12330  *----------
12331  */
12332 static void
12333 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12334                 const char *type, const char *name, const char *subname,
12335                 const char *tag, const char *nspname, const char *owner,
12336                 const char *acls)
12337 {
12338         PQExpBuffer sql;
12339
12340         /* Do nothing if ACL dump is not enabled */
12341         if (aclsSkip)
12342                 return;
12343
12344         /* --data-only skips ACLs *except* BLOB ACLs */
12345         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12346                 return;
12347
12348         sql = createPQExpBuffer();
12349
12350         if (!buildACLCommands(name, subname, type, acls, owner,
12351                                                   "", fout->remoteVersion, sql))
12352                 exit_horribly(NULL,
12353                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12354                                           acls, name, type);
12355
12356         if (sql->len > 0)
12357                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12358                                          tag, nspname,
12359                                          NULL,
12360                                          owner ? owner : "",
12361                                          false, "ACL", SECTION_NONE,
12362                                          sql->data, "", NULL,
12363                                          &(objDumpId), 1,
12364                                          NULL, NULL);
12365
12366         destroyPQExpBuffer(sql);
12367 }
12368
12369 /*
12370  * dumpSecLabel
12371  *
12372  * This routine is used to dump any security labels associated with the
12373  * object handed to this routine. The routine takes a constant character
12374  * string for the target part of the security-label command, plus
12375  * the namespace and owner of the object (for labeling the ArchiveEntry),
12376  * plus catalog ID and subid which are the lookup key for pg_seclabel,
12377  * plus the dump ID for the object (for setting a dependency).
12378  * If a matching pg_seclabel entry is found, it is dumped.
12379  *
12380  * Note: although this routine takes a dumpId for dependency purposes,
12381  * that purpose is just to mark the dependency in the emitted dump file
12382  * for possible future use by pg_restore.  We do NOT use it for determining
12383  * ordering of the label in the dump file, because this routine is called
12384  * after dependency sorting occurs.  This routine should be called just after
12385  * calling ArchiveEntry() for the specified object.
12386  */
12387 static void
12388 dumpSecLabel(Archive *fout, const char *target,
12389                          const char *namespace, const char *owner,
12390                          CatalogId catalogId, int subid, DumpId dumpId)
12391 {
12392         SecLabelItem *labels;
12393         int                     nlabels;
12394         int                     i;
12395         PQExpBuffer query;
12396
12397         /* do nothing, if --no-security-labels is supplied */
12398         if (no_security_labels)
12399                 return;
12400
12401         /* Comments are schema not data ... except blob comments are data */
12402         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12403         {
12404                 if (dataOnly)
12405                         return;
12406         }
12407         else
12408         {
12409                 if (schemaOnly)
12410                         return;
12411         }
12412
12413         /* Search for security labels associated with catalogId, using table */
12414         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12415
12416         query = createPQExpBuffer();
12417
12418         for (i = 0; i < nlabels; i++)
12419         {
12420                 /*
12421                  * Ignore label entries for which the subid doesn't match.
12422                  */
12423                 if (labels[i].objsubid != subid)
12424                         continue;
12425
12426                 appendPQExpBuffer(query,
12427                                                   "SECURITY LABEL FOR %s ON %s IS ",
12428                                                   fmtId(labels[i].provider), target);
12429                 appendStringLiteralAH(query, labels[i].label, fout);
12430                 appendPQExpBuffer(query, ";\n");
12431         }
12432
12433         if (query->len > 0)
12434         {
12435                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12436                                          target, namespace, NULL, owner,
12437                                          false, "SECURITY LABEL", SECTION_NONE,
12438                                          query->data, "", NULL,
12439                                          &(dumpId), 1,
12440                                          NULL, NULL);
12441         }
12442         destroyPQExpBuffer(query);
12443 }
12444
12445 /*
12446  * dumpTableSecLabel
12447  *
12448  * As above, but dump security label for both the specified table (or view)
12449  * and its columns.
12450  */
12451 static void
12452 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12453 {
12454         SecLabelItem *labels;
12455         int                     nlabels;
12456         int                     i;
12457         PQExpBuffer query;
12458         PQExpBuffer target;
12459
12460         /* do nothing, if --no-security-labels is supplied */
12461         if (no_security_labels)
12462                 return;
12463
12464         /* SecLabel are SCHEMA not data */
12465         if (dataOnly)
12466                 return;
12467
12468         /* Search for comments associated with relation, using table */
12469         nlabels = findSecLabels(fout,
12470                                                         tbinfo->dobj.catId.tableoid,
12471                                                         tbinfo->dobj.catId.oid,
12472                                                         &labels);
12473
12474         /* If security labels exist, build SECURITY LABEL statements */
12475         if (nlabels <= 0)
12476                 return;
12477
12478         query = createPQExpBuffer();
12479         target = createPQExpBuffer();
12480
12481         for (i = 0; i < nlabels; i++)
12482         {
12483                 const char *colname;
12484                 const char *provider = labels[i].provider;
12485                 const char *label = labels[i].label;
12486                 int                     objsubid = labels[i].objsubid;
12487
12488                 resetPQExpBuffer(target);
12489                 if (objsubid == 0)
12490                 {
12491                         appendPQExpBuffer(target, "%s %s", reltypename,
12492                                                           fmtId(tbinfo->dobj.name));
12493                 }
12494                 else
12495                 {
12496                         colname = getAttrName(objsubid, tbinfo);
12497                         /* first fmtId result must be consumed before calling it again */
12498                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12499                         appendPQExpBuffer(target, ".%s", fmtId(colname));
12500                 }
12501                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12502                                                   fmtId(provider), target->data);
12503                 appendStringLiteralAH(query, label, fout);
12504                 appendPQExpBuffer(query, ";\n");
12505         }
12506         if (query->len > 0)
12507         {
12508                 resetPQExpBuffer(target);
12509                 appendPQExpBuffer(target, "%s %s", reltypename,
12510                                                   fmtId(tbinfo->dobj.name));
12511                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12512                                          target->data,
12513                                          tbinfo->dobj.namespace->dobj.name,
12514                                          NULL, tbinfo->rolname,
12515                                          false, "SECURITY LABEL", SECTION_NONE,
12516                                          query->data, "", NULL,
12517                                          &(tbinfo->dobj.dumpId), 1,
12518                                          NULL, NULL);
12519         }
12520         destroyPQExpBuffer(query);
12521         destroyPQExpBuffer(target);
12522 }
12523
12524 /*
12525  * findSecLabels
12526  *
12527  * Find the security label(s), if any, associated with the given object.
12528  * All the objsubid values associated with the given classoid/objoid are
12529  * found with one search.
12530  */
12531 static int
12532 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12533 {
12534         /* static storage for table of security labels */
12535         static SecLabelItem *labels = NULL;
12536         static int      nlabels = -1;
12537
12538         SecLabelItem *middle = NULL;
12539         SecLabelItem *low;
12540         SecLabelItem *high;
12541         int                     nmatch;
12542
12543         /* Get security labels if we didn't already */
12544         if (nlabels < 0)
12545                 nlabels = collectSecLabels(fout, &labels);
12546
12547         if (nlabels <= 0)                       /* no labels, so no match is possible */
12548         {
12549                 *items = NULL;
12550                 return 0;
12551         }
12552
12553         /*
12554          * Do binary search to find some item matching the object.
12555          */
12556         low = &labels[0];
12557         high = &labels[nlabels - 1];
12558         while (low <= high)
12559         {
12560                 middle = low + (high - low) / 2;
12561
12562                 if (classoid < middle->classoid)
12563                         high = middle - 1;
12564                 else if (classoid > middle->classoid)
12565                         low = middle + 1;
12566                 else if (objoid < middle->objoid)
12567                         high = middle - 1;
12568                 else if (objoid > middle->objoid)
12569                         low = middle + 1;
12570                 else
12571                         break;                          /* found a match */
12572         }
12573
12574         if (low > high)                         /* no matches */
12575         {
12576                 *items = NULL;
12577                 return 0;
12578         }
12579
12580         /*
12581          * Now determine how many items match the object.  The search loop
12582          * invariant still holds: only items between low and high inclusive could
12583          * match.
12584          */
12585         nmatch = 1;
12586         while (middle > low)
12587         {
12588                 if (classoid != middle[-1].classoid ||
12589                         objoid != middle[-1].objoid)
12590                         break;
12591                 middle--;
12592                 nmatch++;
12593         }
12594
12595         *items = middle;
12596
12597         middle += nmatch;
12598         while (middle <= high)
12599         {
12600                 if (classoid != middle->classoid ||
12601                         objoid != middle->objoid)
12602                         break;
12603                 middle++;
12604                 nmatch++;
12605         }
12606
12607         return nmatch;
12608 }
12609
12610 /*
12611  * collectSecLabels
12612  *
12613  * Construct a table of all security labels available for database objects.
12614  * It's much faster to pull them all at once.
12615  *
12616  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12617  */
12618 static int
12619 collectSecLabels(Archive *fout, SecLabelItem **items)
12620 {
12621         PGresult   *res;
12622         PQExpBuffer query;
12623         int                     i_label;
12624         int                     i_provider;
12625         int                     i_classoid;
12626         int                     i_objoid;
12627         int                     i_objsubid;
12628         int                     ntups;
12629         int                     i;
12630         SecLabelItem *labels;
12631
12632         query = createPQExpBuffer();
12633
12634         appendPQExpBuffer(query,
12635                                           "SELECT label, provider, classoid, objoid, objsubid "
12636                                           "FROM pg_catalog.pg_seclabel "
12637                                           "ORDER BY classoid, objoid, objsubid");
12638
12639         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12640
12641         /* Construct lookup table containing OIDs in numeric form */
12642         i_label = PQfnumber(res, "label");
12643         i_provider = PQfnumber(res, "provider");
12644         i_classoid = PQfnumber(res, "classoid");
12645         i_objoid = PQfnumber(res, "objoid");
12646         i_objsubid = PQfnumber(res, "objsubid");
12647
12648         ntups = PQntuples(res);
12649
12650         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12651
12652         for (i = 0; i < ntups; i++)
12653         {
12654                 labels[i].label = PQgetvalue(res, i, i_label);
12655                 labels[i].provider = PQgetvalue(res, i, i_provider);
12656                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12657                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12658                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12659         }
12660
12661         /* Do NOT free the PGresult since we are keeping pointers into it */
12662         destroyPQExpBuffer(query);
12663
12664         *items = labels;
12665         return ntups;
12666 }
12667
12668 /*
12669  * dumpTable
12670  *        write out to fout the declarations (not data) of a user-defined table
12671  */
12672 static void
12673 dumpTable(Archive *fout, TableInfo *tbinfo)
12674 {
12675         if (tbinfo->dobj.dump && !dataOnly)
12676         {
12677                 char       *namecopy;
12678
12679                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12680                         dumpSequence(fout, tbinfo);
12681                 else
12682                         dumpTableSchema(fout, tbinfo);
12683
12684                 /* Handle the ACL here */
12685                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12686                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12687                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12688                                 "TABLE",
12689                                 namecopy, NULL, tbinfo->dobj.name,
12690                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12691                                 tbinfo->relacl);
12692
12693                 /*
12694                  * Handle column ACLs, if any.  Note: we pull these with a separate
12695                  * query rather than trying to fetch them during getTableAttrs, so
12696                  * that we won't miss ACLs on system columns.
12697                  */
12698                 if (fout->remoteVersion >= 80400)
12699                 {
12700                         PQExpBuffer query = createPQExpBuffer();
12701                         PGresult   *res;
12702                         int                     i;
12703
12704                         appendPQExpBuffer(query,
12705                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12706                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12707                                                           "ORDER BY attnum",
12708                                                           tbinfo->dobj.catId.oid);
12709                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12710
12711                         for (i = 0; i < PQntuples(res); i++)
12712                         {
12713                                 char       *attname = PQgetvalue(res, i, 0);
12714                                 char       *attacl = PQgetvalue(res, i, 1);
12715                                 char       *attnamecopy;
12716                                 char       *acltag;
12717
12718                                 attnamecopy = pg_strdup(fmtId(attname));
12719                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12720                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12721                                 /* Column's GRANT type is always TABLE */
12722                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12723                                                 namecopy, attnamecopy, acltag,
12724                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12725                                                 attacl);
12726                                 free(attnamecopy);
12727                                 free(acltag);
12728                         }
12729                         PQclear(res);
12730                         destroyPQExpBuffer(query);
12731                 }
12732
12733                 free(namecopy);
12734         }
12735 }
12736
12737 /*
12738  * Create the AS clause for a view or materialized view. The semicolon is
12739  * stripped because a materialized view must add a WITH NO DATA clause.
12740  *
12741  * This returns a new buffer which must be freed by the caller.
12742  */
12743 static PQExpBuffer
12744 createViewAsClause(Archive *fout, TableInfo *tbinfo)
12745 {
12746         PQExpBuffer query = createPQExpBuffer();
12747         PQExpBuffer result = createPQExpBuffer();
12748         PGresult   *res;
12749         int                     len;
12750
12751         /* Fetch the view definition */
12752         if (fout->remoteVersion >= 70300)
12753         {
12754                 /* Beginning in 7.3, viewname is not unique; rely on OID */
12755                 appendPQExpBuffer(query,
12756                  "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12757                                                   tbinfo->dobj.catId.oid);
12758         }
12759         else
12760         {
12761                 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12762                                                   "FROM pg_views WHERE viewname = ");
12763                 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12764                 appendPQExpBuffer(query, ";");
12765         }
12766
12767         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12768
12769         if (PQntuples(res) != 1)
12770         {
12771                 if (PQntuples(res) < 1)
12772                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12773                                                   tbinfo->dobj.name);
12774                 else
12775                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12776                                                   tbinfo->dobj.name);
12777         }
12778
12779         len = PQgetlength(res, 0, 0);
12780
12781         if (len == 0)
12782                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12783                                           tbinfo->dobj.name);
12784
12785         /* Strip off the trailing semicolon so that other things may follow. */
12786         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
12787         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
12788
12789         PQclear(res);
12790         destroyPQExpBuffer(query);
12791
12792         return result;
12793 }
12794
12795 /*
12796  * dumpTableSchema
12797  *        write the declaration (not data) of one user-defined table or view
12798  */
12799 static void
12800 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12801 {
12802         PQExpBuffer q = createPQExpBuffer();
12803         PQExpBuffer delq = createPQExpBuffer();
12804         PQExpBuffer labelq = createPQExpBuffer();
12805         int                     numParents;
12806         TableInfo **parents;
12807         int                     actual_atts;    /* number of attrs in this CREATE statement */
12808         const char *reltypename;
12809         char       *storage;
12810         char       *srvname;
12811         char       *ftoptions;
12812         int                     j,
12813                                 k;
12814
12815         /* Make sure we are in proper schema */
12816         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12817
12818         if (binary_upgrade)
12819                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12820                                                                                                 tbinfo->dobj.catId.oid);
12821
12822         /* Is it a table or a view? */
12823         if (tbinfo->relkind == RELKIND_VIEW)
12824         {
12825                 PQExpBuffer result;
12826
12827                 reltypename = "VIEW";
12828
12829                 /*
12830                  * DROP must be fully qualified in case same name appears in
12831                  * pg_catalog
12832                  */
12833                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12834                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12835                 appendPQExpBuffer(delq, "%s;\n",
12836                                                   fmtId(tbinfo->dobj.name));
12837
12838                 if (binary_upgrade)
12839                         binary_upgrade_set_pg_class_oids(fout, q,
12840                                                                                          tbinfo->dobj.catId.oid, false);
12841
12842                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12843                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12844                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12845                 result = createViewAsClause(fout, tbinfo);
12846                 appendPQExpBuffer(q, " AS\n%s", result->data);
12847                 destroyPQExpBuffer(result);
12848
12849                 if (tbinfo->checkoption != NULL)
12850                         appendPQExpBuffer(q, "\n  WITH %s CHECK OPTION", tbinfo->checkoption);
12851                 appendPQExpBuffer(q, ";\n");
12852
12853                 appendPQExpBuffer(labelq, "VIEW %s",
12854                                                   fmtId(tbinfo->dobj.name));
12855         }
12856         else
12857         {
12858                 switch (tbinfo->relkind)
12859                 {
12860                         case (RELKIND_FOREIGN_TABLE):
12861                                 {
12862                                         PQExpBuffer query = createPQExpBuffer();
12863                                         PGresult   *res;
12864                                         int                     i_srvname;
12865                                         int                     i_ftoptions;
12866
12867                                         reltypename = "FOREIGN TABLE";
12868
12869                                         /* retrieve name of foreign server and generic options */
12870                                         appendPQExpBuffer(query,
12871                                                                           "SELECT fs.srvname, "
12872                                                                           "pg_catalog.array_to_string(ARRAY("
12873                                                          "SELECT pg_catalog.quote_ident(option_name) || "
12874                                                          "' ' || pg_catalog.quote_literal(option_value) "
12875                                                         "FROM pg_catalog.pg_options_to_table(ftoptions) "
12876                                                                           "ORDER BY option_name"
12877                                                                           "), E',\n    ') AS ftoptions "
12878                                                                           "FROM pg_catalog.pg_foreign_table ft "
12879                                                                           "JOIN pg_catalog.pg_foreign_server fs "
12880                                                                           "ON (fs.oid = ft.ftserver) "
12881                                                                           "WHERE ft.ftrelid = '%u'",
12882                                                                           tbinfo->dobj.catId.oid);
12883                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12884                                         i_srvname = PQfnumber(res, "srvname");
12885                                         i_ftoptions = PQfnumber(res, "ftoptions");
12886                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12887                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12888                                         PQclear(res);
12889                                         destroyPQExpBuffer(query);
12890                                         break;
12891                                 }
12892                         case (RELKIND_MATVIEW):
12893                                 reltypename = "MATERIALIZED VIEW";
12894                                 srvname = NULL;
12895                                 ftoptions = NULL;
12896                                 break;
12897                         default:
12898                                 reltypename = "TABLE";
12899                                 srvname = NULL;
12900                                 ftoptions = NULL;
12901                 }
12902
12903                 numParents = tbinfo->numParents;
12904                 parents = tbinfo->parents;
12905
12906                 /*
12907                  * DROP must be fully qualified in case same name appears in
12908                  * pg_catalog
12909                  */
12910                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12911                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12912                 appendPQExpBuffer(delq, "%s;\n",
12913                                                   fmtId(tbinfo->dobj.name));
12914
12915                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12916                                                   fmtId(tbinfo->dobj.name));
12917
12918                 if (binary_upgrade)
12919                         binary_upgrade_set_pg_class_oids(fout, q,
12920                                                                                          tbinfo->dobj.catId.oid, false);
12921
12922                 appendPQExpBuffer(q, "CREATE %s%s %s",
12923                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12924                                                   "UNLOGGED " : "",
12925                                                   reltypename,
12926                                                   fmtId(tbinfo->dobj.name));
12927
12928                 /*
12929                  * Attach to type, if reloftype; except in case of a binary upgrade,
12930                  * we dump the table normally and attach it to the type afterward.
12931                  */
12932                 if (tbinfo->reloftype && !binary_upgrade)
12933                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12934
12935                 if (tbinfo->relkind != RELKIND_MATVIEW)
12936                 {
12937                         /* Dump the attributes */
12938                         actual_atts = 0;
12939                         for (j = 0; j < tbinfo->numatts; j++)
12940                         {
12941                                 /*
12942                                  * Normally, dump if it's locally defined in this table, and
12943                                  * not dropped.  But for binary upgrade, we'll dump all the
12944                                  * columns, and then fix up the dropped and nonlocal cases
12945                                  * below.
12946                                  */
12947                                 if (shouldPrintColumn(tbinfo, j))
12948                                 {
12949                                         /*
12950                                          * Default value --- suppress if to be printed separately.
12951                                          */
12952                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12953                                                                                          !tbinfo->attrdefs[j]->separate);
12954
12955                                         /*
12956                                          * Not Null constraint --- suppress if inherited, except
12957                                          * in binary-upgrade case where that won't work.
12958                                          */
12959                                         bool            has_notnull = (tbinfo->notnull[j] &&
12960                                                                                            (!tbinfo->inhNotNull[j] ||
12961                                                                                                 binary_upgrade));
12962
12963                                         /* Skip column if fully defined by reloftype */
12964                                         if (tbinfo->reloftype &&
12965                                                 !has_default && !has_notnull && !binary_upgrade)
12966                                                 continue;
12967
12968                                         /* Format properly if not first attr */
12969                                         if (actual_atts == 0)
12970                                                 appendPQExpBuffer(q, " (");
12971                                         else
12972                                                 appendPQExpBuffer(q, ",");
12973                                         appendPQExpBuffer(q, "\n    ");
12974                                         actual_atts++;
12975
12976                                         /* Attribute name */
12977                                         appendPQExpBuffer(q, "%s",
12978                                                                           fmtId(tbinfo->attnames[j]));
12979
12980                                         if (tbinfo->attisdropped[j])
12981                                         {
12982                                                 /*
12983                                                  * ALTER TABLE DROP COLUMN clears
12984                                                  * pg_attribute.atttypid, so we will not have gotten a
12985                                                  * valid type name; insert INTEGER as a stopgap. We'll
12986                                                  * clean things up later.
12987                                                  */
12988                                                 appendPQExpBuffer(q, " INTEGER /* dummy */");
12989                                                 /* Skip all the rest, too */
12990                                                 continue;
12991                                         }
12992
12993                                         /* Attribute type */
12994                                         if (tbinfo->reloftype && !binary_upgrade)
12995                                         {
12996                                                 appendPQExpBuffer(q, " WITH OPTIONS");
12997                                         }
12998                                         else if (fout->remoteVersion >= 70100)
12999                                         {
13000                                                 appendPQExpBuffer(q, " %s",
13001                                                                                   tbinfo->atttypnames[j]);
13002                                         }
13003                                         else
13004                                         {
13005                                                 /* If no format_type, fake it */
13006                                                 appendPQExpBuffer(q, " %s",
13007                                                                                   myFormatType(tbinfo->atttypnames[j],
13008                                                                                                            tbinfo->atttypmod[j]));
13009                                         }
13010
13011                                         /* Add collation if not default for the type */
13012                                         if (OidIsValid(tbinfo->attcollation[j]))
13013                                         {
13014                                                 CollInfo   *coll;
13015
13016                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
13017                                                 if (coll)
13018                                                 {
13019                                                         /* always schema-qualify, don't try to be smart */
13020                                                         appendPQExpBuffer(q, " COLLATE %s.",
13021                                                                          fmtId(coll->dobj.namespace->dobj.name));
13022                                                         appendPQExpBuffer(q, "%s",
13023                                                                                           fmtId(coll->dobj.name));
13024                                                 }
13025                                         }
13026
13027                                         if (has_default)
13028                                                 appendPQExpBuffer(q, " DEFAULT %s",
13029                                                                                   tbinfo->attrdefs[j]->adef_expr);
13030
13031                                         if (has_notnull)
13032                                                 appendPQExpBuffer(q, " NOT NULL");
13033                                 }
13034                         }
13035
13036                         /*
13037                          * Add non-inherited CHECK constraints, if any.
13038                          */
13039                         for (j = 0; j < tbinfo->ncheck; j++)
13040                         {
13041                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13042
13043                                 if (constr->separate || !constr->conislocal)
13044                                         continue;
13045
13046                                 if (actual_atts == 0)
13047                                         appendPQExpBuffer(q, " (\n    ");
13048                                 else
13049                                         appendPQExpBuffer(q, ",\n    ");
13050
13051                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
13052                                                                   fmtId(constr->dobj.name));
13053                                 appendPQExpBuffer(q, "%s", constr->condef);
13054
13055                                 actual_atts++;
13056                         }
13057
13058                         if (actual_atts)
13059                                 appendPQExpBuffer(q, "\n)");
13060                         else if (!(tbinfo->reloftype && !binary_upgrade))
13061                         {
13062                                 /*
13063                                  * We must have a parenthesized attribute list, even though
13064                                  * empty, when not using the OF TYPE syntax.
13065                                  */
13066                                 appendPQExpBuffer(q, " (\n)");
13067                         }
13068
13069                         if (numParents > 0 && !binary_upgrade)
13070                         {
13071                                 appendPQExpBuffer(q, "\nINHERITS (");
13072                                 for (k = 0; k < numParents; k++)
13073                                 {
13074                                         TableInfo  *parentRel = parents[k];
13075
13076                                         if (k > 0)
13077                                                 appendPQExpBuffer(q, ", ");
13078                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13079                                                 appendPQExpBuffer(q, "%s.",
13080                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
13081                                         appendPQExpBuffer(q, "%s",
13082                                                                           fmtId(parentRel->dobj.name));
13083                                 }
13084                                 appendPQExpBuffer(q, ")");
13085                         }
13086
13087                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
13088                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
13089                 }
13090
13091                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
13092                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
13093                 {
13094                         bool            addcomma = false;
13095
13096                         appendPQExpBuffer(q, "\nWITH (");
13097                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
13098                         {
13099                                 addcomma = true;
13100                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
13101                         }
13102                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
13103                         {
13104                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
13105                                                                   tbinfo->toast_reloptions);
13106                         }
13107                         appendPQExpBuffer(q, ")");
13108                 }
13109
13110                 /* Dump generic options if any */
13111                 if (ftoptions && ftoptions[0])
13112                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
13113
13114                 /*
13115                  * For materialized views, create the AS clause just like a view. At
13116                  * this point, we always mark the view as not populated.
13117                  */
13118                 if (tbinfo->relkind == RELKIND_MATVIEW)
13119                 {
13120                         PQExpBuffer result;
13121
13122                         result = createViewAsClause(fout, tbinfo);
13123                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
13124                                                           result->data);
13125                         destroyPQExpBuffer(result);
13126                 }
13127                 else
13128                         appendPQExpBuffer(q, ";\n");
13129
13130                 /*
13131                  * To create binary-compatible heap files, we have to ensure the same
13132                  * physical column order, including dropped columns, as in the
13133                  * original.  Therefore, we create dropped columns above and drop them
13134                  * here, also updating their attlen/attalign values so that the
13135                  * dropped column can be skipped properly.      (We do not bother with
13136                  * restoring the original attbyval setting.)  Also, inheritance
13137                  * relationships are set up by doing ALTER INHERIT rather than using
13138                  * an INHERITS clause --- the latter would possibly mess up the column
13139                  * order.  That also means we have to take care about setting
13140                  * attislocal correctly, plus fix up any inherited CHECK constraints.
13141                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
13142                  */
13143                 if (binary_upgrade && (tbinfo->relkind == RELKIND_RELATION ||
13144                                                            tbinfo->relkind == RELKIND_FOREIGN_TABLE) )
13145                 {
13146                         for (j = 0; j < tbinfo->numatts; j++)
13147                         {
13148                                 if (tbinfo->attisdropped[j])
13149                                 {
13150                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
13151                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13152                                                                           "SET attlen = %d, "
13153                                                                           "attalign = '%c', attbyval = false\n"
13154                                                                           "WHERE attname = ",
13155                                                                           tbinfo->attlen[j],
13156                                                                           tbinfo->attalign[j]);
13157                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13158                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
13159                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13160                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13161
13162                                         if (tbinfo->relkind == RELKIND_RELATION)
13163                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13164                                                                                   fmtId(tbinfo->dobj.name));
13165                                         else
13166                                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13167                                                                                   fmtId(tbinfo->dobj.name));
13168
13169                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
13170                                                                           fmtId(tbinfo->attnames[j]));
13171                                 }
13172                                 else if (!tbinfo->attislocal[j])
13173                                 {
13174                                         Assert(tbinfo->relkind != RELKIND_FOREIGN_TABLE);
13175                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
13176                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13177                                                                           "SET attislocal = false\n"
13178                                                                           "WHERE attname = ");
13179                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13180                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
13181                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13182                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13183                                 }
13184                         }
13185
13186                         for (k = 0; k < tbinfo->ncheck; k++)
13187                         {
13188                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
13189
13190                                 if (constr->separate || constr->conislocal)
13191                                         continue;
13192
13193                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
13194                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13195                                                                   fmtId(tbinfo->dobj.name));
13196                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13197                                                                   fmtId(constr->dobj.name));
13198                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
13199                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
13200                                                                   "SET conislocal = false\n"
13201                                                                   "WHERE contype = 'c' AND conname = ");
13202                                 appendStringLiteralAH(q, constr->dobj.name, fout);
13203                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
13204                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13205                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13206                         }
13207
13208                         if (numParents > 0)
13209                         {
13210                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
13211                                 for (k = 0; k < numParents; k++)
13212                                 {
13213                                         TableInfo  *parentRel = parents[k];
13214
13215                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
13216                                                                           fmtId(tbinfo->dobj.name));
13217                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13218                                                 appendPQExpBuffer(q, "%s.",
13219                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
13220                                         appendPQExpBuffer(q, "%s;\n",
13221                                                                           fmtId(parentRel->dobj.name));
13222                                 }
13223                         }
13224
13225                         if (tbinfo->reloftype)
13226                         {
13227                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
13228                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
13229                                                                   fmtId(tbinfo->dobj.name),
13230                                                                   tbinfo->reloftype);
13231                         }
13232
13233                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
13234                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13235                                                           "SET relfrozenxid = '%u'\n"
13236                                                           "WHERE oid = ",
13237                                                           tbinfo->frozenxid);
13238                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13239                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13240
13241                         if (tbinfo->toast_oid)
13242                         {
13243                                 /* We preserve the toast oids, so we can use it during restore */
13244                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
13245                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13246                                                                   "SET relfrozenxid = '%u'\n"
13247                                                                   "WHERE oid = '%u';\n",
13248                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
13249                         }
13250                 }
13251
13252                 /*
13253                  * In binary_upgrade mode, restore matviews' populated status by
13254                  * poking pg_class directly.  This is pretty ugly, but we can't use
13255                  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
13256                  * matview is not populated even though this matview is.
13257                  */
13258                 if (binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
13259                         tbinfo->relispopulated)
13260                 {
13261                         appendPQExpBuffer(q, "\n-- For binary upgrade, mark materialized view as populated\n");
13262                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13263                                                           "SET relispopulated = 't'\n"
13264                                                           "WHERE oid = ");
13265                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13266                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13267                 }
13268
13269                 /*
13270                  * Dump additional per-column properties that we can't handle in the
13271                  * main CREATE TABLE command.
13272                  */
13273                 for (j = 0; j < tbinfo->numatts; j++)
13274                 {
13275                         /* None of this applies to dropped columns */
13276                         if (tbinfo->attisdropped[j])
13277                                 continue;
13278
13279                         /*
13280                          * If we didn't dump the column definition explicitly above, and
13281                          * it is NOT NULL and did not inherit that property from a parent,
13282                          * we have to mark it separately.
13283                          */
13284                         if (!shouldPrintColumn(tbinfo, j) &&
13285                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
13286                         {
13287                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13288                                                                   fmtId(tbinfo->dobj.name));
13289                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
13290                                                                   fmtId(tbinfo->attnames[j]));
13291                         }
13292
13293                         /*
13294                          * Dump per-column statistics information. We only issue an ALTER
13295                          * TABLE statement if the attstattarget entry for this column is
13296                          * non-negative (i.e. it's not the default value)
13297                          */
13298                         if (tbinfo->attstattarget[j] >= 0)
13299                         {
13300                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13301                                                                   fmtId(tbinfo->dobj.name));
13302                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13303                                                                   fmtId(tbinfo->attnames[j]));
13304                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
13305                                                                   tbinfo->attstattarget[j]);
13306                         }
13307
13308                         /*
13309                          * Dump per-column storage information.  The statement is only
13310                          * dumped if the storage has been changed from the type's default.
13311                          */
13312                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
13313                         {
13314                                 switch (tbinfo->attstorage[j])
13315                                 {
13316                                         case 'p':
13317                                                 storage = "PLAIN";
13318                                                 break;
13319                                         case 'e':
13320                                                 storage = "EXTERNAL";
13321                                                 break;
13322                                         case 'm':
13323                                                 storage = "MAIN";
13324                                                 break;
13325                                         case 'x':
13326                                                 storage = "EXTENDED";
13327                                                 break;
13328                                         default:
13329                                                 storage = NULL;
13330                                 }
13331
13332                                 /*
13333                                  * Only dump the statement if it's a storage type we recognize
13334                                  */
13335                                 if (storage != NULL)
13336                                 {
13337                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13338                                                                           fmtId(tbinfo->dobj.name));
13339                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
13340                                                                           fmtId(tbinfo->attnames[j]));
13341                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
13342                                                                           storage);
13343                                 }
13344                         }
13345
13346                         /*
13347                          * Dump per-column attributes.
13348                          */
13349                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
13350                         {
13351                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13352                                                                   fmtId(tbinfo->dobj.name));
13353                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13354                                                                   fmtId(tbinfo->attnames[j]));
13355                                 appendPQExpBuffer(q, "SET (%s);\n",
13356                                                                   tbinfo->attoptions[j]);
13357                         }
13358
13359                         /*
13360                          * Dump per-column fdw options.
13361                          */
13362                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
13363                                 tbinfo->attfdwoptions[j] &&
13364                                 tbinfo->attfdwoptions[j][0] != '\0')
13365                         {
13366                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13367                                                                   fmtId(tbinfo->dobj.name));
13368                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13369                                                                   fmtId(tbinfo->attnames[j]));
13370                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
13371                                                                   tbinfo->attfdwoptions[j]);
13372                         }
13373                 }
13374         }
13375
13376         if (binary_upgrade)
13377                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
13378
13379         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13380                                  tbinfo->dobj.name,
13381                                  tbinfo->dobj.namespace->dobj.name,
13382                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
13383                                  tbinfo->rolname,
13384                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
13385                                  reltypename, SECTION_PRE_DATA,
13386                                  q->data, delq->data, NULL,
13387                                  NULL, 0,
13388                                  NULL, NULL);
13389
13390
13391         /* Dump Table Comments */
13392         dumpTableComment(fout, tbinfo, reltypename);
13393
13394         /* Dump Table Security Labels */
13395         dumpTableSecLabel(fout, tbinfo, reltypename);
13396
13397         /* Dump comments on inlined table constraints */
13398         for (j = 0; j < tbinfo->ncheck; j++)
13399         {
13400                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13401
13402                 if (constr->separate || !constr->conislocal)
13403                         continue;
13404
13405                 dumpTableConstraintComment(fout, constr);
13406         }
13407
13408         destroyPQExpBuffer(q);
13409         destroyPQExpBuffer(delq);
13410         destroyPQExpBuffer(labelq);
13411 }
13412
13413 /*
13414  * dumpAttrDef --- dump an attribute's default-value declaration
13415  */
13416 static void
13417 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13418 {
13419         TableInfo  *tbinfo = adinfo->adtable;
13420         int                     adnum = adinfo->adnum;
13421         PQExpBuffer q;
13422         PQExpBuffer delq;
13423
13424         /* Skip if table definition not to be dumped */
13425         if (!tbinfo->dobj.dump || dataOnly)
13426                 return;
13427
13428         /* Skip if not "separate"; it was dumped in the table's definition */
13429         if (!adinfo->separate)
13430                 return;
13431
13432         q = createPQExpBuffer();
13433         delq = createPQExpBuffer();
13434
13435         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13436                                           fmtId(tbinfo->dobj.name));
13437         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13438                                           fmtId(tbinfo->attnames[adnum - 1]),
13439                                           adinfo->adef_expr);
13440
13441         /*
13442          * DROP must be fully qualified in case same name appears in pg_catalog
13443          */
13444         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13445                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13446         appendPQExpBuffer(delq, "%s ",
13447                                           fmtId(tbinfo->dobj.name));
13448         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13449                                           fmtId(tbinfo->attnames[adnum - 1]));
13450
13451         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13452                                  tbinfo->attnames[adnum - 1],
13453                                  tbinfo->dobj.namespace->dobj.name,
13454                                  NULL,
13455                                  tbinfo->rolname,
13456                                  false, "DEFAULT", SECTION_PRE_DATA,
13457                                  q->data, delq->data, NULL,
13458                                  NULL, 0,
13459                                  NULL, NULL);
13460
13461         destroyPQExpBuffer(q);
13462         destroyPQExpBuffer(delq);
13463 }
13464
13465 /*
13466  * getAttrName: extract the correct name for an attribute
13467  *
13468  * The array tblInfo->attnames[] only provides names of user attributes;
13469  * if a system attribute number is supplied, we have to fake it.
13470  * We also do a little bit of bounds checking for safety's sake.
13471  */
13472 static const char *
13473 getAttrName(int attrnum, TableInfo *tblInfo)
13474 {
13475         if (attrnum > 0 && attrnum <= tblInfo->numatts)
13476                 return tblInfo->attnames[attrnum - 1];
13477         switch (attrnum)
13478         {
13479                 case SelfItemPointerAttributeNumber:
13480                         return "ctid";
13481                 case ObjectIdAttributeNumber:
13482                         return "oid";
13483                 case MinTransactionIdAttributeNumber:
13484                         return "xmin";
13485                 case MinCommandIdAttributeNumber:
13486                         return "cmin";
13487                 case MaxTransactionIdAttributeNumber:
13488                         return "xmax";
13489                 case MaxCommandIdAttributeNumber:
13490                         return "cmax";
13491                 case TableOidAttributeNumber:
13492                         return "tableoid";
13493         }
13494         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13495                                   attrnum, tblInfo->dobj.name);
13496         return NULL;                            /* keep compiler quiet */
13497 }
13498
13499 /*
13500  * dumpIndex
13501  *        write out to fout a user-defined index
13502  */
13503 static void
13504 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13505 {
13506         TableInfo  *tbinfo = indxinfo->indextable;
13507         bool            is_constraint = (indxinfo->indexconstraint != 0);
13508         PQExpBuffer q;
13509         PQExpBuffer delq;
13510         PQExpBuffer labelq;
13511
13512         if (dataOnly)
13513                 return;
13514
13515         q = createPQExpBuffer();
13516         delq = createPQExpBuffer();
13517         labelq = createPQExpBuffer();
13518
13519         appendPQExpBuffer(labelq, "INDEX %s",
13520                                           fmtId(indxinfo->dobj.name));
13521
13522         /*
13523          * If there's an associated constraint, don't dump the index per se, but
13524          * do dump any comment for it.  (This is safe because dependency ordering
13525          * will have ensured the constraint is emitted first.)  Note that the
13526          * emitted comment has to be shown as depending on the constraint, not
13527          * the index, in such cases.
13528          */
13529         if (!is_constraint)
13530         {
13531                 if (binary_upgrade)
13532                         binary_upgrade_set_pg_class_oids(fout, q,
13533                                                                                          indxinfo->dobj.catId.oid, true);
13534
13535                 /* Plain secondary index */
13536                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13537
13538                 /* If the index is clustered, we need to record that. */
13539                 if (indxinfo->indisclustered)
13540                 {
13541                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13542                                                           fmtId(tbinfo->dobj.name));
13543                         appendPQExpBuffer(q, " ON %s;\n",
13544                                                           fmtId(indxinfo->dobj.name));
13545                 }
13546
13547                 /*
13548                  * DROP must be fully qualified in case same name appears in
13549                  * pg_catalog
13550                  */
13551                 appendPQExpBuffer(delq, "DROP INDEX %s.",
13552                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13553                 appendPQExpBuffer(delq, "%s;\n",
13554                                                   fmtId(indxinfo->dobj.name));
13555
13556                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13557                                          indxinfo->dobj.name,
13558                                          tbinfo->dobj.namespace->dobj.name,
13559                                          indxinfo->tablespace,
13560                                          tbinfo->rolname, false,
13561                                          "INDEX", SECTION_POST_DATA,
13562                                          q->data, delq->data, NULL,
13563                                          NULL, 0,
13564                                          NULL, NULL);
13565         }
13566
13567         /* Dump Index Comments */
13568         dumpComment(fout, labelq->data,
13569                                 tbinfo->dobj.namespace->dobj.name,
13570                                 tbinfo->rolname,
13571                                 indxinfo->dobj.catId, 0,
13572                                 is_constraint ? indxinfo->indexconstraint :
13573                                 indxinfo->dobj.dumpId);
13574
13575         destroyPQExpBuffer(q);
13576         destroyPQExpBuffer(delq);
13577         destroyPQExpBuffer(labelq);
13578 }
13579
13580 /*
13581  * dumpConstraint
13582  *        write out to fout a user-defined constraint
13583  */
13584 static void
13585 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13586 {
13587         TableInfo  *tbinfo = coninfo->contable;
13588         PQExpBuffer q;
13589         PQExpBuffer delq;
13590
13591         /* Skip if not to be dumped */
13592         if (!coninfo->dobj.dump || dataOnly)
13593                 return;
13594
13595         q = createPQExpBuffer();
13596         delq = createPQExpBuffer();
13597
13598         if (coninfo->contype == 'p' ||
13599                 coninfo->contype == 'u' ||
13600                 coninfo->contype == 'x')
13601         {
13602                 /* Index-related constraint */
13603                 IndxInfo   *indxinfo;
13604                 int                     k;
13605
13606                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13607
13608                 if (indxinfo == NULL)
13609                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13610                                                   coninfo->dobj.name);
13611
13612                 if (binary_upgrade)
13613                         binary_upgrade_set_pg_class_oids(fout, q,
13614                                                                                          indxinfo->dobj.catId.oid, true);
13615
13616                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13617                                                   fmtId(tbinfo->dobj.name));
13618                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
13619                                                   fmtId(coninfo->dobj.name));
13620
13621                 if (coninfo->condef)
13622                 {
13623                         /* pg_get_constraintdef should have provided everything */
13624                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13625                 }
13626                 else
13627                 {
13628                         appendPQExpBuffer(q, "%s (",
13629                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13630                         for (k = 0; k < indxinfo->indnkeys; k++)
13631                         {
13632                                 int                     indkey = (int) indxinfo->indkeys[k];
13633                                 const char *attname;
13634
13635                                 if (indkey == InvalidAttrNumber)
13636                                         break;
13637                                 attname = getAttrName(indkey, tbinfo);
13638
13639                                 appendPQExpBuffer(q, "%s%s",
13640                                                                   (k == 0) ? "" : ", ",
13641                                                                   fmtId(attname));
13642                         }
13643
13644                         appendPQExpBuffer(q, ")");
13645
13646                         if (indxinfo->options && strlen(indxinfo->options) > 0)
13647                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13648
13649                         if (coninfo->condeferrable)
13650                         {
13651                                 appendPQExpBuffer(q, " DEFERRABLE");
13652                                 if (coninfo->condeferred)
13653                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
13654                         }
13655
13656                         appendPQExpBuffer(q, ";\n");
13657                 }
13658
13659                 /* If the index is clustered, we need to record that. */
13660                 if (indxinfo->indisclustered)
13661                 {
13662                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13663                                                           fmtId(tbinfo->dobj.name));
13664                         appendPQExpBuffer(q, " ON %s;\n",
13665                                                           fmtId(indxinfo->dobj.name));
13666                 }
13667
13668                 /*
13669                  * DROP must be fully qualified in case same name appears in
13670                  * pg_catalog
13671                  */
13672                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13673                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13674                 appendPQExpBuffer(delq, "%s ",
13675                                                   fmtId(tbinfo->dobj.name));
13676                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13677                                                   fmtId(coninfo->dobj.name));
13678
13679                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13680                                          coninfo->dobj.name,
13681                                          tbinfo->dobj.namespace->dobj.name,
13682                                          indxinfo->tablespace,
13683                                          tbinfo->rolname, false,
13684                                          "CONSTRAINT", SECTION_POST_DATA,
13685                                          q->data, delq->data, NULL,
13686                                          NULL, 0,
13687                                          NULL, NULL);
13688         }
13689         else if (coninfo->contype == 'f')
13690         {
13691                 /*
13692                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13693                  * current table data is not processed
13694                  */
13695                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13696                                                   fmtId(tbinfo->dobj.name));
13697                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13698                                                   fmtId(coninfo->dobj.name),
13699                                                   coninfo->condef);
13700
13701                 /*
13702                  * DROP must be fully qualified in case same name appears in
13703                  * pg_catalog
13704                  */
13705                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13706                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13707                 appendPQExpBuffer(delq, "%s ",
13708                                                   fmtId(tbinfo->dobj.name));
13709                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13710                                                   fmtId(coninfo->dobj.name));
13711
13712                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13713                                          coninfo->dobj.name,
13714                                          tbinfo->dobj.namespace->dobj.name,
13715                                          NULL,
13716                                          tbinfo->rolname, false,
13717                                          "FK CONSTRAINT", SECTION_POST_DATA,
13718                                          q->data, delq->data, NULL,
13719                                          NULL, 0,
13720                                          NULL, NULL);
13721         }
13722         else if (coninfo->contype == 'c' && tbinfo)
13723         {
13724                 /* CHECK constraint on a table */
13725
13726                 /* Ignore if not to be dumped separately */
13727                 if (coninfo->separate)
13728                 {
13729                         /* not ONLY since we want it to propagate to children */
13730                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13731                                                           fmtId(tbinfo->dobj.name));
13732                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13733                                                           fmtId(coninfo->dobj.name),
13734                                                           coninfo->condef);
13735
13736                         /*
13737                          * DROP must be fully qualified in case same name appears in
13738                          * pg_catalog
13739                          */
13740                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13741                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13742                         appendPQExpBuffer(delq, "%s ",
13743                                                           fmtId(tbinfo->dobj.name));
13744                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13745                                                           fmtId(coninfo->dobj.name));
13746
13747                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13748                                                  coninfo->dobj.name,
13749                                                  tbinfo->dobj.namespace->dobj.name,
13750                                                  NULL,
13751                                                  tbinfo->rolname, false,
13752                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13753                                                  q->data, delq->data, NULL,
13754                                                  NULL, 0,
13755                                                  NULL, NULL);
13756                 }
13757         }
13758         else if (coninfo->contype == 'c' && tbinfo == NULL)
13759         {
13760                 /* CHECK constraint on a domain */
13761                 TypeInfo   *tyinfo = coninfo->condomain;
13762
13763                 /* Ignore if not to be dumped separately */
13764                 if (coninfo->separate)
13765                 {
13766                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13767                                                           fmtId(tyinfo->dobj.name));
13768                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13769                                                           fmtId(coninfo->dobj.name),
13770                                                           coninfo->condef);
13771
13772                         /*
13773                          * DROP must be fully qualified in case same name appears in
13774                          * pg_catalog
13775                          */
13776                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13777                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13778                         appendPQExpBuffer(delq, "%s ",
13779                                                           fmtId(tyinfo->dobj.name));
13780                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13781                                                           fmtId(coninfo->dobj.name));
13782
13783                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13784                                                  coninfo->dobj.name,
13785                                                  tyinfo->dobj.namespace->dobj.name,
13786                                                  NULL,
13787                                                  tyinfo->rolname, false,
13788                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13789                                                  q->data, delq->data, NULL,
13790                                                  NULL, 0,
13791                                                  NULL, NULL);
13792                 }
13793         }
13794         else
13795         {
13796                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13797                                           coninfo->contype);
13798         }
13799
13800         /* Dump Constraint Comments --- only works for table constraints */
13801         if (tbinfo && coninfo->separate)
13802                 dumpTableConstraintComment(fout, coninfo);
13803
13804         destroyPQExpBuffer(q);
13805         destroyPQExpBuffer(delq);
13806 }
13807
13808 /*
13809  * dumpTableConstraintComment --- dump a constraint's comment if any
13810  *
13811  * This is split out because we need the function in two different places
13812  * depending on whether the constraint is dumped as part of CREATE TABLE
13813  * or as a separate ALTER command.
13814  */
13815 static void
13816 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13817 {
13818         TableInfo  *tbinfo = coninfo->contable;
13819         PQExpBuffer labelq = createPQExpBuffer();
13820
13821         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13822                                           fmtId(coninfo->dobj.name));
13823         appendPQExpBuffer(labelq, "ON %s",
13824                                           fmtId(tbinfo->dobj.name));
13825         dumpComment(fout, labelq->data,
13826                                 tbinfo->dobj.namespace->dobj.name,
13827                                 tbinfo->rolname,
13828                                 coninfo->dobj.catId, 0,
13829                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13830
13831         destroyPQExpBuffer(labelq);
13832 }
13833
13834 /*
13835  * findLastBuiltInOid -
13836  * find the last built in oid
13837  *
13838  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13839  * pg_database entry for the current database
13840  */
13841 static Oid
13842 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13843 {
13844         PGresult   *res;
13845         Oid                     last_oid;
13846         PQExpBuffer query = createPQExpBuffer();
13847
13848         resetPQExpBuffer(query);
13849         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13850         appendStringLiteralAH(query, dbname, fout);
13851
13852         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13853         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13854         PQclear(res);
13855         destroyPQExpBuffer(query);
13856         return last_oid;
13857 }
13858
13859 /*
13860  * findLastBuiltInOid -
13861  * find the last built in oid
13862  *
13863  * For 7.0, we do this by assuming that the last thing that initdb does is to
13864  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13865  * initdb won't be changing anymore, it'll do.
13866  */
13867 static Oid
13868 findLastBuiltinOid_V70(Archive *fout)
13869 {
13870         PGresult   *res;
13871         int                     last_oid;
13872
13873         res = ExecuteSqlQueryForSingleRow(fout,
13874                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13875         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13876         PQclear(res);
13877         return last_oid;
13878 }
13879
13880 /*
13881  * dumpSequence
13882  *        write the declaration (not data) of one user-defined sequence
13883  */
13884 static void
13885 dumpSequence(Archive *fout, TableInfo *tbinfo)
13886 {
13887         PGresult   *res;
13888         char       *startv,
13889                            *incby,
13890                            *maxv = NULL,
13891                            *minv = NULL,
13892                            *cache;
13893         char            bufm[100],
13894                                 bufx[100];
13895         bool            cycled;
13896         PQExpBuffer query = createPQExpBuffer();
13897         PQExpBuffer delqry = createPQExpBuffer();
13898         PQExpBuffer labelq = createPQExpBuffer();
13899
13900         /* Make sure we are in proper schema */
13901         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13902
13903         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13904         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13905
13906         if (fout->remoteVersion >= 80400)
13907         {
13908                 appendPQExpBuffer(query,
13909                                                   "SELECT sequence_name, "
13910                                                   "start_value, increment_by, "
13911                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13912                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13913                                                   "     ELSE max_value "
13914                                                   "END AS max_value, "
13915                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13916                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13917                                                   "     ELSE min_value "
13918                                                   "END AS min_value, "
13919                                                   "cache_value, is_cycled FROM %s",
13920                                                   bufx, bufm,
13921                                                   fmtId(tbinfo->dobj.name));
13922         }
13923         else
13924         {
13925                 appendPQExpBuffer(query,
13926                                                   "SELECT sequence_name, "
13927                                                   "0 AS start_value, increment_by, "
13928                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13929                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13930                                                   "     ELSE max_value "
13931                                                   "END AS max_value, "
13932                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13933                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13934                                                   "     ELSE min_value "
13935                                                   "END AS min_value, "
13936                                                   "cache_value, is_cycled FROM %s",
13937                                                   bufx, bufm,
13938                                                   fmtId(tbinfo->dobj.name));
13939         }
13940
13941         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13942
13943         if (PQntuples(res) != 1)
13944         {
13945                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13946                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13947                                                                  PQntuples(res)),
13948                                   tbinfo->dobj.name, PQntuples(res));
13949                 exit_nicely(1);
13950         }
13951
13952         /* Disable this check: it fails if sequence has been renamed */
13953 #ifdef NOT_USED
13954         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13955         {
13956                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13957                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13958                 exit_nicely(1);
13959         }
13960 #endif
13961
13962         startv = PQgetvalue(res, 0, 1);
13963         incby = PQgetvalue(res, 0, 2);
13964         if (!PQgetisnull(res, 0, 3))
13965                 maxv = PQgetvalue(res, 0, 3);
13966         if (!PQgetisnull(res, 0, 4))
13967                 minv = PQgetvalue(res, 0, 4);
13968         cache = PQgetvalue(res, 0, 5);
13969         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13970
13971         /*
13972          * DROP must be fully qualified in case same name appears in pg_catalog
13973          */
13974         appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13975                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13976         appendPQExpBuffer(delqry, "%s;\n",
13977                                           fmtId(tbinfo->dobj.name));
13978
13979         resetPQExpBuffer(query);
13980
13981         if (binary_upgrade)
13982         {
13983                 binary_upgrade_set_pg_class_oids(fout, query,
13984                                                                                  tbinfo->dobj.catId.oid, false);
13985                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13986                                                                                                 tbinfo->dobj.catId.oid);
13987         }
13988
13989         appendPQExpBuffer(query,
13990                                           "CREATE SEQUENCE %s\n",
13991                                           fmtId(tbinfo->dobj.name));
13992
13993         if (fout->remoteVersion >= 80400)
13994                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
13995
13996         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13997
13998         if (minv)
13999                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
14000         else
14001                 appendPQExpBuffer(query, "    NO MINVALUE\n");
14002
14003         if (maxv)
14004                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
14005         else
14006                 appendPQExpBuffer(query, "    NO MAXVALUE\n");
14007
14008         appendPQExpBuffer(query,
14009                                           "    CACHE %s%s",
14010                                           cache, (cycled ? "\n    CYCLE" : ""));
14011
14012         appendPQExpBuffer(query, ";\n");
14013
14014         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
14015
14016         /* binary_upgrade:      no need to clear TOAST table oid */
14017
14018         if (binary_upgrade)
14019                 binary_upgrade_extension_member(query, &tbinfo->dobj,
14020                                                                                 labelq->data);
14021
14022         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
14023                                  tbinfo->dobj.name,
14024                                  tbinfo->dobj.namespace->dobj.name,
14025                                  NULL,
14026                                  tbinfo->rolname,
14027                                  false, "SEQUENCE", SECTION_PRE_DATA,
14028                                  query->data, delqry->data, NULL,
14029                                  NULL, 0,
14030                                  NULL, NULL);
14031
14032         /*
14033          * If the sequence is owned by a table column, emit the ALTER for it as a
14034          * separate TOC entry immediately following the sequence's own entry. It's
14035          * OK to do this rather than using full sorting logic, because the
14036          * dependency that tells us it's owned will have forced the table to be
14037          * created first.  We can't just include the ALTER in the TOC entry
14038          * because it will fail if we haven't reassigned the sequence owner to
14039          * match the table's owner.
14040          *
14041          * We need not schema-qualify the table reference because both sequence
14042          * and table must be in the same schema.
14043          */
14044         if (OidIsValid(tbinfo->owning_tab))
14045         {
14046                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
14047
14048                 if (owning_tab && owning_tab->dobj.dump)
14049                 {
14050                         resetPQExpBuffer(query);
14051                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
14052                                                           fmtId(tbinfo->dobj.name));
14053                         appendPQExpBuffer(query, " OWNED BY %s",
14054                                                           fmtId(owning_tab->dobj.name));
14055                         appendPQExpBuffer(query, ".%s;\n",
14056                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
14057
14058                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
14059                                                  tbinfo->dobj.name,
14060                                                  tbinfo->dobj.namespace->dobj.name,
14061                                                  NULL,
14062                                                  tbinfo->rolname,
14063                                                  false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
14064                                                  query->data, "", NULL,
14065                                                  &(tbinfo->dobj.dumpId), 1,
14066                                                  NULL, NULL);
14067                 }
14068         }
14069
14070         /* Dump Sequence Comments and Security Labels */
14071         dumpComment(fout, labelq->data,
14072                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14073                                 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14074         dumpSecLabel(fout, labelq->data,
14075                                  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14076                                  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14077
14078         PQclear(res);
14079
14080         destroyPQExpBuffer(query);
14081         destroyPQExpBuffer(delqry);
14082         destroyPQExpBuffer(labelq);
14083 }
14084
14085 /*
14086  * dumpSequenceData
14087  *        write the data of one user-defined sequence
14088  */
14089 static void
14090 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
14091 {
14092         TableInfo  *tbinfo = tdinfo->tdtable;
14093         PGresult   *res;
14094         char       *last;
14095         bool            called;
14096         PQExpBuffer query = createPQExpBuffer();
14097
14098         /* Make sure we are in proper schema */
14099         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14100
14101         appendPQExpBuffer(query,
14102                                           "SELECT last_value, is_called FROM %s",
14103                                           fmtId(tbinfo->dobj.name));
14104
14105         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14106
14107         if (PQntuples(res) != 1)
14108         {
14109                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
14110                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
14111                                                                  PQntuples(res)),
14112                                   tbinfo->dobj.name, PQntuples(res));
14113                 exit_nicely(1);
14114         }
14115
14116         last = PQgetvalue(res, 0, 0);
14117         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
14118
14119         resetPQExpBuffer(query);
14120         appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
14121         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
14122         appendPQExpBuffer(query, ", %s, %s);\n",
14123                                           last, (called ? "true" : "false"));
14124
14125         ArchiveEntry(fout, nilCatalogId, createDumpId(),
14126                                  tbinfo->dobj.name,
14127                                  tbinfo->dobj.namespace->dobj.name,
14128                                  NULL,
14129                                  tbinfo->rolname,
14130                                  false, "SEQUENCE SET", SECTION_DATA,
14131                                  query->data, "", NULL,
14132                                  &(tbinfo->dobj.dumpId), 1,
14133                                  NULL, NULL);
14134
14135         PQclear(res);
14136
14137         destroyPQExpBuffer(query);
14138 }
14139
14140 static void
14141 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
14142 {
14143         TableInfo  *tbinfo = tginfo->tgtable;
14144         PQExpBuffer query;
14145         PQExpBuffer delqry;
14146         PQExpBuffer labelq;
14147         char       *tgargs;
14148         size_t          lentgargs;
14149         const char *p;
14150         int                     findx;
14151
14152         if (dataOnly)
14153                 return;
14154
14155         query = createPQExpBuffer();
14156         delqry = createPQExpBuffer();
14157         labelq = createPQExpBuffer();
14158
14159         /*
14160          * DROP must be fully qualified in case same name appears in pg_catalog
14161          */
14162         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
14163                                           fmtId(tginfo->dobj.name));
14164         appendPQExpBuffer(delqry, "ON %s.",
14165                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14166         appendPQExpBuffer(delqry, "%s;\n",
14167                                           fmtId(tbinfo->dobj.name));
14168
14169         if (tginfo->tgdef)
14170         {
14171                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
14172         }
14173         else
14174         {
14175                 if (tginfo->tgisconstraint)
14176                 {
14177                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
14178                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
14179                 }
14180                 else
14181                 {
14182                         appendPQExpBuffer(query, "CREATE TRIGGER ");
14183                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
14184                 }
14185                 appendPQExpBuffer(query, "\n    ");
14186
14187                 /* Trigger type */
14188                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
14189                         appendPQExpBuffer(query, "BEFORE");
14190                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
14191                         appendPQExpBuffer(query, "AFTER");
14192                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
14193                         appendPQExpBuffer(query, "INSTEAD OF");
14194                 else
14195                 {
14196                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
14197                         exit_nicely(1);
14198                 }
14199
14200                 findx = 0;
14201                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
14202                 {
14203                         appendPQExpBuffer(query, " INSERT");
14204                         findx++;
14205                 }
14206                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
14207                 {
14208                         if (findx > 0)
14209                                 appendPQExpBuffer(query, " OR DELETE");
14210                         else
14211                                 appendPQExpBuffer(query, " DELETE");
14212                         findx++;
14213                 }
14214                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
14215                 {
14216                         if (findx > 0)
14217                                 appendPQExpBuffer(query, " OR UPDATE");
14218                         else
14219                                 appendPQExpBuffer(query, " UPDATE");
14220                         findx++;
14221                 }
14222                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
14223                 {
14224                         if (findx > 0)
14225                                 appendPQExpBuffer(query, " OR TRUNCATE");
14226                         else
14227                                 appendPQExpBuffer(query, " TRUNCATE");
14228                         findx++;
14229                 }
14230                 appendPQExpBuffer(query, " ON %s\n",
14231                                                   fmtId(tbinfo->dobj.name));
14232
14233                 if (tginfo->tgisconstraint)
14234                 {
14235                         if (OidIsValid(tginfo->tgconstrrelid))
14236                         {
14237                                 /* If we are using regclass, name is already quoted */
14238                                 if (fout->remoteVersion >= 70300)
14239                                         appendPQExpBuffer(query, "    FROM %s\n    ",
14240                                                                           tginfo->tgconstrrelname);
14241                                 else
14242                                         appendPQExpBuffer(query, "    FROM %s\n    ",
14243                                                                           fmtId(tginfo->tgconstrrelname));
14244                         }
14245                         if (!tginfo->tgdeferrable)
14246                                 appendPQExpBuffer(query, "NOT ");
14247                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
14248                         if (tginfo->tginitdeferred)
14249                                 appendPQExpBuffer(query, "DEFERRED\n");
14250                         else
14251                                 appendPQExpBuffer(query, "IMMEDIATE\n");
14252                 }
14253
14254                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
14255                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
14256                 else
14257                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
14258
14259                 /* In 7.3, result of regproc is already quoted */
14260                 if (fout->remoteVersion >= 70300)
14261                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14262                                                           tginfo->tgfname);
14263                 else
14264                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14265                                                           fmtId(tginfo->tgfname));
14266
14267                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
14268                                                                                   &lentgargs);
14269                 p = tgargs;
14270                 for (findx = 0; findx < tginfo->tgnargs; findx++)
14271                 {
14272                         /* find the embedded null that terminates this trigger argument */
14273                         size_t          tlen = strlen(p);
14274
14275                         if (p + tlen >= tgargs + lentgargs)
14276                         {
14277                                 /* hm, not found before end of bytea value... */
14278                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
14279                                                   tginfo->tgargs,
14280                                                   tginfo->dobj.name,
14281                                                   tbinfo->dobj.name);
14282                                 exit_nicely(1);
14283                         }
14284
14285                         if (findx > 0)
14286                                 appendPQExpBuffer(query, ", ");
14287                         appendStringLiteralAH(query, p, fout);
14288                         p += tlen + 1;
14289                 }
14290                 free(tgargs);
14291                 appendPQExpBuffer(query, ");\n");
14292         }
14293
14294         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
14295         {
14296                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
14297                                                   fmtId(tbinfo->dobj.name));
14298                 switch (tginfo->tgenabled)
14299                 {
14300                         case 'D':
14301                         case 'f':
14302                                 appendPQExpBuffer(query, "DISABLE");
14303                                 break;
14304                         case 'A':
14305                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
14306                                 break;
14307                         case 'R':
14308                                 appendPQExpBuffer(query, "ENABLE REPLICA");
14309                                 break;
14310                         default:
14311                                 appendPQExpBuffer(query, "ENABLE");
14312                                 break;
14313                 }
14314                 appendPQExpBuffer(query, " TRIGGER %s;\n",
14315                                                   fmtId(tginfo->dobj.name));
14316         }
14317
14318         appendPQExpBuffer(labelq, "TRIGGER %s ",
14319                                           fmtId(tginfo->dobj.name));
14320         appendPQExpBuffer(labelq, "ON %s",
14321                                           fmtId(tbinfo->dobj.name));
14322
14323         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
14324                                  tginfo->dobj.name,
14325                                  tbinfo->dobj.namespace->dobj.name,
14326                                  NULL,
14327                                  tbinfo->rolname, false,
14328                                  "TRIGGER", SECTION_POST_DATA,
14329                                  query->data, delqry->data, NULL,
14330                                  NULL, 0,
14331                                  NULL, NULL);
14332
14333         dumpComment(fout, labelq->data,
14334                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14335                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
14336
14337         destroyPQExpBuffer(query);
14338         destroyPQExpBuffer(delqry);
14339         destroyPQExpBuffer(labelq);
14340 }
14341
14342 static void
14343 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
14344 {
14345         PQExpBuffer query;
14346         PQExpBuffer labelq;
14347
14348         query = createPQExpBuffer();
14349         labelq = createPQExpBuffer();
14350
14351         appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
14352         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
14353         appendPQExpBuffer(query, " ON ");
14354         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
14355         appendPQExpBufferStr(query, " ");
14356
14357         if (strcmp("", evtinfo->evttags) != 0)
14358         {
14359                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
14360                 appendPQExpBufferStr(query, evtinfo->evttags);
14361                 appendPQExpBufferStr(query, ") ");
14362         }
14363
14364         appendPQExpBuffer(query, "\n   EXECUTE PROCEDURE ");
14365         appendPQExpBufferStr(query, evtinfo->evtfname);
14366         appendPQExpBuffer(query, "();\n");
14367
14368         if (evtinfo->evtenabled != 'O')
14369         {
14370                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
14371                                                   fmtId(evtinfo->dobj.name));
14372                 switch (evtinfo->evtenabled)
14373                 {
14374                         case 'D':
14375                                 appendPQExpBuffer(query, "DISABLE");
14376                                 break;
14377                         case 'A':
14378                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
14379                                 break;
14380                         case 'R':
14381                                 appendPQExpBuffer(query, "ENABLE REPLICA");
14382                                 break;
14383                         default:
14384                                 appendPQExpBuffer(query, "ENABLE");
14385                                 break;
14386                 }
14387                 appendPQExpBuffer(query, ";\n");
14388         }
14389         appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
14390                                           fmtId(evtinfo->dobj.name));
14391
14392         ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
14393                                  evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
14394                                  "EVENT TRIGGER", SECTION_POST_DATA,
14395                                  query->data, "", NULL, NULL, 0, NULL, NULL);
14396
14397         dumpComment(fout, labelq->data,
14398                                 NULL, NULL,
14399                                 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
14400
14401         destroyPQExpBuffer(query);
14402         destroyPQExpBuffer(labelq);
14403 }
14404
14405 /*
14406  * dumpRule
14407  *              Dump a rule
14408  */
14409 static void
14410 dumpRule(Archive *fout, RuleInfo *rinfo)
14411 {
14412         TableInfo  *tbinfo = rinfo->ruletable;
14413         PQExpBuffer query;
14414         PQExpBuffer cmd;
14415         PQExpBuffer delcmd;
14416         PQExpBuffer labelq;
14417         PGresult   *res;
14418
14419         /* Skip if not to be dumped */
14420         if (!rinfo->dobj.dump || dataOnly)
14421                 return;
14422
14423         /*
14424          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
14425          * we do not want to dump it as a separate object.
14426          */
14427         if (!rinfo->separate)
14428                 return;
14429
14430         /*
14431          * Make sure we are in proper schema.
14432          */
14433         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14434
14435         query = createPQExpBuffer();
14436         cmd = createPQExpBuffer();
14437         delcmd = createPQExpBuffer();
14438         labelq = createPQExpBuffer();
14439
14440         if (fout->remoteVersion >= 70300)
14441         {
14442                 appendPQExpBuffer(query,
14443                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14444                                                   rinfo->dobj.catId.oid);
14445         }
14446         else
14447         {
14448                 /* Rule name was unique before 7.3 ... */
14449                 appendPQExpBuffer(query,
14450                                                   "SELECT pg_get_ruledef('%s') AS definition",
14451                                                   rinfo->dobj.name);
14452         }
14453
14454         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14455
14456         if (PQntuples(res) != 1)
14457         {
14458                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14459                                   rinfo->dobj.name, tbinfo->dobj.name);
14460                 exit_nicely(1);
14461         }
14462
14463         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14464
14465         /*
14466          * Add the command to alter the rules replication firing semantics if it
14467          * differs from the default.
14468          */
14469         if (rinfo->ev_enabled != 'O')
14470         {
14471                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14472                 switch (rinfo->ev_enabled)
14473                 {
14474                         case 'A':
14475                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14476                                                                   fmtId(rinfo->dobj.name));
14477                                 break;
14478                         case 'R':
14479                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14480                                                                   fmtId(rinfo->dobj.name));
14481                                 break;
14482                         case 'D':
14483                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14484                                                                   fmtId(rinfo->dobj.name));
14485                                 break;
14486                 }
14487         }
14488
14489         /*
14490          * Apply view's reloptions when its ON SELECT rule is separate.
14491          */
14492         if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14493         {
14494                 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14495                                                   fmtId(tbinfo->dobj.name),
14496                                                   rinfo->reloptions);
14497         }
14498
14499         /*
14500          * DROP must be fully qualified in case same name appears in pg_catalog
14501          */
14502         appendPQExpBuffer(delcmd, "DROP RULE %s ",
14503                                           fmtId(rinfo->dobj.name));
14504         appendPQExpBuffer(delcmd, "ON %s.",
14505                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14506         appendPQExpBuffer(delcmd, "%s;\n",
14507                                           fmtId(tbinfo->dobj.name));
14508
14509         appendPQExpBuffer(labelq, "RULE %s",
14510                                           fmtId(rinfo->dobj.name));
14511         appendPQExpBuffer(labelq, " ON %s",
14512                                           fmtId(tbinfo->dobj.name));
14513
14514         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14515                                  rinfo->dobj.name,
14516                                  tbinfo->dobj.namespace->dobj.name,
14517                                  NULL,
14518                                  tbinfo->rolname, false,
14519                                  "RULE", SECTION_POST_DATA,
14520                                  cmd->data, delcmd->data, NULL,
14521                                  NULL, 0,
14522                                  NULL, NULL);
14523
14524         /* Dump rule comments */
14525         dumpComment(fout, labelq->data,
14526                                 tbinfo->dobj.namespace->dobj.name,
14527                                 tbinfo->rolname,
14528                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14529
14530         PQclear(res);
14531
14532         destroyPQExpBuffer(query);
14533         destroyPQExpBuffer(cmd);
14534         destroyPQExpBuffer(delcmd);
14535         destroyPQExpBuffer(labelq);
14536 }
14537
14538 /*
14539  * getExtensionMembership --- obtain extension membership data
14540  */
14541 void
14542 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14543                                            int numExtensions)
14544 {
14545         PQExpBuffer query;
14546         PGresult   *res;
14547         int                     ntups,
14548                                 i;
14549         int                     i_classid,
14550                                 i_objid,
14551                                 i_refclassid,
14552                                 i_refobjid;
14553         DumpableObject *dobj,
14554                            *refdobj;
14555
14556         /* Nothing to do if no extensions */
14557         if (numExtensions == 0)
14558                 return;
14559
14560         /* Make sure we are in proper schema */
14561         selectSourceSchema(fout, "pg_catalog");
14562
14563         query = createPQExpBuffer();
14564
14565         /* refclassid constraint is redundant but may speed the search */
14566         appendPQExpBuffer(query, "SELECT "
14567                                           "classid, objid, refclassid, refobjid "
14568                                           "FROM pg_depend "
14569                                           "WHERE refclassid = 'pg_extension'::regclass "
14570                                           "AND deptype = 'e' "
14571                                           "ORDER BY 3,4");
14572
14573         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14574
14575         ntups = PQntuples(res);
14576
14577         i_classid = PQfnumber(res, "classid");
14578         i_objid = PQfnumber(res, "objid");
14579         i_refclassid = PQfnumber(res, "refclassid");
14580         i_refobjid = PQfnumber(res, "refobjid");
14581
14582         /*
14583          * Since we ordered the SELECT by referenced ID, we can expect that
14584          * multiple entries for the same extension will appear together; this
14585          * saves on searches.
14586          */
14587         refdobj = NULL;
14588
14589         for (i = 0; i < ntups; i++)
14590         {
14591                 CatalogId       objId;
14592                 CatalogId       refobjId;
14593
14594                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14595                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14596                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14597                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14598
14599                 if (refdobj == NULL ||
14600                         refdobj->catId.tableoid != refobjId.tableoid ||
14601                         refdobj->catId.oid != refobjId.oid)
14602                         refdobj = findObjectByCatalogId(refobjId);
14603
14604                 /*
14605                  * Failure to find objects mentioned in pg_depend is not unexpected,
14606                  * since for example we don't collect info about TOAST tables.
14607                  */
14608                 if (refdobj == NULL)
14609                 {
14610 #ifdef NOT_USED
14611                         fprintf(stderr, "no referenced object %u %u\n",
14612                                         refobjId.tableoid, refobjId.oid);
14613 #endif
14614                         continue;
14615                 }
14616
14617                 dobj = findObjectByCatalogId(objId);
14618
14619                 if (dobj == NULL)
14620                 {
14621 #ifdef NOT_USED
14622                         fprintf(stderr, "no referencing object %u %u\n",
14623                                         objId.tableoid, objId.oid);
14624 #endif
14625                         continue;
14626                 }
14627
14628                 /* Record dependency so that getDependencies needn't repeat this */
14629                 addObjectDependency(dobj, refdobj->dumpId);
14630
14631                 dobj->ext_member = true;
14632
14633                 /*
14634                  * Normally, mark the member object as not to be dumped.  But in
14635                  * binary upgrades, we still dump the members individually, since the
14636                  * idea is to exactly reproduce the database contents rather than
14637                  * replace the extension contents with something different.
14638                  */
14639                 if (!binary_upgrade)
14640                         dobj->dump = false;
14641                 else
14642                         dobj->dump = refdobj->dump;
14643         }
14644
14645         PQclear(res);
14646
14647         /*
14648          * Now identify extension configuration tables and create TableDataInfo
14649          * objects for them, ensuring their data will be dumped even though the
14650          * tables themselves won't be.
14651          *
14652          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14653          * user data in a configuration table is treated like schema data. This
14654          * seems appropriate since system data in a config table would get
14655          * reloaded by CREATE EXTENSION.
14656          */
14657         for (i = 0; i < numExtensions; i++)
14658         {
14659                 ExtensionInfo *curext = &(extinfo[i]);
14660                 char       *extconfig = curext->extconfig;
14661                 char       *extcondition = curext->extcondition;
14662                 char      **extconfigarray = NULL;
14663                 char      **extconditionarray = NULL;
14664                 int                     nconfigitems;
14665                 int                     nconditionitems;
14666
14667                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14668                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14669                         nconfigitems == nconditionitems)
14670                 {
14671                         int                     j;
14672
14673                         for (j = 0; j < nconfigitems; j++)
14674                         {
14675                                 TableInfo  *configtbl;
14676                                 Oid                     configtbloid = atooid(extconfigarray[j]);
14677                                 bool            dumpobj = curext->dobj.dump;
14678
14679                                 configtbl = findTableByOid(configtbloid);
14680                                 if (configtbl == NULL)
14681                                         continue;
14682
14683                                 /*
14684                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
14685                                  * unless the table or its schema is explicitly included
14686                                  */
14687                                 if (!curext->dobj.dump)
14688                                 {
14689                                         /* check table explicitly requested */
14690                                         if (table_include_oids.head != NULL &&
14691                                                 simple_oid_list_member(&table_include_oids,
14692                                                                                            configtbloid))
14693                                                 dumpobj = true;
14694
14695                                         /* check table's schema explicitly requested */
14696                                         if (configtbl->dobj.namespace->dobj.dump)
14697                                                 dumpobj = true;
14698                                 }
14699
14700                                 /* check table excluded by an exclusion switch */
14701                                 if (table_exclude_oids.head != NULL &&
14702                                         simple_oid_list_member(&table_exclude_oids,
14703                                                                                    configtbloid))
14704                                         dumpobj = false;
14705
14706                                 /* check schema excluded by an exclusion switch */
14707                                 if (simple_oid_list_member(&schema_exclude_oids,
14708                                                                   configtbl->dobj.namespace->dobj.catId.oid))
14709                                         dumpobj = false;
14710
14711                                 if (dumpobj)
14712                                 {
14713                                         /*
14714                                          * Note: config tables are dumped without OIDs regardless
14715                                          * of the --oids setting.  This is because row filtering
14716                                          * conditions aren't compatible with dumping OIDs.
14717                                          */
14718                                         makeTableDataInfo(configtbl, false);
14719                                         if (configtbl->dataObj != NULL)
14720                                         {
14721                                                 if (strlen(extconditionarray[j]) > 0)
14722                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14723                                         }
14724                                 }
14725                         }
14726                 }
14727                 if (extconfigarray)
14728                         free(extconfigarray);
14729                 if (extconditionarray)
14730                         free(extconditionarray);
14731         }
14732
14733         destroyPQExpBuffer(query);
14734 }
14735
14736 /*
14737  * getDependencies --- obtain available dependency data
14738  */
14739 static void
14740 getDependencies(Archive *fout)
14741 {
14742         PQExpBuffer query;
14743         PGresult   *res;
14744         int                     ntups,
14745                                 i;
14746         int                     i_classid,
14747                                 i_objid,
14748                                 i_refclassid,
14749                                 i_refobjid,
14750                                 i_deptype;
14751         DumpableObject *dobj,
14752                            *refdobj;
14753
14754         /* No dependency info available before 7.3 */
14755         if (fout->remoteVersion < 70300)
14756                 return;
14757
14758         if (g_verbose)
14759                 write_msg(NULL, "reading dependency data\n");
14760
14761         /* Make sure we are in proper schema */
14762         selectSourceSchema(fout, "pg_catalog");
14763
14764         query = createPQExpBuffer();
14765
14766         /*
14767          * PIN dependencies aren't interesting, and EXTENSION dependencies were
14768          * already processed by getExtensionMembership.
14769          */
14770         appendPQExpBuffer(query, "SELECT "
14771                                           "classid, objid, refclassid, refobjid, deptype "
14772                                           "FROM pg_depend "
14773                                           "WHERE deptype != 'p' AND deptype != 'e' "
14774                                           "ORDER BY 1,2");
14775
14776         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14777
14778         ntups = PQntuples(res);
14779
14780         i_classid = PQfnumber(res, "classid");
14781         i_objid = PQfnumber(res, "objid");
14782         i_refclassid = PQfnumber(res, "refclassid");
14783         i_refobjid = PQfnumber(res, "refobjid");
14784         i_deptype = PQfnumber(res, "deptype");
14785
14786         /*
14787          * Since we ordered the SELECT by referencing ID, we can expect that
14788          * multiple entries for the same object will appear together; this saves
14789          * on searches.
14790          */
14791         dobj = NULL;
14792
14793         for (i = 0; i < ntups; i++)
14794         {
14795                 CatalogId       objId;
14796                 CatalogId       refobjId;
14797                 char            deptype;
14798
14799                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14800                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14801                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14802                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14803                 deptype = *(PQgetvalue(res, i, i_deptype));
14804
14805                 if (dobj == NULL ||
14806                         dobj->catId.tableoid != objId.tableoid ||
14807                         dobj->catId.oid != objId.oid)
14808                         dobj = findObjectByCatalogId(objId);
14809
14810                 /*
14811                  * Failure to find objects mentioned in pg_depend is not unexpected,
14812                  * since for example we don't collect info about TOAST tables.
14813                  */
14814                 if (dobj == NULL)
14815                 {
14816 #ifdef NOT_USED
14817                         fprintf(stderr, "no referencing object %u %u\n",
14818                                         objId.tableoid, objId.oid);
14819 #endif
14820                         continue;
14821                 }
14822
14823                 refdobj = findObjectByCatalogId(refobjId);
14824
14825                 if (refdobj == NULL)
14826                 {
14827 #ifdef NOT_USED
14828                         fprintf(stderr, "no referenced object %u %u\n",
14829                                         refobjId.tableoid, refobjId.oid);
14830 #endif
14831                         continue;
14832                 }
14833
14834                 /*
14835                  * Ordinarily, table rowtypes have implicit dependencies on their
14836                  * tables.      However, for a composite type the implicit dependency goes
14837                  * the other way in pg_depend; which is the right thing for DROP but
14838                  * it doesn't produce the dependency ordering we need. So in that one
14839                  * case, we reverse the direction of the dependency.
14840                  */
14841                 if (deptype == 'i' &&
14842                         dobj->objType == DO_TABLE &&
14843                         refdobj->objType == DO_TYPE)
14844                         addObjectDependency(refdobj, dobj->dumpId);
14845                 else
14846                         /* normal case */
14847                         addObjectDependency(dobj, refdobj->dumpId);
14848         }
14849
14850         PQclear(res);
14851
14852         destroyPQExpBuffer(query);
14853 }
14854
14855
14856 /*
14857  * createBoundaryObjects - create dummy DumpableObjects to represent
14858  * dump section boundaries.
14859  */
14860 static DumpableObject *
14861 createBoundaryObjects(void)
14862 {
14863         DumpableObject *dobjs;
14864
14865         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14866
14867         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14868         dobjs[0].catId = nilCatalogId;
14869         AssignDumpId(dobjs + 0);
14870         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14871
14872         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14873         dobjs[1].catId = nilCatalogId;
14874         AssignDumpId(dobjs + 1);
14875         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14876
14877         return dobjs;
14878 }
14879
14880 /*
14881  * addBoundaryDependencies - add dependencies as needed to enforce the dump
14882  * section boundaries.
14883  */
14884 static void
14885 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14886                                                 DumpableObject *boundaryObjs)
14887 {
14888         DumpableObject *preDataBound = boundaryObjs + 0;
14889         DumpableObject *postDataBound = boundaryObjs + 1;
14890         int                     i;
14891
14892         for (i = 0; i < numObjs; i++)
14893         {
14894                 DumpableObject *dobj = dobjs[i];
14895
14896                 /*
14897                  * The classification of object types here must match the SECTION_xxx
14898                  * values assigned during subsequent ArchiveEntry calls!
14899                  */
14900                 switch (dobj->objType)
14901                 {
14902                         case DO_NAMESPACE:
14903                         case DO_EXTENSION:
14904                         case DO_TYPE:
14905                         case DO_SHELL_TYPE:
14906                         case DO_FUNC:
14907                         case DO_AGG:
14908                         case DO_OPERATOR:
14909                         case DO_OPCLASS:
14910                         case DO_OPFAMILY:
14911                         case DO_COLLATION:
14912                         case DO_CONVERSION:
14913                         case DO_TABLE:
14914                         case DO_ATTRDEF:
14915                         case DO_PROCLANG:
14916                         case DO_CAST:
14917                         case DO_DUMMY_TYPE:
14918                         case DO_TSPARSER:
14919                         case DO_TSDICT:
14920                         case DO_TSTEMPLATE:
14921                         case DO_TSCONFIG:
14922                         case DO_FDW:
14923                         case DO_FOREIGN_SERVER:
14924                         case DO_BLOB:
14925                                 /* Pre-data objects: must come before the pre-data boundary */
14926                                 addObjectDependency(preDataBound, dobj->dumpId);
14927                                 break;
14928                         case DO_TABLE_DATA:
14929                         case DO_BLOB_DATA:
14930                                 /* Data objects: must come between the boundaries */
14931                                 addObjectDependency(dobj, preDataBound->dumpId);
14932                                 addObjectDependency(postDataBound, dobj->dumpId);
14933                                 break;
14934                         case DO_INDEX:
14935                         case DO_REFRESH_MATVIEW:
14936                         case DO_TRIGGER:
14937                         case DO_EVENT_TRIGGER:
14938                         case DO_DEFAULT_ACL:
14939                                 /* Post-data objects: must come after the post-data boundary */
14940                                 addObjectDependency(dobj, postDataBound->dumpId);
14941                                 break;
14942                         case DO_RULE:
14943                                 /* Rules are post-data, but only if dumped separately */
14944                                 if (((RuleInfo *) dobj)->separate)
14945                                         addObjectDependency(dobj, postDataBound->dumpId);
14946                                 break;
14947                         case DO_CONSTRAINT:
14948                         case DO_FK_CONSTRAINT:
14949                                 /* Constraints are post-data, but only if dumped separately */
14950                                 if (((ConstraintInfo *) dobj)->separate)
14951                                         addObjectDependency(dobj, postDataBound->dumpId);
14952                                 break;
14953                         case DO_PRE_DATA_BOUNDARY:
14954                                 /* nothing to do */
14955                                 break;
14956                         case DO_POST_DATA_BOUNDARY:
14957                                 /* must come after the pre-data boundary */
14958                                 addObjectDependency(dobj, preDataBound->dumpId);
14959                                 break;
14960                 }
14961         }
14962 }
14963
14964
14965 /*
14966  * BuildArchiveDependencies - create dependency data for archive TOC entries
14967  *
14968  * The raw dependency data obtained by getDependencies() is not terribly
14969  * useful in an archive dump, because in many cases there are dependency
14970  * chains linking through objects that don't appear explicitly in the dump.
14971  * For example, a view will depend on its _RETURN rule while the _RETURN rule
14972  * will depend on other objects --- but the rule will not appear as a separate
14973  * object in the dump.  We need to adjust the view's dependencies to include
14974  * whatever the rule depends on that is included in the dump.
14975  *
14976  * Just to make things more complicated, there are also "special" dependencies
14977  * such as the dependency of a TABLE DATA item on its TABLE, which we must
14978  * not rearrange because pg_restore knows that TABLE DATA only depends on
14979  * its table.  In these cases we must leave the dependencies strictly as-is
14980  * even if they refer to not-to-be-dumped objects.
14981  *
14982  * To handle this, the convention is that "special" dependencies are created
14983  * during ArchiveEntry calls, and an archive TOC item that has any such
14984  * entries will not be touched here.  Otherwise, we recursively search the
14985  * DumpableObject data structures to build the correct dependencies for each
14986  * archive TOC item.
14987  */
14988 static void
14989 BuildArchiveDependencies(Archive *fout)
14990 {
14991         ArchiveHandle *AH = (ArchiveHandle *) fout;
14992         TocEntry   *te;
14993
14994         /* Scan all TOC entries in the archive */
14995         for (te = AH->toc->next; te != AH->toc; te = te->next)
14996         {
14997                 DumpableObject *dobj;
14998                 DumpId     *dependencies;
14999                 int                     nDeps;
15000                 int                     allocDeps;
15001
15002                 /* No need to process entries that will not be dumped */
15003                 if (te->reqs == 0)
15004                         continue;
15005                 /* Ignore entries that already have "special" dependencies */
15006                 if (te->nDeps > 0)
15007                         continue;
15008                 /* Otherwise, look up the item's original DumpableObject, if any */
15009                 dobj = findObjectByDumpId(te->dumpId);
15010                 if (dobj == NULL)
15011                         continue;
15012                 /* No work if it has no dependencies */
15013                 if (dobj->nDeps <= 0)
15014                         continue;
15015                 /* Set up work array */
15016                 allocDeps = 64;
15017                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
15018                 nDeps = 0;
15019                 /* Recursively find all dumpable dependencies */
15020                 findDumpableDependencies(AH, dobj,
15021                                                                  &dependencies, &nDeps, &allocDeps);
15022                 /* And save 'em ... */
15023                 if (nDeps > 0)
15024                 {
15025                         dependencies = (DumpId *) pg_realloc(dependencies,
15026                                                                                                  nDeps * sizeof(DumpId));
15027                         te->dependencies = dependencies;
15028                         te->nDeps = nDeps;
15029                 }
15030                 else
15031                         free(dependencies);
15032         }
15033 }
15034
15035 /* Recursive search subroutine for BuildArchiveDependencies */
15036 static void
15037 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
15038                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
15039 {
15040         int                     i;
15041
15042         /*
15043          * Ignore section boundary objects: if we search through them, we'll
15044          * report lots of bogus dependencies.
15045          */
15046         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
15047                 dobj->objType == DO_POST_DATA_BOUNDARY)
15048                 return;
15049
15050         for (i = 0; i < dobj->nDeps; i++)
15051         {
15052                 DumpId          depid = dobj->dependencies[i];
15053
15054                 if (TocIDRequired(AH, depid) != 0)
15055                 {
15056                         /* Object will be dumped, so just reference it as a dependency */
15057                         if (*nDeps >= *allocDeps)
15058                         {
15059                                 *allocDeps *= 2;
15060                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
15061                                                                                                 *allocDeps * sizeof(DumpId));
15062                         }
15063                         (*dependencies)[*nDeps] = depid;
15064                         (*nDeps)++;
15065                 }
15066                 else
15067                 {
15068                         /*
15069                          * Object will not be dumped, so recursively consider its deps. We
15070                          * rely on the assumption that sortDumpableObjects already broke
15071                          * any dependency loops, else we might recurse infinitely.
15072                          */
15073                         DumpableObject *otherdobj = findObjectByDumpId(depid);
15074
15075                         if (otherdobj)
15076                                 findDumpableDependencies(AH, otherdobj,
15077                                                                                  dependencies, nDeps, allocDeps);
15078                 }
15079         }
15080 }
15081
15082
15083 /*
15084  * selectSourceSchema - make the specified schema the active search path
15085  * in the source database.
15086  *
15087  * NB: pg_catalog is explicitly searched after the specified schema;
15088  * so user names are only qualified if they are cross-schema references,
15089  * and system names are only qualified if they conflict with a user name
15090  * in the current schema.
15091  *
15092  * Whenever the selected schema is not pg_catalog, be careful to qualify
15093  * references to system catalogs and types in our emitted commands!
15094  *
15095  * This function is called only from selectSourceSchemaOnAH and
15096  * selectSourceSchema.
15097  */
15098 static void
15099 selectSourceSchema(Archive *fout, const char *schemaName)
15100 {
15101         PQExpBuffer query;
15102
15103         /* This is checked by the callers already */
15104         Assert(schemaName != NULL && *schemaName != '\0');
15105
15106         /* Not relevant if fetching from pre-7.3 DB */
15107         if (fout->remoteVersion < 70300)
15108                 return;
15109
15110         query = createPQExpBuffer();
15111         appendPQExpBuffer(query, "SET search_path = %s",
15112                                           fmtId(schemaName));
15113         if (strcmp(schemaName, "pg_catalog") != 0)
15114                 appendPQExpBuffer(query, ", pg_catalog");
15115
15116         ExecuteSqlStatement(fout, query->data);
15117
15118         destroyPQExpBuffer(query);
15119 }
15120
15121 /*
15122  * getFormattedTypeName - retrieve a nicely-formatted type name for the
15123  * given type name.
15124  *
15125  * NB: in 7.3 and up the result may depend on the currently-selected
15126  * schema; this is why we don't try to cache the names.
15127  */
15128 static char *
15129 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
15130 {
15131         char       *result;
15132         PQExpBuffer query;
15133         PGresult   *res;
15134
15135         if (oid == 0)
15136         {
15137                 if ((opts & zeroAsOpaque) != 0)
15138                         return pg_strdup(g_opaque_type);
15139                 else if ((opts & zeroAsAny) != 0)
15140                         return pg_strdup("'any'");
15141                 else if ((opts & zeroAsStar) != 0)
15142                         return pg_strdup("*");
15143                 else if ((opts & zeroAsNone) != 0)
15144                         return pg_strdup("NONE");
15145         }
15146
15147         query = createPQExpBuffer();
15148         if (fout->remoteVersion >= 70300)
15149         {
15150                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
15151                                                   oid);
15152         }
15153         else if (fout->remoteVersion >= 70100)
15154         {
15155                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
15156                                                   oid);
15157         }
15158         else
15159         {
15160                 appendPQExpBuffer(query, "SELECT typname "
15161                                                   "FROM pg_type "
15162                                                   "WHERE oid = '%u'::oid",
15163                                                   oid);
15164         }
15165
15166         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15167
15168         if (fout->remoteVersion >= 70100)
15169         {
15170                 /* already quoted */
15171                 result = pg_strdup(PQgetvalue(res, 0, 0));
15172         }
15173         else
15174         {
15175                 /* may need to quote it */
15176                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
15177         }
15178
15179         PQclear(res);
15180         destroyPQExpBuffer(query);
15181
15182         return result;
15183 }
15184
15185 /*
15186  * myFormatType --- local implementation of format_type for use with 7.0.
15187  */
15188 static char *
15189 myFormatType(const char *typname, int32 typmod)
15190 {
15191         char       *result;
15192         bool            isarray = false;
15193         PQExpBuffer buf = createPQExpBuffer();
15194
15195         /* Handle array types */
15196         if (typname[0] == '_')
15197         {
15198                 isarray = true;
15199                 typname++;
15200         }
15201
15202         /* Show lengths on bpchar and varchar */
15203         if (strcmp(typname, "bpchar") == 0)
15204         {
15205                 int                     len = (typmod - VARHDRSZ);
15206
15207                 appendPQExpBuffer(buf, "character");
15208                 if (len > 1)
15209                         appendPQExpBuffer(buf, "(%d)",
15210                                                           typmod - VARHDRSZ);
15211         }
15212         else if (strcmp(typname, "varchar") == 0)
15213         {
15214                 appendPQExpBuffer(buf, "character varying");
15215                 if (typmod != -1)
15216                         appendPQExpBuffer(buf, "(%d)",
15217                                                           typmod - VARHDRSZ);
15218         }
15219         else if (strcmp(typname, "numeric") == 0)
15220         {
15221                 appendPQExpBuffer(buf, "numeric");
15222                 if (typmod != -1)
15223                 {
15224                         int32           tmp_typmod;
15225                         int                     precision;
15226                         int                     scale;
15227
15228                         tmp_typmod = typmod - VARHDRSZ;
15229                         precision = (tmp_typmod >> 16) & 0xffff;
15230                         scale = tmp_typmod & 0xffff;
15231                         appendPQExpBuffer(buf, "(%d,%d)",
15232                                                           precision, scale);
15233                 }
15234         }
15235
15236         /*
15237          * char is an internal single-byte data type; Let's make sure we force it
15238          * through with quotes. - thomas 1998-12-13
15239          */
15240         else if (strcmp(typname, "char") == 0)
15241                 appendPQExpBuffer(buf, "\"char\"");
15242         else
15243                 appendPQExpBuffer(buf, "%s", fmtId(typname));
15244
15245         /* Append array qualifier for array types */
15246         if (isarray)
15247                 appendPQExpBuffer(buf, "[]");
15248
15249         result = pg_strdup(buf->data);
15250         destroyPQExpBuffer(buf);
15251
15252         return result;
15253 }
15254
15255 /*
15256  * Return a column list clause for the given relation.
15257  *
15258  * Special case: if there are no undropped columns in the relation, return
15259  * "", not an invalid "()" column list.
15260  */
15261 static const char *
15262 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
15263 {
15264         int                     numatts = ti->numatts;
15265         char      **attnames = ti->attnames;
15266         bool       *attisdropped = ti->attisdropped;
15267         bool            needComma;
15268         int                     i;
15269
15270         appendPQExpBuffer(buffer, "(");
15271         needComma = false;
15272         for (i = 0; i < numatts; i++)
15273         {
15274                 if (attisdropped[i])
15275                         continue;
15276                 if (needComma)
15277                         appendPQExpBuffer(buffer, ", ");
15278                 appendPQExpBuffer(buffer, "%s", fmtId(attnames[i]));
15279                 needComma = true;
15280         }
15281
15282         if (!needComma)
15283                 return "";                              /* no undropped columns */
15284
15285         appendPQExpBuffer(buffer, ")");
15286         return buffer->data;
15287 }
15288
15289 /*
15290  * Execute an SQL query and verify that we got exactly one row back.
15291  */
15292 static PGresult *
15293 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
15294 {
15295         PGresult   *res;
15296         int                     ntups;
15297
15298         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
15299
15300         /* Expecting a single result only */
15301         ntups = PQntuples(res);
15302         if (ntups != 1)
15303                 exit_horribly(NULL,
15304                                           ngettext("query returned %d row instead of one: %s\n",
15305                                                            "query returned %d rows instead of one: %s\n",
15306                                                            ntups),
15307                                           ntups, query);
15308
15309         return res;
15310 }