]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Execute SET TRANSACTION SNAPSHOT during pg_dump
[postgresql] / src / bin / pg_dump / pg_dump.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_dump.c
4  *        pg_dump is a utility for dumping out a postgres database
5  *        into a script file.
6  *
7  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *      pg_dump will read the system catalogs in a database and dump out a
11  *      script that reproduces the schema in terms of SQL that is understood
12  *      by PostgreSQL
13  *
14  *      Note that pg_dump runs in a transaction-snapshot mode transaction,
15  *      so it sees a consistent snapshot of the database including system
16  *      catalogs. However, it relies in part on various specialized backend
17  *      functions like pg_get_indexdef(), and those things tend to run on
18  *      SnapshotNow time, ie they look at the currently committed state.  So
19  *      it is possible to get 'cache lookup failed' error if someone
20  *      performs DDL changes while a dump is happening. The window for this
21  *      sort of thing is from the acquisition of the transaction snapshot to
22  *      getSchemaData() (when pg_dump acquires AccessShareLock on every
23  *      table it intends to dump). It isn't very large, but it can happen.
24  *
25  *      http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
26  *
27  * IDENTIFICATION
28  *        src/bin/pg_dump/pg_dump.c
29  *
30  *-------------------------------------------------------------------------
31  */
32
33 #include "postgres_fe.h"
34
35 #include <unistd.h>
36 #include <ctype.h>
37 #ifdef ENABLE_NLS
38 #include <locale.h>
39 #endif
40 #ifdef HAVE_TERMIOS_H
41 #include <termios.h>
42 #endif
43
44 #include "getopt_long.h"
45
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_event_trigger.h"
53 #include "catalog/pg_largeobject.h"
54 #include "catalog/pg_largeobject_metadata.h"
55 #include "catalog/pg_proc.h"
56 #include "catalog/pg_trigger.h"
57 #include "catalog/pg_type.h"
58 #include "libpq/libpq-fs.h"
59
60 #include "pg_backup_archiver.h"
61 #include "pg_backup_db.h"
62 #include "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 scannable, skip this. */
1763         if (!tbinfo->isscannable)
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->isscannable)
1971                         tbinfo->isscannable = 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_class_reltoastidxid;
2782
2783         appendPQExpBuffer(upgrade_query,
2784                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2785                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2786                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
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_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
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_class_reltoastidxid);
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_isscannable;
4223         int                     i_owning_tab;
4224         int                     i_owning_col;
4225         int                     i_reltablespace;
4226         int                     i_reloptions;
4227         int                     i_toastreloptions;
4228         int                     i_reloftype;
4229         int                     i_relpages;
4230
4231         /* Make sure we are in proper schema */
4232         selectSourceSchema(fout, "pg_catalog");
4233
4234         /*
4235          * Find all the tables and table-like objects.
4236          *
4237          * We include system catalogs, so that we can work if a user table is
4238          * defined to inherit from a system catalog (pretty weird, but...)
4239          *
4240          * We ignore relations that are not ordinary tables, sequences, views,
4241          * materialized views, composite types, or foreign tables.
4242          *
4243          * Composite-type table entries won't be dumped as such, but we have to
4244          * make a DumpableObject for them so that we can track dependencies of the
4245          * composite type (pg_depend entries for columns of the composite type
4246          * link to the pg_class entry not the pg_type entry).
4247          *
4248          * Note: in this phase we should collect only a minimal amount of
4249          * information about each table, basically just enough to decide if it is
4250          * interesting. We must fetch all tables in this phase because otherwise
4251          * we cannot correctly identify inherited columns, owned sequences, etc.
4252          */
4253
4254         if (fout->remoteVersion >= 90300)
4255         {
4256                 /*
4257                  * Left join to pick up dependency info linking sequences to their
4258                  * owning column, if any (note this dependency is AUTO as of 8.2)
4259                  */
4260                 appendPQExpBuffer(query,
4261                                                   "SELECT c.tableoid, c.oid, c.relname, "
4262                                                   "c.relacl, c.relkind, c.relnamespace, "
4263                                                   "(%s c.relowner) AS rolname, "
4264                                                   "c.relchecks, c.relhastriggers, "
4265                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4266                                                   "c.relfrozenxid, tc.oid AS toid, "
4267                                                   "tc.relfrozenxid AS tfrozenxid, "
4268                                                   "c.relpersistence, "
4269                                                   "CASE WHEN c.relkind = '%c' THEN pg_relation_is_scannable(c.oid) ELSE 't'::bool END as isscannable, "
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(c.reloptions, ', ') AS reloptions, "
4276                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4277                                                   "FROM pg_class c "
4278                                                   "LEFT JOIN pg_depend d ON "
4279                                                   "(c.relkind = '%c' AND "
4280                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4281                                                   "d.objsubid = 0 AND "
4282                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4283                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4284                                    "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4285                                                   "ORDER BY c.oid",
4286                                                   username_subquery,
4287                                                   RELKIND_MATVIEW,
4288                                                   RELKIND_SEQUENCE,
4289                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4290                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4291                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4292         }
4293         else if (fout->remoteVersion >= 90100)
4294         {
4295                 /*
4296                  * Left join to pick up dependency info linking sequences to their
4297                  * owning column, if any (note this dependency is AUTO as of 8.2)
4298                  */
4299                 appendPQExpBuffer(query,
4300                                                   "SELECT c.tableoid, c.oid, c.relname, "
4301                                                   "c.relacl, c.relkind, c.relnamespace, "
4302                                                   "(%s c.relowner) AS rolname, "
4303                                                   "c.relchecks, c.relhastriggers, "
4304                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4305                                                   "c.relfrozenxid, tc.oid AS toid, "
4306                                                   "tc.relfrozenxid AS tfrozenxid, "
4307                                                   "c.relpersistence, 't'::bool as isscannable, "
4308                                                   "c.relpages, "
4309                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4310                                                   "d.refobjid AS owning_tab, "
4311                                                   "d.refobjsubid AS owning_col, "
4312                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4313                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4314                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4315                                                   "FROM pg_class c "
4316                                                   "LEFT JOIN pg_depend d ON "
4317                                                   "(c.relkind = '%c' AND "
4318                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4319                                                   "d.objsubid = 0 AND "
4320                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4321                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4322                                    "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4323                                                   "ORDER BY c.oid",
4324                                                   username_subquery,
4325                                                   RELKIND_SEQUENCE,
4326                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4327                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4328                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4329         }
4330         else if (fout->remoteVersion >= 90000)
4331         {
4332                 /*
4333                  * Left join to pick up dependency info linking sequences to their
4334                  * owning column, if any (note this dependency is AUTO as of 8.2)
4335                  */
4336                 appendPQExpBuffer(query,
4337                                                   "SELECT c.tableoid, c.oid, c.relname, "
4338                                                   "c.relacl, c.relkind, c.relnamespace, "
4339                                                   "(%s c.relowner) AS rolname, "
4340                                                   "c.relchecks, c.relhastriggers, "
4341                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4342                                                   "c.relfrozenxid, tc.oid AS toid, "
4343                                                   "tc.relfrozenxid AS tfrozenxid, "
4344                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4345                                                   "c.relpages, "
4346                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4347                                                   "d.refobjid AS owning_tab, "
4348                                                   "d.refobjsubid AS owning_col, "
4349                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4350                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4351                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4352                                                   "FROM pg_class c "
4353                                                   "LEFT JOIN pg_depend d ON "
4354                                                   "(c.relkind = '%c' AND "
4355                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4356                                                   "d.objsubid = 0 AND "
4357                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4358                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4359                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4360                                                   "ORDER BY c.oid",
4361                                                   username_subquery,
4362                                                   RELKIND_SEQUENCE,
4363                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4364                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4365         }
4366         else if (fout->remoteVersion >= 80400)
4367         {
4368                 /*
4369                  * Left join to pick up dependency info linking sequences to their
4370                  * owning column, if any (note this dependency is AUTO as of 8.2)
4371                  */
4372                 appendPQExpBuffer(query,
4373                                                   "SELECT c.tableoid, c.oid, c.relname, "
4374                                                   "c.relacl, c.relkind, c.relnamespace, "
4375                                                   "(%s c.relowner) AS rolname, "
4376                                                   "c.relchecks, c.relhastriggers, "
4377                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4378                                                   "c.relfrozenxid, tc.oid AS toid, "
4379                                                   "tc.relfrozenxid AS tfrozenxid, "
4380                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4381                                                   "c.relpages, "
4382                                                   "NULL AS reloftype, "
4383                                                   "d.refobjid AS owning_tab, "
4384                                                   "d.refobjsubid AS owning_col, "
4385                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4386                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4387                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4388                                                   "FROM pg_class c "
4389                                                   "LEFT JOIN pg_depend d ON "
4390                                                   "(c.relkind = '%c' AND "
4391                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4392                                                   "d.objsubid = 0 AND "
4393                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4394                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4395                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4396                                                   "ORDER BY c.oid",
4397                                                   username_subquery,
4398                                                   RELKIND_SEQUENCE,
4399                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4400                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4401         }
4402         else if (fout->remoteVersion >= 80200)
4403         {
4404                 /*
4405                  * Left join to pick up dependency info linking sequences to their
4406                  * owning column, if any (note this dependency is AUTO as of 8.2)
4407                  */
4408                 appendPQExpBuffer(query,
4409                                                   "SELECT c.tableoid, c.oid, c.relname, "
4410                                                   "c.relacl, c.relkind, c.relnamespace, "
4411                                                   "(%s c.relowner) AS rolname, "
4412                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4413                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4414                                                   "c.relfrozenxid, tc.oid AS toid, "
4415                                                   "tc.relfrozenxid AS tfrozenxid, "
4416                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4417                                                   "c.relpages, "
4418                                                   "NULL AS reloftype, "
4419                                                   "d.refobjid AS owning_tab, "
4420                                                   "d.refobjsubid AS owning_col, "
4421                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4422                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4423                                                   "NULL AS toast_reloptions "
4424                                                   "FROM pg_class c "
4425                                                   "LEFT JOIN pg_depend d ON "
4426                                                   "(c.relkind = '%c' AND "
4427                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4428                                                   "d.objsubid = 0 AND "
4429                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4430                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4431                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4432                                                   "ORDER BY c.oid",
4433                                                   username_subquery,
4434                                                   RELKIND_SEQUENCE,
4435                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4436                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4437         }
4438         else if (fout->remoteVersion >= 80000)
4439         {
4440                 /*
4441                  * Left join to pick up dependency info linking sequences to their
4442                  * owning column, if any
4443                  */
4444                 appendPQExpBuffer(query,
4445                                                   "SELECT c.tableoid, c.oid, relname, "
4446                                                   "relacl, relkind, relnamespace, "
4447                                                   "(%s relowner) AS rolname, "
4448                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4449                                                   "relhasindex, relhasrules, relhasoids, "
4450                                                   "0 AS relfrozenxid, "
4451                                                   "0 AS toid, "
4452                                                   "0 AS tfrozenxid, "
4453                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4454                                                   "relpages, "
4455                                                   "NULL AS reloftype, "
4456                                                   "d.refobjid AS owning_tab, "
4457                                                   "d.refobjsubid AS owning_col, "
4458                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4459                                                   "NULL AS reloptions, "
4460                                                   "NULL AS toast_reloptions "
4461                                                   "FROM pg_class c "
4462                                                   "LEFT JOIN pg_depend d ON "
4463                                                   "(c.relkind = '%c' AND "
4464                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4465                                                   "d.objsubid = 0 AND "
4466                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4467                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4468                                                   "ORDER BY c.oid",
4469                                                   username_subquery,
4470                                                   RELKIND_SEQUENCE,
4471                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4472                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4473         }
4474         else if (fout->remoteVersion >= 70300)
4475         {
4476                 /*
4477                  * Left join to pick up dependency info linking sequences to their
4478                  * owning column, if any
4479                  */
4480                 appendPQExpBuffer(query,
4481                                                   "SELECT c.tableoid, c.oid, relname, "
4482                                                   "relacl, relkind, relnamespace, "
4483                                                   "(%s relowner) AS rolname, "
4484                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4485                                                   "relhasindex, relhasrules, relhasoids, "
4486                                                   "0 AS relfrozenxid, "
4487                                                   "0 AS toid, "
4488                                                   "0 AS tfrozenxid, "
4489                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4490                                                   "relpages, "
4491                                                   "NULL AS reloftype, "
4492                                                   "d.refobjid AS owning_tab, "
4493                                                   "d.refobjsubid AS owning_col, "
4494                                                   "NULL AS reltablespace, "
4495                                                   "NULL AS reloptions, "
4496                                                   "NULL AS toast_reloptions "
4497                                                   "FROM pg_class c "
4498                                                   "LEFT JOIN pg_depend d ON "
4499                                                   "(c.relkind = '%c' AND "
4500                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4501                                                   "d.objsubid = 0 AND "
4502                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4503                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4504                                                   "ORDER BY c.oid",
4505                                                   username_subquery,
4506                                                   RELKIND_SEQUENCE,
4507                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4508                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4509         }
4510         else if (fout->remoteVersion >= 70200)
4511         {
4512                 appendPQExpBuffer(query,
4513                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4514                                                   "0::oid AS relnamespace, "
4515                                                   "(%s relowner) AS rolname, "
4516                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4517                                                   "relhasindex, relhasrules, relhasoids, "
4518                                                   "0 AS relfrozenxid, "
4519                                                   "0 AS toid, "
4520                                                   "0 AS tfrozenxid, "
4521                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4522                                                   "relpages, "
4523                                                   "NULL AS reloftype, "
4524                                                   "NULL::oid AS owning_tab, "
4525                                                   "NULL::int4 AS owning_col, "
4526                                                   "NULL AS reltablespace, "
4527                                                   "NULL AS reloptions, "
4528                                                   "NULL AS toast_reloptions "
4529                                                   "FROM pg_class "
4530                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4531                                                   "ORDER BY oid",
4532                                                   username_subquery,
4533                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4534         }
4535         else if (fout->remoteVersion >= 70100)
4536         {
4537                 /* all tables have oids in 7.1 */
4538                 appendPQExpBuffer(query,
4539                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4540                                                   "0::oid AS relnamespace, "
4541                                                   "(%s relowner) AS rolname, "
4542                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4543                                                   "relhasindex, relhasrules, "
4544                                                   "'t'::bool AS relhasoids, "
4545                                                   "0 AS relfrozenxid, "
4546                                                   "0 AS toid, "
4547                                                   "0 AS tfrozenxid, "
4548                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4549                                                   "relpages, "
4550                                                   "NULL AS reloftype, "
4551                                                   "NULL::oid AS owning_tab, "
4552                                                   "NULL::int4 AS owning_col, "
4553                                                   "NULL AS reltablespace, "
4554                                                   "NULL AS reloptions, "
4555                                                   "NULL AS toast_reloptions "
4556                                                   "FROM pg_class "
4557                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4558                                                   "ORDER BY oid",
4559                                                   username_subquery,
4560                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4561         }
4562         else
4563         {
4564                 /*
4565                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4566                  * have a view by looking for a rule in pg_rewrite.
4567                  */
4568                 appendPQExpBuffer(query,
4569                                                   "SELECT "
4570                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4571                                                   "oid, relname, relacl, "
4572                                                   "CASE WHEN relhasrules and relkind = 'r' "
4573                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4574                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4575                                                   "THEN '%c'::\"char\" "
4576                                                   "ELSE relkind END AS relkind,"
4577                                                   "0::oid AS relnamespace, "
4578                                                   "(%s relowner) AS rolname, "
4579                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4580                                                   "relhasindex, relhasrules, "
4581                                                   "'t'::bool AS relhasoids, "
4582                                                   "0 as relfrozenxid, "
4583                                                   "0 AS toid, "
4584                                                   "0 AS tfrozenxid, "
4585                                                   "'p' AS relpersistence, 't'::bool as isscannable, "
4586                                                   "0 AS relpages, "
4587                                                   "NULL AS reloftype, "
4588                                                   "NULL::oid AS owning_tab, "
4589                                                   "NULL::int4 AS owning_col, "
4590                                                   "NULL AS reltablespace, "
4591                                                   "NULL AS reloptions, "
4592                                                   "NULL AS toast_reloptions "
4593                                                   "FROM pg_class c "
4594                                                   "WHERE relkind IN ('%c', '%c') "
4595                                                   "ORDER BY oid",
4596                                                   RELKIND_VIEW,
4597                                                   username_subquery,
4598                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4599         }
4600
4601         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4602
4603         ntups = PQntuples(res);
4604
4605         *numTables = ntups;
4606
4607         /*
4608          * Extract data from result and lock dumpable tables.  We do the locking
4609          * before anything else, to minimize the window wherein a table could
4610          * disappear under us.
4611          *
4612          * Note that we have to save info about all tables here, even when dumping
4613          * only one, because we don't yet know which tables might be inheritance
4614          * ancestors of the target table.
4615          */
4616         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4617
4618         i_reltableoid = PQfnumber(res, "tableoid");
4619         i_reloid = PQfnumber(res, "oid");
4620         i_relname = PQfnumber(res, "relname");
4621         i_relnamespace = PQfnumber(res, "relnamespace");
4622         i_relacl = PQfnumber(res, "relacl");
4623         i_relkind = PQfnumber(res, "relkind");
4624         i_rolname = PQfnumber(res, "rolname");
4625         i_relchecks = PQfnumber(res, "relchecks");
4626         i_relhastriggers = PQfnumber(res, "relhastriggers");
4627         i_relhasindex = PQfnumber(res, "relhasindex");
4628         i_relhasrules = PQfnumber(res, "relhasrules");
4629         i_relhasoids = PQfnumber(res, "relhasoids");
4630         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4631         i_toastoid = PQfnumber(res, "toid");
4632         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4633         i_relpersistence = PQfnumber(res, "relpersistence");
4634         i_isscannable = PQfnumber(res, "isscannable");
4635         i_relpages = PQfnumber(res, "relpages");
4636         i_owning_tab = PQfnumber(res, "owning_tab");
4637         i_owning_col = PQfnumber(res, "owning_col");
4638         i_reltablespace = PQfnumber(res, "reltablespace");
4639         i_reloptions = PQfnumber(res, "reloptions");
4640         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4641         i_reloftype = PQfnumber(res, "reloftype");
4642
4643         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4644         {
4645                 /*
4646                  * Arrange to fail instead of waiting forever for a table lock.
4647                  *
4648                  * NB: this coding assumes that the only queries issued within the
4649                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4650                  * applied to other things too.
4651                  */
4652                 resetPQExpBuffer(query);
4653                 appendPQExpBuffer(query, "SET statement_timeout = ");
4654                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4655                 ExecuteSqlStatement(fout, query->data);
4656         }
4657
4658         for (i = 0; i < ntups; i++)
4659         {
4660                 tblinfo[i].dobj.objType = DO_TABLE;
4661                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4662                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4663                 AssignDumpId(&tblinfo[i].dobj);
4664                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4665                 tblinfo[i].dobj.namespace =
4666                         findNamespace(fout,
4667                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4668                                                   tblinfo[i].dobj.catId.oid);
4669                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4670                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4671                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4672                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4673                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4674                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4675                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4676                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4677                 tblinfo[i].isscannable = (strcmp(PQgetvalue(res, i, i_isscannable), "t") == 0);
4678                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
4679                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4680                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4681                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4682                 if (PQgetisnull(res, i, i_reloftype))
4683                         tblinfo[i].reloftype = NULL;
4684                 else
4685                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4686                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4687                 if (PQgetisnull(res, i, i_owning_tab))
4688                 {
4689                         tblinfo[i].owning_tab = InvalidOid;
4690                         tblinfo[i].owning_col = 0;
4691                 }
4692                 else
4693                 {
4694                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4695                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4696                 }
4697                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4698                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4699                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4700
4701                 /* other fields were zeroed above */
4702
4703                 /*
4704                  * Decide whether we want to dump this table.
4705                  */
4706                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4707                         tblinfo[i].dobj.dump = false;
4708                 else
4709                         selectDumpableTable(&tblinfo[i]);
4710                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4711
4712                 /*
4713                  * Read-lock target tables to make sure they aren't DROPPED or altered
4714                  * in schema before we get around to dumping them.
4715                  *
4716                  * Note that we don't explicitly lock parents of the target tables; we
4717                  * assume our lock on the child is enough to prevent schema
4718                  * alterations to parent tables.
4719                  *
4720                  * NOTE: it'd be kinda nice to lock other relations too, not only
4721                  * plain tables, but the backend doesn't presently allow that.
4722                  */
4723                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4724                 {
4725                         resetPQExpBuffer(query);
4726                         appendPQExpBuffer(query,
4727                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4728                                                           fmtQualifiedId(fout->remoteVersion,
4729                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4730                                                                                          tblinfo[i].dobj.name));
4731                         ExecuteSqlStatement(fout, query->data);
4732                 }
4733
4734                 /* Emit notice if join for owner failed */
4735                 if (strlen(tblinfo[i].rolname) == 0)
4736                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4737                                           tblinfo[i].dobj.name);
4738         }
4739
4740         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4741         {
4742                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4743         }
4744
4745         PQclear(res);
4746
4747         destroyPQExpBuffer(query);
4748
4749         return tblinfo;
4750 }
4751
4752 /*
4753  * getOwnedSeqs
4754  *        identify owned sequences and mark them as dumpable if owning table is
4755  *
4756  * We used to do this in getTables(), but it's better to do it after the
4757  * index used by findTableByOid() has been set up.
4758  */
4759 void
4760 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4761 {
4762         int                     i;
4763
4764         /*
4765          * Force sequences that are "owned" by table columns to be dumped whenever
4766          * their owning table is being dumped.
4767          */
4768         for (i = 0; i < numTables; i++)
4769         {
4770                 TableInfo  *seqinfo = &tblinfo[i];
4771                 TableInfo  *owning_tab;
4772
4773                 if (!OidIsValid(seqinfo->owning_tab))
4774                         continue;                       /* not an owned sequence */
4775                 if (seqinfo->dobj.dump)
4776                         continue;                       /* no need to search */
4777                 owning_tab = findTableByOid(seqinfo->owning_tab);
4778                 if (owning_tab && owning_tab->dobj.dump)
4779                 {
4780                         seqinfo->interesting = true;
4781                         seqinfo->dobj.dump = true;
4782                 }
4783         }
4784 }
4785
4786 /*
4787  * getInherits
4788  *        read all the inheritance information
4789  * from the system catalogs return them in the InhInfo* structure
4790  *
4791  * numInherits is set to the number of pairs read in
4792  */
4793 InhInfo *
4794 getInherits(Archive *fout, int *numInherits)
4795 {
4796         PGresult   *res;
4797         int                     ntups;
4798         int                     i;
4799         PQExpBuffer query = createPQExpBuffer();
4800         InhInfo    *inhinfo;
4801
4802         int                     i_inhrelid;
4803         int                     i_inhparent;
4804
4805         /* Make sure we are in proper schema */
4806         selectSourceSchema(fout, "pg_catalog");
4807
4808         /* find all the inheritance information */
4809
4810         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4811
4812         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4813
4814         ntups = PQntuples(res);
4815
4816         *numInherits = ntups;
4817
4818         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4819
4820         i_inhrelid = PQfnumber(res, "inhrelid");
4821         i_inhparent = PQfnumber(res, "inhparent");
4822
4823         for (i = 0; i < ntups; i++)
4824         {
4825                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4826                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4827         }
4828
4829         PQclear(res);
4830
4831         destroyPQExpBuffer(query);
4832
4833         return inhinfo;
4834 }
4835
4836 /*
4837  * getIndexes
4838  *        get information about every index on a dumpable table
4839  *
4840  * Note: index data is not returned directly to the caller, but it
4841  * does get entered into the DumpableObject tables.
4842  */
4843 void
4844 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4845 {
4846         int                     i,
4847                                 j;
4848         PQExpBuffer query = createPQExpBuffer();
4849         PGresult   *res;
4850         IndxInfo   *indxinfo;
4851         ConstraintInfo *constrinfo;
4852         int                     i_tableoid,
4853                                 i_oid,
4854                                 i_indexname,
4855                                 i_indexdef,
4856                                 i_indnkeys,
4857                                 i_indkey,
4858                                 i_indisclustered,
4859                                 i_contype,
4860                                 i_conname,
4861                                 i_condeferrable,
4862                                 i_condeferred,
4863                                 i_contableoid,
4864                                 i_conoid,
4865                                 i_condef,
4866                                 i_tablespace,
4867                                 i_options,
4868                                 i_relpages;
4869         int                     ntups;
4870
4871         for (i = 0; i < numTables; i++)
4872         {
4873                 TableInfo  *tbinfo = &tblinfo[i];
4874
4875                 /* Only plain tables and materialized views have indexes. */
4876                 if (tbinfo->relkind != RELKIND_RELATION &&
4877                         tbinfo->relkind != RELKIND_MATVIEW)
4878                         continue;
4879                 if (!tbinfo->hasindex)
4880                         continue;
4881
4882                 /* Ignore indexes of tables not to be dumped */
4883                 if (!tbinfo->dobj.dump)
4884                         continue;
4885
4886                 if (g_verbose)
4887                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4888                                           tbinfo->dobj.name);
4889
4890                 /* Make sure we are in proper schema so indexdef is right */
4891                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4892
4893                 /*
4894                  * The point of the messy-looking outer join is to find a constraint
4895                  * that is related by an internal dependency link to the index. If we
4896                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4897                  * assume an index won't have more than one internal dependency.
4898                  *
4899                  * As of 9.0 we don't need to look at pg_depend but can check for a
4900                  * match to pg_constraint.conindid.  The check on conrelid is
4901                  * redundant but useful because that column is indexed while conindid
4902                  * is not.
4903                  */
4904                 resetPQExpBuffer(query);
4905                 if (fout->remoteVersion >= 90000)
4906                 {
4907                         /*
4908                          * the test on indisready is necessary in 9.2, and harmless in
4909                          * earlier/later versions
4910                          */
4911                         appendPQExpBuffer(query,
4912                                                           "SELECT t.tableoid, t.oid, "
4913                                                           "t.relname AS indexname, "
4914                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4915                                                           "t.relnatts AS indnkeys, "
4916                                                           "i.indkey, i.indisclustered, "
4917                                                           "t.relpages, "
4918                                                           "c.contype, c.conname, "
4919                                                           "c.condeferrable, c.condeferred, "
4920                                                           "c.tableoid AS contableoid, "
4921                                                           "c.oid AS conoid, "
4922                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4923                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4924                                                         "array_to_string(t.reloptions, ', ') AS options "
4925                                                           "FROM pg_catalog.pg_index i "
4926                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4927                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4928                                                           "ON (i.indrelid = c.conrelid AND "
4929                                                           "i.indexrelid = c.conindid AND "
4930                                                           "c.contype IN ('p','u','x')) "
4931                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4932                                                           "AND i.indisvalid AND i.indisready "
4933                                                           "ORDER BY indexname",
4934                                                           tbinfo->dobj.catId.oid);
4935                 }
4936                 else if (fout->remoteVersion >= 80200)
4937                 {
4938                         appendPQExpBuffer(query,
4939                                                           "SELECT t.tableoid, t.oid, "
4940                                                           "t.relname AS indexname, "
4941                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4942                                                           "t.relnatts AS indnkeys, "
4943                                                           "i.indkey, i.indisclustered, "
4944                                                           "t.relpages, "
4945                                                           "c.contype, c.conname, "
4946                                                           "c.condeferrable, c.condeferred, "
4947                                                           "c.tableoid AS contableoid, "
4948                                                           "c.oid AS conoid, "
4949                                                           "null AS condef, "
4950                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4951                                                         "array_to_string(t.reloptions, ', ') AS options "
4952                                                           "FROM pg_catalog.pg_index i "
4953                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4954                                                           "LEFT JOIN pg_catalog.pg_depend d "
4955                                                           "ON (d.classid = t.tableoid "
4956                                                           "AND d.objid = t.oid "
4957                                                           "AND d.deptype = 'i') "
4958                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4959                                                           "ON (d.refclassid = c.tableoid "
4960                                                           "AND d.refobjid = c.oid) "
4961                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4962                                                           "AND i.indisvalid "
4963                                                           "ORDER BY indexname",
4964                                                           tbinfo->dobj.catId.oid);
4965                 }
4966                 else if (fout->remoteVersion >= 80000)
4967                 {
4968                         appendPQExpBuffer(query,
4969                                                           "SELECT t.tableoid, t.oid, "
4970                                                           "t.relname AS indexname, "
4971                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4972                                                           "t.relnatts AS indnkeys, "
4973                                                           "i.indkey, i.indisclustered, "
4974                                                           "t.relpages, "
4975                                                           "c.contype, c.conname, "
4976                                                           "c.condeferrable, c.condeferred, "
4977                                                           "c.tableoid AS contableoid, "
4978                                                           "c.oid AS conoid, "
4979                                                           "null AS condef, "
4980                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4981                                                           "null AS options "
4982                                                           "FROM pg_catalog.pg_index i "
4983                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4984                                                           "LEFT JOIN pg_catalog.pg_depend d "
4985                                                           "ON (d.classid = t.tableoid "
4986                                                           "AND d.objid = t.oid "
4987                                                           "AND d.deptype = 'i') "
4988                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4989                                                           "ON (d.refclassid = c.tableoid "
4990                                                           "AND d.refobjid = c.oid) "
4991                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4992                                                           "ORDER BY indexname",
4993                                                           tbinfo->dobj.catId.oid);
4994                 }
4995                 else if (fout->remoteVersion >= 70300)
4996                 {
4997                         appendPQExpBuffer(query,
4998                                                           "SELECT t.tableoid, t.oid, "
4999                                                           "t.relname AS indexname, "
5000                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
5001                                                           "t.relnatts AS indnkeys, "
5002                                                           "i.indkey, i.indisclustered, "
5003                                                           "t.relpages, "
5004                                                           "c.contype, c.conname, "
5005                                                           "c.condeferrable, c.condeferred, "
5006                                                           "c.tableoid AS contableoid, "
5007                                                           "c.oid AS conoid, "
5008                                                           "null AS condef, "
5009                                                           "NULL AS tablespace, "
5010                                                           "null AS options "
5011                                                           "FROM pg_catalog.pg_index i "
5012                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
5013                                                           "LEFT JOIN pg_catalog.pg_depend d "
5014                                                           "ON (d.classid = t.tableoid "
5015                                                           "AND d.objid = t.oid "
5016                                                           "AND d.deptype = 'i') "
5017                                                           "LEFT JOIN pg_catalog.pg_constraint c "
5018                                                           "ON (d.refclassid = c.tableoid "
5019                                                           "AND d.refobjid = c.oid) "
5020                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
5021                                                           "ORDER BY indexname",
5022                                                           tbinfo->dobj.catId.oid);
5023                 }
5024                 else if (fout->remoteVersion >= 70100)
5025                 {
5026                         appendPQExpBuffer(query,
5027                                                           "SELECT t.tableoid, t.oid, "
5028                                                           "t.relname AS indexname, "
5029                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
5030                                                           "t.relnatts AS indnkeys, "
5031                                                           "i.indkey, false AS indisclustered, "
5032                                                           "t.relpages, "
5033                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
5034                                                           "ELSE '0'::char END AS contype, "
5035                                                           "t.relname AS conname, "
5036                                                           "false AS condeferrable, "
5037                                                           "false AS condeferred, "
5038                                                           "0::oid AS contableoid, "
5039                                                           "t.oid AS conoid, "
5040                                                           "null AS condef, "
5041                                                           "NULL AS tablespace, "
5042                                                           "null AS options "
5043                                                           "FROM pg_index i, pg_class t "
5044                                                           "WHERE t.oid = i.indexrelid "
5045                                                           "AND i.indrelid = '%u'::oid "
5046                                                           "ORDER BY indexname",
5047                                                           tbinfo->dobj.catId.oid);
5048                 }
5049                 else
5050                 {
5051                         appendPQExpBuffer(query,
5052                                                           "SELECT "
5053                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
5054                                                           "t.oid, "
5055                                                           "t.relname AS indexname, "
5056                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
5057                                                           "t.relnatts AS indnkeys, "
5058                                                           "i.indkey, false AS indisclustered, "
5059                                                           "t.relpages, "
5060                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
5061                                                           "ELSE '0'::char END AS contype, "
5062                                                           "t.relname AS conname, "
5063                                                           "false AS condeferrable, "
5064                                                           "false AS condeferred, "
5065                                                           "0::oid AS contableoid, "
5066                                                           "t.oid AS conoid, "
5067                                                           "null AS condef, "
5068                                                           "NULL AS tablespace, "
5069                                                           "null AS options "
5070                                                           "FROM pg_index i, pg_class t "
5071                                                           "WHERE t.oid = i.indexrelid "
5072                                                           "AND i.indrelid = '%u'::oid "
5073                                                           "ORDER BY indexname",
5074                                                           tbinfo->dobj.catId.oid);
5075                 }
5076
5077                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5078
5079                 ntups = PQntuples(res);
5080
5081                 i_tableoid = PQfnumber(res, "tableoid");
5082                 i_oid = PQfnumber(res, "oid");
5083                 i_indexname = PQfnumber(res, "indexname");
5084                 i_indexdef = PQfnumber(res, "indexdef");
5085                 i_indnkeys = PQfnumber(res, "indnkeys");
5086                 i_indkey = PQfnumber(res, "indkey");
5087                 i_indisclustered = PQfnumber(res, "indisclustered");
5088                 i_relpages = PQfnumber(res, "relpages");
5089                 i_contype = PQfnumber(res, "contype");
5090                 i_conname = PQfnumber(res, "conname");
5091                 i_condeferrable = PQfnumber(res, "condeferrable");
5092                 i_condeferred = PQfnumber(res, "condeferred");
5093                 i_contableoid = PQfnumber(res, "contableoid");
5094                 i_conoid = PQfnumber(res, "conoid");
5095                 i_condef = PQfnumber(res, "condef");
5096                 i_tablespace = PQfnumber(res, "tablespace");
5097                 i_options = PQfnumber(res, "options");
5098
5099                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
5100                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5101
5102                 for (j = 0; j < ntups; j++)
5103                 {
5104                         char            contype;
5105
5106                         indxinfo[j].dobj.objType = DO_INDEX;
5107                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5108                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5109                         AssignDumpId(&indxinfo[j].dobj);
5110                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
5111                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5112                         indxinfo[j].indextable = tbinfo;
5113                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
5114                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
5115                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
5116                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
5117
5118                         /*
5119                          * In pre-7.4 releases, indkeys may contain more entries than
5120                          * indnkeys says (since indnkeys will be 1 for a functional
5121                          * index).      We don't actually care about this case since we don't
5122                          * examine indkeys except for indexes associated with PRIMARY and
5123                          * UNIQUE constraints, which are never functional indexes. But we
5124                          * have to allocate enough space to keep parseOidArray from
5125                          * complaining.
5126                          */
5127                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
5128                         parseOidArray(PQgetvalue(res, j, i_indkey),
5129                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
5130                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
5131                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
5132                         contype = *(PQgetvalue(res, j, i_contype));
5133
5134                         if (contype == 'p' || contype == 'u' || contype == 'x')
5135                         {
5136                                 /*
5137                                  * If we found a constraint matching the index, create an
5138                                  * entry for it.
5139                                  *
5140                                  * In a pre-7.3 database, we take this path iff the index was
5141                                  * marked indisprimary.
5142                                  */
5143                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
5144                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5145                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5146                                 AssignDumpId(&constrinfo[j].dobj);
5147                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5148                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5149                                 constrinfo[j].contable = tbinfo;
5150                                 constrinfo[j].condomain = NULL;
5151                                 constrinfo[j].contype = contype;
5152                                 if (contype == 'x')
5153                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5154                                 else
5155                                         constrinfo[j].condef = NULL;
5156                                 constrinfo[j].confrelid = InvalidOid;
5157                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
5158                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
5159                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
5160                                 constrinfo[j].conislocal = true;
5161                                 constrinfo[j].separate = true;
5162
5163                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
5164
5165                                 /* If pre-7.3 DB, better make sure table comes first */
5166                                 addObjectDependency(&constrinfo[j].dobj,
5167                                                                         tbinfo->dobj.dumpId);
5168                         }
5169                         else
5170                         {
5171                                 /* Plain secondary index */
5172                                 indxinfo[j].indexconstraint = 0;
5173                         }
5174                 }
5175
5176                 PQclear(res);
5177         }
5178
5179         destroyPQExpBuffer(query);
5180 }
5181
5182 /*
5183  * getConstraints
5184  *
5185  * Get info about constraints on dumpable tables.
5186  *
5187  * Currently handles foreign keys only.
5188  * Unique and primary key constraints are handled with indexes,
5189  * while check constraints are processed in getTableAttrs().
5190  */
5191 void
5192 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
5193 {
5194         int                     i,
5195                                 j;
5196         ConstraintInfo *constrinfo;
5197         PQExpBuffer query;
5198         PGresult   *res;
5199         int                     i_contableoid,
5200                                 i_conoid,
5201                                 i_conname,
5202                                 i_confrelid,
5203                                 i_condef;
5204         int                     ntups;
5205
5206         /* pg_constraint was created in 7.3, so nothing to do if older */
5207         if (fout->remoteVersion < 70300)
5208                 return;
5209
5210         query = createPQExpBuffer();
5211
5212         for (i = 0; i < numTables; i++)
5213         {
5214                 TableInfo  *tbinfo = &tblinfo[i];
5215
5216                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5217                         continue;
5218
5219                 if (g_verbose)
5220                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
5221                                           tbinfo->dobj.name);
5222
5223                 /*
5224                  * select table schema to ensure constraint expr is qualified if
5225                  * needed
5226                  */
5227                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5228
5229                 resetPQExpBuffer(query);
5230                 appendPQExpBuffer(query,
5231                                                   "SELECT tableoid, oid, conname, confrelid, "
5232                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
5233                                                   "FROM pg_catalog.pg_constraint "
5234                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5235                                                   "AND contype = 'f'",
5236                                                   tbinfo->dobj.catId.oid);
5237                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5238
5239                 ntups = PQntuples(res);
5240
5241                 i_contableoid = PQfnumber(res, "tableoid");
5242                 i_conoid = PQfnumber(res, "oid");
5243                 i_conname = PQfnumber(res, "conname");
5244                 i_confrelid = PQfnumber(res, "confrelid");
5245                 i_condef = PQfnumber(res, "condef");
5246
5247                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5248
5249                 for (j = 0; j < ntups; j++)
5250                 {
5251                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
5252                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5253                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5254                         AssignDumpId(&constrinfo[j].dobj);
5255                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5256                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5257                         constrinfo[j].contable = tbinfo;
5258                         constrinfo[j].condomain = NULL;
5259                         constrinfo[j].contype = 'f';
5260                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5261                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
5262                         constrinfo[j].conindex = 0;
5263                         constrinfo[j].condeferrable = false;
5264                         constrinfo[j].condeferred = false;
5265                         constrinfo[j].conislocal = true;
5266                         constrinfo[j].separate = true;
5267                 }
5268
5269                 PQclear(res);
5270         }
5271
5272         destroyPQExpBuffer(query);
5273 }
5274
5275 /*
5276  * getDomainConstraints
5277  *
5278  * Get info about constraints on a domain.
5279  */
5280 static void
5281 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
5282 {
5283         int                     i;
5284         ConstraintInfo *constrinfo;
5285         PQExpBuffer query;
5286         PGresult   *res;
5287         int                     i_tableoid,
5288                                 i_oid,
5289                                 i_conname,
5290                                 i_consrc;
5291         int                     ntups;
5292
5293         /* pg_constraint was created in 7.3, so nothing to do if older */
5294         if (fout->remoteVersion < 70300)
5295                 return;
5296
5297         /*
5298          * select appropriate schema to ensure names in constraint are properly
5299          * qualified
5300          */
5301         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
5302
5303         query = createPQExpBuffer();
5304
5305         if (fout->remoteVersion >= 90100)
5306                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5307                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5308                                                   "convalidated "
5309                                                   "FROM pg_catalog.pg_constraint "
5310                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5311                                                   "ORDER BY conname",
5312                                                   tyinfo->dobj.catId.oid);
5313
5314         else if (fout->remoteVersion >= 70400)
5315                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5316                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5317                                                   "true as convalidated "
5318                                                   "FROM pg_catalog.pg_constraint "
5319                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5320                                                   "ORDER BY conname",
5321                                                   tyinfo->dobj.catId.oid);
5322         else
5323                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5324                                                   "'CHECK (' || consrc || ')' AS consrc, "
5325                                                   "true as convalidated "
5326                                                   "FROM pg_catalog.pg_constraint "
5327                                                   "WHERE contypid = '%u'::pg_catalog.oid "
5328                                                   "ORDER BY conname",
5329                                                   tyinfo->dobj.catId.oid);
5330
5331         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5332
5333         ntups = PQntuples(res);
5334
5335         i_tableoid = PQfnumber(res, "tableoid");
5336         i_oid = PQfnumber(res, "oid");
5337         i_conname = PQfnumber(res, "conname");
5338         i_consrc = PQfnumber(res, "consrc");
5339
5340         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5341
5342         tyinfo->nDomChecks = ntups;
5343         tyinfo->domChecks = constrinfo;
5344
5345         for (i = 0; i < ntups; i++)
5346         {
5347                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
5348
5349                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5350                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5351                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5352                 AssignDumpId(&constrinfo[i].dobj);
5353                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5354                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5355                 constrinfo[i].contable = NULL;
5356                 constrinfo[i].condomain = tyinfo;
5357                 constrinfo[i].contype = 'c';
5358                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5359                 constrinfo[i].confrelid = InvalidOid;
5360                 constrinfo[i].conindex = 0;
5361                 constrinfo[i].condeferrable = false;
5362                 constrinfo[i].condeferred = false;
5363                 constrinfo[i].conislocal = true;
5364
5365                 constrinfo[i].separate = !validated;
5366
5367                 /*
5368                  * Make the domain depend on the constraint, ensuring it won't be
5369                  * output till any constraint dependencies are OK.      If the constraint
5370                  * has not been validated, it's going to be dumped after the domain
5371                  * anyway, so this doesn't matter.
5372                  */
5373                 if (validated)
5374                         addObjectDependency(&tyinfo->dobj,
5375                                                                 constrinfo[i].dobj.dumpId);
5376         }
5377
5378         PQclear(res);
5379
5380         destroyPQExpBuffer(query);
5381 }
5382
5383 /*
5384  * getRules
5385  *        get basic information about every rule in the system
5386  *
5387  * numRules is set to the number of rules read in
5388  */
5389 RuleInfo *
5390 getRules(Archive *fout, int *numRules)
5391 {
5392         PGresult   *res;
5393         int                     ntups;
5394         int                     i;
5395         PQExpBuffer query = createPQExpBuffer();
5396         RuleInfo   *ruleinfo;
5397         int                     i_tableoid;
5398         int                     i_oid;
5399         int                     i_rulename;
5400         int                     i_ruletable;
5401         int                     i_ev_type;
5402         int                     i_is_instead;
5403         int                     i_ev_enabled;
5404
5405         /* Make sure we are in proper schema */
5406         selectSourceSchema(fout, "pg_catalog");
5407
5408         if (fout->remoteVersion >= 80300)
5409         {
5410                 appendPQExpBuffer(query, "SELECT "
5411                                                   "tableoid, oid, rulename, "
5412                                                   "ev_class AS ruletable, ev_type, is_instead, "
5413                                                   "ev_enabled "
5414                                                   "FROM pg_rewrite "
5415                                                   "ORDER BY oid");
5416         }
5417         else if (fout->remoteVersion >= 70100)
5418         {
5419                 appendPQExpBuffer(query, "SELECT "
5420                                                   "tableoid, oid, rulename, "
5421                                                   "ev_class AS ruletable, ev_type, is_instead, "
5422                                                   "'O'::char AS ev_enabled "
5423                                                   "FROM pg_rewrite "
5424                                                   "ORDER BY oid");
5425         }
5426         else
5427         {
5428                 appendPQExpBuffer(query, "SELECT "
5429                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5430                                                   "oid, rulename, "
5431                                                   "ev_class AS ruletable, ev_type, is_instead, "
5432                                                   "'O'::char AS ev_enabled "
5433                                                   "FROM pg_rewrite "
5434                                                   "ORDER BY oid");
5435         }
5436
5437         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5438
5439         ntups = PQntuples(res);
5440
5441         *numRules = ntups;
5442
5443         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5444
5445         i_tableoid = PQfnumber(res, "tableoid");
5446         i_oid = PQfnumber(res, "oid");
5447         i_rulename = PQfnumber(res, "rulename");
5448         i_ruletable = PQfnumber(res, "ruletable");
5449         i_ev_type = PQfnumber(res, "ev_type");
5450         i_is_instead = PQfnumber(res, "is_instead");
5451         i_ev_enabled = PQfnumber(res, "ev_enabled");
5452
5453         for (i = 0; i < ntups; i++)
5454         {
5455                 Oid                     ruletableoid;
5456
5457                 ruleinfo[i].dobj.objType = DO_RULE;
5458                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5459                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5460                 AssignDumpId(&ruleinfo[i].dobj);
5461                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5462                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5463                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5464                 if (ruleinfo[i].ruletable == NULL)
5465                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5466                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5467                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5468                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5469                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5470                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5471                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5472                 if (ruleinfo[i].ruletable)
5473                 {
5474                         /*
5475                          * If the table is a view or materialized view, force its ON
5476                          * SELECT rule to be sorted before the view itself --- this
5477                          * ensures that any dependencies for the rule affect the table's
5478                          * positioning. Other rules are forced to appear after their
5479                          * table.
5480                          */
5481                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
5482                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
5483                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5484                         {
5485                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5486                                                                         ruleinfo[i].dobj.dumpId);
5487                                 /* We'll merge the rule into CREATE VIEW, if possible */
5488                                 ruleinfo[i].separate = false;
5489                         }
5490                         else
5491                         {
5492                                 addObjectDependency(&ruleinfo[i].dobj,
5493                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5494                                 ruleinfo[i].separate = true;
5495                         }
5496                 }
5497                 else
5498                         ruleinfo[i].separate = true;
5499
5500                 /*
5501                  * If we're forced to break a dependency loop by dumping a view as a
5502                  * table and separate _RETURN rule, we'll move the view's reloptions
5503                  * to the rule.  (This is necessary because tables and views have
5504                  * different valid reloptions, so we can't apply the options until the
5505                  * backend knows it's a view.)  Otherwise the rule's reloptions stay
5506                  * NULL.
5507                  */
5508                 ruleinfo[i].reloptions = NULL;
5509         }
5510
5511         PQclear(res);
5512
5513         destroyPQExpBuffer(query);
5514
5515         return ruleinfo;
5516 }
5517
5518 /*
5519  * getTriggers
5520  *        get information about every trigger on a dumpable table
5521  *
5522  * Note: trigger data is not returned directly to the caller, but it
5523  * does get entered into the DumpableObject tables.
5524  */
5525 void
5526 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5527 {
5528         int                     i,
5529                                 j;
5530         PQExpBuffer query = createPQExpBuffer();
5531         PGresult   *res;
5532         TriggerInfo *tginfo;
5533         int                     i_tableoid,
5534                                 i_oid,
5535                                 i_tgname,
5536                                 i_tgfname,
5537                                 i_tgtype,
5538                                 i_tgnargs,
5539                                 i_tgargs,
5540                                 i_tgisconstraint,
5541                                 i_tgconstrname,
5542                                 i_tgconstrrelid,
5543                                 i_tgconstrrelname,
5544                                 i_tgenabled,
5545                                 i_tgdeferrable,
5546                                 i_tginitdeferred,
5547                                 i_tgdef;
5548         int                     ntups;
5549
5550         for (i = 0; i < numTables; i++)
5551         {
5552                 TableInfo  *tbinfo = &tblinfo[i];
5553
5554                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5555                         continue;
5556
5557                 if (g_verbose)
5558                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5559                                           tbinfo->dobj.name);
5560
5561                 /*
5562                  * select table schema to ensure regproc name is qualified if needed
5563                  */
5564                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5565
5566                 resetPQExpBuffer(query);
5567                 if (fout->remoteVersion >= 90000)
5568                 {
5569                         /*
5570                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5571                          * could result in non-forward-compatible dumps of WHEN clauses
5572                          * due to under-parenthesization.
5573                          */
5574                         appendPQExpBuffer(query,
5575                                                           "SELECT tgname, "
5576                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5577                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5578                                                           "tgenabled, tableoid, oid "
5579                                                           "FROM pg_catalog.pg_trigger t "
5580                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5581                                                           "AND NOT tgisinternal",
5582                                                           tbinfo->dobj.catId.oid);
5583                 }
5584                 else if (fout->remoteVersion >= 80300)
5585                 {
5586                         /*
5587                          * We ignore triggers that are tied to a foreign-key constraint
5588                          */
5589                         appendPQExpBuffer(query,
5590                                                           "SELECT tgname, "
5591                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5592                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5593                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5594                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5595                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5596                                                           "FROM pg_catalog.pg_trigger t "
5597                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5598                                                           "AND tgconstraint = 0",
5599                                                           tbinfo->dobj.catId.oid);
5600                 }
5601                 else if (fout->remoteVersion >= 70300)
5602                 {
5603                         /*
5604                          * We ignore triggers that are tied to a foreign-key constraint,
5605                          * but in these versions we have to grovel through pg_constraint
5606                          * to find out
5607                          */
5608                         appendPQExpBuffer(query,
5609                                                           "SELECT tgname, "
5610                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5611                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5612                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5613                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5614                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5615                                                           "FROM pg_catalog.pg_trigger t "
5616                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5617                                                           "AND (NOT tgisconstraint "
5618                                                           " OR NOT EXISTS"
5619                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5620                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5621                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5622                                                           tbinfo->dobj.catId.oid);
5623                 }
5624                 else if (fout->remoteVersion >= 70100)
5625                 {
5626                         appendPQExpBuffer(query,
5627                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5628                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5629                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5630                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5631                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5632                                                           "             AS tgconstrrelname "
5633                                                           "FROM pg_trigger "
5634                                                           "WHERE tgrelid = '%u'::oid",
5635                                                           tbinfo->dobj.catId.oid);
5636                 }
5637                 else
5638                 {
5639                         appendPQExpBuffer(query,
5640                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5641                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5642                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5643                                                           "tgconstrrelid, tginitdeferred, "
5644                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5645                                                           "oid, "
5646                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5647                                                           "             AS tgconstrrelname "
5648                                                           "FROM pg_trigger "
5649                                                           "WHERE tgrelid = '%u'::oid",
5650                                                           tbinfo->dobj.catId.oid);
5651                 }
5652                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5653
5654                 ntups = PQntuples(res);
5655
5656                 i_tableoid = PQfnumber(res, "tableoid");
5657                 i_oid = PQfnumber(res, "oid");
5658                 i_tgname = PQfnumber(res, "tgname");
5659                 i_tgfname = PQfnumber(res, "tgfname");
5660                 i_tgtype = PQfnumber(res, "tgtype");
5661                 i_tgnargs = PQfnumber(res, "tgnargs");
5662                 i_tgargs = PQfnumber(res, "tgargs");
5663                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5664                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5665                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5666                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5667                 i_tgenabled = PQfnumber(res, "tgenabled");
5668                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5669                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5670                 i_tgdef = PQfnumber(res, "tgdef");
5671
5672                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5673
5674                 for (j = 0; j < ntups; j++)
5675                 {
5676                         tginfo[j].dobj.objType = DO_TRIGGER;
5677                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5678                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5679                         AssignDumpId(&tginfo[j].dobj);
5680                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5681                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5682                         tginfo[j].tgtable = tbinfo;
5683                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5684                         if (i_tgdef >= 0)
5685                         {
5686                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5687
5688                                 /* remaining fields are not valid if we have tgdef */
5689                                 tginfo[j].tgfname = NULL;
5690                                 tginfo[j].tgtype = 0;
5691                                 tginfo[j].tgnargs = 0;
5692                                 tginfo[j].tgargs = NULL;
5693                                 tginfo[j].tgisconstraint = false;
5694                                 tginfo[j].tgdeferrable = false;
5695                                 tginfo[j].tginitdeferred = false;
5696                                 tginfo[j].tgconstrname = NULL;
5697                                 tginfo[j].tgconstrrelid = InvalidOid;
5698                                 tginfo[j].tgconstrrelname = NULL;
5699                         }
5700                         else
5701                         {
5702                                 tginfo[j].tgdef = NULL;
5703
5704                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5705                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5706                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5707                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5708                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5709                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5710                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5711
5712                                 if (tginfo[j].tgisconstraint)
5713                                 {
5714                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5715                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5716                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5717                                         {
5718                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5719                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5720                                                                                   tginfo[j].dobj.name,
5721                                                                                   tbinfo->dobj.name,
5722                                                                                   tginfo[j].tgconstrrelid);
5723                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5724                                         }
5725                                         else
5726                                                 tginfo[j].tgconstrrelname = NULL;
5727                                 }
5728                                 else
5729                                 {
5730                                         tginfo[j].tgconstrname = NULL;
5731                                         tginfo[j].tgconstrrelid = InvalidOid;
5732                                         tginfo[j].tgconstrrelname = NULL;
5733                                 }
5734                         }
5735                 }
5736
5737                 PQclear(res);
5738         }
5739
5740         destroyPQExpBuffer(query);
5741 }
5742
5743 /*
5744  * getEventTriggers
5745  *        get information about event triggers
5746  */
5747 EventTriggerInfo *
5748 getEventTriggers(Archive *fout, int *numEventTriggers)
5749 {
5750         int                     i;
5751         PQExpBuffer query = createPQExpBuffer();
5752         PGresult   *res;
5753         EventTriggerInfo *evtinfo;
5754         int                     i_tableoid,
5755                                 i_oid,
5756                                 i_evtname,
5757                                 i_evtevent,
5758                                 i_evtowner,
5759                                 i_evttags,
5760                                 i_evtfname,
5761                                 i_evtenabled;
5762         int                     ntups;
5763
5764         /* Before 9.3, there are no event triggers */
5765         if (fout->remoteVersion < 90300)
5766         {
5767                 *numEventTriggers = 0;
5768                 return NULL;
5769         }
5770
5771         /* Make sure we are in proper schema */
5772         selectSourceSchema(fout, "pg_catalog");
5773
5774         appendPQExpBuffer(query,
5775                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5776                                           "evtevent, (%s evtowner) AS evtowner, "
5777                                           "array_to_string(array("
5778                                           "select quote_literal(x) "
5779                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
5780                                           "e.evtfoid::regproc as evtfname "
5781                                           "FROM pg_event_trigger e "
5782                                           "ORDER BY e.oid",
5783                                           username_subquery);
5784
5785         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5786
5787         ntups = PQntuples(res);
5788
5789         *numEventTriggers = ntups;
5790
5791         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5792
5793         i_tableoid = PQfnumber(res, "tableoid");
5794         i_oid = PQfnumber(res, "oid");
5795         i_evtname = PQfnumber(res, "evtname");
5796         i_evtevent = PQfnumber(res, "evtevent");
5797         i_evtowner = PQfnumber(res, "evtowner");
5798         i_evttags = PQfnumber(res, "evttags");
5799         i_evtfname = PQfnumber(res, "evtfname");
5800         i_evtenabled = PQfnumber(res, "evtenabled");
5801
5802         for (i = 0; i < ntups; i++)
5803         {
5804                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5805                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5806                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5807                 AssignDumpId(&evtinfo[i].dobj);
5808                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5809                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5810                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5811                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5812                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5813                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5814                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5815         }
5816
5817         PQclear(res);
5818
5819         destroyPQExpBuffer(query);
5820
5821         return evtinfo;
5822 }
5823
5824 /*
5825  * getProcLangs
5826  *        get basic information about every procedural language in the system
5827  *
5828  * numProcLangs is set to the number of langs read in
5829  *
5830  * NB: this must run after getFuncs() because we assume we can do
5831  * findFuncByOid().
5832  */
5833 ProcLangInfo *
5834 getProcLangs(Archive *fout, int *numProcLangs)
5835 {
5836         PGresult   *res;
5837         int                     ntups;
5838         int                     i;
5839         PQExpBuffer query = createPQExpBuffer();
5840         ProcLangInfo *planginfo;
5841         int                     i_tableoid;
5842         int                     i_oid;
5843         int                     i_lanname;
5844         int                     i_lanpltrusted;
5845         int                     i_lanplcallfoid;
5846         int                     i_laninline;
5847         int                     i_lanvalidator;
5848         int                     i_lanacl;
5849         int                     i_lanowner;
5850
5851         /* Make sure we are in proper schema */
5852         selectSourceSchema(fout, "pg_catalog");
5853
5854         if (fout->remoteVersion >= 90000)
5855         {
5856                 /* pg_language has a laninline column */
5857                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5858                                                   "lanname, lanpltrusted, lanplcallfoid, "
5859                                                   "laninline, lanvalidator,  lanacl, "
5860                                                   "(%s lanowner) AS lanowner "
5861                                                   "FROM pg_language "
5862                                                   "WHERE lanispl "
5863                                                   "ORDER BY oid",
5864                                                   username_subquery);
5865         }
5866         else if (fout->remoteVersion >= 80300)
5867         {
5868                 /* pg_language has a lanowner column */
5869                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5870                                                   "lanname, lanpltrusted, lanplcallfoid, "
5871                                                   "lanvalidator,  lanacl, "
5872                                                   "(%s lanowner) AS lanowner "
5873                                                   "FROM pg_language "
5874                                                   "WHERE lanispl "
5875                                                   "ORDER BY oid",
5876                                                   username_subquery);
5877         }
5878         else if (fout->remoteVersion >= 80100)
5879         {
5880                 /* Languages are owned by the bootstrap superuser, OID 10 */
5881                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5882                                                   "(%s '10') AS lanowner "
5883                                                   "FROM pg_language "
5884                                                   "WHERE lanispl "
5885                                                   "ORDER BY oid",
5886                                                   username_subquery);
5887         }
5888         else if (fout->remoteVersion >= 70400)
5889         {
5890                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5891                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5892                                                   "(%s '1') AS lanowner "
5893                                                   "FROM pg_language "
5894                                                   "WHERE lanispl "
5895                                                   "ORDER BY oid",
5896                                                   username_subquery);
5897         }
5898         else if (fout->remoteVersion >= 70100)
5899         {
5900                 /* No clear notion of an owner at all before 7.4 ... */
5901                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5902                                                   "WHERE lanispl "
5903                                                   "ORDER BY oid");
5904         }
5905         else
5906         {
5907                 appendPQExpBuffer(query, "SELECT "
5908                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5909                                                   "oid, * FROM pg_language "
5910                                                   "WHERE lanispl "
5911                                                   "ORDER BY oid");
5912         }
5913
5914         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5915
5916         ntups = PQntuples(res);
5917
5918         *numProcLangs = ntups;
5919
5920         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5921
5922         i_tableoid = PQfnumber(res, "tableoid");
5923         i_oid = PQfnumber(res, "oid");
5924         i_lanname = PQfnumber(res, "lanname");
5925         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5926         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5927         /* these may fail and return -1: */
5928         i_laninline = PQfnumber(res, "laninline");
5929         i_lanvalidator = PQfnumber(res, "lanvalidator");
5930         i_lanacl = PQfnumber(res, "lanacl");
5931         i_lanowner = PQfnumber(res, "lanowner");
5932
5933         for (i = 0; i < ntups; i++)
5934         {
5935                 planginfo[i].dobj.objType = DO_PROCLANG;
5936                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5937                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5938                 AssignDumpId(&planginfo[i].dobj);
5939
5940                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5941                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5942                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5943                 if (i_laninline >= 0)
5944                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5945                 else
5946                         planginfo[i].laninline = InvalidOid;
5947                 if (i_lanvalidator >= 0)
5948                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5949                 else
5950                         planginfo[i].lanvalidator = InvalidOid;
5951                 if (i_lanacl >= 0)
5952                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5953                 else
5954                         planginfo[i].lanacl = pg_strdup("{=U}");
5955                 if (i_lanowner >= 0)
5956                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5957                 else
5958                         planginfo[i].lanowner = pg_strdup("");
5959
5960                 if (fout->remoteVersion < 70300)
5961                 {
5962                         /*
5963                          * We need to make a dependency to ensure the function will be
5964                          * dumped first.  (In 7.3 and later the regular dependency
5965                          * mechanism will handle this for us.)
5966                          */
5967                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5968
5969                         if (funcInfo)
5970                                 addObjectDependency(&planginfo[i].dobj,
5971                                                                         funcInfo->dobj.dumpId);
5972                 }
5973         }
5974
5975         PQclear(res);
5976
5977         destroyPQExpBuffer(query);
5978
5979         return planginfo;
5980 }
5981
5982 /*
5983  * getCasts
5984  *        get basic information about every cast in the system
5985  *
5986  * numCasts is set to the number of casts read in
5987  */
5988 CastInfo *
5989 getCasts(Archive *fout, int *numCasts)
5990 {
5991         PGresult   *res;
5992         int                     ntups;
5993         int                     i;
5994         PQExpBuffer query = createPQExpBuffer();
5995         CastInfo   *castinfo;
5996         int                     i_tableoid;
5997         int                     i_oid;
5998         int                     i_castsource;
5999         int                     i_casttarget;
6000         int                     i_castfunc;
6001         int                     i_castcontext;
6002         int                     i_castmethod;
6003
6004         /* Make sure we are in proper schema */
6005         selectSourceSchema(fout, "pg_catalog");
6006
6007         if (fout->remoteVersion >= 80400)
6008         {
6009                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6010                                                   "castsource, casttarget, castfunc, castcontext, "
6011                                                   "castmethod "
6012                                                   "FROM pg_cast ORDER BY 3,4");
6013         }
6014         else if (fout->remoteVersion >= 70300)
6015         {
6016                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6017                                                   "castsource, casttarget, castfunc, castcontext, "
6018                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
6019                                                   "FROM pg_cast ORDER BY 3,4");
6020         }
6021         else
6022         {
6023                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
6024                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
6025                                                   "p.oid AS castfunc, 'e' AS castcontext, "
6026                                                   "'f' AS castmethod "
6027                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
6028                                                   "WHERE p.pronargs = 1 AND "
6029                                                   "p.proargtypes[0] = t1.oid AND "
6030                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
6031                                                   "ORDER BY 3,4");
6032         }
6033
6034         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6035
6036         ntups = PQntuples(res);
6037
6038         *numCasts = ntups;
6039
6040         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
6041
6042         i_tableoid = PQfnumber(res, "tableoid");
6043         i_oid = PQfnumber(res, "oid");
6044         i_castsource = PQfnumber(res, "castsource");
6045         i_casttarget = PQfnumber(res, "casttarget");
6046         i_castfunc = PQfnumber(res, "castfunc");
6047         i_castcontext = PQfnumber(res, "castcontext");
6048         i_castmethod = PQfnumber(res, "castmethod");
6049
6050         for (i = 0; i < ntups; i++)
6051         {
6052                 PQExpBufferData namebuf;
6053                 TypeInfo   *sTypeInfo;
6054                 TypeInfo   *tTypeInfo;
6055
6056                 castinfo[i].dobj.objType = DO_CAST;
6057                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6058                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6059                 AssignDumpId(&castinfo[i].dobj);
6060                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
6061                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
6062                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
6063                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
6064                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
6065
6066                 /*
6067                  * Try to name cast as concatenation of typnames.  This is only used
6068                  * for purposes of sorting.  If we fail to find either type, the name
6069                  * will be an empty string.
6070                  */
6071                 initPQExpBuffer(&namebuf);
6072                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
6073                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
6074                 if (sTypeInfo && tTypeInfo)
6075                         appendPQExpBuffer(&namebuf, "%s %s",
6076                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
6077                 castinfo[i].dobj.name = namebuf.data;
6078
6079                 if (OidIsValid(castinfo[i].castfunc))
6080                 {
6081                         /*
6082                          * We need to make a dependency to ensure the function will be
6083                          * dumped first.  (In 7.3 and later the regular dependency
6084                          * mechanism will handle this for us.)
6085                          */
6086                         FuncInfo   *funcInfo;
6087
6088                         funcInfo = findFuncByOid(castinfo[i].castfunc);
6089                         if (funcInfo)
6090                                 addObjectDependency(&castinfo[i].dobj,
6091                                                                         funcInfo->dobj.dumpId);
6092                 }
6093         }
6094
6095         PQclear(res);
6096
6097         destroyPQExpBuffer(query);
6098
6099         return castinfo;
6100 }
6101
6102 /*
6103  * getTableAttrs -
6104  *        for each interesting table, read info about its attributes
6105  *        (names, types, default values, CHECK constraints, etc)
6106  *
6107  * This is implemented in a very inefficient way right now, looping
6108  * through the tblinfo and doing a join per table to find the attrs and their
6109  * types.  However, because we want type names and so forth to be named
6110  * relative to the schema of each table, we couldn't do it in just one
6111  * query.  (Maybe one query per schema?)
6112  *
6113  *      modifies tblinfo
6114  */
6115 void
6116 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
6117 {
6118         int                     i,
6119                                 j;
6120         PQExpBuffer q = createPQExpBuffer();
6121         int                     i_attnum;
6122         int                     i_attname;
6123         int                     i_atttypname;
6124         int                     i_atttypmod;
6125         int                     i_attstattarget;
6126         int                     i_attstorage;
6127         int                     i_typstorage;
6128         int                     i_attnotnull;
6129         int                     i_atthasdef;
6130         int                     i_attisdropped;
6131         int                     i_attlen;
6132         int                     i_attalign;
6133         int                     i_attislocal;
6134         int                     i_attoptions;
6135         int                     i_attcollation;
6136         int                     i_attfdwoptions;
6137         PGresult   *res;
6138         int                     ntups;
6139         bool            hasdefaults;
6140
6141         for (i = 0; i < numTables; i++)
6142         {
6143                 TableInfo  *tbinfo = &tblinfo[i];
6144
6145                 /* Don't bother to collect info for sequences */
6146                 if (tbinfo->relkind == RELKIND_SEQUENCE)
6147                         continue;
6148
6149                 /* Don't bother with uninteresting tables, either */
6150                 if (!tbinfo->interesting)
6151                         continue;
6152
6153                 /*
6154                  * Make sure we are in proper schema for this table; this allows
6155                  * correct retrieval of formatted type names and default exprs
6156                  */
6157                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6158
6159                 /* find all the user attributes and their types */
6160
6161                 /*
6162                  * we must read the attribute names in attribute number order! because
6163                  * we will use the attnum to index into the attnames array later.  We
6164                  * actually ask to order by "attrelid, attnum" because (at least up to
6165                  * 7.3) the planner is not smart enough to realize it needn't re-sort
6166                  * the output of an indexscan on pg_attribute_relid_attnum_index.
6167                  */
6168                 if (g_verbose)
6169                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
6170                                           tbinfo->dobj.name);
6171
6172                 resetPQExpBuffer(q);
6173
6174                 if (fout->remoteVersion >= 90200)
6175                 {
6176                         /*
6177                          * attfdwoptions is new in 9.2.
6178                          */
6179                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6180                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6181                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6182                                                           "a.attlen, a.attalign, a.attislocal, "
6183                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6184                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6185                                                           "CASE WHEN a.attcollation <> t.typcollation "
6186                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
6187                                                           "pg_catalog.array_to_string(ARRAY("
6188                                                           "SELECT pg_catalog.quote_ident(option_name) || "
6189                                                           "' ' || pg_catalog.quote_literal(option_value) "
6190                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
6191                                                           "ORDER BY option_name"
6192                                                           "), E',\n    ') AS attfdwoptions "
6193                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6194                                                           "ON a.atttypid = t.oid "
6195                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6196                                                           "AND a.attnum > 0::pg_catalog.int2 "
6197                                                           "ORDER BY a.attrelid, a.attnum",
6198                                                           tbinfo->dobj.catId.oid);
6199                 }
6200                 else if (fout->remoteVersion >= 90100)
6201                 {
6202                         /*
6203                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
6204                          * clauses for attributes whose collation is different from their
6205                          * type's default, we use a CASE here to suppress uninteresting
6206                          * attcollations cheaply.
6207                          */
6208                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6209                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6210                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6211                                                           "a.attlen, a.attalign, a.attislocal, "
6212                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6213                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6214                                                           "CASE WHEN a.attcollation <> t.typcollation "
6215                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
6216                                                           "NULL AS attfdwoptions "
6217                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6218                                                           "ON a.atttypid = t.oid "
6219                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6220                                                           "AND a.attnum > 0::pg_catalog.int2 "
6221                                                           "ORDER BY a.attrelid, a.attnum",
6222                                                           tbinfo->dobj.catId.oid);
6223                 }
6224                 else if (fout->remoteVersion >= 90000)
6225                 {
6226                         /* attoptions is new in 9.0 */
6227                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6228                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6229                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6230                                                           "a.attlen, a.attalign, a.attislocal, "
6231                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6232                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
6233                                                           "0 AS attcollation, "
6234                                                           "NULL AS attfdwoptions "
6235                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6236                                                           "ON a.atttypid = t.oid "
6237                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6238                                                           "AND a.attnum > 0::pg_catalog.int2 "
6239                                                           "ORDER BY a.attrelid, a.attnum",
6240                                                           tbinfo->dobj.catId.oid);
6241                 }
6242                 else if (fout->remoteVersion >= 70300)
6243                 {
6244                         /* need left join here to not fail on dropped columns ... */
6245                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6246                                                           "a.attstattarget, a.attstorage, t.typstorage, "
6247                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
6248                                                           "a.attlen, a.attalign, a.attislocal, "
6249                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6250                                                           "'' AS attoptions, 0 AS attcollation, "
6251                                                           "NULL AS attfdwoptions "
6252                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6253                                                           "ON a.atttypid = t.oid "
6254                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
6255                                                           "AND a.attnum > 0::pg_catalog.int2 "
6256                                                           "ORDER BY a.attrelid, a.attnum",
6257                                                           tbinfo->dobj.catId.oid);
6258                 }
6259                 else if (fout->remoteVersion >= 70100)
6260                 {
6261                         /*
6262                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
6263                          * we don't dump it because we can't tell whether it's been
6264                          * explicitly set or was just a default.
6265                          *
6266                          * attislocal doesn't exist before 7.3, either; in older databases
6267                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
6268                          */
6269                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6270                                                           "-1 AS attstattarget, a.attstorage, "
6271                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
6272                                                           "false AS attisdropped, a.attlen, "
6273                                                           "a.attalign, true AS attislocal, "
6274                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
6275                                                           "'' AS attoptions, 0 AS attcollation, "
6276                                                           "NULL AS attfdwoptions "
6277                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
6278                                                           "ON a.atttypid = t.oid "
6279                                                           "WHERE a.attrelid = '%u'::oid "
6280                                                           "AND a.attnum > 0::int2 "
6281                                                           "ORDER BY a.attrelid, a.attnum",
6282                                                           tbinfo->dobj.catId.oid);
6283                 }
6284                 else
6285                 {
6286                         /* format_type not available before 7.1 */
6287                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
6288                                                           "-1 AS attstattarget, "
6289                                                           "attstorage, attstorage AS typstorage, "
6290                                                           "attnotnull, atthasdef, false AS attisdropped, "
6291                                                           "attlen, attalign, "
6292                                                           "true AS attislocal, "
6293                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
6294                                                           "'' AS attoptions, 0 AS attcollation, "
6295                                                           "NULL AS attfdwoptions "
6296                                                           "FROM pg_attribute a "
6297                                                           "WHERE attrelid = '%u'::oid "
6298                                                           "AND attnum > 0::int2 "
6299                                                           "ORDER BY attrelid, attnum",
6300                                                           tbinfo->dobj.catId.oid);
6301                 }
6302
6303                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6304
6305                 ntups = PQntuples(res);
6306
6307                 i_attnum = PQfnumber(res, "attnum");
6308                 i_attname = PQfnumber(res, "attname");
6309                 i_atttypname = PQfnumber(res, "atttypname");
6310                 i_atttypmod = PQfnumber(res, "atttypmod");
6311                 i_attstattarget = PQfnumber(res, "attstattarget");
6312                 i_attstorage = PQfnumber(res, "attstorage");
6313                 i_typstorage = PQfnumber(res, "typstorage");
6314                 i_attnotnull = PQfnumber(res, "attnotnull");
6315                 i_atthasdef = PQfnumber(res, "atthasdef");
6316                 i_attisdropped = PQfnumber(res, "attisdropped");
6317                 i_attlen = PQfnumber(res, "attlen");
6318                 i_attalign = PQfnumber(res, "attalign");
6319                 i_attislocal = PQfnumber(res, "attislocal");
6320                 i_attoptions = PQfnumber(res, "attoptions");
6321                 i_attcollation = PQfnumber(res, "attcollation");
6322                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
6323
6324                 tbinfo->numatts = ntups;
6325                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
6326                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
6327                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
6328                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
6329                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
6330                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
6331                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
6332                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
6333                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
6334                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
6335                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
6336                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
6337                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
6338                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
6339                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
6340                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
6341                 hasdefaults = false;
6342
6343                 for (j = 0; j < ntups; j++)
6344                 {
6345                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
6346                                 exit_horribly(NULL,
6347                                                           "invalid column numbering in table \"%s\"\n",
6348                                                           tbinfo->dobj.name);
6349                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6350                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6351                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6352                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6353                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6354                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6355                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6356                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6357                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6358                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6359                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6360                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6361                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6362                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6363                         tbinfo->attrdefs[j] = NULL; /* fix below */
6364                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6365                                 hasdefaults = true;
6366                         /* these flags will be set in flagInhAttrs() */
6367                         tbinfo->inhNotNull[j] = false;
6368                 }
6369
6370                 PQclear(res);
6371
6372                 /*
6373                  * Get info about column defaults
6374                  */
6375                 if (hasdefaults)
6376                 {
6377                         AttrDefInfo *attrdefs;
6378                         int                     numDefaults;
6379
6380                         if (g_verbose)
6381                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6382                                                   tbinfo->dobj.name);
6383
6384                         resetPQExpBuffer(q);
6385                         if (fout->remoteVersion >= 70300)
6386                         {
6387                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6388                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6389                                                                   "FROM pg_catalog.pg_attrdef "
6390                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
6391                                                                   tbinfo->dobj.catId.oid);
6392                         }
6393                         else if (fout->remoteVersion >= 70200)
6394                         {
6395                                 /* 7.2 did not have OIDs in pg_attrdef */
6396                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6397                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
6398                                                                   "FROM pg_attrdef "
6399                                                                   "WHERE adrelid = '%u'::oid",
6400                                                                   tbinfo->dobj.catId.oid);
6401                         }
6402                         else if (fout->remoteVersion >= 70100)
6403                         {
6404                                 /* no pg_get_expr, so must rely on adsrc */
6405                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6406                                                                   "FROM pg_attrdef "
6407                                                                   "WHERE adrelid = '%u'::oid",
6408                                                                   tbinfo->dobj.catId.oid);
6409                         }
6410                         else
6411                         {
6412                                 /* no pg_get_expr, no tableoid either */
6413                                 appendPQExpBuffer(q, "SELECT "
6414                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6415                                                                   "oid, adnum, adsrc "
6416                                                                   "FROM pg_attrdef "
6417                                                                   "WHERE adrelid = '%u'::oid",
6418                                                                   tbinfo->dobj.catId.oid);
6419                         }
6420                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6421
6422                         numDefaults = PQntuples(res);
6423                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6424
6425                         for (j = 0; j < numDefaults; j++)
6426                         {
6427                                 int                     adnum;
6428
6429                                 adnum = atoi(PQgetvalue(res, j, 2));
6430
6431                                 if (adnum <= 0 || adnum > ntups)
6432                                         exit_horribly(NULL,
6433                                                                   "invalid adnum value %d for table \"%s\"\n",
6434                                                                   adnum, tbinfo->dobj.name);
6435
6436                                 /*
6437                                  * dropped columns shouldn't have defaults, but just in case,
6438                                  * ignore 'em
6439                                  */
6440                                 if (tbinfo->attisdropped[adnum - 1])
6441                                         continue;
6442
6443                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
6444                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6445                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6446                                 AssignDumpId(&attrdefs[j].dobj);
6447                                 attrdefs[j].adtable = tbinfo;
6448                                 attrdefs[j].adnum = adnum;
6449                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6450
6451                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6452                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6453
6454                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6455
6456                                 /*
6457                                  * Defaults on a VIEW must always be dumped as separate ALTER
6458                                  * TABLE commands.      Defaults on regular tables are dumped as
6459                                  * part of the CREATE TABLE if possible, which it won't be if
6460                                  * the column is not going to be emitted explicitly.
6461                                  */
6462                                 if (tbinfo->relkind == RELKIND_VIEW)
6463                                 {
6464                                         attrdefs[j].separate = true;
6465                                         /* needed in case pre-7.3 DB: */
6466                                         addObjectDependency(&attrdefs[j].dobj,
6467                                                                                 tbinfo->dobj.dumpId);
6468                                 }
6469                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6470                                 {
6471                                         /* column will be suppressed, print default separately */
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
6478                                 {
6479                                         attrdefs[j].separate = false;
6480
6481                                         /*
6482                                          * Mark the default as needing to appear before the table,
6483                                          * so that any dependencies it has must be emitted before
6484                                          * the CREATE TABLE.  If this is not possible, we'll
6485                                          * change to "separate" mode while sorting dependencies.
6486                                          */
6487                                         addObjectDependency(&tbinfo->dobj,
6488                                                                                 attrdefs[j].dobj.dumpId);
6489                                 }
6490
6491                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6492                         }
6493                         PQclear(res);
6494                 }
6495
6496                 /*
6497                  * Get info about table CHECK constraints
6498                  */
6499                 if (tbinfo->ncheck > 0)
6500                 {
6501                         ConstraintInfo *constrs;
6502                         int                     numConstrs;
6503
6504                         if (g_verbose)
6505                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6506                                                   tbinfo->dobj.name);
6507
6508                         resetPQExpBuffer(q);
6509                         if (fout->remoteVersion >= 90200)
6510                         {
6511                                 /*
6512                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
6513                                  * but it wasn't ever false for check constraints until 9.2).
6514                                  */
6515                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6516                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6517                                                                   "conislocal, convalidated "
6518                                                                   "FROM pg_catalog.pg_constraint "
6519                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6520                                                                   "   AND contype = 'c' "
6521                                                                   "ORDER BY conname",
6522                                                                   tbinfo->dobj.catId.oid);
6523                         }
6524                         else if (fout->remoteVersion >= 80400)
6525                         {
6526                                 /* conislocal is new in 8.4 */
6527                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6528                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6529                                                                   "conislocal, true AS convalidated "
6530                                                                   "FROM pg_catalog.pg_constraint "
6531                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6532                                                                   "   AND contype = 'c' "
6533                                                                   "ORDER BY conname",
6534                                                                   tbinfo->dobj.catId.oid);
6535                         }
6536                         else if (fout->remoteVersion >= 70400)
6537                         {
6538                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6539                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6540                                                                   "true AS conislocal, true AS convalidated "
6541                                                                   "FROM pg_catalog.pg_constraint "
6542                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6543                                                                   "   AND contype = 'c' "
6544                                                                   "ORDER BY conname",
6545                                                                   tbinfo->dobj.catId.oid);
6546                         }
6547                         else if (fout->remoteVersion >= 70300)
6548                         {
6549                                 /* no pg_get_constraintdef, must use consrc */
6550                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6551                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6552                                                                   "true AS conislocal, true AS convalidated "
6553                                                                   "FROM pg_catalog.pg_constraint "
6554                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6555                                                                   "   AND contype = 'c' "
6556                                                                   "ORDER BY conname",
6557                                                                   tbinfo->dobj.catId.oid);
6558                         }
6559                         else if (fout->remoteVersion >= 70200)
6560                         {
6561                                 /* 7.2 did not have OIDs in pg_relcheck */
6562                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6563                                                                   "rcname AS conname, "
6564                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6565                                                                   "true AS conislocal, true AS convalidated "
6566                                                                   "FROM pg_relcheck "
6567                                                                   "WHERE rcrelid = '%u'::oid "
6568                                                                   "ORDER BY rcname",
6569                                                                   tbinfo->dobj.catId.oid);
6570                         }
6571                         else if (fout->remoteVersion >= 70100)
6572                         {
6573                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6574                                                                   "rcname AS conname, "
6575                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6576                                                                   "true AS conislocal, true AS convalidated "
6577                                                                   "FROM pg_relcheck "
6578                                                                   "WHERE rcrelid = '%u'::oid "
6579                                                                   "ORDER BY rcname",
6580                                                                   tbinfo->dobj.catId.oid);
6581                         }
6582                         else
6583                         {
6584                                 /* no tableoid in 7.0 */
6585                                 appendPQExpBuffer(q, "SELECT "
6586                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6587                                                                   "oid, rcname AS conname, "
6588                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6589                                                                   "true AS conislocal, true AS convalidated "
6590                                                                   "FROM pg_relcheck "
6591                                                                   "WHERE rcrelid = '%u'::oid "
6592                                                                   "ORDER BY rcname",
6593                                                                   tbinfo->dobj.catId.oid);
6594                         }
6595                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6596
6597                         numConstrs = PQntuples(res);
6598                         if (numConstrs != tbinfo->ncheck)
6599                         {
6600                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6601                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6602                                                                                  tbinfo->ncheck),
6603                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6604                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6605                                 exit_nicely(1);
6606                         }
6607
6608                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6609                         tbinfo->checkexprs = constrs;
6610
6611                         for (j = 0; j < numConstrs; j++)
6612                         {
6613                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6614
6615                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6616                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6617                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6618                                 AssignDumpId(&constrs[j].dobj);
6619                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6620                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6621                                 constrs[j].contable = tbinfo;
6622                                 constrs[j].condomain = NULL;
6623                                 constrs[j].contype = 'c';
6624                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6625                                 constrs[j].confrelid = InvalidOid;
6626                                 constrs[j].conindex = 0;
6627                                 constrs[j].condeferrable = false;
6628                                 constrs[j].condeferred = false;
6629                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6630
6631                                 /*
6632                                  * An unvalidated constraint needs to be dumped separately, so
6633                                  * that potentially-violating existing data is loaded before
6634                                  * the constraint.
6635                                  */
6636                                 constrs[j].separate = !validated;
6637
6638                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6639
6640                                 /*
6641                                  * Mark the constraint as needing to appear before the table
6642                                  * --- this is so that any other dependencies of the
6643                                  * constraint will be emitted before we try to create the
6644                                  * table.  If the constraint is to be dumped separately, it
6645                                  * will be dumped after data is loaded anyway, so don't do it.
6646                                  * (There's an automatic dependency in the opposite direction
6647                                  * anyway, so don't need to add one manually here.)
6648                                  */
6649                                 if (!constrs[j].separate)
6650                                         addObjectDependency(&tbinfo->dobj,
6651                                                                                 constrs[j].dobj.dumpId);
6652
6653                                 /*
6654                                  * If the constraint is inherited, this will be detected later
6655                                  * (in pre-8.4 databases).      We also detect later if the
6656                                  * constraint must be split out from the table definition.
6657                                  */
6658                         }
6659                         PQclear(res);
6660                 }
6661         }
6662
6663         destroyPQExpBuffer(q);
6664 }
6665
6666 /*
6667  * Test whether a column should be printed as part of table's CREATE TABLE.
6668  * Column number is zero-based.
6669  *
6670  * Normally this is always true, but it's false for dropped columns, as well
6671  * as those that were inherited without any local definition.  (If we print
6672  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6673  * However, in binary_upgrade mode, we must print all such columns anyway and
6674  * fix the attislocal/attisdropped state later, so as to keep control of the
6675  * physical column order.
6676  *
6677  * This function exists because there are scattered nonobvious places that
6678  * must be kept in sync with this decision.
6679  */
6680 bool
6681 shouldPrintColumn(TableInfo *tbinfo, int colno)
6682 {
6683         if (binary_upgrade)
6684                 return true;
6685         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6686 }
6687
6688
6689 /*
6690  * getTSParsers:
6691  *        read all text search parsers in the system catalogs and return them
6692  *        in the TSParserInfo* structure
6693  *
6694  *      numTSParsers is set to the number of parsers read in
6695  */
6696 TSParserInfo *
6697 getTSParsers(Archive *fout, int *numTSParsers)
6698 {
6699         PGresult   *res;
6700         int                     ntups;
6701         int                     i;
6702         PQExpBuffer query;
6703         TSParserInfo *prsinfo;
6704         int                     i_tableoid;
6705         int                     i_oid;
6706         int                     i_prsname;
6707         int                     i_prsnamespace;
6708         int                     i_prsstart;
6709         int                     i_prstoken;
6710         int                     i_prsend;
6711         int                     i_prsheadline;
6712         int                     i_prslextype;
6713
6714         /* Before 8.3, there is no built-in text search support */
6715         if (fout->remoteVersion < 80300)
6716         {
6717                 *numTSParsers = 0;
6718                 return NULL;
6719         }
6720
6721         query = createPQExpBuffer();
6722
6723         /*
6724          * find all text search objects, including builtin ones; we filter out
6725          * system-defined objects at dump-out time.
6726          */
6727
6728         /* Make sure we are in proper schema */
6729         selectSourceSchema(fout, "pg_catalog");
6730
6731         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6732                                           "prsstart::oid, prstoken::oid, "
6733                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6734                                           "FROM pg_ts_parser");
6735
6736         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6737
6738         ntups = PQntuples(res);
6739         *numTSParsers = ntups;
6740
6741         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6742
6743         i_tableoid = PQfnumber(res, "tableoid");
6744         i_oid = PQfnumber(res, "oid");
6745         i_prsname = PQfnumber(res, "prsname");
6746         i_prsnamespace = PQfnumber(res, "prsnamespace");
6747         i_prsstart = PQfnumber(res, "prsstart");
6748         i_prstoken = PQfnumber(res, "prstoken");
6749         i_prsend = PQfnumber(res, "prsend");
6750         i_prsheadline = PQfnumber(res, "prsheadline");
6751         i_prslextype = PQfnumber(res, "prslextype");
6752
6753         for (i = 0; i < ntups; i++)
6754         {
6755                 prsinfo[i].dobj.objType = DO_TSPARSER;
6756                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6757                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6758                 AssignDumpId(&prsinfo[i].dobj);
6759                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6760                 prsinfo[i].dobj.namespace =
6761                         findNamespace(fout,
6762                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6763                                                   prsinfo[i].dobj.catId.oid);
6764                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6765                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6766                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6767                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6768                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6769
6770                 /* Decide whether we want to dump it */
6771                 selectDumpableObject(&(prsinfo[i].dobj));
6772         }
6773
6774         PQclear(res);
6775
6776         destroyPQExpBuffer(query);
6777
6778         return prsinfo;
6779 }
6780
6781 /*
6782  * getTSDictionaries:
6783  *        read all text search dictionaries in the system catalogs and return them
6784  *        in the TSDictInfo* structure
6785  *
6786  *      numTSDicts is set to the number of dictionaries read in
6787  */
6788 TSDictInfo *
6789 getTSDictionaries(Archive *fout, int *numTSDicts)
6790 {
6791         PGresult   *res;
6792         int                     ntups;
6793         int                     i;
6794         PQExpBuffer query;
6795         TSDictInfo *dictinfo;
6796         int                     i_tableoid;
6797         int                     i_oid;
6798         int                     i_dictname;
6799         int                     i_dictnamespace;
6800         int                     i_rolname;
6801         int                     i_dicttemplate;
6802         int                     i_dictinitoption;
6803
6804         /* Before 8.3, there is no built-in text search support */
6805         if (fout->remoteVersion < 80300)
6806         {
6807                 *numTSDicts = 0;
6808                 return NULL;
6809         }
6810
6811         query = createPQExpBuffer();
6812
6813         /* Make sure we are in proper schema */
6814         selectSourceSchema(fout, "pg_catalog");
6815
6816         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6817                                           "dictnamespace, (%s dictowner) AS rolname, "
6818                                           "dicttemplate, dictinitoption "
6819                                           "FROM pg_ts_dict",
6820                                           username_subquery);
6821
6822         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6823
6824         ntups = PQntuples(res);
6825         *numTSDicts = ntups;
6826
6827         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6828
6829         i_tableoid = PQfnumber(res, "tableoid");
6830         i_oid = PQfnumber(res, "oid");
6831         i_dictname = PQfnumber(res, "dictname");
6832         i_dictnamespace = PQfnumber(res, "dictnamespace");
6833         i_rolname = PQfnumber(res, "rolname");
6834         i_dictinitoption = PQfnumber(res, "dictinitoption");
6835         i_dicttemplate = PQfnumber(res, "dicttemplate");
6836
6837         for (i = 0; i < ntups; i++)
6838         {
6839                 dictinfo[i].dobj.objType = DO_TSDICT;
6840                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6841                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6842                 AssignDumpId(&dictinfo[i].dobj);
6843                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6844                 dictinfo[i].dobj.namespace =
6845                         findNamespace(fout,
6846                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6847                                                   dictinfo[i].dobj.catId.oid);
6848                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6849                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6850                 if (PQgetisnull(res, i, i_dictinitoption))
6851                         dictinfo[i].dictinitoption = NULL;
6852                 else
6853                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6854
6855                 /* Decide whether we want to dump it */
6856                 selectDumpableObject(&(dictinfo[i].dobj));
6857         }
6858
6859         PQclear(res);
6860
6861         destroyPQExpBuffer(query);
6862
6863         return dictinfo;
6864 }
6865
6866 /*
6867  * getTSTemplates:
6868  *        read all text search templates in the system catalogs and return them
6869  *        in the TSTemplateInfo* structure
6870  *
6871  *      numTSTemplates is set to the number of templates read in
6872  */
6873 TSTemplateInfo *
6874 getTSTemplates(Archive *fout, int *numTSTemplates)
6875 {
6876         PGresult   *res;
6877         int                     ntups;
6878         int                     i;
6879         PQExpBuffer query;
6880         TSTemplateInfo *tmplinfo;
6881         int                     i_tableoid;
6882         int                     i_oid;
6883         int                     i_tmplname;
6884         int                     i_tmplnamespace;
6885         int                     i_tmplinit;
6886         int                     i_tmpllexize;
6887
6888         /* Before 8.3, there is no built-in text search support */
6889         if (fout->remoteVersion < 80300)
6890         {
6891                 *numTSTemplates = 0;
6892                 return NULL;
6893         }
6894
6895         query = createPQExpBuffer();
6896
6897         /* Make sure we are in proper schema */
6898         selectSourceSchema(fout, "pg_catalog");
6899
6900         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6901                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6902                                           "FROM pg_ts_template");
6903
6904         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6905
6906         ntups = PQntuples(res);
6907         *numTSTemplates = ntups;
6908
6909         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6910
6911         i_tableoid = PQfnumber(res, "tableoid");
6912         i_oid = PQfnumber(res, "oid");
6913         i_tmplname = PQfnumber(res, "tmplname");
6914         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6915         i_tmplinit = PQfnumber(res, "tmplinit");
6916         i_tmpllexize = PQfnumber(res, "tmpllexize");
6917
6918         for (i = 0; i < ntups; i++)
6919         {
6920                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6921                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6922                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6923                 AssignDumpId(&tmplinfo[i].dobj);
6924                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6925                 tmplinfo[i].dobj.namespace =
6926                         findNamespace(fout,
6927                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6928                                                   tmplinfo[i].dobj.catId.oid);
6929                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6930                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6931
6932                 /* Decide whether we want to dump it */
6933                 selectDumpableObject(&(tmplinfo[i].dobj));
6934         }
6935
6936         PQclear(res);
6937
6938         destroyPQExpBuffer(query);
6939
6940         return tmplinfo;
6941 }
6942
6943 /*
6944  * getTSConfigurations:
6945  *        read all text search configurations in the system catalogs and return
6946  *        them in the TSConfigInfo* structure
6947  *
6948  *      numTSConfigs is set to the number of configurations read in
6949  */
6950 TSConfigInfo *
6951 getTSConfigurations(Archive *fout, int *numTSConfigs)
6952 {
6953         PGresult   *res;
6954         int                     ntups;
6955         int                     i;
6956         PQExpBuffer query;
6957         TSConfigInfo *cfginfo;
6958         int                     i_tableoid;
6959         int                     i_oid;
6960         int                     i_cfgname;
6961         int                     i_cfgnamespace;
6962         int                     i_rolname;
6963         int                     i_cfgparser;
6964
6965         /* Before 8.3, there is no built-in text search support */
6966         if (fout->remoteVersion < 80300)
6967         {
6968                 *numTSConfigs = 0;
6969                 return NULL;
6970         }
6971
6972         query = createPQExpBuffer();
6973
6974         /* Make sure we are in proper schema */
6975         selectSourceSchema(fout, "pg_catalog");
6976
6977         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6978                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6979                                           "FROM pg_ts_config",
6980                                           username_subquery);
6981
6982         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6983
6984         ntups = PQntuples(res);
6985         *numTSConfigs = ntups;
6986
6987         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6988
6989         i_tableoid = PQfnumber(res, "tableoid");
6990         i_oid = PQfnumber(res, "oid");
6991         i_cfgname = PQfnumber(res, "cfgname");
6992         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6993         i_rolname = PQfnumber(res, "rolname");
6994         i_cfgparser = PQfnumber(res, "cfgparser");
6995
6996         for (i = 0; i < ntups; i++)
6997         {
6998                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6999                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7000                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7001                 AssignDumpId(&cfginfo[i].dobj);
7002                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
7003                 cfginfo[i].dobj.namespace =
7004                         findNamespace(fout,
7005                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
7006                                                   cfginfo[i].dobj.catId.oid);
7007                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7008                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
7009
7010                 /* Decide whether we want to dump it */
7011                 selectDumpableObject(&(cfginfo[i].dobj));
7012         }
7013
7014         PQclear(res);
7015
7016         destroyPQExpBuffer(query);
7017
7018         return cfginfo;
7019 }
7020
7021 /*
7022  * getForeignDataWrappers:
7023  *        read all foreign-data wrappers in the system catalogs and return
7024  *        them in the FdwInfo* structure
7025  *
7026  *      numForeignDataWrappers is set to the number of fdws read in
7027  */
7028 FdwInfo *
7029 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
7030 {
7031         PGresult   *res;
7032         int                     ntups;
7033         int                     i;
7034         PQExpBuffer query = createPQExpBuffer();
7035         FdwInfo    *fdwinfo;
7036         int                     i_tableoid;
7037         int                     i_oid;
7038         int                     i_fdwname;
7039         int                     i_rolname;
7040         int                     i_fdwhandler;
7041         int                     i_fdwvalidator;
7042         int                     i_fdwacl;
7043         int                     i_fdwoptions;
7044
7045         /* Before 8.4, there are no foreign-data wrappers */
7046         if (fout->remoteVersion < 80400)
7047         {
7048                 *numForeignDataWrappers = 0;
7049                 return NULL;
7050         }
7051
7052         /* Make sure we are in proper schema */
7053         selectSourceSchema(fout, "pg_catalog");
7054
7055         if (fout->remoteVersion >= 90100)
7056         {
7057                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7058                                                   "(%s fdwowner) AS rolname, "
7059                                                   "fdwhandler::pg_catalog.regproc, "
7060                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
7061                                                   "array_to_string(ARRAY("
7062                                                   "SELECT quote_ident(option_name) || ' ' || "
7063                                                   "quote_literal(option_value) "
7064                                                   "FROM pg_options_to_table(fdwoptions) "
7065                                                   "ORDER BY option_name"
7066                                                   "), E',\n    ') AS fdwoptions "
7067                                                   "FROM pg_foreign_data_wrapper",
7068                                                   username_subquery);
7069         }
7070         else
7071         {
7072                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7073                                                   "(%s fdwowner) AS rolname, "
7074                                                   "'-' AS fdwhandler, "
7075                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
7076                                                   "array_to_string(ARRAY("
7077                                                   "SELECT quote_ident(option_name) || ' ' || "
7078                                                   "quote_literal(option_value) "
7079                                                   "FROM pg_options_to_table(fdwoptions) "
7080                                                   "ORDER BY option_name"
7081                                                   "), E',\n    ') AS fdwoptions "
7082                                                   "FROM pg_foreign_data_wrapper",
7083                                                   username_subquery);
7084         }
7085
7086         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7087
7088         ntups = PQntuples(res);
7089         *numForeignDataWrappers = ntups;
7090
7091         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
7092
7093         i_tableoid = PQfnumber(res, "tableoid");
7094         i_oid = PQfnumber(res, "oid");
7095         i_fdwname = PQfnumber(res, "fdwname");
7096         i_rolname = PQfnumber(res, "rolname");
7097         i_fdwhandler = PQfnumber(res, "fdwhandler");
7098         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
7099         i_fdwacl = PQfnumber(res, "fdwacl");
7100         i_fdwoptions = PQfnumber(res, "fdwoptions");
7101
7102         for (i = 0; i < ntups; i++)
7103         {
7104                 fdwinfo[i].dobj.objType = DO_FDW;
7105                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7106                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7107                 AssignDumpId(&fdwinfo[i].dobj);
7108                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
7109                 fdwinfo[i].dobj.namespace = NULL;
7110                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7111                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
7112                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
7113                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
7114                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
7115
7116                 /* Decide whether we want to dump it */
7117                 selectDumpableObject(&(fdwinfo[i].dobj));
7118         }
7119
7120         PQclear(res);
7121
7122         destroyPQExpBuffer(query);
7123
7124         return fdwinfo;
7125 }
7126
7127 /*
7128  * getForeignServers:
7129  *        read all foreign servers in the system catalogs and return
7130  *        them in the ForeignServerInfo * structure
7131  *
7132  *      numForeignServers is set to the number of servers read in
7133  */
7134 ForeignServerInfo *
7135 getForeignServers(Archive *fout, int *numForeignServers)
7136 {
7137         PGresult   *res;
7138         int                     ntups;
7139         int                     i;
7140         PQExpBuffer query = createPQExpBuffer();
7141         ForeignServerInfo *srvinfo;
7142         int                     i_tableoid;
7143         int                     i_oid;
7144         int                     i_srvname;
7145         int                     i_rolname;
7146         int                     i_srvfdw;
7147         int                     i_srvtype;
7148         int                     i_srvversion;
7149         int                     i_srvacl;
7150         int                     i_srvoptions;
7151
7152         /* Before 8.4, there are no foreign servers */
7153         if (fout->remoteVersion < 80400)
7154         {
7155                 *numForeignServers = 0;
7156                 return NULL;
7157         }
7158
7159         /* Make sure we are in proper schema */
7160         selectSourceSchema(fout, "pg_catalog");
7161
7162         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
7163                                           "(%s srvowner) AS rolname, "
7164                                           "srvfdw, srvtype, srvversion, srvacl,"
7165                                           "array_to_string(ARRAY("
7166                                           "SELECT quote_ident(option_name) || ' ' || "
7167                                           "quote_literal(option_value) "
7168                                           "FROM pg_options_to_table(srvoptions) "
7169                                           "ORDER BY option_name"
7170                                           "), E',\n    ') AS srvoptions "
7171                                           "FROM pg_foreign_server",
7172                                           username_subquery);
7173
7174         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7175
7176         ntups = PQntuples(res);
7177         *numForeignServers = ntups;
7178
7179         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
7180
7181         i_tableoid = PQfnumber(res, "tableoid");
7182         i_oid = PQfnumber(res, "oid");
7183         i_srvname = PQfnumber(res, "srvname");
7184         i_rolname = PQfnumber(res, "rolname");
7185         i_srvfdw = PQfnumber(res, "srvfdw");
7186         i_srvtype = PQfnumber(res, "srvtype");
7187         i_srvversion = PQfnumber(res, "srvversion");
7188         i_srvacl = PQfnumber(res, "srvacl");
7189         i_srvoptions = PQfnumber(res, "srvoptions");
7190
7191         for (i = 0; i < ntups; i++)
7192         {
7193                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
7194                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7195                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7196                 AssignDumpId(&srvinfo[i].dobj);
7197                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
7198                 srvinfo[i].dobj.namespace = NULL;
7199                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7200                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
7201                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
7202                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
7203                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
7204                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
7205
7206                 /* Decide whether we want to dump it */
7207                 selectDumpableObject(&(srvinfo[i].dobj));
7208         }
7209
7210         PQclear(res);
7211
7212         destroyPQExpBuffer(query);
7213
7214         return srvinfo;
7215 }
7216
7217 /*
7218  * getDefaultACLs:
7219  *        read all default ACL information in the system catalogs and return
7220  *        them in the DefaultACLInfo structure
7221  *
7222  *      numDefaultACLs is set to the number of ACLs read in
7223  */
7224 DefaultACLInfo *
7225 getDefaultACLs(Archive *fout, int *numDefaultACLs)
7226 {
7227         DefaultACLInfo *daclinfo;
7228         PQExpBuffer query;
7229         PGresult   *res;
7230         int                     i_oid;
7231         int                     i_tableoid;
7232         int                     i_defaclrole;
7233         int                     i_defaclnamespace;
7234         int                     i_defaclobjtype;
7235         int                     i_defaclacl;
7236         int                     i,
7237                                 ntups;
7238
7239         if (fout->remoteVersion < 90000)
7240         {
7241                 *numDefaultACLs = 0;
7242                 return NULL;
7243         }
7244
7245         query = createPQExpBuffer();
7246
7247         /* Make sure we are in proper schema */
7248         selectSourceSchema(fout, "pg_catalog");
7249
7250         appendPQExpBuffer(query, "SELECT oid, tableoid, "
7251                                           "(%s defaclrole) AS defaclrole, "
7252                                           "defaclnamespace, "
7253                                           "defaclobjtype, "
7254                                           "defaclacl "
7255                                           "FROM pg_default_acl",
7256                                           username_subquery);
7257
7258         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7259
7260         ntups = PQntuples(res);
7261         *numDefaultACLs = ntups;
7262
7263         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
7264
7265         i_oid = PQfnumber(res, "oid");
7266         i_tableoid = PQfnumber(res, "tableoid");
7267         i_defaclrole = PQfnumber(res, "defaclrole");
7268         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
7269         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
7270         i_defaclacl = PQfnumber(res, "defaclacl");
7271
7272         for (i = 0; i < ntups; i++)
7273         {
7274                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
7275
7276                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
7277                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7278                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7279                 AssignDumpId(&daclinfo[i].dobj);
7280                 /* cheesy ... is it worth coming up with a better object name? */
7281                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
7282
7283                 if (nspid != InvalidOid)
7284                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
7285                                                                                                  daclinfo[i].dobj.catId.oid);
7286                 else
7287                         daclinfo[i].dobj.namespace = NULL;
7288
7289                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
7290                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
7291                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
7292
7293                 /* Decide whether we want to dump it */
7294                 selectDumpableDefaultACL(&(daclinfo[i]));
7295         }
7296
7297         PQclear(res);
7298
7299         destroyPQExpBuffer(query);
7300
7301         return daclinfo;
7302 }
7303
7304 /*
7305  * dumpComment --
7306  *
7307  * This routine is used to dump any comments associated with the
7308  * object handed to this routine. The routine takes a constant character
7309  * string for the target part of the comment-creation command, plus
7310  * the namespace and owner of the object (for labeling the ArchiveEntry),
7311  * plus catalog ID and subid which are the lookup key for pg_description,
7312  * plus the dump ID for the object (for setting a dependency).
7313  * If a matching pg_description entry is found, it is dumped.
7314  *
7315  * Note: although this routine takes a dumpId for dependency purposes,
7316  * that purpose is just to mark the dependency in the emitted dump file
7317  * for possible future use by pg_restore.  We do NOT use it for determining
7318  * ordering of the comment in the dump file, because this routine is called
7319  * after dependency sorting occurs.  This routine should be called just after
7320  * calling ArchiveEntry() for the specified object.
7321  */
7322 static void
7323 dumpComment(Archive *fout, const char *target,
7324                         const char *namespace, const char *owner,
7325                         CatalogId catalogId, int subid, DumpId dumpId)
7326 {
7327         CommentItem *comments;
7328         int                     ncomments;
7329
7330         /* Comments are schema not data ... except blob comments are data */
7331         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
7332         {
7333                 if (dataOnly)
7334                         return;
7335         }
7336         else
7337         {
7338                 if (schemaOnly)
7339                         return;
7340         }
7341
7342         /* Search for comments associated with catalogId, using table */
7343         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
7344                                                          &comments);
7345
7346         /* Is there one matching the subid? */
7347         while (ncomments > 0)
7348         {
7349                 if (comments->objsubid == subid)
7350                         break;
7351                 comments++;
7352                 ncomments--;
7353         }
7354
7355         /* If a comment exists, build COMMENT ON statement */
7356         if (ncomments > 0)
7357         {
7358                 PQExpBuffer query = createPQExpBuffer();
7359
7360                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7361                 appendStringLiteralAH(query, comments->descr, fout);
7362                 appendPQExpBuffer(query, ";\n");
7363
7364                 /*
7365                  * We mark comments as SECTION_NONE because they really belong in the
7366                  * same section as their parent, whether that is pre-data or
7367                  * post-data.
7368                  */
7369                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7370                                          target, namespace, NULL, owner,
7371                                          false, "COMMENT", SECTION_NONE,
7372                                          query->data, "", NULL,
7373                                          &(dumpId), 1,
7374                                          NULL, NULL);
7375
7376                 destroyPQExpBuffer(query);
7377         }
7378 }
7379
7380 /*
7381  * dumpTableComment --
7382  *
7383  * As above, but dump comments for both the specified table (or view)
7384  * and its columns.
7385  */
7386 static void
7387 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7388                                  const char *reltypename)
7389 {
7390         CommentItem *comments;
7391         int                     ncomments;
7392         PQExpBuffer query;
7393         PQExpBuffer target;
7394
7395         /* Comments are SCHEMA not data */
7396         if (dataOnly)
7397                 return;
7398
7399         /* Search for comments associated with relation, using table */
7400         ncomments = findComments(fout,
7401                                                          tbinfo->dobj.catId.tableoid,
7402                                                          tbinfo->dobj.catId.oid,
7403                                                          &comments);
7404
7405         /* If comments exist, build COMMENT ON statements */
7406         if (ncomments <= 0)
7407                 return;
7408
7409         query = createPQExpBuffer();
7410         target = createPQExpBuffer();
7411
7412         while (ncomments > 0)
7413         {
7414                 const char *descr = comments->descr;
7415                 int                     objsubid = comments->objsubid;
7416
7417                 if (objsubid == 0)
7418                 {
7419                         resetPQExpBuffer(target);
7420                         appendPQExpBuffer(target, "%s %s", reltypename,
7421                                                           fmtId(tbinfo->dobj.name));
7422
7423                         resetPQExpBuffer(query);
7424                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7425                         appendStringLiteralAH(query, descr, fout);
7426                         appendPQExpBuffer(query, ";\n");
7427
7428                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7429                                                  target->data,
7430                                                  tbinfo->dobj.namespace->dobj.name,
7431                                                  NULL, tbinfo->rolname,
7432                                                  false, "COMMENT", SECTION_NONE,
7433                                                  query->data, "", NULL,
7434                                                  &(tbinfo->dobj.dumpId), 1,
7435                                                  NULL, NULL);
7436                 }
7437                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7438                 {
7439                         resetPQExpBuffer(target);
7440                         appendPQExpBuffer(target, "COLUMN %s.",
7441                                                           fmtId(tbinfo->dobj.name));
7442                         appendPQExpBuffer(target, "%s",
7443                                                           fmtId(tbinfo->attnames[objsubid - 1]));
7444
7445                         resetPQExpBuffer(query);
7446                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7447                         appendStringLiteralAH(query, descr, fout);
7448                         appendPQExpBuffer(query, ";\n");
7449
7450                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7451                                                  target->data,
7452                                                  tbinfo->dobj.namespace->dobj.name,
7453                                                  NULL, tbinfo->rolname,
7454                                                  false, "COMMENT", SECTION_NONE,
7455                                                  query->data, "", NULL,
7456                                                  &(tbinfo->dobj.dumpId), 1,
7457                                                  NULL, NULL);
7458                 }
7459
7460                 comments++;
7461                 ncomments--;
7462         }
7463
7464         destroyPQExpBuffer(query);
7465         destroyPQExpBuffer(target);
7466 }
7467
7468 /*
7469  * findComments --
7470  *
7471  * Find the comment(s), if any, associated with the given object.  All the
7472  * objsubid values associated with the given classoid/objoid are found with
7473  * one search.
7474  */
7475 static int
7476 findComments(Archive *fout, Oid classoid, Oid objoid,
7477                          CommentItem **items)
7478 {
7479         /* static storage for table of comments */
7480         static CommentItem *comments = NULL;
7481         static int      ncomments = -1;
7482
7483         CommentItem *middle = NULL;
7484         CommentItem *low;
7485         CommentItem *high;
7486         int                     nmatch;
7487
7488         /* Get comments if we didn't already */
7489         if (ncomments < 0)
7490                 ncomments = collectComments(fout, &comments);
7491
7492         /*
7493          * Pre-7.2, pg_description does not contain classoid, so collectComments
7494          * just stores a zero.  If there's a collision on object OID, well, you
7495          * get duplicate comments.
7496          */
7497         if (fout->remoteVersion < 70200)
7498                 classoid = 0;
7499
7500         /*
7501          * Do binary search to find some item matching the object.
7502          */
7503         low = &comments[0];
7504         high = &comments[ncomments - 1];
7505         while (low <= high)
7506         {
7507                 middle = low + (high - low) / 2;
7508
7509                 if (classoid < middle->classoid)
7510                         high = middle - 1;
7511                 else if (classoid > middle->classoid)
7512                         low = middle + 1;
7513                 else if (objoid < middle->objoid)
7514                         high = middle - 1;
7515                 else if (objoid > middle->objoid)
7516                         low = middle + 1;
7517                 else
7518                         break;                          /* found a match */
7519         }
7520
7521         if (low > high)                         /* no matches */
7522         {
7523                 *items = NULL;
7524                 return 0;
7525         }
7526
7527         /*
7528          * Now determine how many items match the object.  The search loop
7529          * invariant still holds: only items between low and high inclusive could
7530          * match.
7531          */
7532         nmatch = 1;
7533         while (middle > low)
7534         {
7535                 if (classoid != middle[-1].classoid ||
7536                         objoid != middle[-1].objoid)
7537                         break;
7538                 middle--;
7539                 nmatch++;
7540         }
7541
7542         *items = middle;
7543
7544         middle += nmatch;
7545         while (middle <= high)
7546         {
7547                 if (classoid != middle->classoid ||
7548                         objoid != middle->objoid)
7549                         break;
7550                 middle++;
7551                 nmatch++;
7552         }
7553
7554         return nmatch;
7555 }
7556
7557 /*
7558  * collectComments --
7559  *
7560  * Construct a table of all comments available for database objects.
7561  * We used to do per-object queries for the comments, but it's much faster
7562  * to pull them all over at once, and on most databases the memory cost
7563  * isn't high.
7564  *
7565  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7566  */
7567 static int
7568 collectComments(Archive *fout, CommentItem **items)
7569 {
7570         PGresult   *res;
7571         PQExpBuffer query;
7572         int                     i_description;
7573         int                     i_classoid;
7574         int                     i_objoid;
7575         int                     i_objsubid;
7576         int                     ntups;
7577         int                     i;
7578         CommentItem *comments;
7579
7580         /*
7581          * Note we do NOT change source schema here; preserve the caller's
7582          * setting, instead.
7583          */
7584
7585         query = createPQExpBuffer();
7586
7587         if (fout->remoteVersion >= 70300)
7588         {
7589                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7590                                                   "FROM pg_catalog.pg_description "
7591                                                   "ORDER BY classoid, objoid, objsubid");
7592         }
7593         else if (fout->remoteVersion >= 70200)
7594         {
7595                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7596                                                   "FROM pg_description "
7597                                                   "ORDER BY classoid, objoid, objsubid");
7598         }
7599         else
7600         {
7601                 /* Note: this will fail to find attribute comments in pre-7.2... */
7602                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7603                                                   "FROM pg_description "
7604                                                   "ORDER BY objoid");
7605         }
7606
7607         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7608
7609         /* Construct lookup table containing OIDs in numeric form */
7610
7611         i_description = PQfnumber(res, "description");
7612         i_classoid = PQfnumber(res, "classoid");
7613         i_objoid = PQfnumber(res, "objoid");
7614         i_objsubid = PQfnumber(res, "objsubid");
7615
7616         ntups = PQntuples(res);
7617
7618         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7619
7620         for (i = 0; i < ntups; i++)
7621         {
7622                 comments[i].descr = PQgetvalue(res, i, i_description);
7623                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7624                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7625                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7626         }
7627
7628         /* Do NOT free the PGresult since we are keeping pointers into it */
7629         destroyPQExpBuffer(query);
7630
7631         *items = comments;
7632         return ntups;
7633 }
7634
7635 /*
7636  * dumpDumpableObject
7637  *
7638  * This routine and its subsidiaries are responsible for creating
7639  * ArchiveEntries (TOC objects) for each object to be dumped.
7640  */
7641 static void
7642 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7643 {
7644         switch (dobj->objType)
7645         {
7646                 case DO_NAMESPACE:
7647                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7648                         break;
7649                 case DO_EXTENSION:
7650                         dumpExtension(fout, (ExtensionInfo *) dobj);
7651                         break;
7652                 case DO_TYPE:
7653                         dumpType(fout, (TypeInfo *) dobj);
7654                         break;
7655                 case DO_SHELL_TYPE:
7656                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7657                         break;
7658                 case DO_FUNC:
7659                         dumpFunc(fout, (FuncInfo *) dobj);
7660                         break;
7661                 case DO_AGG:
7662                         dumpAgg(fout, (AggInfo *) dobj);
7663                         break;
7664                 case DO_OPERATOR:
7665                         dumpOpr(fout, (OprInfo *) dobj);
7666                         break;
7667                 case DO_OPCLASS:
7668                         dumpOpclass(fout, (OpclassInfo *) dobj);
7669                         break;
7670                 case DO_OPFAMILY:
7671                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7672                         break;
7673                 case DO_COLLATION:
7674                         dumpCollation(fout, (CollInfo *) dobj);
7675                         break;
7676                 case DO_CONVERSION:
7677                         dumpConversion(fout, (ConvInfo *) dobj);
7678                         break;
7679                 case DO_TABLE:
7680                         dumpTable(fout, (TableInfo *) dobj);
7681                         break;
7682                 case DO_ATTRDEF:
7683                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7684                         break;
7685                 case DO_INDEX:
7686                         dumpIndex(fout, (IndxInfo *) dobj);
7687                         break;
7688                 case DO_REFRESH_MATVIEW:
7689                         refreshMatViewData(fout, (TableDataInfo *) dobj);
7690                         break;
7691                 case DO_RULE:
7692                         dumpRule(fout, (RuleInfo *) dobj);
7693                         break;
7694                 case DO_TRIGGER:
7695                         dumpTrigger(fout, (TriggerInfo *) dobj);
7696                         break;
7697                 case DO_EVENT_TRIGGER:
7698                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7699                         break;
7700                 case DO_CONSTRAINT:
7701                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7702                         break;
7703                 case DO_FK_CONSTRAINT:
7704                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7705                         break;
7706                 case DO_PROCLANG:
7707                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7708                         break;
7709                 case DO_CAST:
7710                         dumpCast(fout, (CastInfo *) dobj);
7711                         break;
7712                 case DO_TABLE_DATA:
7713                         if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7714                                 dumpSequenceData(fout, (TableDataInfo *) dobj);
7715                         else
7716                                 dumpTableData(fout, (TableDataInfo *) dobj);
7717                         break;
7718                 case DO_DUMMY_TYPE:
7719                         /* table rowtypes and array types are never dumped separately */
7720                         break;
7721                 case DO_TSPARSER:
7722                         dumpTSParser(fout, (TSParserInfo *) dobj);
7723                         break;
7724                 case DO_TSDICT:
7725                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7726                         break;
7727                 case DO_TSTEMPLATE:
7728                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7729                         break;
7730                 case DO_TSCONFIG:
7731                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7732                         break;
7733                 case DO_FDW:
7734                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7735                         break;
7736                 case DO_FOREIGN_SERVER:
7737                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7738                         break;
7739                 case DO_DEFAULT_ACL:
7740                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7741                         break;
7742                 case DO_BLOB:
7743                         dumpBlob(fout, (BlobInfo *) dobj);
7744                         break;
7745                 case DO_BLOB_DATA:
7746                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7747                                                  dobj->name, NULL, NULL, "",
7748                                                  false, "BLOBS", SECTION_DATA,
7749                                                  "", "", NULL,
7750                                                  NULL, 0,
7751                                                  dumpBlobs, NULL);
7752                         break;
7753                 case DO_PRE_DATA_BOUNDARY:
7754                 case DO_POST_DATA_BOUNDARY:
7755                         /* never dumped, nothing to do */
7756                         break;
7757         }
7758 }
7759
7760 /*
7761  * dumpNamespace
7762  *        writes out to fout the queries to recreate a user-defined namespace
7763  */
7764 static void
7765 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7766 {
7767         PQExpBuffer q;
7768         PQExpBuffer delq;
7769         PQExpBuffer labelq;
7770         char       *qnspname;
7771
7772         /* Skip if not to be dumped */
7773         if (!nspinfo->dobj.dump || dataOnly)
7774                 return;
7775
7776         /* don't dump dummy namespace from pre-7.3 source */
7777         if (strlen(nspinfo->dobj.name) == 0)
7778                 return;
7779
7780         q = createPQExpBuffer();
7781         delq = createPQExpBuffer();
7782         labelq = createPQExpBuffer();
7783
7784         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7785
7786         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7787
7788         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7789
7790         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7791
7792         if (binary_upgrade)
7793                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7794
7795         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7796                                  nspinfo->dobj.name,
7797                                  NULL, NULL,
7798                                  nspinfo->rolname,
7799                                  false, "SCHEMA", SECTION_PRE_DATA,
7800                                  q->data, delq->data, NULL,
7801                                  NULL, 0,
7802                                  NULL, NULL);
7803
7804         /* Dump Schema Comments and Security Labels */
7805         dumpComment(fout, labelq->data,
7806                                 NULL, nspinfo->rolname,
7807                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7808         dumpSecLabel(fout, labelq->data,
7809                                  NULL, nspinfo->rolname,
7810                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7811
7812         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7813                         qnspname, NULL, nspinfo->dobj.name, NULL,
7814                         nspinfo->rolname, nspinfo->nspacl);
7815
7816         free(qnspname);
7817
7818         destroyPQExpBuffer(q);
7819         destroyPQExpBuffer(delq);
7820         destroyPQExpBuffer(labelq);
7821 }
7822
7823 /*
7824  * dumpExtension
7825  *        writes out to fout the queries to recreate an extension
7826  */
7827 static void
7828 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7829 {
7830         PQExpBuffer q;
7831         PQExpBuffer delq;
7832         PQExpBuffer labelq;
7833         char       *qextname;
7834
7835         /* Skip if not to be dumped */
7836         if (!extinfo->dobj.dump || dataOnly)
7837                 return;
7838
7839         q = createPQExpBuffer();
7840         delq = createPQExpBuffer();
7841         labelq = createPQExpBuffer();
7842
7843         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7844
7845         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7846
7847         if (!binary_upgrade)
7848         {
7849                 /*
7850                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7851                  * problem if the extension already exists in the target database;
7852                  * this is essential for installed-by-default extensions such as
7853                  * plpgsql.
7854                  *
7855                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7856                  * built-in extensions based on their OIDs; see
7857                  * selectDumpableExtension.
7858                  */
7859                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7860                                                   qextname, fmtId(extinfo->namespace));
7861         }
7862         else
7863         {
7864                 int                     i;
7865                 int                     n;
7866
7867                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7868
7869                 /*
7870                  * We unconditionally create the extension, so we must drop it if it
7871                  * exists.      This could happen if the user deleted 'plpgsql' and then
7872                  * readded it, causing its oid to be greater than FirstNormalObjectId.
7873                  * The FirstNormalObjectId test was kept to avoid repeatedly dropping
7874                  * and recreating extensions like 'plpgsql'.
7875                  */
7876                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7877
7878                 appendPQExpBuffer(q,
7879                                                   "SELECT binary_upgrade.create_empty_extension(");
7880                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7881                 appendPQExpBuffer(q, ", ");
7882                 appendStringLiteralAH(q, extinfo->namespace, fout);
7883                 appendPQExpBuffer(q, ", ");
7884                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7885                 appendStringLiteralAH(q, extinfo->extversion, fout);
7886                 appendPQExpBuffer(q, ", ");
7887
7888                 /*
7889                  * Note that we're pushing extconfig (an OID array) back into
7890                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7891                  * preserved in binary upgrade.
7892                  */
7893                 if (strlen(extinfo->extconfig) > 2)
7894                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7895                 else
7896                         appendPQExpBuffer(q, "NULL");
7897                 appendPQExpBuffer(q, ", ");
7898                 if (strlen(extinfo->extcondition) > 2)
7899                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7900                 else
7901                         appendPQExpBuffer(q, "NULL");
7902                 appendPQExpBuffer(q, ", ");
7903                 appendPQExpBuffer(q, "ARRAY[");
7904                 n = 0;
7905                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7906                 {
7907                         DumpableObject *extobj;
7908
7909                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7910                         if (extobj && extobj->objType == DO_EXTENSION)
7911                         {
7912                                 if (n++ > 0)
7913                                         appendPQExpBuffer(q, ",");
7914                                 appendStringLiteralAH(q, extobj->name, fout);
7915                         }
7916                 }
7917                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7918                 appendPQExpBuffer(q, ");\n");
7919         }
7920
7921         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7922
7923         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7924                                  extinfo->dobj.name,
7925                                  NULL, NULL,
7926                                  "",
7927                                  false, "EXTENSION", SECTION_PRE_DATA,
7928                                  q->data, delq->data, NULL,
7929                                  NULL, 0,
7930                                  NULL, NULL);
7931
7932         /* Dump Extension Comments and Security Labels */
7933         dumpComment(fout, labelq->data,
7934                                 NULL, "",
7935                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7936         dumpSecLabel(fout, labelq->data,
7937                                  NULL, "",
7938                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7939
7940         free(qextname);
7941
7942         destroyPQExpBuffer(q);
7943         destroyPQExpBuffer(delq);
7944         destroyPQExpBuffer(labelq);
7945 }
7946
7947 /*
7948  * dumpType
7949  *        writes out to fout the queries to recreate a user-defined type
7950  */
7951 static void
7952 dumpType(Archive *fout, TypeInfo *tyinfo)
7953 {
7954         /* Skip if not to be dumped */
7955         if (!tyinfo->dobj.dump || dataOnly)
7956                 return;
7957
7958         /* Dump out in proper style */
7959         if (tyinfo->typtype == TYPTYPE_BASE)
7960                 dumpBaseType(fout, tyinfo);
7961         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7962                 dumpDomain(fout, tyinfo);
7963         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7964                 dumpCompositeType(fout, tyinfo);
7965         else if (tyinfo->typtype == TYPTYPE_ENUM)
7966                 dumpEnumType(fout, tyinfo);
7967         else if (tyinfo->typtype == TYPTYPE_RANGE)
7968                 dumpRangeType(fout, tyinfo);
7969         else
7970                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7971                                   tyinfo->dobj.name);
7972 }
7973
7974 /*
7975  * dumpEnumType
7976  *        writes out to fout the queries to recreate a user-defined enum type
7977  */
7978 static void
7979 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7980 {
7981         PQExpBuffer q = createPQExpBuffer();
7982         PQExpBuffer delq = createPQExpBuffer();
7983         PQExpBuffer labelq = createPQExpBuffer();
7984         PQExpBuffer query = createPQExpBuffer();
7985         PGresult   *res;
7986         int                     num,
7987                                 i;
7988         Oid                     enum_oid;
7989         char       *qtypname;
7990         char       *label;
7991
7992         /* Set proper schema search path */
7993         selectSourceSchema(fout, "pg_catalog");
7994
7995         if (fout->remoteVersion >= 90100)
7996                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7997                                                   "FROM pg_catalog.pg_enum "
7998                                                   "WHERE enumtypid = '%u'"
7999                                                   "ORDER BY enumsortorder",
8000                                                   tyinfo->dobj.catId.oid);
8001         else
8002                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
8003                                                   "FROM pg_catalog.pg_enum "
8004                                                   "WHERE enumtypid = '%u'"
8005                                                   "ORDER BY oid",
8006                                                   tyinfo->dobj.catId.oid);
8007
8008         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8009
8010         num = PQntuples(res);
8011
8012         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8013
8014         /*
8015          * DROP must be fully qualified in case same name appears in pg_catalog.
8016          * CASCADE shouldn't be required here as for normal types since the I/O
8017          * functions are generic and do not get dropped.
8018          */
8019         appendPQExpBuffer(delq, "DROP TYPE %s.",
8020                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8021         appendPQExpBuffer(delq, "%s;\n",
8022                                           qtypname);
8023
8024         if (binary_upgrade)
8025                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8026                                                                                                  tyinfo->dobj.catId.oid);
8027
8028         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
8029                                           qtypname);
8030
8031         if (!binary_upgrade)
8032         {
8033                 /* Labels with server-assigned oids */
8034                 for (i = 0; i < num; i++)
8035                 {
8036                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8037                         if (i > 0)
8038                                 appendPQExpBuffer(q, ",");
8039                         appendPQExpBuffer(q, "\n    ");
8040                         appendStringLiteralAH(q, label, fout);
8041                 }
8042         }
8043
8044         appendPQExpBuffer(q, "\n);\n");
8045
8046         if (binary_upgrade)
8047         {
8048                 /* Labels with dump-assigned (preserved) oids */
8049                 for (i = 0; i < num; i++)
8050                 {
8051                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
8052                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8053
8054                         if (i == 0)
8055                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
8056                         appendPQExpBuffer(q,
8057                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
8058                                                           enum_oid);
8059                         appendPQExpBuffer(q, "ALTER TYPE %s.",
8060                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8061                         appendPQExpBuffer(q, "%s ADD VALUE ",
8062                                                           qtypname);
8063                         appendStringLiteralAH(q, label, fout);
8064                         appendPQExpBuffer(q, ";\n\n");
8065                 }
8066         }
8067
8068         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8069
8070         if (binary_upgrade)
8071                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8072
8073         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8074                                  tyinfo->dobj.name,
8075                                  tyinfo->dobj.namespace->dobj.name,
8076                                  NULL,
8077                                  tyinfo->rolname, false,
8078                                  "TYPE", SECTION_PRE_DATA,
8079                                  q->data, delq->data, NULL,
8080                                  NULL, 0,
8081                                  NULL, NULL);
8082
8083         /* Dump Type Comments and Security Labels */
8084         dumpComment(fout, labelq->data,
8085                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8086                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8087         dumpSecLabel(fout, labelq->data,
8088                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8089                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8090
8091         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8092                         qtypname, NULL, tyinfo->dobj.name,
8093                         tyinfo->dobj.namespace->dobj.name,
8094                         tyinfo->rolname, tyinfo->typacl);
8095
8096         PQclear(res);
8097         destroyPQExpBuffer(q);
8098         destroyPQExpBuffer(delq);
8099         destroyPQExpBuffer(labelq);
8100         destroyPQExpBuffer(query);
8101 }
8102
8103 /*
8104  * dumpRangeType
8105  *        writes out to fout the queries to recreate a user-defined range type
8106  */
8107 static void
8108 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
8109 {
8110         PQExpBuffer q = createPQExpBuffer();
8111         PQExpBuffer delq = createPQExpBuffer();
8112         PQExpBuffer labelq = createPQExpBuffer();
8113         PQExpBuffer query = createPQExpBuffer();
8114         PGresult   *res;
8115         Oid                     collationOid;
8116         char       *qtypname;
8117         char       *procname;
8118
8119         /*
8120          * select appropriate schema to ensure names in CREATE are properly
8121          * qualified
8122          */
8123         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8124
8125         appendPQExpBuffer(query,
8126                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
8127                                           "opc.opcname AS opcname, "
8128                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
8129                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
8130                                           "opc.opcdefault, "
8131                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
8132                                           "     ELSE rngcollation END AS collation, "
8133                                           "rngcanonical, rngsubdiff "
8134                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
8135                                           "     pg_catalog.pg_opclass opc "
8136                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
8137                                           "rngtypid = '%u'",
8138                                           tyinfo->dobj.catId.oid);
8139
8140         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8141
8142         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8143
8144         /*
8145          * DROP must be fully qualified in case same name appears in pg_catalog.
8146          * CASCADE shouldn't be required here as for normal types since the I/O
8147          * functions are generic and do not get dropped.
8148          */
8149         appendPQExpBuffer(delq, "DROP TYPE %s.",
8150                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8151         appendPQExpBuffer(delq, "%s;\n",
8152                                           qtypname);
8153
8154         if (binary_upgrade)
8155                 binary_upgrade_set_type_oids_by_type_oid(fout,
8156                                                                                                  q, tyinfo->dobj.catId.oid);
8157
8158         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
8159                                           qtypname);
8160
8161         appendPQExpBuffer(q, "\n    subtype = %s",
8162                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
8163
8164         /* print subtype_opclass only if not default for subtype */
8165         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
8166         {
8167                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
8168                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
8169
8170                 /* always schema-qualify, don't try to be smart */
8171                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
8172                                                   fmtId(nspname));
8173                 appendPQExpBuffer(q, "%s", fmtId(opcname));
8174         }
8175
8176         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
8177         if (OidIsValid(collationOid))
8178         {
8179                 CollInfo   *coll = findCollationByOid(collationOid);
8180
8181                 if (coll)
8182                 {
8183                         /* always schema-qualify, don't try to be smart */
8184                         appendPQExpBuffer(q, ",\n    collation = %s.",
8185                                                           fmtId(coll->dobj.namespace->dobj.name));
8186                         appendPQExpBuffer(q, "%s",
8187                                                           fmtId(coll->dobj.name));
8188                 }
8189         }
8190
8191         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
8192         if (strcmp(procname, "-") != 0)
8193                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
8194
8195         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
8196         if (strcmp(procname, "-") != 0)
8197                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
8198
8199         appendPQExpBuffer(q, "\n);\n");
8200
8201         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8202
8203         if (binary_upgrade)
8204                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8205
8206         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8207                                  tyinfo->dobj.name,
8208                                  tyinfo->dobj.namespace->dobj.name,
8209                                  NULL,
8210                                  tyinfo->rolname, false,
8211                                  "TYPE", SECTION_PRE_DATA,
8212                                  q->data, delq->data, NULL,
8213                                  NULL, 0,
8214                                  NULL, NULL);
8215
8216         /* Dump Type Comments and Security Labels */
8217         dumpComment(fout, labelq->data,
8218                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8219                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8220         dumpSecLabel(fout, labelq->data,
8221                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8222                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8223
8224         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8225                         qtypname, NULL, tyinfo->dobj.name,
8226                         tyinfo->dobj.namespace->dobj.name,
8227                         tyinfo->rolname, tyinfo->typacl);
8228
8229         PQclear(res);
8230         destroyPQExpBuffer(q);
8231         destroyPQExpBuffer(delq);
8232         destroyPQExpBuffer(labelq);
8233         destroyPQExpBuffer(query);
8234 }
8235
8236 /*
8237  * dumpBaseType
8238  *        writes out to fout the queries to recreate a user-defined base type
8239  */
8240 static void
8241 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
8242 {
8243         PQExpBuffer q = createPQExpBuffer();
8244         PQExpBuffer delq = createPQExpBuffer();
8245         PQExpBuffer labelq = createPQExpBuffer();
8246         PQExpBuffer query = createPQExpBuffer();
8247         PGresult   *res;
8248         char       *qtypname;
8249         char       *typlen;
8250         char       *typinput;
8251         char       *typoutput;
8252         char       *typreceive;
8253         char       *typsend;
8254         char       *typmodin;
8255         char       *typmodout;
8256         char       *typanalyze;
8257         Oid                     typreceiveoid;
8258         Oid                     typsendoid;
8259         Oid                     typmodinoid;
8260         Oid                     typmodoutoid;
8261         Oid                     typanalyzeoid;
8262         char       *typcategory;
8263         char       *typispreferred;
8264         char       *typdelim;
8265         char       *typbyval;
8266         char       *typalign;
8267         char       *typstorage;
8268         char       *typcollatable;
8269         char       *typdefault;
8270         bool            typdefault_is_literal = false;
8271
8272         /* Set proper schema search path so regproc references list correctly */
8273         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8274
8275         /* Fetch type-specific details */
8276         if (fout->remoteVersion >= 90100)
8277         {
8278                 appendPQExpBuffer(query, "SELECT typlen, "
8279                                                   "typinput, typoutput, typreceive, typsend, "
8280                                                   "typmodin, typmodout, typanalyze, "
8281                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8282                                                   "typsend::pg_catalog.oid AS typsendoid, "
8283                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8284                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8285                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8286                                                   "typcategory, typispreferred, "
8287                                                   "typdelim, typbyval, typalign, typstorage, "
8288                                                   "(typcollation <> 0) AS typcollatable, "
8289                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8290                                                   "FROM pg_catalog.pg_type "
8291                                                   "WHERE oid = '%u'::pg_catalog.oid",
8292                                                   tyinfo->dobj.catId.oid);
8293         }
8294         else if (fout->remoteVersion >= 80400)
8295         {
8296                 appendPQExpBuffer(query, "SELECT typlen, "
8297                                                   "typinput, typoutput, typreceive, typsend, "
8298                                                   "typmodin, typmodout, typanalyze, "
8299                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8300                                                   "typsend::pg_catalog.oid AS typsendoid, "
8301                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8302                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8303                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8304                                                   "typcategory, typispreferred, "
8305                                                   "typdelim, typbyval, typalign, typstorage, "
8306                                                   "false AS typcollatable, "
8307                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8308                                                   "FROM pg_catalog.pg_type "
8309                                                   "WHERE oid = '%u'::pg_catalog.oid",
8310                                                   tyinfo->dobj.catId.oid);
8311         }
8312         else if (fout->remoteVersion >= 80300)
8313         {
8314                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
8315                 appendPQExpBuffer(query, "SELECT typlen, "
8316                                                   "typinput, typoutput, typreceive, typsend, "
8317                                                   "typmodin, typmodout, typanalyze, "
8318                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8319                                                   "typsend::pg_catalog.oid AS typsendoid, "
8320                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
8321                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
8322                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8323                                                   "'U' AS typcategory, false AS typispreferred, "
8324                                                   "typdelim, typbyval, typalign, typstorage, "
8325                                                   "false AS typcollatable, "
8326                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8327                                                   "FROM pg_catalog.pg_type "
8328                                                   "WHERE oid = '%u'::pg_catalog.oid",
8329                                                   tyinfo->dobj.catId.oid);
8330         }
8331         else if (fout->remoteVersion >= 80000)
8332         {
8333                 appendPQExpBuffer(query, "SELECT typlen, "
8334                                                   "typinput, typoutput, typreceive, typsend, "
8335                                                   "'-' AS typmodin, '-' AS typmodout, "
8336                                                   "typanalyze, "
8337                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8338                                                   "typsend::pg_catalog.oid AS typsendoid, "
8339                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8340                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8341                                                   "'U' AS typcategory, false AS typispreferred, "
8342                                                   "typdelim, typbyval, typalign, typstorage, "
8343                                                   "false AS typcollatable, "
8344                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8345                                                   "FROM pg_catalog.pg_type "
8346                                                   "WHERE oid = '%u'::pg_catalog.oid",
8347                                                   tyinfo->dobj.catId.oid);
8348         }
8349         else if (fout->remoteVersion >= 70400)
8350         {
8351                 appendPQExpBuffer(query, "SELECT typlen, "
8352                                                   "typinput, typoutput, typreceive, typsend, "
8353                                                   "'-' AS typmodin, '-' AS typmodout, "
8354                                                   "'-' AS typanalyze, "
8355                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8356                                                   "typsend::pg_catalog.oid AS typsendoid, "
8357                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8358                                                   "0 AS typanalyzeoid, "
8359                                                   "'U' AS typcategory, false AS typispreferred, "
8360                                                   "typdelim, typbyval, typalign, typstorage, "
8361                                                   "false AS typcollatable, "
8362                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8363                                                   "FROM pg_catalog.pg_type "
8364                                                   "WHERE oid = '%u'::pg_catalog.oid",
8365                                                   tyinfo->dobj.catId.oid);
8366         }
8367         else if (fout->remoteVersion >= 70300)
8368         {
8369                 appendPQExpBuffer(query, "SELECT typlen, "
8370                                                   "typinput, typoutput, "
8371                                                   "'-' AS typreceive, '-' AS typsend, "
8372                                                   "'-' AS typmodin, '-' AS typmodout, "
8373                                                   "'-' AS typanalyze, "
8374                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8375                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8376                                                   "0 AS typanalyzeoid, "
8377                                                   "'U' AS typcategory, false AS typispreferred, "
8378                                                   "typdelim, typbyval, typalign, typstorage, "
8379                                                   "false AS typcollatable, "
8380                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8381                                                   "FROM pg_catalog.pg_type "
8382                                                   "WHERE oid = '%u'::pg_catalog.oid",
8383                                                   tyinfo->dobj.catId.oid);
8384         }
8385         else if (fout->remoteVersion >= 70200)
8386         {
8387                 /*
8388                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
8389                  * ignore them because they are not right.
8390                  */
8391                 appendPQExpBuffer(query, "SELECT typlen, "
8392                                                   "typinput, typoutput, "
8393                                                   "'-' AS typreceive, '-' AS typsend, "
8394                                                   "'-' AS typmodin, '-' AS typmodout, "
8395                                                   "'-' AS typanalyze, "
8396                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8397                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8398                                                   "0 AS typanalyzeoid, "
8399                                                   "'U' AS typcategory, false AS typispreferred, "
8400                                                   "typdelim, typbyval, typalign, typstorage, "
8401                                                   "false AS typcollatable, "
8402                                                   "NULL AS typdefaultbin, typdefault "
8403                                                   "FROM pg_type "
8404                                                   "WHERE oid = '%u'::oid",
8405                                                   tyinfo->dobj.catId.oid);
8406         }
8407         else if (fout->remoteVersion >= 70100)
8408         {
8409                 /*
8410                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
8411                  * representation.
8412                  */
8413                 appendPQExpBuffer(query, "SELECT typlen, "
8414                                                   "typinput, typoutput, "
8415                                                   "'-' AS typreceive, '-' AS typsend, "
8416                                                   "'-' AS typmodin, '-' AS typmodout, "
8417                                                   "'-' AS typanalyze, "
8418                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8419                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8420                                                   "0 AS typanalyzeoid, "
8421                                                   "'U' AS typcategory, false AS typispreferred, "
8422                                                   "typdelim, typbyval, typalign, typstorage, "
8423                                                   "false AS typcollatable, "
8424                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8425                                                   "FROM pg_type "
8426                                                   "WHERE oid = '%u'::oid",
8427                                                   tyinfo->dobj.catId.oid);
8428         }
8429         else
8430         {
8431                 appendPQExpBuffer(query, "SELECT typlen, "
8432                                                   "typinput, typoutput, "
8433                                                   "'-' AS typreceive, '-' AS typsend, "
8434                                                   "'-' AS typmodin, '-' AS typmodout, "
8435                                                   "'-' AS typanalyze, "
8436                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8437                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8438                                                   "0 AS typanalyzeoid, "
8439                                                   "'U' AS typcategory, false AS typispreferred, "
8440                                                   "typdelim, typbyval, typalign, "
8441                                                   "'p'::char AS typstorage, "
8442                                                   "false AS typcollatable, "
8443                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8444                                                   "FROM pg_type "
8445                                                   "WHERE oid = '%u'::oid",
8446                                                   tyinfo->dobj.catId.oid);
8447         }
8448
8449         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8450
8451         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8452         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8453         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8454         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8455         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8456         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8457         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8458         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8459         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8460         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8461         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8462         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8463         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8464         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8465         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8466         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8467         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8468         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8469         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8470         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8471         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8472                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8473         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8474         {
8475                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8476                 typdefault_is_literal = true;   /* it needs quotes */
8477         }
8478         else
8479                 typdefault = NULL;
8480
8481         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8482
8483         /*
8484          * DROP must be fully qualified in case same name appears in pg_catalog.
8485          * The reason we include CASCADE is that the circular dependency between
8486          * the type and its I/O functions makes it impossible to drop the type any
8487          * other way.
8488          */
8489         appendPQExpBuffer(delq, "DROP TYPE %s.",
8490                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8491         appendPQExpBuffer(delq, "%s CASCADE;\n",
8492                                           qtypname);
8493
8494         /* We might already have a shell type, but setting pg_type_oid is harmless */
8495         if (binary_upgrade)
8496                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8497                                                                                                  tyinfo->dobj.catId.oid);
8498
8499         appendPQExpBuffer(q,
8500                                           "CREATE TYPE %s (\n"
8501                                           "    INTERNALLENGTH = %s",
8502                                           qtypname,
8503                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8504
8505         if (fout->remoteVersion >= 70300)
8506         {
8507                 /* regproc result is correctly quoted as of 7.3 */
8508                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
8509                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
8510                 if (OidIsValid(typreceiveoid))
8511                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
8512                 if (OidIsValid(typsendoid))
8513                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
8514                 if (OidIsValid(typmodinoid))
8515                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
8516                 if (OidIsValid(typmodoutoid))
8517                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
8518                 if (OidIsValid(typanalyzeoid))
8519                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
8520         }
8521         else
8522         {
8523                 /* regproc delivers an unquoted name before 7.3 */
8524                 /* cannot combine these because fmtId uses static result area */
8525                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
8526                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
8527                 /* receive/send/typmodin/typmodout/analyze need not be printed */
8528         }
8529
8530         if (strcmp(typcollatable, "t") == 0)
8531                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
8532
8533         if (typdefault != NULL)
8534         {
8535                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
8536                 if (typdefault_is_literal)
8537                         appendStringLiteralAH(q, typdefault, fout);
8538                 else
8539                         appendPQExpBufferStr(q, typdefault);
8540         }
8541
8542         if (OidIsValid(tyinfo->typelem))
8543         {
8544                 char       *elemType;
8545
8546                 /* reselect schema in case changed by function dump */
8547                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8548                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8549                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8550                 free(elemType);
8551         }
8552
8553         if (strcmp(typcategory, "U") != 0)
8554         {
8555                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8556                 appendStringLiteralAH(q, typcategory, fout);
8557         }
8558
8559         if (strcmp(typispreferred, "t") == 0)
8560                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8561
8562         if (typdelim && strcmp(typdelim, ",") != 0)
8563         {
8564                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8565                 appendStringLiteralAH(q, typdelim, fout);
8566         }
8567
8568         if (strcmp(typalign, "c") == 0)
8569                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8570         else if (strcmp(typalign, "s") == 0)
8571                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8572         else if (strcmp(typalign, "i") == 0)
8573                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8574         else if (strcmp(typalign, "d") == 0)
8575                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8576
8577         if (strcmp(typstorage, "p") == 0)
8578                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8579         else if (strcmp(typstorage, "e") == 0)
8580                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8581         else if (strcmp(typstorage, "x") == 0)
8582                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8583         else if (strcmp(typstorage, "m") == 0)
8584                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8585
8586         if (strcmp(typbyval, "t") == 0)
8587                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8588
8589         appendPQExpBuffer(q, "\n);\n");
8590
8591         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8592
8593         if (binary_upgrade)
8594                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8595
8596         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8597                                  tyinfo->dobj.name,
8598                                  tyinfo->dobj.namespace->dobj.name,
8599                                  NULL,
8600                                  tyinfo->rolname, false,
8601                                  "TYPE", SECTION_PRE_DATA,
8602                                  q->data, delq->data, NULL,
8603                                  NULL, 0,
8604                                  NULL, NULL);
8605
8606         /* Dump Type Comments and Security Labels */
8607         dumpComment(fout, labelq->data,
8608                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8609                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8610         dumpSecLabel(fout, labelq->data,
8611                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8612                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8613
8614         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8615                         qtypname, NULL, tyinfo->dobj.name,
8616                         tyinfo->dobj.namespace->dobj.name,
8617                         tyinfo->rolname, tyinfo->typacl);
8618
8619         PQclear(res);
8620         destroyPQExpBuffer(q);
8621         destroyPQExpBuffer(delq);
8622         destroyPQExpBuffer(labelq);
8623         destroyPQExpBuffer(query);
8624 }
8625
8626 /*
8627  * dumpDomain
8628  *        writes out to fout the queries to recreate a user-defined domain
8629  */
8630 static void
8631 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8632 {
8633         PQExpBuffer q = createPQExpBuffer();
8634         PQExpBuffer delq = createPQExpBuffer();
8635         PQExpBuffer labelq = createPQExpBuffer();
8636         PQExpBuffer query = createPQExpBuffer();
8637         PGresult   *res;
8638         int                     i;
8639         char       *qtypname;
8640         char       *typnotnull;
8641         char       *typdefn;
8642         char       *typdefault;
8643         Oid                     typcollation;
8644         bool            typdefault_is_literal = false;
8645
8646         /* Set proper schema search path so type references list correctly */
8647         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8648
8649         /* Fetch domain specific details */
8650         if (fout->remoteVersion >= 90100)
8651         {
8652                 /* typcollation is new in 9.1 */
8653                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8654                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8655                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8656                                                   "t.typdefault, "
8657                                                   "CASE WHEN t.typcollation <> u.typcollation "
8658                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8659                                                   "FROM pg_catalog.pg_type t "
8660                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8661                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8662                                                   tyinfo->dobj.catId.oid);
8663         }
8664         else
8665         {
8666                 /* We assume here that remoteVersion must be at least 70300 */
8667                 appendPQExpBuffer(query, "SELECT typnotnull, "
8668                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8669                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8670                                                   "typdefault, 0 AS typcollation "
8671                                                   "FROM pg_catalog.pg_type "
8672                                                   "WHERE oid = '%u'::pg_catalog.oid",
8673                                                   tyinfo->dobj.catId.oid);
8674         }
8675
8676         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8677
8678         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8679         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8680         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8681                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8682         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8683         {
8684                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8685                 typdefault_is_literal = true;   /* it needs quotes */
8686         }
8687         else
8688                 typdefault = NULL;
8689         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8690
8691         if (binary_upgrade)
8692                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8693                                                                                                  tyinfo->dobj.catId.oid);
8694
8695         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8696
8697         appendPQExpBuffer(q,
8698                                           "CREATE DOMAIN %s AS %s",
8699                                           qtypname,
8700                                           typdefn);
8701
8702         /* Print collation only if different from base type's collation */
8703         if (OidIsValid(typcollation))
8704         {
8705                 CollInfo   *coll;
8706
8707                 coll = findCollationByOid(typcollation);
8708                 if (coll)
8709                 {
8710                         /* always schema-qualify, don't try to be smart */
8711                         appendPQExpBuffer(q, " COLLATE %s.",
8712                                                           fmtId(coll->dobj.namespace->dobj.name));
8713                         appendPQExpBuffer(q, "%s",
8714                                                           fmtId(coll->dobj.name));
8715                 }
8716         }
8717
8718         if (typnotnull[0] == 't')
8719                 appendPQExpBuffer(q, " NOT NULL");
8720
8721         if (typdefault != NULL)
8722         {
8723                 appendPQExpBuffer(q, " DEFAULT ");
8724                 if (typdefault_is_literal)
8725                         appendStringLiteralAH(q, typdefault, fout);
8726                 else
8727                         appendPQExpBufferStr(q, typdefault);
8728         }
8729
8730         PQclear(res);
8731
8732         /*
8733          * Add any CHECK constraints for the domain
8734          */
8735         for (i = 0; i < tyinfo->nDomChecks; i++)
8736         {
8737                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8738
8739                 if (!domcheck->separate)
8740                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8741                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8742         }
8743
8744         appendPQExpBuffer(q, ";\n");
8745
8746         /*
8747          * DROP must be fully qualified in case same name appears in pg_catalog
8748          */
8749         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8750                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8751         appendPQExpBuffer(delq, "%s;\n",
8752                                           qtypname);
8753
8754         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8755
8756         if (binary_upgrade)
8757                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8758
8759         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8760                                  tyinfo->dobj.name,
8761                                  tyinfo->dobj.namespace->dobj.name,
8762                                  NULL,
8763                                  tyinfo->rolname, false,
8764                                  "DOMAIN", SECTION_PRE_DATA,
8765                                  q->data, delq->data, NULL,
8766                                  NULL, 0,
8767                                  NULL, NULL);
8768
8769         /* Dump Domain Comments and Security Labels */
8770         dumpComment(fout, labelq->data,
8771                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8772                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8773         dumpSecLabel(fout, labelq->data,
8774                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8775                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8776
8777         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8778                         qtypname, NULL, tyinfo->dobj.name,
8779                         tyinfo->dobj.namespace->dobj.name,
8780                         tyinfo->rolname, tyinfo->typacl);
8781
8782         destroyPQExpBuffer(q);
8783         destroyPQExpBuffer(delq);
8784         destroyPQExpBuffer(labelq);
8785         destroyPQExpBuffer(query);
8786 }
8787
8788 /*
8789  * dumpCompositeType
8790  *        writes out to fout the queries to recreate a user-defined stand-alone
8791  *        composite type
8792  */
8793 static void
8794 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8795 {
8796         PQExpBuffer q = createPQExpBuffer();
8797         PQExpBuffer dropped = createPQExpBuffer();
8798         PQExpBuffer delq = createPQExpBuffer();
8799         PQExpBuffer labelq = createPQExpBuffer();
8800         PQExpBuffer query = createPQExpBuffer();
8801         PGresult   *res;
8802         char       *qtypname;
8803         int                     ntups;
8804         int                     i_attname;
8805         int                     i_atttypdefn;
8806         int                     i_attlen;
8807         int                     i_attalign;
8808         int                     i_attisdropped;
8809         int                     i_attcollation;
8810         int                     i_typrelid;
8811         int                     i;
8812         int                     actual_atts;
8813
8814         /* Set proper schema search path so type references list correctly */
8815         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8816
8817         /* Fetch type specific details */
8818         if (fout->remoteVersion >= 90100)
8819         {
8820                 /*
8821                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8822                  * clauses for attributes whose collation is different from their
8823                  * type's default, we use a CASE here to suppress uninteresting
8824                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8825                  * collation does not matter for those.
8826                  */
8827                 appendPQExpBuffer(query, "SELECT a.attname, "
8828                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8829                                                   "a.attlen, a.attalign, a.attisdropped, "
8830                                                   "CASE WHEN a.attcollation <> at.typcollation "
8831                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8832                                                   "ct.typrelid "
8833                                                   "FROM pg_catalog.pg_type ct "
8834                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8835                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8836                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8837                                                   "ORDER BY a.attnum ",
8838                                                   tyinfo->dobj.catId.oid);
8839         }
8840         else
8841         {
8842                 /*
8843                  * We assume here that remoteVersion must be at least 70300.  Since
8844                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8845                  * always be false.
8846                  */
8847                 appendPQExpBuffer(query, "SELECT a.attname, "
8848                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8849                                                   "a.attlen, a.attalign, a.attisdropped, "
8850                                                   "0 AS attcollation, "
8851                                                   "ct.typrelid "
8852                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8853                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8854                                                   "AND a.attrelid = ct.typrelid "
8855                                                   "ORDER BY a.attnum ",
8856                                                   tyinfo->dobj.catId.oid);
8857         }
8858
8859         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8860
8861         ntups = PQntuples(res);
8862
8863         i_attname = PQfnumber(res, "attname");
8864         i_atttypdefn = PQfnumber(res, "atttypdefn");
8865         i_attlen = PQfnumber(res, "attlen");
8866         i_attalign = PQfnumber(res, "attalign");
8867         i_attisdropped = PQfnumber(res, "attisdropped");
8868         i_attcollation = PQfnumber(res, "attcollation");
8869         i_typrelid = PQfnumber(res, "typrelid");
8870
8871         if (binary_upgrade)
8872         {
8873                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8874
8875                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8876                                                                                                  tyinfo->dobj.catId.oid);
8877                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8878         }
8879
8880         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8881
8882         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8883                                           qtypname);
8884
8885         actual_atts = 0;
8886         for (i = 0; i < ntups; i++)
8887         {
8888                 char       *attname;
8889                 char       *atttypdefn;
8890                 char       *attlen;
8891                 char       *attalign;
8892                 bool            attisdropped;
8893                 Oid                     attcollation;
8894
8895                 attname = PQgetvalue(res, i, i_attname);
8896                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8897                 attlen = PQgetvalue(res, i, i_attlen);
8898                 attalign = PQgetvalue(res, i, i_attalign);
8899                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8900                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8901
8902                 if (attisdropped && !binary_upgrade)
8903                         continue;
8904
8905                 /* Format properly if not first attr */
8906                 if (actual_atts++ > 0)
8907                         appendPQExpBuffer(q, ",");
8908                 appendPQExpBuffer(q, "\n\t");
8909
8910                 if (!attisdropped)
8911                 {
8912                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8913
8914                         /* Add collation if not default for the column type */
8915                         if (OidIsValid(attcollation))
8916                         {
8917                                 CollInfo   *coll;
8918
8919                                 coll = findCollationByOid(attcollation);
8920                                 if (coll)
8921                                 {
8922                                         /* always schema-qualify, don't try to be smart */
8923                                         appendPQExpBuffer(q, " COLLATE %s.",
8924                                                                           fmtId(coll->dobj.namespace->dobj.name));
8925                                         appendPQExpBuffer(q, "%s",
8926                                                                           fmtId(coll->dobj.name));
8927                                 }
8928                         }
8929                 }
8930                 else
8931                 {
8932                         /*
8933                          * This is a dropped attribute and we're in binary_upgrade mode.
8934                          * Insert a placeholder for it in the CREATE TYPE command, and set
8935                          * length and alignment with direct UPDATE to the catalogs
8936                          * afterwards. See similar code in dumpTableSchema().
8937                          */
8938                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8939
8940                         /* stash separately for insertion after the CREATE TYPE */
8941                         appendPQExpBuffer(dropped,
8942                                           "\n-- For binary upgrade, recreate dropped column.\n");
8943                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8944                                                           "SET attlen = %s, "
8945                                                           "attalign = '%s', attbyval = false\n"
8946                                                           "WHERE attname = ", attlen, attalign);
8947                         appendStringLiteralAH(dropped, attname, fout);
8948                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8949                         appendStringLiteralAH(dropped, qtypname, fout);
8950                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8951
8952                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8953                                                           qtypname);
8954                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8955                                                           fmtId(attname));
8956                 }
8957         }
8958         appendPQExpBuffer(q, "\n);\n");
8959         appendPQExpBufferStr(q, dropped->data);
8960
8961         /*
8962          * DROP must be fully qualified in case same name appears in pg_catalog
8963          */
8964         appendPQExpBuffer(delq, "DROP TYPE %s.",
8965                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8966         appendPQExpBuffer(delq, "%s;\n",
8967                                           qtypname);
8968
8969         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8970
8971         if (binary_upgrade)
8972                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8973
8974         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8975                                  tyinfo->dobj.name,
8976                                  tyinfo->dobj.namespace->dobj.name,
8977                                  NULL,
8978                                  tyinfo->rolname, false,
8979                                  "TYPE", SECTION_PRE_DATA,
8980                                  q->data, delq->data, NULL,
8981                                  NULL, 0,
8982                                  NULL, NULL);
8983
8984
8985         /* Dump Type Comments and Security Labels */
8986         dumpComment(fout, labelq->data,
8987                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8988                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8989         dumpSecLabel(fout, labelq->data,
8990                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8991                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8992
8993         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8994                         qtypname, NULL, tyinfo->dobj.name,
8995                         tyinfo->dobj.namespace->dobj.name,
8996                         tyinfo->rolname, tyinfo->typacl);
8997
8998         PQclear(res);
8999         destroyPQExpBuffer(q);
9000         destroyPQExpBuffer(dropped);
9001         destroyPQExpBuffer(delq);
9002         destroyPQExpBuffer(labelq);
9003         destroyPQExpBuffer(query);
9004
9005         /* Dump any per-column comments */
9006         dumpCompositeTypeColComments(fout, tyinfo);
9007 }
9008
9009 /*
9010  * dumpCompositeTypeColComments
9011  *        writes out to fout the queries to recreate comments on the columns of
9012  *        a user-defined stand-alone composite type
9013  */
9014 static void
9015 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
9016 {
9017         CommentItem *comments;
9018         int                     ncomments;
9019         PGresult   *res;
9020         PQExpBuffer query;
9021         PQExpBuffer target;
9022         Oid                     pgClassOid;
9023         int                     i;
9024         int                     ntups;
9025         int                     i_attname;
9026         int                     i_attnum;
9027
9028         query = createPQExpBuffer();
9029
9030         /* We assume here that remoteVersion must be at least 70300 */
9031         appendPQExpBuffer(query,
9032                                           "SELECT c.tableoid, a.attname, a.attnum "
9033                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
9034                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
9035                                           "  AND NOT a.attisdropped "
9036                                           "ORDER BY a.attnum ",
9037                                           tyinfo->typrelid);
9038
9039         /* Fetch column attnames */
9040         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9041
9042         ntups = PQntuples(res);
9043         if (ntups < 1)
9044         {
9045                 PQclear(res);
9046                 destroyPQExpBuffer(query);
9047                 return;
9048         }
9049
9050         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
9051
9052         /* Search for comments associated with type's pg_class OID */
9053         ncomments = findComments(fout,
9054                                                          pgClassOid,
9055                                                          tyinfo->typrelid,
9056                                                          &comments);
9057
9058         /* If no comments exist, we're done */
9059         if (ncomments <= 0)
9060         {
9061                 PQclear(res);
9062                 destroyPQExpBuffer(query);
9063                 return;
9064         }
9065
9066         /* Build COMMENT ON statements */
9067         target = createPQExpBuffer();
9068
9069         i_attnum = PQfnumber(res, "attnum");
9070         i_attname = PQfnumber(res, "attname");
9071         while (ncomments > 0)
9072         {
9073                 const char *attname;
9074
9075                 attname = NULL;
9076                 for (i = 0; i < ntups; i++)
9077                 {
9078                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
9079                         {
9080                                 attname = PQgetvalue(res, i, i_attname);
9081                                 break;
9082                         }
9083                 }
9084                 if (attname)                    /* just in case we don't find it */
9085                 {
9086                         const char *descr = comments->descr;
9087
9088                         resetPQExpBuffer(target);
9089                         appendPQExpBuffer(target, "COLUMN %s.",
9090                                                           fmtId(tyinfo->dobj.name));
9091                         appendPQExpBuffer(target, "%s",
9092                                                           fmtId(attname));
9093
9094                         resetPQExpBuffer(query);
9095                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9096                         appendStringLiteralAH(query, descr, fout);
9097                         appendPQExpBuffer(query, ";\n");
9098
9099                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9100                                                  target->data,
9101                                                  tyinfo->dobj.namespace->dobj.name,
9102                                                  NULL, tyinfo->rolname,
9103                                                  false, "COMMENT", SECTION_NONE,
9104                                                  query->data, "", NULL,
9105                                                  &(tyinfo->dobj.dumpId), 1,
9106                                                  NULL, NULL);
9107                 }
9108
9109                 comments++;
9110                 ncomments--;
9111         }
9112
9113         PQclear(res);
9114         destroyPQExpBuffer(query);
9115         destroyPQExpBuffer(target);
9116 }
9117
9118 /*
9119  * dumpShellType
9120  *        writes out to fout the queries to create a shell type
9121  *
9122  * We dump a shell definition in advance of the I/O functions for the type.
9123  */
9124 static void
9125 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
9126 {
9127         PQExpBuffer q;
9128
9129         /* Skip if not to be dumped */
9130         if (!stinfo->dobj.dump || dataOnly)
9131                 return;
9132
9133         q = createPQExpBuffer();
9134
9135         /*
9136          * Note the lack of a DROP command for the shell type; any required DROP
9137          * is driven off the base type entry, instead.  This interacts with
9138          * _printTocEntry()'s use of the presence of a DROP command to decide
9139          * whether an entry needs an ALTER OWNER command.  We don't want to alter
9140          * the shell type's owner immediately on creation; that should happen only
9141          * after it's filled in, otherwise the backend complains.
9142          */
9143
9144         if (binary_upgrade)
9145                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
9146                                                                                    stinfo->baseType->dobj.catId.oid);
9147
9148         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
9149                                           fmtId(stinfo->dobj.name));
9150
9151         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
9152                                  stinfo->dobj.name,
9153                                  stinfo->dobj.namespace->dobj.name,
9154                                  NULL,
9155                                  stinfo->baseType->rolname, false,
9156                                  "SHELL TYPE", SECTION_PRE_DATA,
9157                                  q->data, "", NULL,
9158                                  NULL, 0,
9159                                  NULL, NULL);
9160
9161         destroyPQExpBuffer(q);
9162 }
9163
9164 /*
9165  * Determine whether we want to dump definitions for procedural languages.
9166  * Since the languages themselves don't have schemas, we can't rely on
9167  * the normal schema-based selection mechanism.  We choose to dump them
9168  * whenever neither --schema nor --table was given.  (Before 8.1, we used
9169  * the dump flag of the PL's call handler function, but in 8.1 this will
9170  * probably always be false since call handlers are created in pg_catalog.)
9171  *
9172  * For some backwards compatibility with the older behavior, we forcibly
9173  * dump a PL if its handler function (and validator if any) are in a
9174  * dumpable namespace.  That case is not checked here.
9175  *
9176  * Also, if the PL belongs to an extension, we do not use this heuristic.
9177  * That case isn't checked here either.
9178  */
9179 static bool
9180 shouldDumpProcLangs(void)
9181 {
9182         if (!include_everything)
9183                 return false;
9184         /* And they're schema not data */
9185         if (dataOnly)
9186                 return false;
9187         return true;
9188 }
9189
9190 /*
9191  * dumpProcLang
9192  *                writes out to fout the queries to recreate a user-defined
9193  *                procedural language
9194  */
9195 static void
9196 dumpProcLang(Archive *fout, ProcLangInfo *plang)
9197 {
9198         PQExpBuffer defqry;
9199         PQExpBuffer delqry;
9200         PQExpBuffer labelq;
9201         bool            useParams;
9202         char       *qlanname;
9203         char       *lanschema;
9204         FuncInfo   *funcInfo;
9205         FuncInfo   *inlineInfo = NULL;
9206         FuncInfo   *validatorInfo = NULL;
9207
9208         /* Skip if not to be dumped */
9209         if (!plang->dobj.dump || dataOnly)
9210                 return;
9211
9212         /*
9213          * Try to find the support function(s).  It is not an error if we don't
9214          * find them --- if the functions are in the pg_catalog schema, as is
9215          * standard in 8.1 and up, then we won't have loaded them. (In this case
9216          * we will emit a parameterless CREATE LANGUAGE command, which will
9217          * require PL template knowledge in the backend to reload.)
9218          */
9219
9220         funcInfo = findFuncByOid(plang->lanplcallfoid);
9221         if (funcInfo != NULL && !funcInfo->dobj.dump)
9222                 funcInfo = NULL;                /* treat not-dumped same as not-found */
9223
9224         if (OidIsValid(plang->laninline))
9225         {
9226                 inlineInfo = findFuncByOid(plang->laninline);
9227                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
9228                         inlineInfo = NULL;
9229         }
9230
9231         if (OidIsValid(plang->lanvalidator))
9232         {
9233                 validatorInfo = findFuncByOid(plang->lanvalidator);
9234                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
9235                         validatorInfo = NULL;
9236         }
9237
9238         /*
9239          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
9240          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
9241          * dump it.
9242          *
9243          * However, for a language that belongs to an extension, we must not use
9244          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
9245          * told to (via dobj.dump).  Generally the support functions will belong
9246          * to the same extension and so have the same dump flags ... if they
9247          * don't, this might not work terribly nicely.
9248          */
9249         useParams = (funcInfo != NULL &&
9250                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
9251                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
9252
9253         if (!plang->dobj.ext_member)
9254         {
9255                 if (!useParams && !shouldDumpProcLangs())
9256                         return;
9257         }
9258
9259         defqry = createPQExpBuffer();
9260         delqry = createPQExpBuffer();
9261         labelq = createPQExpBuffer();
9262
9263         qlanname = pg_strdup(fmtId(plang->dobj.name));
9264
9265         /*
9266          * If dumping a HANDLER clause, treat the language as being in the handler
9267          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
9268          * it doesn't really have a schema.
9269          */
9270         if (useParams)
9271                 lanschema = funcInfo->dobj.namespace->dobj.name;
9272         else
9273                 lanschema = NULL;
9274
9275         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
9276                                           qlanname);
9277
9278         if (useParams)
9279         {
9280                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
9281                                                   plang->lanpltrusted ? "TRUSTED " : "",
9282                                                   qlanname);
9283                 appendPQExpBuffer(defqry, " HANDLER %s",
9284                                                   fmtId(funcInfo->dobj.name));
9285                 if (OidIsValid(plang->laninline))
9286                 {
9287                         appendPQExpBuffer(defqry, " INLINE ");
9288                         /* Cope with possibility that inline is in different schema */
9289                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
9290                                 appendPQExpBuffer(defqry, "%s.",
9291                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
9292                         appendPQExpBuffer(defqry, "%s",
9293                                                           fmtId(inlineInfo->dobj.name));
9294                 }
9295                 if (OidIsValid(plang->lanvalidator))
9296                 {
9297                         appendPQExpBuffer(defqry, " VALIDATOR ");
9298                         /* Cope with possibility that validator is in different schema */
9299                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
9300                                 appendPQExpBuffer(defqry, "%s.",
9301                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
9302                         appendPQExpBuffer(defqry, "%s",
9303                                                           fmtId(validatorInfo->dobj.name));
9304                 }
9305         }
9306         else
9307         {
9308                 /*
9309                  * If not dumping parameters, then use CREATE OR REPLACE so that the
9310                  * command will not fail if the language is preinstalled in the target
9311                  * database.  We restrict the use of REPLACE to this case so as to
9312                  * eliminate the risk of replacing a language with incompatible
9313                  * parameter settings: this command will only succeed at all if there
9314                  * is a pg_pltemplate entry, and if there is one, the existing entry
9315                  * must match it too.
9316                  */
9317                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
9318                                                   qlanname);
9319         }
9320         appendPQExpBuffer(defqry, ";\n");
9321
9322         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
9323
9324         if (binary_upgrade)
9325                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
9326
9327         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
9328                                  plang->dobj.name,
9329                                  lanschema, NULL, plang->lanowner,
9330                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
9331                                  defqry->data, delqry->data, NULL,
9332                                  NULL, 0,
9333                                  NULL, NULL);
9334
9335         /* Dump Proc Lang Comments and Security Labels */
9336         dumpComment(fout, labelq->data,
9337                                 NULL, "",
9338                                 plang->dobj.catId, 0, plang->dobj.dumpId);
9339         dumpSecLabel(fout, labelq->data,
9340                                  NULL, "",
9341                                  plang->dobj.catId, 0, plang->dobj.dumpId);
9342
9343         if (plang->lanpltrusted)
9344                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
9345                                 qlanname, NULL, plang->dobj.name,
9346                                 lanschema,
9347                                 plang->lanowner, plang->lanacl);
9348
9349         free(qlanname);
9350
9351         destroyPQExpBuffer(defqry);
9352         destroyPQExpBuffer(delqry);
9353         destroyPQExpBuffer(labelq);
9354 }
9355
9356 /*
9357  * format_function_arguments: generate function name and argument list
9358  *
9359  * This is used when we can rely on pg_get_function_arguments to format
9360  * the argument list.
9361  */
9362 static char *
9363 format_function_arguments(FuncInfo *finfo, char *funcargs)
9364 {
9365         PQExpBufferData fn;
9366
9367         initPQExpBuffer(&fn);
9368         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9369         return fn.data;
9370 }
9371
9372 /*
9373  * format_function_arguments_old: generate function name and argument list
9374  *
9375  * The argument type names are qualified if needed.  The function name
9376  * is never qualified.
9377  *
9378  * This is used only with pre-8.4 servers, so we aren't expecting to see
9379  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9380  *
9381  * Any or all of allargtypes, argmodes, argnames may be NULL.
9382  */
9383 static char *
9384 format_function_arguments_old(Archive *fout,
9385                                                           FuncInfo *finfo, int nallargs,
9386                                                           char **allargtypes,
9387                                                           char **argmodes,
9388                                                           char **argnames)
9389 {
9390         PQExpBufferData fn;
9391         int                     j;
9392
9393         initPQExpBuffer(&fn);
9394         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9395         for (j = 0; j < nallargs; j++)
9396         {
9397                 Oid                     typid;
9398                 char       *typname;
9399                 const char *argmode;
9400                 const char *argname;
9401
9402                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9403                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9404
9405                 if (argmodes)
9406                 {
9407                         switch (argmodes[j][0])
9408                         {
9409                                 case PROARGMODE_IN:
9410                                         argmode = "";
9411                                         break;
9412                                 case PROARGMODE_OUT:
9413                                         argmode = "OUT ";
9414                                         break;
9415                                 case PROARGMODE_INOUT:
9416                                         argmode = "INOUT ";
9417                                         break;
9418                                 default:
9419                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9420                                         argmode = "";
9421                                         break;
9422                         }
9423                 }
9424                 else
9425                         argmode = "";
9426
9427                 argname = argnames ? argnames[j] : (char *) NULL;
9428                 if (argname && argname[0] == '\0')
9429                         argname = NULL;
9430
9431                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9432                                                   (j > 0) ? ", " : "",
9433                                                   argmode,
9434                                                   argname ? fmtId(argname) : "",
9435                                                   argname ? " " : "",
9436                                                   typname);
9437                 free(typname);
9438         }
9439         appendPQExpBuffer(&fn, ")");
9440         return fn.data;
9441 }
9442
9443 /*
9444  * format_function_signature: generate function name and argument list
9445  *
9446  * This is like format_function_arguments_old except that only a minimal
9447  * list of input argument types is generated; this is sufficient to
9448  * reference the function, but not to define it.
9449  *
9450  * If honor_quotes is false then the function name is never quoted.
9451  * This is appropriate for use in TOC tags, but not in SQL commands.
9452  */
9453 static char *
9454 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9455 {
9456         PQExpBufferData fn;
9457         int                     j;
9458
9459         initPQExpBuffer(&fn);
9460         if (honor_quotes)
9461                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9462         else
9463                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9464         for (j = 0; j < finfo->nargs; j++)
9465         {
9466                 char       *typname;
9467
9468                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9469                                                                            zeroAsOpaque);
9470
9471                 appendPQExpBuffer(&fn, "%s%s",
9472                                                   (j > 0) ? ", " : "",
9473                                                   typname);
9474                 free(typname);
9475         }
9476         appendPQExpBuffer(&fn, ")");
9477         return fn.data;
9478 }
9479
9480
9481 /*
9482  * dumpFunc:
9483  *        dump out one function
9484  */
9485 static void
9486 dumpFunc(Archive *fout, FuncInfo *finfo)
9487 {
9488         PQExpBuffer query;
9489         PQExpBuffer q;
9490         PQExpBuffer delqry;
9491         PQExpBuffer labelq;
9492         PQExpBuffer asPart;
9493         PGresult   *res;
9494         char       *funcsig;            /* identity signature */
9495         char       *funcfullsig;        /* full signature */
9496         char       *funcsig_tag;
9497         char       *proretset;
9498         char       *prosrc;
9499         char       *probin;
9500         char       *funcargs;
9501         char       *funciargs;
9502         char       *funcresult;
9503         char       *proallargtypes;
9504         char       *proargmodes;
9505         char       *proargnames;
9506         char       *proiswindow;
9507         char       *provolatile;
9508         char       *proisstrict;
9509         char       *prosecdef;
9510         char       *proleakproof;
9511         char       *proconfig;
9512         char       *procost;
9513         char       *prorows;
9514         char       *lanname;
9515         char       *rettypename;
9516         int                     nallargs;
9517         char      **allargtypes = NULL;
9518         char      **argmodes = NULL;
9519         char      **argnames = NULL;
9520         char      **configitems = NULL;
9521         int                     nconfigitems = 0;
9522         int                     i;
9523
9524         /* Skip if not to be dumped */
9525         if (!finfo->dobj.dump || dataOnly)
9526                 return;
9527
9528         query = createPQExpBuffer();
9529         q = createPQExpBuffer();
9530         delqry = createPQExpBuffer();
9531         labelq = createPQExpBuffer();
9532         asPart = createPQExpBuffer();
9533
9534         /* Set proper schema search path so type references list correctly */
9535         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9536
9537         /* Fetch function-specific details */
9538         if (fout->remoteVersion >= 90200)
9539         {
9540                 /*
9541                  * proleakproof was added at v9.2
9542                  */
9543                 appendPQExpBuffer(query,
9544                                                   "SELECT proretset, prosrc, probin, "
9545                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9546                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9547                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9548                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9549                                                   "proleakproof, proconfig, procost, prorows, "
9550                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9551                                                   "FROM pg_catalog.pg_proc "
9552                                                   "WHERE oid = '%u'::pg_catalog.oid",
9553                                                   finfo->dobj.catId.oid);
9554         }
9555         else if (fout->remoteVersion >= 80400)
9556         {
9557                 /*
9558                  * In 8.4 and up we rely on pg_get_function_arguments and
9559                  * pg_get_function_result instead of examining proallargtypes etc.
9560                  */
9561                 appendPQExpBuffer(query,
9562                                                   "SELECT proretset, prosrc, probin, "
9563                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9564                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9565                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9566                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9567                                                   "false AS proleakproof, "
9568                                                   " proconfig, procost, prorows, "
9569                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9570                                                   "FROM pg_catalog.pg_proc "
9571                                                   "WHERE oid = '%u'::pg_catalog.oid",
9572                                                   finfo->dobj.catId.oid);
9573         }
9574         else if (fout->remoteVersion >= 80300)
9575         {
9576                 appendPQExpBuffer(query,
9577                                                   "SELECT proretset, prosrc, probin, "
9578                                                   "proallargtypes, proargmodes, proargnames, "
9579                                                   "false AS proiswindow, "
9580                                                   "provolatile, proisstrict, prosecdef, "
9581                                                   "false AS proleakproof, "
9582                                                   "proconfig, procost, prorows, "
9583                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9584                                                   "FROM pg_catalog.pg_proc "
9585                                                   "WHERE oid = '%u'::pg_catalog.oid",
9586                                                   finfo->dobj.catId.oid);
9587         }
9588         else if (fout->remoteVersion >= 80100)
9589         {
9590                 appendPQExpBuffer(query,
9591                                                   "SELECT proretset, prosrc, probin, "
9592                                                   "proallargtypes, proargmodes, proargnames, "
9593                                                   "false AS proiswindow, "
9594                                                   "provolatile, proisstrict, prosecdef, "
9595                                                   "false AS proleakproof, "
9596                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9597                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9598                                                   "FROM pg_catalog.pg_proc "
9599                                                   "WHERE oid = '%u'::pg_catalog.oid",
9600                                                   finfo->dobj.catId.oid);
9601         }
9602         else if (fout->remoteVersion >= 80000)
9603         {
9604                 appendPQExpBuffer(query,
9605                                                   "SELECT proretset, prosrc, probin, "
9606                                                   "null AS proallargtypes, "
9607                                                   "null AS proargmodes, "
9608                                                   "proargnames, "
9609                                                   "false AS proiswindow, "
9610                                                   "provolatile, proisstrict, prosecdef, "
9611                                                   "false AS proleakproof, "
9612                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9613                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9614                                                   "FROM pg_catalog.pg_proc "
9615                                                   "WHERE oid = '%u'::pg_catalog.oid",
9616                                                   finfo->dobj.catId.oid);
9617         }
9618         else if (fout->remoteVersion >= 70300)
9619         {
9620                 appendPQExpBuffer(query,
9621                                                   "SELECT proretset, prosrc, probin, "
9622                                                   "null AS proallargtypes, "
9623                                                   "null AS proargmodes, "
9624                                                   "null AS proargnames, "
9625                                                   "false AS proiswindow, "
9626                                                   "provolatile, proisstrict, prosecdef, "
9627                                                   "false AS proleakproof, "
9628                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9629                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9630                                                   "FROM pg_catalog.pg_proc "
9631                                                   "WHERE oid = '%u'::pg_catalog.oid",
9632                                                   finfo->dobj.catId.oid);
9633         }
9634         else if (fout->remoteVersion >= 70100)
9635         {
9636                 appendPQExpBuffer(query,
9637                                                   "SELECT proretset, prosrc, probin, "
9638                                                   "null AS proallargtypes, "
9639                                                   "null AS proargmodes, "
9640                                                   "null AS proargnames, "
9641                                                   "false AS proiswindow, "
9642                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9643                                                   "proisstrict, "
9644                                                   "false AS prosecdef, "
9645                                                   "false AS proleakproof, "
9646                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9647                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9648                                                   "FROM pg_proc "
9649                                                   "WHERE oid = '%u'::oid",
9650                                                   finfo->dobj.catId.oid);
9651         }
9652         else
9653         {
9654                 appendPQExpBuffer(query,
9655                                                   "SELECT proretset, prosrc, probin, "
9656                                                   "null AS proallargtypes, "
9657                                                   "null AS proargmodes, "
9658                                                   "null AS proargnames, "
9659                                                   "false AS proiswindow, "
9660                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9661                                                   "false AS proisstrict, "
9662                                                   "false AS prosecdef, "
9663                                                   "false AS proleakproof, "
9664                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9665                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9666                                                   "FROM pg_proc "
9667                                                   "WHERE oid = '%u'::oid",
9668                                                   finfo->dobj.catId.oid);
9669         }
9670
9671         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9672
9673         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9674         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9675         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9676         if (fout->remoteVersion >= 80400)
9677         {
9678                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9679                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9680                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9681                 proallargtypes = proargmodes = proargnames = NULL;
9682         }
9683         else
9684         {
9685                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9686                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9687                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9688                 funcargs = funciargs = funcresult = NULL;
9689         }
9690         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9691         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9692         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9693         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9694         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9695         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9696         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9697         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9698         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9699
9700         /*
9701          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9702          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9703          * versions would set it to "-".  There are no known cases in which prosrc
9704          * is unused, so the tests below for "-" are probably useless.
9705          */
9706         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9707         {
9708                 appendPQExpBuffer(asPart, "AS ");
9709                 appendStringLiteralAH(asPart, probin, fout);
9710                 if (strcmp(prosrc, "-") != 0)
9711                 {
9712                         appendPQExpBuffer(asPart, ", ");
9713
9714                         /*
9715                          * where we have bin, use dollar quoting if allowed and src
9716                          * contains quote or backslash; else use regular quoting.
9717                          */
9718                         if (disable_dollar_quoting ||
9719                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9720                                 appendStringLiteralAH(asPart, prosrc, fout);
9721                         else
9722                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9723                 }
9724         }
9725         else
9726         {
9727                 if (strcmp(prosrc, "-") != 0)
9728                 {
9729                         appendPQExpBuffer(asPart, "AS ");
9730                         /* with no bin, dollar quote src unconditionally if allowed */
9731                         if (disable_dollar_quoting)
9732                                 appendStringLiteralAH(asPart, prosrc, fout);
9733                         else
9734                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9735                 }
9736         }
9737
9738         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9739
9740         if (proallargtypes && *proallargtypes)
9741         {
9742                 int                     nitems = 0;
9743
9744                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9745                         nitems < finfo->nargs)
9746                 {
9747                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9748                         if (allargtypes)
9749                                 free(allargtypes);
9750                         allargtypes = NULL;
9751                 }
9752                 else
9753                         nallargs = nitems;
9754         }
9755
9756         if (proargmodes && *proargmodes)
9757         {
9758                 int                     nitems = 0;
9759
9760                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9761                         nitems != nallargs)
9762                 {
9763                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9764                         if (argmodes)
9765                                 free(argmodes);
9766                         argmodes = NULL;
9767                 }
9768         }
9769
9770         if (proargnames && *proargnames)
9771         {
9772                 int                     nitems = 0;
9773
9774                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9775                         nitems != nallargs)
9776                 {
9777                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9778                         if (argnames)
9779                                 free(argnames);
9780                         argnames = NULL;
9781                 }
9782         }
9783
9784         if (proconfig && *proconfig)
9785         {
9786                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9787                 {
9788                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9789                         if (configitems)
9790                                 free(configitems);
9791                         configitems = NULL;
9792                         nconfigitems = 0;
9793                 }
9794         }
9795
9796         if (funcargs)
9797         {
9798                 /* 8.4 or later; we rely on server-side code for most of the work */
9799                 funcfullsig = format_function_arguments(finfo, funcargs);
9800                 funcsig = format_function_arguments(finfo, funciargs);
9801         }
9802         else
9803         {
9804                 /* pre-8.4, do it ourselves */
9805                 funcsig = format_function_arguments_old(fout,
9806                                                                                                 finfo, nallargs, allargtypes,
9807                                                                                                 argmodes, argnames);
9808                 funcfullsig = funcsig;
9809         }
9810
9811         funcsig_tag = format_function_signature(fout, finfo, false);
9812
9813         /*
9814          * DROP must be fully qualified in case same name appears in pg_catalog
9815          */
9816         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9817                                           fmtId(finfo->dobj.namespace->dobj.name),
9818                                           funcsig);
9819
9820         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9821         if (funcresult)
9822                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9823         else
9824         {
9825                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9826                                                                                    zeroAsOpaque);
9827                 appendPQExpBuffer(q, "RETURNS %s%s",
9828                                                   (proretset[0] == 't') ? "SETOF " : "",
9829                                                   rettypename);
9830                 free(rettypename);
9831         }
9832
9833         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9834
9835         if (proiswindow[0] == 't')
9836                 appendPQExpBuffer(q, " WINDOW");
9837
9838         if (provolatile[0] != PROVOLATILE_VOLATILE)
9839         {
9840                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9841                         appendPQExpBuffer(q, " IMMUTABLE");
9842                 else if (provolatile[0] == PROVOLATILE_STABLE)
9843                         appendPQExpBuffer(q, " STABLE");
9844                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9845                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9846                                                   finfo->dobj.name);
9847         }
9848
9849         if (proisstrict[0] == 't')
9850                 appendPQExpBuffer(q, " STRICT");
9851
9852         if (prosecdef[0] == 't')
9853                 appendPQExpBuffer(q, " SECURITY DEFINER");
9854
9855         if (proleakproof[0] == 't')
9856                 appendPQExpBuffer(q, " LEAKPROOF");
9857
9858         /*
9859          * COST and ROWS are emitted only if present and not default, so as not to
9860          * break backwards-compatibility of the dump without need.      Keep this code
9861          * in sync with the defaults in functioncmds.c.
9862          */
9863         if (strcmp(procost, "0") != 0)
9864         {
9865                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9866                 {
9867                         /* default cost is 1 */
9868                         if (strcmp(procost, "1") != 0)
9869                                 appendPQExpBuffer(q, " COST %s", procost);
9870                 }
9871                 else
9872                 {
9873                         /* default cost is 100 */
9874                         if (strcmp(procost, "100") != 0)
9875                                 appendPQExpBuffer(q, " COST %s", procost);
9876                 }
9877         }
9878         if (proretset[0] == 't' &&
9879                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9880                 appendPQExpBuffer(q, " ROWS %s", prorows);
9881
9882         for (i = 0; i < nconfigitems; i++)
9883         {
9884                 /* we feel free to scribble on configitems[] here */
9885                 char       *configitem = configitems[i];
9886                 char       *pos;
9887
9888                 pos = strchr(configitem, '=');
9889                 if (pos == NULL)
9890                         continue;
9891                 *pos++ = '\0';
9892                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9893
9894                 /*
9895                  * Some GUC variable names are 'LIST' type and hence must not be
9896                  * quoted.
9897                  */
9898                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9899                         || pg_strcasecmp(configitem, "search_path") == 0)
9900                         appendPQExpBuffer(q, "%s", pos);
9901                 else
9902                         appendStringLiteralAH(q, pos, fout);
9903         }
9904
9905         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9906
9907         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9908
9909         if (binary_upgrade)
9910                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9911
9912         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9913                                  funcsig_tag,
9914                                  finfo->dobj.namespace->dobj.name,
9915                                  NULL,
9916                                  finfo->rolname, false,
9917                                  "FUNCTION", SECTION_PRE_DATA,
9918                                  q->data, delqry->data, NULL,
9919                                  NULL, 0,
9920                                  NULL, NULL);
9921
9922         /* Dump Function Comments and Security Labels */
9923         dumpComment(fout, labelq->data,
9924                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9925                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9926         dumpSecLabel(fout, labelq->data,
9927                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9928                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9929
9930         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9931                         funcsig, NULL, funcsig_tag,
9932                         finfo->dobj.namespace->dobj.name,
9933                         finfo->rolname, finfo->proacl);
9934
9935         PQclear(res);
9936
9937         destroyPQExpBuffer(query);
9938         destroyPQExpBuffer(q);
9939         destroyPQExpBuffer(delqry);
9940         destroyPQExpBuffer(labelq);
9941         destroyPQExpBuffer(asPart);
9942         free(funcsig);
9943         free(funcsig_tag);
9944         if (allargtypes)
9945                 free(allargtypes);
9946         if (argmodes)
9947                 free(argmodes);
9948         if (argnames)
9949                 free(argnames);
9950         if (configitems)
9951                 free(configitems);
9952 }
9953
9954
9955 /*
9956  * Dump a user-defined cast
9957  */
9958 static void
9959 dumpCast(Archive *fout, CastInfo *cast)
9960 {
9961         PQExpBuffer defqry;
9962         PQExpBuffer delqry;
9963         PQExpBuffer labelq;
9964         FuncInfo   *funcInfo = NULL;
9965
9966         /* Skip if not to be dumped */
9967         if (!cast->dobj.dump || dataOnly)
9968                 return;
9969
9970         /* Cannot dump if we don't have the cast function's info */
9971         if (OidIsValid(cast->castfunc))
9972         {
9973                 funcInfo = findFuncByOid(cast->castfunc);
9974                 if (funcInfo == NULL)
9975                         return;
9976         }
9977
9978         /*
9979          * As per discussion we dump casts if one or more of the underlying
9980          * objects (the conversion function and the two data types) are not
9981          * builtin AND if all of the non-builtin objects are included in the dump.
9982          * Builtin meaning, the namespace name does not start with "pg_".
9983          *
9984          * However, for a cast that belongs to an extension, we must not use this
9985          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9986          */
9987         if (!cast->dobj.ext_member)
9988         {
9989                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9990                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9991
9992                 if (sourceInfo == NULL || targetInfo == NULL)
9993                         return;
9994
9995                 /*
9996                  * Skip this cast if all objects are from pg_
9997                  */
9998                 if ((funcInfo == NULL ||
9999                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
10000                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
10001                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
10002                         return;
10003
10004                 /*
10005                  * Skip cast if function isn't from pg_ and is not to be dumped.
10006                  */
10007                 if (funcInfo &&
10008                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10009                         !funcInfo->dobj.dump)
10010                         return;
10011
10012                 /*
10013                  * Same for the source type
10014                  */
10015                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10016                         !sourceInfo->dobj.dump)
10017                         return;
10018
10019                 /*
10020                  * and the target type.
10021                  */
10022                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10023                         !targetInfo->dobj.dump)
10024                         return;
10025         }
10026
10027         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
10028         selectSourceSchema(fout, "pg_catalog");
10029
10030         defqry = createPQExpBuffer();
10031         delqry = createPQExpBuffer();
10032         labelq = createPQExpBuffer();
10033
10034         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
10035                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10036                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10037
10038         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
10039                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10040                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10041
10042         switch (cast->castmethod)
10043         {
10044                 case COERCION_METHOD_BINARY:
10045                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
10046                         break;
10047                 case COERCION_METHOD_INOUT:
10048                         appendPQExpBuffer(defqry, "WITH INOUT");
10049                         break;
10050                 case COERCION_METHOD_FUNCTION:
10051                         if (funcInfo)
10052                         {
10053                                 char       *fsig = format_function_signature(fout, funcInfo, true);
10054
10055                                 /*
10056                                  * Always qualify the function name, in case it is not in
10057                                  * pg_catalog schema (format_function_signature won't qualify
10058                                  * it).
10059                                  */
10060                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
10061                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
10062                                 free(fsig);
10063                         }
10064                         else
10065                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
10066                         break;
10067                 default:
10068                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
10069         }
10070
10071         if (cast->castcontext == 'a')
10072                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
10073         else if (cast->castcontext == 'i')
10074                 appendPQExpBuffer(defqry, " AS IMPLICIT");
10075         appendPQExpBuffer(defqry, ";\n");
10076
10077         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
10078                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10079                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10080
10081         if (binary_upgrade)
10082                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
10083
10084         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
10085                                  labelq->data,
10086                                  "pg_catalog", NULL, "",
10087                                  false, "CAST", SECTION_PRE_DATA,
10088                                  defqry->data, delqry->data, NULL,
10089                                  NULL, 0,
10090                                  NULL, NULL);
10091
10092         /* Dump Cast Comments */
10093         dumpComment(fout, labelq->data,
10094                                 NULL, "",
10095                                 cast->dobj.catId, 0, cast->dobj.dumpId);
10096
10097         destroyPQExpBuffer(defqry);
10098         destroyPQExpBuffer(delqry);
10099         destroyPQExpBuffer(labelq);
10100 }
10101
10102 /*
10103  * dumpOpr
10104  *        write out a single operator definition
10105  */
10106 static void
10107 dumpOpr(Archive *fout, OprInfo *oprinfo)
10108 {
10109         PQExpBuffer query;
10110         PQExpBuffer q;
10111         PQExpBuffer delq;
10112         PQExpBuffer labelq;
10113         PQExpBuffer oprid;
10114         PQExpBuffer details;
10115         const char *name;
10116         PGresult   *res;
10117         int                     i_oprkind;
10118         int                     i_oprcode;
10119         int                     i_oprleft;
10120         int                     i_oprright;
10121         int                     i_oprcom;
10122         int                     i_oprnegate;
10123         int                     i_oprrest;
10124         int                     i_oprjoin;
10125         int                     i_oprcanmerge;
10126         int                     i_oprcanhash;
10127         char       *oprkind;
10128         char       *oprcode;
10129         char       *oprleft;
10130         char       *oprright;
10131         char       *oprcom;
10132         char       *oprnegate;
10133         char       *oprrest;
10134         char       *oprjoin;
10135         char       *oprcanmerge;
10136         char       *oprcanhash;
10137
10138         /* Skip if not to be dumped */
10139         if (!oprinfo->dobj.dump || dataOnly)
10140                 return;
10141
10142         /*
10143          * some operators are invalid because they were the result of user
10144          * defining operators before commutators exist
10145          */
10146         if (!OidIsValid(oprinfo->oprcode))
10147                 return;
10148
10149         query = createPQExpBuffer();
10150         q = createPQExpBuffer();
10151         delq = createPQExpBuffer();
10152         labelq = createPQExpBuffer();
10153         oprid = createPQExpBuffer();
10154         details = createPQExpBuffer();
10155
10156         /* Make sure we are in proper schema so regoperator works correctly */
10157         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
10158
10159         if (fout->remoteVersion >= 80300)
10160         {
10161                 appendPQExpBuffer(query, "SELECT oprkind, "
10162                                                   "oprcode::pg_catalog.regprocedure, "
10163                                                   "oprleft::pg_catalog.regtype, "
10164                                                   "oprright::pg_catalog.regtype, "
10165                                                   "oprcom::pg_catalog.regoperator, "
10166                                                   "oprnegate::pg_catalog.regoperator, "
10167                                                   "oprrest::pg_catalog.regprocedure, "
10168                                                   "oprjoin::pg_catalog.regprocedure, "
10169                                                   "oprcanmerge, oprcanhash "
10170                                                   "FROM pg_catalog.pg_operator "
10171                                                   "WHERE oid = '%u'::pg_catalog.oid",
10172                                                   oprinfo->dobj.catId.oid);
10173         }
10174         else if (fout->remoteVersion >= 70300)
10175         {
10176                 appendPQExpBuffer(query, "SELECT oprkind, "
10177                                                   "oprcode::pg_catalog.regprocedure, "
10178                                                   "oprleft::pg_catalog.regtype, "
10179                                                   "oprright::pg_catalog.regtype, "
10180                                                   "oprcom::pg_catalog.regoperator, "
10181                                                   "oprnegate::pg_catalog.regoperator, "
10182                                                   "oprrest::pg_catalog.regprocedure, "
10183                                                   "oprjoin::pg_catalog.regprocedure, "
10184                                                   "(oprlsortop != 0) AS oprcanmerge, "
10185                                                   "oprcanhash "
10186                                                   "FROM pg_catalog.pg_operator "
10187                                                   "WHERE oid = '%u'::pg_catalog.oid",
10188                                                   oprinfo->dobj.catId.oid);
10189         }
10190         else if (fout->remoteVersion >= 70100)
10191         {
10192                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10193                                                   "CASE WHEN oprleft = 0 THEN '-' "
10194                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
10195                                                   "CASE WHEN oprright = 0 THEN '-' "
10196                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
10197                                                   "oprcom, oprnegate, oprrest, oprjoin, "
10198                                                   "(oprlsortop != 0) AS oprcanmerge, "
10199                                                   "oprcanhash "
10200                                                   "FROM pg_operator "
10201                                                   "WHERE oid = '%u'::oid",
10202                                                   oprinfo->dobj.catId.oid);
10203         }
10204         else
10205         {
10206                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10207                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
10208                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
10209                                                   "CASE WHEN oprright = 0 THEN '-'::name "
10210                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
10211                                                   "oprcom, oprnegate, oprrest, oprjoin, "
10212                                                   "(oprlsortop != 0) AS oprcanmerge, "
10213                                                   "oprcanhash "
10214                                                   "FROM pg_operator "
10215                                                   "WHERE oid = '%u'::oid",
10216                                                   oprinfo->dobj.catId.oid);
10217         }
10218
10219         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10220
10221         i_oprkind = PQfnumber(res, "oprkind");
10222         i_oprcode = PQfnumber(res, "oprcode");
10223         i_oprleft = PQfnumber(res, "oprleft");
10224         i_oprright = PQfnumber(res, "oprright");
10225         i_oprcom = PQfnumber(res, "oprcom");
10226         i_oprnegate = PQfnumber(res, "oprnegate");
10227         i_oprrest = PQfnumber(res, "oprrest");
10228         i_oprjoin = PQfnumber(res, "oprjoin");
10229         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
10230         i_oprcanhash = PQfnumber(res, "oprcanhash");
10231
10232         oprkind = PQgetvalue(res, 0, i_oprkind);
10233         oprcode = PQgetvalue(res, 0, i_oprcode);
10234         oprleft = PQgetvalue(res, 0, i_oprleft);
10235         oprright = PQgetvalue(res, 0, i_oprright);
10236         oprcom = PQgetvalue(res, 0, i_oprcom);
10237         oprnegate = PQgetvalue(res, 0, i_oprnegate);
10238         oprrest = PQgetvalue(res, 0, i_oprrest);
10239         oprjoin = PQgetvalue(res, 0, i_oprjoin);
10240         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
10241         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
10242
10243         appendPQExpBuffer(details, "    PROCEDURE = %s",
10244                                           convertRegProcReference(fout, oprcode));
10245
10246         appendPQExpBuffer(oprid, "%s (",
10247                                           oprinfo->dobj.name);
10248
10249         /*
10250          * right unary means there's a left arg and left unary means there's a
10251          * right arg
10252          */
10253         if (strcmp(oprkind, "r") == 0 ||
10254                 strcmp(oprkind, "b") == 0)
10255         {
10256                 if (fout->remoteVersion >= 70100)
10257                         name = oprleft;
10258                 else
10259                         name = fmtId(oprleft);
10260                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
10261                 appendPQExpBuffer(oprid, "%s", name);
10262         }
10263         else
10264                 appendPQExpBuffer(oprid, "NONE");
10265
10266         if (strcmp(oprkind, "l") == 0 ||
10267                 strcmp(oprkind, "b") == 0)
10268         {
10269                 if (fout->remoteVersion >= 70100)
10270                         name = oprright;
10271                 else
10272                         name = fmtId(oprright);
10273                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
10274                 appendPQExpBuffer(oprid, ", %s)", name);
10275         }
10276         else
10277                 appendPQExpBuffer(oprid, ", NONE)");
10278
10279         name = convertOperatorReference(fout, oprcom);
10280         if (name)
10281                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
10282
10283         name = convertOperatorReference(fout, oprnegate);
10284         if (name)
10285                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
10286
10287         if (strcmp(oprcanmerge, "t") == 0)
10288                 appendPQExpBuffer(details, ",\n    MERGES");
10289
10290         if (strcmp(oprcanhash, "t") == 0)
10291                 appendPQExpBuffer(details, ",\n    HASHES");
10292
10293         name = convertRegProcReference(fout, oprrest);
10294         if (name)
10295                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
10296
10297         name = convertRegProcReference(fout, oprjoin);
10298         if (name)
10299                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
10300
10301         /*
10302          * DROP must be fully qualified in case same name appears in pg_catalog
10303          */
10304         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
10305                                           fmtId(oprinfo->dobj.namespace->dobj.name),
10306                                           oprid->data);
10307
10308         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
10309                                           oprinfo->dobj.name, details->data);
10310
10311         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
10312
10313         if (binary_upgrade)
10314                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
10315
10316         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
10317                                  oprinfo->dobj.name,
10318                                  oprinfo->dobj.namespace->dobj.name,
10319                                  NULL,
10320                                  oprinfo->rolname,
10321                                  false, "OPERATOR", SECTION_PRE_DATA,
10322                                  q->data, delq->data, NULL,
10323                                  NULL, 0,
10324                                  NULL, NULL);
10325
10326         /* Dump Operator Comments */
10327         dumpComment(fout, labelq->data,
10328                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
10329                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
10330
10331         PQclear(res);
10332
10333         destroyPQExpBuffer(query);
10334         destroyPQExpBuffer(q);
10335         destroyPQExpBuffer(delq);
10336         destroyPQExpBuffer(labelq);
10337         destroyPQExpBuffer(oprid);
10338         destroyPQExpBuffer(details);
10339 }
10340
10341 /*
10342  * Convert a function reference obtained from pg_operator
10343  *
10344  * Returns what to print, or NULL if function references is InvalidOid
10345  *
10346  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
10347  * argument-types part.  In prior versions, the input is a REGPROC display.
10348  */
10349 static const char *
10350 convertRegProcReference(Archive *fout, const char *proc)
10351 {
10352         /* In all cases "-" means a null reference */
10353         if (strcmp(proc, "-") == 0)
10354                 return NULL;
10355
10356         if (fout->remoteVersion >= 70300)
10357         {
10358                 char       *name;
10359                 char       *paren;
10360                 bool            inquote;
10361
10362                 name = pg_strdup(proc);
10363                 /* find non-double-quoted left paren */
10364                 inquote = false;
10365                 for (paren = name; *paren; paren++)
10366                 {
10367                         if (*paren == '(' && !inquote)
10368                         {
10369                                 *paren = '\0';
10370                                 break;
10371                         }
10372                         if (*paren == '"')
10373                                 inquote = !inquote;
10374                 }
10375                 return name;
10376         }
10377
10378         /* REGPROC before 7.3 does not quote its result */
10379         return fmtId(proc);
10380 }
10381
10382 /*
10383  * Convert an operator cross-reference obtained from pg_operator
10384  *
10385  * Returns what to print, or NULL to print nothing
10386  *
10387  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10388  * argument-types part, and add OPERATOR() decoration if the name is
10389  * schema-qualified.  In older versions, the input is just a numeric OID,
10390  * which we search our operator list for.
10391  */
10392 static const char *
10393 convertOperatorReference(Archive *fout, const char *opr)
10394 {
10395         OprInfo    *oprInfo;
10396
10397         /* In all cases "0" means a null reference */
10398         if (strcmp(opr, "0") == 0)
10399                 return NULL;
10400
10401         if (fout->remoteVersion >= 70300)
10402         {
10403                 char       *name;
10404                 char       *oname;
10405                 char       *ptr;
10406                 bool            inquote;
10407                 bool            sawdot;
10408
10409                 name = pg_strdup(opr);
10410                 /* find non-double-quoted left paren, and check for non-quoted dot */
10411                 inquote = false;
10412                 sawdot = false;
10413                 for (ptr = name; *ptr; ptr++)
10414                 {
10415                         if (*ptr == '"')
10416                                 inquote = !inquote;
10417                         else if (*ptr == '.' && !inquote)
10418                                 sawdot = true;
10419                         else if (*ptr == '(' && !inquote)
10420                         {
10421                                 *ptr = '\0';
10422                                 break;
10423                         }
10424                 }
10425                 /* If not schema-qualified, don't need to add OPERATOR() */
10426                 if (!sawdot)
10427                         return name;
10428                 oname = pg_malloc(strlen(name) + 11);
10429                 sprintf(oname, "OPERATOR(%s)", name);
10430                 free(name);
10431                 return oname;
10432         }
10433
10434         oprInfo = findOprByOid(atooid(opr));
10435         if (oprInfo == NULL)
10436         {
10437                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10438                                   opr);
10439                 return NULL;
10440         }
10441         return oprInfo->dobj.name;
10442 }
10443
10444 /*
10445  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10446  *
10447  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10448  * argument lists of these functions are predetermined.  Note that the
10449  * caller should ensure we are in the proper schema, because the results
10450  * are search path dependent!
10451  */
10452 static const char *
10453 convertTSFunction(Archive *fout, Oid funcOid)
10454 {
10455         char       *result;
10456         char            query[128];
10457         PGresult   *res;
10458
10459         snprintf(query, sizeof(query),
10460                          "SELECT '%u'::pg_catalog.regproc", funcOid);
10461         res = ExecuteSqlQueryForSingleRow(fout, query);
10462
10463         result = pg_strdup(PQgetvalue(res, 0, 0));
10464
10465         PQclear(res);
10466
10467         return result;
10468 }
10469
10470
10471 /*
10472  * dumpOpclass
10473  *        write out a single operator class definition
10474  */
10475 static void
10476 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10477 {
10478         PQExpBuffer query;
10479         PQExpBuffer q;
10480         PQExpBuffer delq;
10481         PQExpBuffer labelq;
10482         PGresult   *res;
10483         int                     ntups;
10484         int                     i_opcintype;
10485         int                     i_opckeytype;
10486         int                     i_opcdefault;
10487         int                     i_opcfamily;
10488         int                     i_opcfamilyname;
10489         int                     i_opcfamilynsp;
10490         int                     i_amname;
10491         int                     i_amopstrategy;
10492         int                     i_amopreqcheck;
10493         int                     i_amopopr;
10494         int                     i_sortfamily;
10495         int                     i_sortfamilynsp;
10496         int                     i_amprocnum;
10497         int                     i_amproc;
10498         int                     i_amproclefttype;
10499         int                     i_amprocrighttype;
10500         char       *opcintype;
10501         char       *opckeytype;
10502         char       *opcdefault;
10503         char       *opcfamily;
10504         char       *opcfamilyname;
10505         char       *opcfamilynsp;
10506         char       *amname;
10507         char       *amopstrategy;
10508         char       *amopreqcheck;
10509         char       *amopopr;
10510         char       *sortfamily;
10511         char       *sortfamilynsp;
10512         char       *amprocnum;
10513         char       *amproc;
10514         char       *amproclefttype;
10515         char       *amprocrighttype;
10516         bool            needComma;
10517         int                     i;
10518
10519         /* Skip if not to be dumped */
10520         if (!opcinfo->dobj.dump || dataOnly)
10521                 return;
10522
10523         /*
10524          * XXX currently we do not implement dumping of operator classes from
10525          * pre-7.3 databases.  This could be done but it seems not worth the
10526          * trouble.
10527          */
10528         if (fout->remoteVersion < 70300)
10529                 return;
10530
10531         query = createPQExpBuffer();
10532         q = createPQExpBuffer();
10533         delq = createPQExpBuffer();
10534         labelq = createPQExpBuffer();
10535
10536         /* Make sure we are in proper schema so regoperator works correctly */
10537         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10538
10539         /* Get additional fields from the pg_opclass row */
10540         if (fout->remoteVersion >= 80300)
10541         {
10542                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10543                                                   "opckeytype::pg_catalog.regtype, "
10544                                                   "opcdefault, opcfamily, "
10545                                                   "opfname AS opcfamilyname, "
10546                                                   "nspname AS opcfamilynsp, "
10547                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10548                                                   "FROM pg_catalog.pg_opclass c "
10549                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10550                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10551                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
10552                                                   opcinfo->dobj.catId.oid);
10553         }
10554         else
10555         {
10556                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10557                                                   "opckeytype::pg_catalog.regtype, "
10558                                                   "opcdefault, NULL AS opcfamily, "
10559                                                   "NULL AS opcfamilyname, "
10560                                                   "NULL AS opcfamilynsp, "
10561                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10562                                                   "FROM pg_catalog.pg_opclass "
10563                                                   "WHERE oid = '%u'::pg_catalog.oid",
10564                                                   opcinfo->dobj.catId.oid);
10565         }
10566
10567         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10568
10569         i_opcintype = PQfnumber(res, "opcintype");
10570         i_opckeytype = PQfnumber(res, "opckeytype");
10571         i_opcdefault = PQfnumber(res, "opcdefault");
10572         i_opcfamily = PQfnumber(res, "opcfamily");
10573         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10574         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10575         i_amname = PQfnumber(res, "amname");
10576
10577         opcintype = PQgetvalue(res, 0, i_opcintype);
10578         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10579         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10580         /* opcfamily will still be needed after we PQclear res */
10581         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10582         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10583         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10584         /* amname will still be needed after we PQclear res */
10585         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10586
10587         /*
10588          * DROP must be fully qualified in case same name appears in pg_catalog
10589          */
10590         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10591                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10592         appendPQExpBuffer(delq, ".%s",
10593                                           fmtId(opcinfo->dobj.name));
10594         appendPQExpBuffer(delq, " USING %s;\n",
10595                                           fmtId(amname));
10596
10597         /* Build the fixed portion of the CREATE command */
10598         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10599                                           fmtId(opcinfo->dobj.name));
10600         if (strcmp(opcdefault, "t") == 0)
10601                 appendPQExpBuffer(q, "DEFAULT ");
10602         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10603                                           opcintype,
10604                                           fmtId(amname));
10605         if (strlen(opcfamilyname) > 0 &&
10606                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10607                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10608         {
10609                 appendPQExpBuffer(q, " FAMILY ");
10610                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10611                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10612                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10613         }
10614         appendPQExpBuffer(q, " AS\n    ");
10615
10616         needComma = false;
10617
10618         if (strcmp(opckeytype, "-") != 0)
10619         {
10620                 appendPQExpBuffer(q, "STORAGE %s",
10621                                                   opckeytype);
10622                 needComma = true;
10623         }
10624
10625         PQclear(res);
10626
10627         /*
10628          * Now fetch and print the OPERATOR entries (pg_amop rows).
10629          *
10630          * Print only those opfamily members that are tied to the opclass by
10631          * pg_depend entries.
10632          *
10633          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10634          * older server's opclass in which it is used.  This is to avoid
10635          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10636          * older server and then reload into that old version.  This can go away
10637          * once 8.3 is so old as to not be of interest to anyone.
10638          */
10639         resetPQExpBuffer(query);
10640
10641         if (fout->remoteVersion >= 90100)
10642         {
10643                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10644                                                   "amopopr::pg_catalog.regoperator, "
10645                                                   "opfname AS sortfamily, "
10646                                                   "nspname AS sortfamilynsp "
10647                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10648                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10649                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10650                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10651                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10652                                                   "AND refobjid = '%u'::pg_catalog.oid "
10653                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10654                                                   "ORDER BY amopstrategy",
10655                                                   opcinfo->dobj.catId.oid,
10656                                                   opcfamily);
10657         }
10658         else if (fout->remoteVersion >= 80400)
10659         {
10660                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10661                                                   "amopopr::pg_catalog.regoperator, "
10662                                                   "NULL AS sortfamily, "
10663                                                   "NULL AS sortfamilynsp "
10664                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10665                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10666                                                   "AND refobjid = '%u'::pg_catalog.oid "
10667                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10668                                                   "AND objid = ao.oid "
10669                                                   "ORDER BY amopstrategy",
10670                                                   opcinfo->dobj.catId.oid);
10671         }
10672         else if (fout->remoteVersion >= 80300)
10673         {
10674                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10675                                                   "amopopr::pg_catalog.regoperator, "
10676                                                   "NULL AS sortfamily, "
10677                                                   "NULL AS sortfamilynsp "
10678                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10679                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10680                                                   "AND refobjid = '%u'::pg_catalog.oid "
10681                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10682                                                   "AND objid = ao.oid "
10683                                                   "ORDER BY amopstrategy",
10684                                                   opcinfo->dobj.catId.oid);
10685         }
10686         else
10687         {
10688                 /*
10689                  * Here, we print all entries since there are no opfamilies and hence
10690                  * no loose operators to worry about.
10691                  */
10692                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10693                                                   "amopopr::pg_catalog.regoperator, "
10694                                                   "NULL AS sortfamily, "
10695                                                   "NULL AS sortfamilynsp "
10696                                                   "FROM pg_catalog.pg_amop "
10697                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10698                                                   "ORDER BY amopstrategy",
10699                                                   opcinfo->dobj.catId.oid);
10700         }
10701
10702         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10703
10704         ntups = PQntuples(res);
10705
10706         i_amopstrategy = PQfnumber(res, "amopstrategy");
10707         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10708         i_amopopr = PQfnumber(res, "amopopr");
10709         i_sortfamily = PQfnumber(res, "sortfamily");
10710         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10711
10712         for (i = 0; i < ntups; i++)
10713         {
10714                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10715                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10716                 amopopr = PQgetvalue(res, i, i_amopopr);
10717                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10718                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10719
10720                 if (needComma)
10721                         appendPQExpBuffer(q, " ,\n    ");
10722
10723                 appendPQExpBuffer(q, "OPERATOR %s %s",
10724                                                   amopstrategy, amopopr);
10725
10726                 if (strlen(sortfamily) > 0)
10727                 {
10728                         appendPQExpBuffer(q, " FOR ORDER BY ");
10729                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10730                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10731                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10732                 }
10733
10734                 if (strcmp(amopreqcheck, "t") == 0)
10735                         appendPQExpBuffer(q, " RECHECK");
10736
10737                 needComma = true;
10738         }
10739
10740         PQclear(res);
10741
10742         /*
10743          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10744          *
10745          * Print only those opfamily members that are tied to the opclass by
10746          * pg_depend entries.
10747          *
10748          * We print the amproclefttype/amprocrighttype even though in most cases
10749          * the backend could deduce the right values, because of the corner case
10750          * of a btree sort support function for a cross-type comparison.  That's
10751          * only allowed in 9.2 and later, but for simplicity print them in all
10752          * versions that have the columns.
10753          */
10754         resetPQExpBuffer(query);
10755
10756         if (fout->remoteVersion >= 80300)
10757         {
10758                 appendPQExpBuffer(query, "SELECT amprocnum, "
10759                                                   "amproc::pg_catalog.regprocedure, "
10760                                                   "amproclefttype::pg_catalog.regtype, "
10761                                                   "amprocrighttype::pg_catalog.regtype "
10762                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10763                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10764                                                   "AND refobjid = '%u'::pg_catalog.oid "
10765                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10766                                                   "AND objid = ap.oid "
10767                                                   "ORDER BY amprocnum",
10768                                                   opcinfo->dobj.catId.oid);
10769         }
10770         else
10771         {
10772                 appendPQExpBuffer(query, "SELECT amprocnum, "
10773                                                   "amproc::pg_catalog.regprocedure, "
10774                                                   "'' AS amproclefttype, "
10775                                                   "'' AS amprocrighttype "
10776                                                   "FROM pg_catalog.pg_amproc "
10777                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10778                                                   "ORDER BY amprocnum",
10779                                                   opcinfo->dobj.catId.oid);
10780         }
10781
10782         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10783
10784         ntups = PQntuples(res);
10785
10786         i_amprocnum = PQfnumber(res, "amprocnum");
10787         i_amproc = PQfnumber(res, "amproc");
10788         i_amproclefttype = PQfnumber(res, "amproclefttype");
10789         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10790
10791         for (i = 0; i < ntups; i++)
10792         {
10793                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10794                 amproc = PQgetvalue(res, i, i_amproc);
10795                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10796                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10797
10798                 if (needComma)
10799                         appendPQExpBuffer(q, " ,\n    ");
10800
10801                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10802
10803                 if (*amproclefttype && *amprocrighttype)
10804                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10805
10806                 appendPQExpBuffer(q, " %s", amproc);
10807
10808                 needComma = true;
10809         }
10810
10811         PQclear(res);
10812
10813         appendPQExpBuffer(q, ";\n");
10814
10815         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10816                                           fmtId(opcinfo->dobj.name));
10817         appendPQExpBuffer(labelq, " USING %s",
10818                                           fmtId(amname));
10819
10820         if (binary_upgrade)
10821                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10822
10823         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10824                                  opcinfo->dobj.name,
10825                                  opcinfo->dobj.namespace->dobj.name,
10826                                  NULL,
10827                                  opcinfo->rolname,
10828                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10829                                  q->data, delq->data, NULL,
10830                                  NULL, 0,
10831                                  NULL, NULL);
10832
10833         /* Dump Operator Class Comments */
10834         dumpComment(fout, labelq->data,
10835                                 NULL, opcinfo->rolname,
10836                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10837
10838         free(amname);
10839         destroyPQExpBuffer(query);
10840         destroyPQExpBuffer(q);
10841         destroyPQExpBuffer(delq);
10842         destroyPQExpBuffer(labelq);
10843 }
10844
10845 /*
10846  * dumpOpfamily
10847  *        write out a single operator family definition
10848  *
10849  * Note: this also dumps any "loose" operator members that aren't bound to a
10850  * specific opclass within the opfamily.
10851  */
10852 static void
10853 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10854 {
10855         PQExpBuffer query;
10856         PQExpBuffer q;
10857         PQExpBuffer delq;
10858         PQExpBuffer labelq;
10859         PGresult   *res;
10860         PGresult   *res_ops;
10861         PGresult   *res_procs;
10862         int                     ntups;
10863         int                     i_amname;
10864         int                     i_amopstrategy;
10865         int                     i_amopreqcheck;
10866         int                     i_amopopr;
10867         int                     i_sortfamily;
10868         int                     i_sortfamilynsp;
10869         int                     i_amprocnum;
10870         int                     i_amproc;
10871         int                     i_amproclefttype;
10872         int                     i_amprocrighttype;
10873         char       *amname;
10874         char       *amopstrategy;
10875         char       *amopreqcheck;
10876         char       *amopopr;
10877         char       *sortfamily;
10878         char       *sortfamilynsp;
10879         char       *amprocnum;
10880         char       *amproc;
10881         char       *amproclefttype;
10882         char       *amprocrighttype;
10883         bool            needComma;
10884         int                     i;
10885
10886         /* Skip if not to be dumped */
10887         if (!opfinfo->dobj.dump || dataOnly)
10888                 return;
10889
10890         /*
10891          * We want to dump the opfamily only if (1) it contains "loose" operators
10892          * or functions, or (2) it contains an opclass with a different name or
10893          * owner.  Otherwise it's sufficient to let it be created during creation
10894          * of the contained opclass, and not dumping it improves portability of
10895          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10896          * that first.
10897          */
10898
10899         query = createPQExpBuffer();
10900         q = createPQExpBuffer();
10901         delq = createPQExpBuffer();
10902         labelq = createPQExpBuffer();
10903
10904         /* Make sure we are in proper schema so regoperator works correctly */
10905         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10906
10907         /*
10908          * Fetch only those opfamily members that are tied directly to the
10909          * opfamily by pg_depend entries.
10910          *
10911          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10912          * older server's opclass in which it is used.  This is to avoid
10913          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10914          * older server and then reload into that old version.  This can go away
10915          * once 8.3 is so old as to not be of interest to anyone.
10916          */
10917         if (fout->remoteVersion >= 90100)
10918         {
10919                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10920                                                   "amopopr::pg_catalog.regoperator, "
10921                                                   "opfname AS sortfamily, "
10922                                                   "nspname AS sortfamilynsp "
10923                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10924                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10925                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10926                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10927                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10928                                                   "AND refobjid = '%u'::pg_catalog.oid "
10929                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10930                                                   "ORDER BY amopstrategy",
10931                                                   opfinfo->dobj.catId.oid,
10932                                                   opfinfo->dobj.catId.oid);
10933         }
10934         else if (fout->remoteVersion >= 80400)
10935         {
10936                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10937                                                   "amopopr::pg_catalog.regoperator, "
10938                                                   "NULL AS sortfamily, "
10939                                                   "NULL AS sortfamilynsp "
10940                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10941                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10942                                                   "AND refobjid = '%u'::pg_catalog.oid "
10943                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10944                                                   "AND objid = ao.oid "
10945                                                   "ORDER BY amopstrategy",
10946                                                   opfinfo->dobj.catId.oid);
10947         }
10948         else
10949         {
10950                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10951                                                   "amopopr::pg_catalog.regoperator, "
10952                                                   "NULL AS sortfamily, "
10953                                                   "NULL AS sortfamilynsp "
10954                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10955                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10956                                                   "AND refobjid = '%u'::pg_catalog.oid "
10957                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10958                                                   "AND objid = ao.oid "
10959                                                   "ORDER BY amopstrategy",
10960                                                   opfinfo->dobj.catId.oid);
10961         }
10962
10963         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10964
10965         resetPQExpBuffer(query);
10966
10967         appendPQExpBuffer(query, "SELECT amprocnum, "
10968                                           "amproc::pg_catalog.regprocedure, "
10969                                           "amproclefttype::pg_catalog.regtype, "
10970                                           "amprocrighttype::pg_catalog.regtype "
10971                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10972                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10973                                           "AND refobjid = '%u'::pg_catalog.oid "
10974                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10975                                           "AND objid = ap.oid "
10976                                           "ORDER BY amprocnum",
10977                                           opfinfo->dobj.catId.oid);
10978
10979         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10980
10981         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10982         {
10983                 /* No loose members, so check contained opclasses */
10984                 resetPQExpBuffer(query);
10985
10986                 appendPQExpBuffer(query, "SELECT 1 "
10987                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10988                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10989                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10990                                                   "AND refobjid = f.oid "
10991                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10992                                                   "AND objid = c.oid "
10993                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10994                                                   "LIMIT 1",
10995                                                   opfinfo->dobj.catId.oid);
10996
10997                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10998
10999                 if (PQntuples(res) == 0)
11000                 {
11001                         /* no need to dump it, so bail out */
11002                         PQclear(res);
11003                         PQclear(res_ops);
11004                         PQclear(res_procs);
11005                         destroyPQExpBuffer(query);
11006                         destroyPQExpBuffer(q);
11007                         destroyPQExpBuffer(delq);
11008                         destroyPQExpBuffer(labelq);
11009                         return;
11010                 }
11011
11012                 PQclear(res);
11013         }
11014
11015         /* Get additional fields from the pg_opfamily row */
11016         resetPQExpBuffer(query);
11017
11018         appendPQExpBuffer(query, "SELECT "
11019          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
11020                                           "FROM pg_catalog.pg_opfamily "
11021                                           "WHERE oid = '%u'::pg_catalog.oid",
11022                                           opfinfo->dobj.catId.oid);
11023
11024         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11025
11026         i_amname = PQfnumber(res, "amname");
11027
11028         /* amname will still be needed after we PQclear res */
11029         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
11030
11031         /*
11032          * DROP must be fully qualified in case same name appears in pg_catalog
11033          */
11034         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
11035                                           fmtId(opfinfo->dobj.namespace->dobj.name));
11036         appendPQExpBuffer(delq, ".%s",
11037                                           fmtId(opfinfo->dobj.name));
11038         appendPQExpBuffer(delq, " USING %s;\n",
11039                                           fmtId(amname));
11040
11041         /* Build the fixed portion of the CREATE command */
11042         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
11043                                           fmtId(opfinfo->dobj.name));
11044         appendPQExpBuffer(q, " USING %s;\n",
11045                                           fmtId(amname));
11046
11047         PQclear(res);
11048
11049         /* Do we need an ALTER to add loose members? */
11050         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
11051         {
11052                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
11053                                                   fmtId(opfinfo->dobj.name));
11054                 appendPQExpBuffer(q, " USING %s ADD\n    ",
11055                                                   fmtId(amname));
11056
11057                 needComma = false;
11058
11059                 /*
11060                  * Now fetch and print the OPERATOR entries (pg_amop rows).
11061                  */
11062                 ntups = PQntuples(res_ops);
11063
11064                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
11065                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
11066                 i_amopopr = PQfnumber(res_ops, "amopopr");
11067                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
11068                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
11069
11070                 for (i = 0; i < ntups; i++)
11071                 {
11072                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
11073                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
11074                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
11075                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
11076                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
11077
11078                         if (needComma)
11079                                 appendPQExpBuffer(q, " ,\n    ");
11080
11081                         appendPQExpBuffer(q, "OPERATOR %s %s",
11082                                                           amopstrategy, amopopr);
11083
11084                         if (strlen(sortfamily) > 0)
11085                         {
11086                                 appendPQExpBuffer(q, " FOR ORDER BY ");
11087                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
11088                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
11089                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
11090                         }
11091
11092                         if (strcmp(amopreqcheck, "t") == 0)
11093                                 appendPQExpBuffer(q, " RECHECK");
11094
11095                         needComma = true;
11096                 }
11097
11098                 /*
11099                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
11100                  */
11101                 ntups = PQntuples(res_procs);
11102
11103                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
11104                 i_amproc = PQfnumber(res_procs, "amproc");
11105                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
11106                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
11107
11108                 for (i = 0; i < ntups; i++)
11109                 {
11110                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
11111                         amproc = PQgetvalue(res_procs, i, i_amproc);
11112                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
11113                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
11114
11115                         if (needComma)
11116                                 appendPQExpBuffer(q, " ,\n    ");
11117
11118                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
11119                                                           amprocnum, amproclefttype, amprocrighttype,
11120                                                           amproc);
11121
11122                         needComma = true;
11123                 }
11124
11125                 appendPQExpBuffer(q, ";\n");
11126         }
11127
11128         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
11129                                           fmtId(opfinfo->dobj.name));
11130         appendPQExpBuffer(labelq, " USING %s",
11131                                           fmtId(amname));
11132
11133         if (binary_upgrade)
11134                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
11135
11136         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
11137                                  opfinfo->dobj.name,
11138                                  opfinfo->dobj.namespace->dobj.name,
11139                                  NULL,
11140                                  opfinfo->rolname,
11141                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
11142                                  q->data, delq->data, NULL,
11143                                  NULL, 0,
11144                                  NULL, NULL);
11145
11146         /* Dump Operator Family Comments */
11147         dumpComment(fout, labelq->data,
11148                                 NULL, opfinfo->rolname,
11149                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
11150
11151         free(amname);
11152         PQclear(res_ops);
11153         PQclear(res_procs);
11154         destroyPQExpBuffer(query);
11155         destroyPQExpBuffer(q);
11156         destroyPQExpBuffer(delq);
11157         destroyPQExpBuffer(labelq);
11158 }
11159
11160 /*
11161  * dumpCollation
11162  *        write out a single collation definition
11163  */
11164 static void
11165 dumpCollation(Archive *fout, CollInfo *collinfo)
11166 {
11167         PQExpBuffer query;
11168         PQExpBuffer q;
11169         PQExpBuffer delq;
11170         PQExpBuffer labelq;
11171         PGresult   *res;
11172         int                     i_collcollate;
11173         int                     i_collctype;
11174         const char *collcollate;
11175         const char *collctype;
11176
11177         /* Skip if not to be dumped */
11178         if (!collinfo->dobj.dump || dataOnly)
11179                 return;
11180
11181         query = createPQExpBuffer();
11182         q = createPQExpBuffer();
11183         delq = createPQExpBuffer();
11184         labelq = createPQExpBuffer();
11185
11186         /* Make sure we are in proper schema */
11187         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
11188
11189         /* Get conversion-specific details */
11190         appendPQExpBuffer(query, "SELECT "
11191                                           "collcollate, "
11192                                           "collctype "
11193                                           "FROM pg_catalog.pg_collation c "
11194                                           "WHERE c.oid = '%u'::pg_catalog.oid",
11195                                           collinfo->dobj.catId.oid);
11196
11197         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11198
11199         i_collcollate = PQfnumber(res, "collcollate");
11200         i_collctype = PQfnumber(res, "collctype");
11201
11202         collcollate = PQgetvalue(res, 0, i_collcollate);
11203         collctype = PQgetvalue(res, 0, i_collctype);
11204
11205         /*
11206          * DROP must be fully qualified in case same name appears in pg_catalog
11207          */
11208         appendPQExpBuffer(delq, "DROP COLLATION %s",
11209                                           fmtId(collinfo->dobj.namespace->dobj.name));
11210         appendPQExpBuffer(delq, ".%s;\n",
11211                                           fmtId(collinfo->dobj.name));
11212
11213         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
11214                                           fmtId(collinfo->dobj.name));
11215         appendStringLiteralAH(q, collcollate, fout);
11216         appendPQExpBuffer(q, ", lc_ctype = ");
11217         appendStringLiteralAH(q, collctype, fout);
11218         appendPQExpBuffer(q, ");\n");
11219
11220         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
11221
11222         if (binary_upgrade)
11223                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
11224
11225         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
11226                                  collinfo->dobj.name,
11227                                  collinfo->dobj.namespace->dobj.name,
11228                                  NULL,
11229                                  collinfo->rolname,
11230                                  false, "COLLATION", SECTION_PRE_DATA,
11231                                  q->data, delq->data, NULL,
11232                                  NULL, 0,
11233                                  NULL, NULL);
11234
11235         /* Dump Collation Comments */
11236         dumpComment(fout, labelq->data,
11237                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
11238                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
11239
11240         PQclear(res);
11241
11242         destroyPQExpBuffer(query);
11243         destroyPQExpBuffer(q);
11244         destroyPQExpBuffer(delq);
11245         destroyPQExpBuffer(labelq);
11246 }
11247
11248 /*
11249  * dumpConversion
11250  *        write out a single conversion definition
11251  */
11252 static void
11253 dumpConversion(Archive *fout, ConvInfo *convinfo)
11254 {
11255         PQExpBuffer query;
11256         PQExpBuffer q;
11257         PQExpBuffer delq;
11258         PQExpBuffer labelq;
11259         PGresult   *res;
11260         int                     i_conforencoding;
11261         int                     i_contoencoding;
11262         int                     i_conproc;
11263         int                     i_condefault;
11264         const char *conforencoding;
11265         const char *contoencoding;
11266         const char *conproc;
11267         bool            condefault;
11268
11269         /* Skip if not to be dumped */
11270         if (!convinfo->dobj.dump || dataOnly)
11271                 return;
11272
11273         query = createPQExpBuffer();
11274         q = createPQExpBuffer();
11275         delq = createPQExpBuffer();
11276         labelq = createPQExpBuffer();
11277
11278         /* Make sure we are in proper schema */
11279         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
11280
11281         /* Get conversion-specific details */
11282         appendPQExpBuffer(query, "SELECT "
11283                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
11284                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
11285                                           "conproc, condefault "
11286                                           "FROM pg_catalog.pg_conversion c "
11287                                           "WHERE c.oid = '%u'::pg_catalog.oid",
11288                                           convinfo->dobj.catId.oid);
11289
11290         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11291
11292         i_conforencoding = PQfnumber(res, "conforencoding");
11293         i_contoencoding = PQfnumber(res, "contoencoding");
11294         i_conproc = PQfnumber(res, "conproc");
11295         i_condefault = PQfnumber(res, "condefault");
11296
11297         conforencoding = PQgetvalue(res, 0, i_conforencoding);
11298         contoencoding = PQgetvalue(res, 0, i_contoencoding);
11299         conproc = PQgetvalue(res, 0, i_conproc);
11300         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
11301
11302         /*
11303          * DROP must be fully qualified in case same name appears in pg_catalog
11304          */
11305         appendPQExpBuffer(delq, "DROP CONVERSION %s",
11306                                           fmtId(convinfo->dobj.namespace->dobj.name));
11307         appendPQExpBuffer(delq, ".%s;\n",
11308                                           fmtId(convinfo->dobj.name));
11309
11310         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
11311                                           (condefault) ? "DEFAULT " : "",
11312                                           fmtId(convinfo->dobj.name));
11313         appendStringLiteralAH(q, conforencoding, fout);
11314         appendPQExpBuffer(q, " TO ");
11315         appendStringLiteralAH(q, contoencoding, fout);
11316         /* regproc is automatically quoted in 7.3 and above */
11317         appendPQExpBuffer(q, " FROM %s;\n", conproc);
11318
11319         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
11320
11321         if (binary_upgrade)
11322                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
11323
11324         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
11325                                  convinfo->dobj.name,
11326                                  convinfo->dobj.namespace->dobj.name,
11327                                  NULL,
11328                                  convinfo->rolname,
11329                                  false, "CONVERSION", SECTION_PRE_DATA,
11330                                  q->data, delq->data, NULL,
11331                                  NULL, 0,
11332                                  NULL, NULL);
11333
11334         /* Dump Conversion Comments */
11335         dumpComment(fout, labelq->data,
11336                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
11337                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
11338
11339         PQclear(res);
11340
11341         destroyPQExpBuffer(query);
11342         destroyPQExpBuffer(q);
11343         destroyPQExpBuffer(delq);
11344         destroyPQExpBuffer(labelq);
11345 }
11346
11347 /*
11348  * format_aggregate_signature: generate aggregate name and argument list
11349  *
11350  * The argument type names are qualified if needed.  The aggregate name
11351  * is never qualified.
11352  */
11353 static char *
11354 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11355 {
11356         PQExpBufferData buf;
11357         int                     j;
11358
11359         initPQExpBuffer(&buf);
11360         if (honor_quotes)
11361                 appendPQExpBuffer(&buf, "%s",
11362                                                   fmtId(agginfo->aggfn.dobj.name));
11363         else
11364                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11365
11366         if (agginfo->aggfn.nargs == 0)
11367                 appendPQExpBuffer(&buf, "(*)");
11368         else
11369         {
11370                 appendPQExpBuffer(&buf, "(");
11371                 for (j = 0; j < agginfo->aggfn.nargs; j++)
11372                 {
11373                         char       *typname;
11374
11375                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11376                                                                                    zeroAsOpaque);
11377
11378                         appendPQExpBuffer(&buf, "%s%s",
11379                                                           (j > 0) ? ", " : "",
11380                                                           typname);
11381                         free(typname);
11382                 }
11383                 appendPQExpBuffer(&buf, ")");
11384         }
11385         return buf.data;
11386 }
11387
11388 /*
11389  * dumpAgg
11390  *        write out a single aggregate definition
11391  */
11392 static void
11393 dumpAgg(Archive *fout, AggInfo *agginfo)
11394 {
11395         PQExpBuffer query;
11396         PQExpBuffer q;
11397         PQExpBuffer delq;
11398         PQExpBuffer labelq;
11399         PQExpBuffer details;
11400         char       *aggsig;
11401         char       *aggsig_tag;
11402         PGresult   *res;
11403         int                     i_aggtransfn;
11404         int                     i_aggfinalfn;
11405         int                     i_aggsortop;
11406         int                     i_aggtranstype;
11407         int                     i_agginitval;
11408         int                     i_convertok;
11409         const char *aggtransfn;
11410         const char *aggfinalfn;
11411         const char *aggsortop;
11412         const char *aggtranstype;
11413         const char *agginitval;
11414         bool            convertok;
11415
11416         /* Skip if not to be dumped */
11417         if (!agginfo->aggfn.dobj.dump || dataOnly)
11418                 return;
11419
11420         query = createPQExpBuffer();
11421         q = createPQExpBuffer();
11422         delq = createPQExpBuffer();
11423         labelq = createPQExpBuffer();
11424         details = createPQExpBuffer();
11425
11426         /* Make sure we are in proper schema */
11427         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11428
11429         /* Get aggregate-specific details */
11430         if (fout->remoteVersion >= 80100)
11431         {
11432                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11433                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11434                                                   "aggsortop::pg_catalog.regoperator, "
11435                                                   "agginitval, "
11436                                                   "'t'::boolean AS convertok "
11437                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11438                                                   "WHERE a.aggfnoid = p.oid "
11439                                                   "AND p.oid = '%u'::pg_catalog.oid",
11440                                                   agginfo->aggfn.dobj.catId.oid);
11441         }
11442         else if (fout->remoteVersion >= 70300)
11443         {
11444                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11445                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11446                                                   "0 AS aggsortop, "
11447                                                   "agginitval, "
11448                                                   "'t'::boolean AS convertok "
11449                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11450                                                   "WHERE a.aggfnoid = p.oid "
11451                                                   "AND p.oid = '%u'::pg_catalog.oid",
11452                                                   agginfo->aggfn.dobj.catId.oid);
11453         }
11454         else if (fout->remoteVersion >= 70100)
11455         {
11456                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11457                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
11458                                                   "0 AS aggsortop, "
11459                                                   "agginitval, "
11460                                                   "'t'::boolean AS convertok "
11461                                                   "FROM pg_aggregate "
11462                                                   "WHERE oid = '%u'::oid",
11463                                                   agginfo->aggfn.dobj.catId.oid);
11464         }
11465         else
11466         {
11467                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11468                                                   "aggfinalfn, "
11469                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11470                                                   "0 AS aggsortop, "
11471                                                   "agginitval1 AS agginitval, "
11472                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11473                                                   "FROM pg_aggregate "
11474                                                   "WHERE oid = '%u'::oid",
11475                                                   agginfo->aggfn.dobj.catId.oid);
11476         }
11477
11478         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11479
11480         i_aggtransfn = PQfnumber(res, "aggtransfn");
11481         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11482         i_aggsortop = PQfnumber(res, "aggsortop");
11483         i_aggtranstype = PQfnumber(res, "aggtranstype");
11484         i_agginitval = PQfnumber(res, "agginitval");
11485         i_convertok = PQfnumber(res, "convertok");
11486
11487         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11488         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11489         aggsortop = PQgetvalue(res, 0, i_aggsortop);
11490         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11491         agginitval = PQgetvalue(res, 0, i_agginitval);
11492         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11493
11494         aggsig = format_aggregate_signature(agginfo, fout, true);
11495         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11496
11497         if (!convertok)
11498         {
11499                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11500                                   aggsig);
11501                 return;
11502         }
11503
11504         if (fout->remoteVersion >= 70300)
11505         {
11506                 /* If using 7.3's regproc or regtype, data is already quoted */
11507                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11508                                                   aggtransfn,
11509                                                   aggtranstype);
11510         }
11511         else if (fout->remoteVersion >= 70100)
11512         {
11513                 /* format_type quotes, regproc does not */
11514                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11515                                                   fmtId(aggtransfn),
11516                                                   aggtranstype);
11517         }
11518         else
11519         {
11520                 /* need quotes all around */
11521                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
11522                                                   fmtId(aggtransfn));
11523                 appendPQExpBuffer(details, "    STYPE = %s",
11524                                                   fmtId(aggtranstype));
11525         }
11526
11527         if (!PQgetisnull(res, 0, i_agginitval))
11528         {
11529                 appendPQExpBuffer(details, ",\n    INITCOND = ");
11530                 appendStringLiteralAH(details, agginitval, fout);
11531         }
11532
11533         if (strcmp(aggfinalfn, "-") != 0)
11534         {
11535                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
11536                                                   aggfinalfn);
11537         }
11538
11539         aggsortop = convertOperatorReference(fout, aggsortop);
11540         if (aggsortop)
11541         {
11542                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
11543                                                   aggsortop);
11544         }
11545
11546         /*
11547          * DROP must be fully qualified in case same name appears in pg_catalog
11548          */
11549         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11550                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11551                                           aggsig);
11552
11553         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11554                                           aggsig, details->data);
11555
11556         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11557
11558         if (binary_upgrade)
11559                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11560
11561         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11562                                  aggsig_tag,
11563                                  agginfo->aggfn.dobj.namespace->dobj.name,
11564                                  NULL,
11565                                  agginfo->aggfn.rolname,
11566                                  false, "AGGREGATE", SECTION_PRE_DATA,
11567                                  q->data, delq->data, NULL,
11568                                  NULL, 0,
11569                                  NULL, NULL);
11570
11571         /* Dump Aggregate Comments */
11572         dumpComment(fout, labelq->data,
11573                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11574                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11575         dumpSecLabel(fout, labelq->data,
11576                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11577                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11578
11579         /*
11580          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11581          * command look like a function's GRANT; in particular this affects the
11582          * syntax for zero-argument aggregates.
11583          */
11584         free(aggsig);
11585         free(aggsig_tag);
11586
11587         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11588         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11589
11590         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11591                         "FUNCTION",
11592                         aggsig, NULL, aggsig_tag,
11593                         agginfo->aggfn.dobj.namespace->dobj.name,
11594                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11595
11596         free(aggsig);
11597         free(aggsig_tag);
11598
11599         PQclear(res);
11600
11601         destroyPQExpBuffer(query);
11602         destroyPQExpBuffer(q);
11603         destroyPQExpBuffer(delq);
11604         destroyPQExpBuffer(labelq);
11605         destroyPQExpBuffer(details);
11606 }
11607
11608 /*
11609  * dumpTSParser
11610  *        write out a single text search parser
11611  */
11612 static void
11613 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11614 {
11615         PQExpBuffer q;
11616         PQExpBuffer delq;
11617         PQExpBuffer labelq;
11618
11619         /* Skip if not to be dumped */
11620         if (!prsinfo->dobj.dump || dataOnly)
11621                 return;
11622
11623         q = createPQExpBuffer();
11624         delq = createPQExpBuffer();
11625         labelq = createPQExpBuffer();
11626
11627         /* Make sure we are in proper schema */
11628         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11629
11630         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11631                                           fmtId(prsinfo->dobj.name));
11632
11633         appendPQExpBuffer(q, "    START = %s,\n",
11634                                           convertTSFunction(fout, prsinfo->prsstart));
11635         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11636                                           convertTSFunction(fout, prsinfo->prstoken));
11637         appendPQExpBuffer(q, "    END = %s,\n",
11638                                           convertTSFunction(fout, prsinfo->prsend));
11639         if (prsinfo->prsheadline != InvalidOid)
11640                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11641                                                   convertTSFunction(fout, prsinfo->prsheadline));
11642         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11643                                           convertTSFunction(fout, prsinfo->prslextype));
11644
11645         /*
11646          * DROP must be fully qualified in case same name appears in pg_catalog
11647          */
11648         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11649                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11650         appendPQExpBuffer(delq, ".%s;\n",
11651                                           fmtId(prsinfo->dobj.name));
11652
11653         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11654                                           fmtId(prsinfo->dobj.name));
11655
11656         if (binary_upgrade)
11657                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11658
11659         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11660                                  prsinfo->dobj.name,
11661                                  prsinfo->dobj.namespace->dobj.name,
11662                                  NULL,
11663                                  "",
11664                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11665                                  q->data, delq->data, NULL,
11666                                  NULL, 0,
11667                                  NULL, NULL);
11668
11669         /* Dump Parser Comments */
11670         dumpComment(fout, labelq->data,
11671                                 NULL, "",
11672                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11673
11674         destroyPQExpBuffer(q);
11675         destroyPQExpBuffer(delq);
11676         destroyPQExpBuffer(labelq);
11677 }
11678
11679 /*
11680  * dumpTSDictionary
11681  *        write out a single text search dictionary
11682  */
11683 static void
11684 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11685 {
11686         PQExpBuffer q;
11687         PQExpBuffer delq;
11688         PQExpBuffer labelq;
11689         PQExpBuffer query;
11690         PGresult   *res;
11691         char       *nspname;
11692         char       *tmplname;
11693
11694         /* Skip if not to be dumped */
11695         if (!dictinfo->dobj.dump || dataOnly)
11696                 return;
11697
11698         q = createPQExpBuffer();
11699         delq = createPQExpBuffer();
11700         labelq = createPQExpBuffer();
11701         query = createPQExpBuffer();
11702
11703         /* Fetch name and namespace of the dictionary's template */
11704         selectSourceSchema(fout, "pg_catalog");
11705         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11706                                           "FROM pg_ts_template p, pg_namespace n "
11707                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11708                                           dictinfo->dicttemplate);
11709         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11710         nspname = PQgetvalue(res, 0, 0);
11711         tmplname = PQgetvalue(res, 0, 1);
11712
11713         /* Make sure we are in proper schema */
11714         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11715
11716         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11717                                           fmtId(dictinfo->dobj.name));
11718
11719         appendPQExpBuffer(q, "    TEMPLATE = ");
11720         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11721                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11722         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11723
11724         PQclear(res);
11725
11726         /* the dictinitoption can be dumped straight into the command */
11727         if (dictinfo->dictinitoption)
11728                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11729
11730         appendPQExpBuffer(q, " );\n");
11731
11732         /*
11733          * DROP must be fully qualified in case same name appears in pg_catalog
11734          */
11735         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11736                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11737         appendPQExpBuffer(delq, ".%s;\n",
11738                                           fmtId(dictinfo->dobj.name));
11739
11740         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11741                                           fmtId(dictinfo->dobj.name));
11742
11743         if (binary_upgrade)
11744                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11745
11746         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11747                                  dictinfo->dobj.name,
11748                                  dictinfo->dobj.namespace->dobj.name,
11749                                  NULL,
11750                                  dictinfo->rolname,
11751                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11752                                  q->data, delq->data, NULL,
11753                                  NULL, 0,
11754                                  NULL, NULL);
11755
11756         /* Dump Dictionary Comments */
11757         dumpComment(fout, labelq->data,
11758                                 NULL, dictinfo->rolname,
11759                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11760
11761         destroyPQExpBuffer(q);
11762         destroyPQExpBuffer(delq);
11763         destroyPQExpBuffer(labelq);
11764         destroyPQExpBuffer(query);
11765 }
11766
11767 /*
11768  * dumpTSTemplate
11769  *        write out a single text search template
11770  */
11771 static void
11772 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11773 {
11774         PQExpBuffer q;
11775         PQExpBuffer delq;
11776         PQExpBuffer labelq;
11777
11778         /* Skip if not to be dumped */
11779         if (!tmplinfo->dobj.dump || dataOnly)
11780                 return;
11781
11782         q = createPQExpBuffer();
11783         delq = createPQExpBuffer();
11784         labelq = createPQExpBuffer();
11785
11786         /* Make sure we are in proper schema */
11787         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11788
11789         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11790                                           fmtId(tmplinfo->dobj.name));
11791
11792         if (tmplinfo->tmplinit != InvalidOid)
11793                 appendPQExpBuffer(q, "    INIT = %s,\n",
11794                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11795         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11796                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11797
11798         /*
11799          * DROP must be fully qualified in case same name appears in pg_catalog
11800          */
11801         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11802                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11803         appendPQExpBuffer(delq, ".%s;\n",
11804                                           fmtId(tmplinfo->dobj.name));
11805
11806         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11807                                           fmtId(tmplinfo->dobj.name));
11808
11809         if (binary_upgrade)
11810                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11811
11812         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11813                                  tmplinfo->dobj.name,
11814                                  tmplinfo->dobj.namespace->dobj.name,
11815                                  NULL,
11816                                  "",
11817                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11818                                  q->data, delq->data, NULL,
11819                                  NULL, 0,
11820                                  NULL, NULL);
11821
11822         /* Dump Template Comments */
11823         dumpComment(fout, labelq->data,
11824                                 NULL, "",
11825                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11826
11827         destroyPQExpBuffer(q);
11828         destroyPQExpBuffer(delq);
11829         destroyPQExpBuffer(labelq);
11830 }
11831
11832 /*
11833  * dumpTSConfig
11834  *        write out a single text search configuration
11835  */
11836 static void
11837 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11838 {
11839         PQExpBuffer q;
11840         PQExpBuffer delq;
11841         PQExpBuffer labelq;
11842         PQExpBuffer query;
11843         PGresult   *res;
11844         char       *nspname;
11845         char       *prsname;
11846         int                     ntups,
11847                                 i;
11848         int                     i_tokenname;
11849         int                     i_dictname;
11850
11851         /* Skip if not to be dumped */
11852         if (!cfginfo->dobj.dump || dataOnly)
11853                 return;
11854
11855         q = createPQExpBuffer();
11856         delq = createPQExpBuffer();
11857         labelq = createPQExpBuffer();
11858         query = createPQExpBuffer();
11859
11860         /* Fetch name and namespace of the config's parser */
11861         selectSourceSchema(fout, "pg_catalog");
11862         appendPQExpBuffer(query, "SELECT nspname, prsname "
11863                                           "FROM pg_ts_parser p, pg_namespace n "
11864                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11865                                           cfginfo->cfgparser);
11866         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11867         nspname = PQgetvalue(res, 0, 0);
11868         prsname = PQgetvalue(res, 0, 1);
11869
11870         /* Make sure we are in proper schema */
11871         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11872
11873         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11874                                           fmtId(cfginfo->dobj.name));
11875
11876         appendPQExpBuffer(q, "    PARSER = ");
11877         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11878                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11879         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11880
11881         PQclear(res);
11882
11883         resetPQExpBuffer(query);
11884         appendPQExpBuffer(query,
11885                                           "SELECT \n"
11886                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11887                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11888                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11889                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11890                                           "WHERE m.mapcfg = '%u' \n"
11891                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11892                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11893
11894         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11895         ntups = PQntuples(res);
11896
11897         i_tokenname = PQfnumber(res, "tokenname");
11898         i_dictname = PQfnumber(res, "dictname");
11899
11900         for (i = 0; i < ntups; i++)
11901         {
11902                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11903                 char       *dictname = PQgetvalue(res, i, i_dictname);
11904
11905                 if (i == 0 ||
11906                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11907                 {
11908                         /* starting a new token type, so start a new command */
11909                         if (i > 0)
11910                                 appendPQExpBuffer(q, ";\n");
11911                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11912                                                           fmtId(cfginfo->dobj.name));
11913                         /* tokenname needs quoting, dictname does NOT */
11914                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11915                                                           fmtId(tokenname), dictname);
11916                 }
11917                 else
11918                         appendPQExpBuffer(q, ", %s", dictname);
11919         }
11920
11921         if (ntups > 0)
11922                 appendPQExpBuffer(q, ";\n");
11923
11924         PQclear(res);
11925
11926         /*
11927          * DROP must be fully qualified in case same name appears in pg_catalog
11928          */
11929         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11930                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11931         appendPQExpBuffer(delq, ".%s;\n",
11932                                           fmtId(cfginfo->dobj.name));
11933
11934         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11935                                           fmtId(cfginfo->dobj.name));
11936
11937         if (binary_upgrade)
11938                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11939
11940         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11941                                  cfginfo->dobj.name,
11942                                  cfginfo->dobj.namespace->dobj.name,
11943                                  NULL,
11944                                  cfginfo->rolname,
11945                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11946                                  q->data, delq->data, NULL,
11947                                  NULL, 0,
11948                                  NULL, NULL);
11949
11950         /* Dump Configuration Comments */
11951         dumpComment(fout, labelq->data,
11952                                 NULL, cfginfo->rolname,
11953                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11954
11955         destroyPQExpBuffer(q);
11956         destroyPQExpBuffer(delq);
11957         destroyPQExpBuffer(labelq);
11958         destroyPQExpBuffer(query);
11959 }
11960
11961 /*
11962  * dumpForeignDataWrapper
11963  *        write out a single foreign-data wrapper definition
11964  */
11965 static void
11966 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11967 {
11968         PQExpBuffer q;
11969         PQExpBuffer delq;
11970         PQExpBuffer labelq;
11971         char       *qfdwname;
11972
11973         /* Skip if not to be dumped */
11974         if (!fdwinfo->dobj.dump || dataOnly)
11975                 return;
11976
11977         /*
11978          * FDWs that belong to an extension are dumped based on their "dump"
11979          * field. Otherwise omit them if we are only dumping some specific object.
11980          */
11981         if (!fdwinfo->dobj.ext_member)
11982                 if (!include_everything)
11983                         return;
11984
11985         q = createPQExpBuffer();
11986         delq = createPQExpBuffer();
11987         labelq = createPQExpBuffer();
11988
11989         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11990
11991         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11992                                           qfdwname);
11993
11994         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11995                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11996
11997         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11998                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11999
12000         if (strlen(fdwinfo->fdwoptions) > 0)
12001                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
12002
12003         appendPQExpBuffer(q, ";\n");
12004
12005         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
12006                                           qfdwname);
12007
12008         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
12009                                           qfdwname);
12010
12011         if (binary_upgrade)
12012                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
12013
12014         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12015                                  fdwinfo->dobj.name,
12016                                  NULL,
12017                                  NULL,
12018                                  fdwinfo->rolname,
12019                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
12020                                  q->data, delq->data, NULL,
12021                                  NULL, 0,
12022                                  NULL, NULL);
12023
12024         /* Handle the ACL */
12025         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12026                         "FOREIGN DATA WRAPPER",
12027                         qfdwname, NULL, fdwinfo->dobj.name,
12028                         NULL, fdwinfo->rolname,
12029                         fdwinfo->fdwacl);
12030
12031         /* Dump Foreign Data Wrapper Comments */
12032         dumpComment(fout, labelq->data,
12033                                 NULL, fdwinfo->rolname,
12034                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
12035
12036         free(qfdwname);
12037
12038         destroyPQExpBuffer(q);
12039         destroyPQExpBuffer(delq);
12040         destroyPQExpBuffer(labelq);
12041 }
12042
12043 /*
12044  * dumpForeignServer
12045  *        write out a foreign server definition
12046  */
12047 static void
12048 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
12049 {
12050         PQExpBuffer q;
12051         PQExpBuffer delq;
12052         PQExpBuffer labelq;
12053         PQExpBuffer query;
12054         PGresult   *res;
12055         char       *qsrvname;
12056         char       *fdwname;
12057
12058         /* Skip if not to be dumped */
12059         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
12060                 return;
12061
12062         q = createPQExpBuffer();
12063         delq = createPQExpBuffer();
12064         labelq = createPQExpBuffer();
12065         query = createPQExpBuffer();
12066
12067         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
12068
12069         /* look up the foreign-data wrapper */
12070         selectSourceSchema(fout, "pg_catalog");
12071         appendPQExpBuffer(query, "SELECT fdwname "
12072                                           "FROM pg_foreign_data_wrapper w "
12073                                           "WHERE w.oid = '%u'",
12074                                           srvinfo->srvfdw);
12075         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12076         fdwname = PQgetvalue(res, 0, 0);
12077
12078         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
12079         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
12080         {
12081                 appendPQExpBuffer(q, " TYPE ");
12082                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
12083         }
12084         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
12085         {
12086                 appendPQExpBuffer(q, " VERSION ");
12087                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
12088         }
12089
12090         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
12091         appendPQExpBuffer(q, "%s", fmtId(fdwname));
12092
12093         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
12094                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
12095
12096         appendPQExpBuffer(q, ";\n");
12097
12098         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
12099                                           qsrvname);
12100
12101         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
12102
12103         if (binary_upgrade)
12104                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
12105
12106         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12107                                  srvinfo->dobj.name,
12108                                  NULL,
12109                                  NULL,
12110                                  srvinfo->rolname,
12111                                  false, "SERVER", SECTION_PRE_DATA,
12112                                  q->data, delq->data, NULL,
12113                                  NULL, 0,
12114                                  NULL, NULL);
12115
12116         /* Handle the ACL */
12117         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12118                         "FOREIGN SERVER",
12119                         qsrvname, NULL, srvinfo->dobj.name,
12120                         NULL, srvinfo->rolname,
12121                         srvinfo->srvacl);
12122
12123         /* Dump user mappings */
12124         dumpUserMappings(fout,
12125                                          srvinfo->dobj.name, NULL,
12126                                          srvinfo->rolname,
12127                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
12128
12129         /* Dump Foreign Server Comments */
12130         dumpComment(fout, labelq->data,
12131                                 NULL, srvinfo->rolname,
12132                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
12133
12134         free(qsrvname);
12135
12136         destroyPQExpBuffer(q);
12137         destroyPQExpBuffer(delq);
12138         destroyPQExpBuffer(labelq);
12139 }
12140
12141 /*
12142  * dumpUserMappings
12143  *
12144  * This routine is used to dump any user mappings associated with the
12145  * server handed to this routine. Should be called after ArchiveEntry()
12146  * for the server.
12147  */
12148 static void
12149 dumpUserMappings(Archive *fout,
12150                                  const char *servername, const char *namespace,
12151                                  const char *owner,
12152                                  CatalogId catalogId, DumpId dumpId)
12153 {
12154         PQExpBuffer q;
12155         PQExpBuffer delq;
12156         PQExpBuffer query;
12157         PQExpBuffer tag;
12158         PGresult   *res;
12159         int                     ntups;
12160         int                     i_usename;
12161         int                     i_umoptions;
12162         int                     i;
12163
12164         q = createPQExpBuffer();
12165         tag = createPQExpBuffer();
12166         delq = createPQExpBuffer();
12167         query = createPQExpBuffer();
12168
12169         /*
12170          * We read from the publicly accessible view pg_user_mappings, so as not
12171          * to fail if run by a non-superuser.  Note that the view will show
12172          * umoptions as null if the user hasn't got privileges for the associated
12173          * server; this means that pg_dump will dump such a mapping, but with no
12174          * OPTIONS clause.      A possible alternative is to skip such mappings
12175          * altogether, but it's not clear that that's an improvement.
12176          */
12177         selectSourceSchema(fout, "pg_catalog");
12178
12179         appendPQExpBuffer(query,
12180                                           "SELECT usename, "
12181                                           "array_to_string(ARRAY("
12182                                           "SELECT quote_ident(option_name) || ' ' || "
12183                                           "quote_literal(option_value) "
12184                                           "FROM pg_options_to_table(umoptions) "
12185                                           "ORDER BY option_name"
12186                                           "), E',\n    ') AS umoptions "
12187                                           "FROM pg_user_mappings "
12188                                           "WHERE srvid = '%u' "
12189                                           "ORDER BY usename",
12190                                           catalogId.oid);
12191
12192         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12193
12194         ntups = PQntuples(res);
12195         i_usename = PQfnumber(res, "usename");
12196         i_umoptions = PQfnumber(res, "umoptions");
12197
12198         for (i = 0; i < ntups; i++)
12199         {
12200                 char       *usename;
12201                 char       *umoptions;
12202
12203                 usename = PQgetvalue(res, i, i_usename);
12204                 umoptions = PQgetvalue(res, i, i_umoptions);
12205
12206                 resetPQExpBuffer(q);
12207                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
12208                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
12209
12210                 if (umoptions && strlen(umoptions) > 0)
12211                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
12212
12213                 appendPQExpBuffer(q, ";\n");
12214
12215                 resetPQExpBuffer(delq);
12216                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
12217                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
12218
12219                 resetPQExpBuffer(tag);
12220                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
12221                                                   usename, servername);
12222
12223                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12224                                          tag->data,
12225                                          namespace,
12226                                          NULL,
12227                                          owner, false,
12228                                          "USER MAPPING", SECTION_PRE_DATA,
12229                                          q->data, delq->data, NULL,
12230                                          &dumpId, 1,
12231                                          NULL, NULL);
12232         }
12233
12234         PQclear(res);
12235
12236         destroyPQExpBuffer(query);
12237         destroyPQExpBuffer(delq);
12238         destroyPQExpBuffer(q);
12239 }
12240
12241 /*
12242  * Write out default privileges information
12243  */
12244 static void
12245 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
12246 {
12247         PQExpBuffer q;
12248         PQExpBuffer tag;
12249         const char *type;
12250
12251         /* Skip if not to be dumped */
12252         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
12253                 return;
12254
12255         q = createPQExpBuffer();
12256         tag = createPQExpBuffer();
12257
12258         switch (daclinfo->defaclobjtype)
12259         {
12260                 case DEFACLOBJ_RELATION:
12261                         type = "TABLES";
12262                         break;
12263                 case DEFACLOBJ_SEQUENCE:
12264                         type = "SEQUENCES";
12265                         break;
12266                 case DEFACLOBJ_FUNCTION:
12267                         type = "FUNCTIONS";
12268                         break;
12269                 case DEFACLOBJ_TYPE:
12270                         type = "TYPES";
12271                         break;
12272                 default:
12273                         /* shouldn't get here */
12274                         exit_horribly(NULL,
12275                                           "unrecognized object type in default privileges: %d\n",
12276                                                   (int) daclinfo->defaclobjtype);
12277                         type = "";                      /* keep compiler quiet */
12278         }
12279
12280         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
12281
12282         /* build the actual command(s) for this tuple */
12283         if (!buildDefaultACLCommands(type,
12284                                                                  daclinfo->dobj.namespace != NULL ?
12285                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
12286                                                                  daclinfo->defaclacl,
12287                                                                  daclinfo->defaclrole,
12288                                                                  fout->remoteVersion,
12289                                                                  q))
12290                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
12291                                           daclinfo->defaclacl);
12292
12293         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
12294                                  tag->data,
12295            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
12296                                  NULL,
12297                                  daclinfo->defaclrole,
12298                                  false, "DEFAULT ACL", SECTION_POST_DATA,
12299                                  q->data, "", NULL,
12300                                  NULL, 0,
12301                                  NULL, NULL);
12302
12303         destroyPQExpBuffer(tag);
12304         destroyPQExpBuffer(q);
12305 }
12306
12307 /*----------
12308  * Write out grant/revoke information
12309  *
12310  * 'objCatId' is the catalog ID of the underlying object.
12311  * 'objDumpId' is the dump ID of the underlying object.
12312  * 'type' must be one of
12313  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
12314  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
12315  * 'name' is the formatted name of the object.  Must be quoted etc. already.
12316  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
12317  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12318  * 'nspname' is the namespace the object is in (NULL if none).
12319  * 'owner' is the owner, NULL if there is no owner (for languages).
12320  * 'acls' is the string read out of the fooacl system catalog field;
12321  *              it will be parsed here.
12322  *----------
12323  */
12324 static void
12325 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12326                 const char *type, const char *name, const char *subname,
12327                 const char *tag, const char *nspname, const char *owner,
12328                 const char *acls)
12329 {
12330         PQExpBuffer sql;
12331
12332         /* Do nothing if ACL dump is not enabled */
12333         if (aclsSkip)
12334                 return;
12335
12336         /* --data-only skips ACLs *except* BLOB ACLs */
12337         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12338                 return;
12339
12340         sql = createPQExpBuffer();
12341
12342         if (!buildACLCommands(name, subname, type, acls, owner,
12343                                                   "", fout->remoteVersion, sql))
12344                 exit_horribly(NULL,
12345                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12346                                           acls, name, type);
12347
12348         if (sql->len > 0)
12349                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12350                                          tag, nspname,
12351                                          NULL,
12352                                          owner ? owner : "",
12353                                          false, "ACL", SECTION_NONE,
12354                                          sql->data, "", NULL,
12355                                          &(objDumpId), 1,
12356                                          NULL, NULL);
12357
12358         destroyPQExpBuffer(sql);
12359 }
12360
12361 /*
12362  * dumpSecLabel
12363  *
12364  * This routine is used to dump any security labels associated with the
12365  * object handed to this routine. The routine takes a constant character
12366  * string for the target part of the security-label command, plus
12367  * the namespace and owner of the object (for labeling the ArchiveEntry),
12368  * plus catalog ID and subid which are the lookup key for pg_seclabel,
12369  * plus the dump ID for the object (for setting a dependency).
12370  * If a matching pg_seclabel entry is found, it is dumped.
12371  *
12372  * Note: although this routine takes a dumpId for dependency purposes,
12373  * that purpose is just to mark the dependency in the emitted dump file
12374  * for possible future use by pg_restore.  We do NOT use it for determining
12375  * ordering of the label in the dump file, because this routine is called
12376  * after dependency sorting occurs.  This routine should be called just after
12377  * calling ArchiveEntry() for the specified object.
12378  */
12379 static void
12380 dumpSecLabel(Archive *fout, const char *target,
12381                          const char *namespace, const char *owner,
12382                          CatalogId catalogId, int subid, DumpId dumpId)
12383 {
12384         SecLabelItem *labels;
12385         int                     nlabels;
12386         int                     i;
12387         PQExpBuffer query;
12388
12389         /* do nothing, if --no-security-labels is supplied */
12390         if (no_security_labels)
12391                 return;
12392
12393         /* Comments are schema not data ... except blob comments are data */
12394         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12395         {
12396                 if (dataOnly)
12397                         return;
12398         }
12399         else
12400         {
12401                 if (schemaOnly)
12402                         return;
12403         }
12404
12405         /* Search for security labels associated with catalogId, using table */
12406         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12407
12408         query = createPQExpBuffer();
12409
12410         for (i = 0; i < nlabels; i++)
12411         {
12412                 /*
12413                  * Ignore label entries for which the subid doesn't match.
12414                  */
12415                 if (labels[i].objsubid != subid)
12416                         continue;
12417
12418                 appendPQExpBuffer(query,
12419                                                   "SECURITY LABEL FOR %s ON %s IS ",
12420                                                   fmtId(labels[i].provider), target);
12421                 appendStringLiteralAH(query, labels[i].label, fout);
12422                 appendPQExpBuffer(query, ";\n");
12423         }
12424
12425         if (query->len > 0)
12426         {
12427                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12428                                          target, namespace, NULL, owner,
12429                                          false, "SECURITY LABEL", SECTION_NONE,
12430                                          query->data, "", NULL,
12431                                          &(dumpId), 1,
12432                                          NULL, NULL);
12433         }
12434         destroyPQExpBuffer(query);
12435 }
12436
12437 /*
12438  * dumpTableSecLabel
12439  *
12440  * As above, but dump security label for both the specified table (or view)
12441  * and its columns.
12442  */
12443 static void
12444 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12445 {
12446         SecLabelItem *labels;
12447         int                     nlabels;
12448         int                     i;
12449         PQExpBuffer query;
12450         PQExpBuffer target;
12451
12452         /* do nothing, if --no-security-labels is supplied */
12453         if (no_security_labels)
12454                 return;
12455
12456         /* SecLabel are SCHEMA not data */
12457         if (dataOnly)
12458                 return;
12459
12460         /* Search for comments associated with relation, using table */
12461         nlabels = findSecLabels(fout,
12462                                                         tbinfo->dobj.catId.tableoid,
12463                                                         tbinfo->dobj.catId.oid,
12464                                                         &labels);
12465
12466         /* If security labels exist, build SECURITY LABEL statements */
12467         if (nlabels <= 0)
12468                 return;
12469
12470         query = createPQExpBuffer();
12471         target = createPQExpBuffer();
12472
12473         for (i = 0; i < nlabels; i++)
12474         {
12475                 const char *colname;
12476                 const char *provider = labels[i].provider;
12477                 const char *label = labels[i].label;
12478                 int                     objsubid = labels[i].objsubid;
12479
12480                 resetPQExpBuffer(target);
12481                 if (objsubid == 0)
12482                 {
12483                         appendPQExpBuffer(target, "%s %s", reltypename,
12484                                                           fmtId(tbinfo->dobj.name));
12485                 }
12486                 else
12487                 {
12488                         colname = getAttrName(objsubid, tbinfo);
12489                         /* first fmtId result must be consumed before calling it again */
12490                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12491                         appendPQExpBuffer(target, ".%s", fmtId(colname));
12492                 }
12493                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12494                                                   fmtId(provider), target->data);
12495                 appendStringLiteralAH(query, label, fout);
12496                 appendPQExpBuffer(query, ";\n");
12497         }
12498         if (query->len > 0)
12499         {
12500                 resetPQExpBuffer(target);
12501                 appendPQExpBuffer(target, "%s %s", reltypename,
12502                                                   fmtId(tbinfo->dobj.name));
12503                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12504                                          target->data,
12505                                          tbinfo->dobj.namespace->dobj.name,
12506                                          NULL, tbinfo->rolname,
12507                                          false, "SECURITY LABEL", SECTION_NONE,
12508                                          query->data, "", NULL,
12509                                          &(tbinfo->dobj.dumpId), 1,
12510                                          NULL, NULL);
12511         }
12512         destroyPQExpBuffer(query);
12513         destroyPQExpBuffer(target);
12514 }
12515
12516 /*
12517  * findSecLabels
12518  *
12519  * Find the security label(s), if any, associated with the given object.
12520  * All the objsubid values associated with the given classoid/objoid are
12521  * found with one search.
12522  */
12523 static int
12524 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12525 {
12526         /* static storage for table of security labels */
12527         static SecLabelItem *labels = NULL;
12528         static int      nlabels = -1;
12529
12530         SecLabelItem *middle = NULL;
12531         SecLabelItem *low;
12532         SecLabelItem *high;
12533         int                     nmatch;
12534
12535         /* Get security labels if we didn't already */
12536         if (nlabels < 0)
12537                 nlabels = collectSecLabels(fout, &labels);
12538
12539         if (nlabels <= 0)                       /* no labels, so no match is possible */
12540         {
12541                 *items = NULL;
12542                 return 0;
12543         }
12544
12545         /*
12546          * Do binary search to find some item matching the object.
12547          */
12548         low = &labels[0];
12549         high = &labels[nlabels - 1];
12550         while (low <= high)
12551         {
12552                 middle = low + (high - low) / 2;
12553
12554                 if (classoid < middle->classoid)
12555                         high = middle - 1;
12556                 else if (classoid > middle->classoid)
12557                         low = middle + 1;
12558                 else if (objoid < middle->objoid)
12559                         high = middle - 1;
12560                 else if (objoid > middle->objoid)
12561                         low = middle + 1;
12562                 else
12563                         break;                          /* found a match */
12564         }
12565
12566         if (low > high)                         /* no matches */
12567         {
12568                 *items = NULL;
12569                 return 0;
12570         }
12571
12572         /*
12573          * Now determine how many items match the object.  The search loop
12574          * invariant still holds: only items between low and high inclusive could
12575          * match.
12576          */
12577         nmatch = 1;
12578         while (middle > low)
12579         {
12580                 if (classoid != middle[-1].classoid ||
12581                         objoid != middle[-1].objoid)
12582                         break;
12583                 middle--;
12584                 nmatch++;
12585         }
12586
12587         *items = middle;
12588
12589         middle += nmatch;
12590         while (middle <= high)
12591         {
12592                 if (classoid != middle->classoid ||
12593                         objoid != middle->objoid)
12594                         break;
12595                 middle++;
12596                 nmatch++;
12597         }
12598
12599         return nmatch;
12600 }
12601
12602 /*
12603  * collectSecLabels
12604  *
12605  * Construct a table of all security labels available for database objects.
12606  * It's much faster to pull them all at once.
12607  *
12608  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12609  */
12610 static int
12611 collectSecLabels(Archive *fout, SecLabelItem **items)
12612 {
12613         PGresult   *res;
12614         PQExpBuffer query;
12615         int                     i_label;
12616         int                     i_provider;
12617         int                     i_classoid;
12618         int                     i_objoid;
12619         int                     i_objsubid;
12620         int                     ntups;
12621         int                     i;
12622         SecLabelItem *labels;
12623
12624         query = createPQExpBuffer();
12625
12626         appendPQExpBuffer(query,
12627                                           "SELECT label, provider, classoid, objoid, objsubid "
12628                                           "FROM pg_catalog.pg_seclabel "
12629                                           "ORDER BY classoid, objoid, objsubid");
12630
12631         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12632
12633         /* Construct lookup table containing OIDs in numeric form */
12634         i_label = PQfnumber(res, "label");
12635         i_provider = PQfnumber(res, "provider");
12636         i_classoid = PQfnumber(res, "classoid");
12637         i_objoid = PQfnumber(res, "objoid");
12638         i_objsubid = PQfnumber(res, "objsubid");
12639
12640         ntups = PQntuples(res);
12641
12642         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12643
12644         for (i = 0; i < ntups; i++)
12645         {
12646                 labels[i].label = PQgetvalue(res, i, i_label);
12647                 labels[i].provider = PQgetvalue(res, i, i_provider);
12648                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12649                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12650                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12651         }
12652
12653         /* Do NOT free the PGresult since we are keeping pointers into it */
12654         destroyPQExpBuffer(query);
12655
12656         *items = labels;
12657         return ntups;
12658 }
12659
12660 /*
12661  * dumpTable
12662  *        write out to fout the declarations (not data) of a user-defined table
12663  */
12664 static void
12665 dumpTable(Archive *fout, TableInfo *tbinfo)
12666 {
12667         if (tbinfo->dobj.dump && !dataOnly)
12668         {
12669                 char       *namecopy;
12670
12671                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12672                         dumpSequence(fout, tbinfo);
12673                 else
12674                         dumpTableSchema(fout, tbinfo);
12675
12676                 /* Handle the ACL here */
12677                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12678                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12679                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12680                                 "TABLE",
12681                                 namecopy, NULL, tbinfo->dobj.name,
12682                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12683                                 tbinfo->relacl);
12684
12685                 /*
12686                  * Handle column ACLs, if any.  Note: we pull these with a separate
12687                  * query rather than trying to fetch them during getTableAttrs, so
12688                  * that we won't miss ACLs on system columns.
12689                  */
12690                 if (fout->remoteVersion >= 80400)
12691                 {
12692                         PQExpBuffer query = createPQExpBuffer();
12693                         PGresult   *res;
12694                         int                     i;
12695
12696                         appendPQExpBuffer(query,
12697                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12698                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12699                                                           "ORDER BY attnum",
12700                                                           tbinfo->dobj.catId.oid);
12701                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12702
12703                         for (i = 0; i < PQntuples(res); i++)
12704                         {
12705                                 char       *attname = PQgetvalue(res, i, 0);
12706                                 char       *attacl = PQgetvalue(res, i, 1);
12707                                 char       *attnamecopy;
12708                                 char       *acltag;
12709
12710                                 attnamecopy = pg_strdup(fmtId(attname));
12711                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12712                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12713                                 /* Column's GRANT type is always TABLE */
12714                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12715                                                 namecopy, attnamecopy, acltag,
12716                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12717                                                 attacl);
12718                                 free(attnamecopy);
12719                                 free(acltag);
12720                         }
12721                         PQclear(res);
12722                         destroyPQExpBuffer(query);
12723                 }
12724
12725                 free(namecopy);
12726         }
12727 }
12728
12729 /*
12730  * Create the AS clause for a view or materialized view. The semicolon is
12731  * stripped because a materialized view must add a WITH NO DATA clause.
12732  *
12733  * This returns a new buffer which must be freed by the caller.
12734  */
12735 static PQExpBuffer
12736 createViewAsClause(Archive *fout, TableInfo *tbinfo)
12737 {
12738         PQExpBuffer query = createPQExpBuffer();
12739         PQExpBuffer result = createPQExpBuffer();
12740         PGresult   *res;
12741         int                     len;
12742
12743         /* Fetch the view definition */
12744         if (fout->remoteVersion >= 70300)
12745         {
12746                 /* Beginning in 7.3, viewname is not unique; rely on OID */
12747                 appendPQExpBuffer(query,
12748                  "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12749                                                   tbinfo->dobj.catId.oid);
12750         }
12751         else
12752         {
12753                 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12754                                                   "FROM pg_views WHERE viewname = ");
12755                 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12756                 appendPQExpBuffer(query, ";");
12757         }
12758
12759         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12760
12761         if (PQntuples(res) != 1)
12762         {
12763                 if (PQntuples(res) < 1)
12764                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12765                                                   tbinfo->dobj.name);
12766                 else
12767                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12768                                                   tbinfo->dobj.name);
12769         }
12770
12771         len = PQgetlength(res, 0, 0);
12772
12773         if (len == 0)
12774                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12775                                           tbinfo->dobj.name);
12776
12777         /* Strip off the trailing semicolon so that other things may follow. */
12778         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
12779         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
12780
12781         PQclear(res);
12782         destroyPQExpBuffer(query);
12783
12784         return result;
12785 }
12786
12787 /*
12788  * dumpTableSchema
12789  *        write the declaration (not data) of one user-defined table or view
12790  */
12791 static void
12792 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12793 {
12794         PQExpBuffer q = createPQExpBuffer();
12795         PQExpBuffer delq = createPQExpBuffer();
12796         PQExpBuffer labelq = createPQExpBuffer();
12797         int                     numParents;
12798         TableInfo **parents;
12799         int                     actual_atts;    /* number of attrs in this CREATE statement */
12800         const char *reltypename;
12801         char       *storage;
12802         char       *srvname;
12803         char       *ftoptions;
12804         int                     j,
12805                                 k;
12806
12807         /* Make sure we are in proper schema */
12808         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12809
12810         if (binary_upgrade)
12811                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12812                                                                                                 tbinfo->dobj.catId.oid);
12813
12814         /* Is it a table or a view? */
12815         if (tbinfo->relkind == RELKIND_VIEW)
12816         {
12817                 PQExpBuffer result;
12818
12819                 reltypename = "VIEW";
12820
12821                 /*
12822                  * DROP must be fully qualified in case same name appears in
12823                  * pg_catalog
12824                  */
12825                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12826                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12827                 appendPQExpBuffer(delq, "%s;\n",
12828                                                   fmtId(tbinfo->dobj.name));
12829
12830                 if (binary_upgrade)
12831                         binary_upgrade_set_pg_class_oids(fout, q,
12832                                                                                          tbinfo->dobj.catId.oid, false);
12833
12834                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12835                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12836                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12837                 result = createViewAsClause(fout, tbinfo);
12838                 appendPQExpBuffer(q, " AS\n%s;\n", result->data);
12839                 destroyPQExpBuffer(result);
12840
12841                 appendPQExpBuffer(labelq, "VIEW %s",
12842                                                   fmtId(tbinfo->dobj.name));
12843         }
12844         else
12845         {
12846                 switch (tbinfo->relkind)
12847                 {
12848                         case (RELKIND_FOREIGN_TABLE):
12849                                 {
12850                                         PQExpBuffer query = createPQExpBuffer();
12851                                         PGresult   *res;
12852                                         int                     i_srvname;
12853                                         int                     i_ftoptions;
12854
12855                                         reltypename = "FOREIGN TABLE";
12856
12857                                         /* retrieve name of foreign server and generic options */
12858                                         appendPQExpBuffer(query,
12859                                                                           "SELECT fs.srvname, "
12860                                                                           "pg_catalog.array_to_string(ARRAY("
12861                                                          "SELECT pg_catalog.quote_ident(option_name) || "
12862                                                          "' ' || pg_catalog.quote_literal(option_value) "
12863                                                         "FROM pg_catalog.pg_options_to_table(ftoptions) "
12864                                                                           "ORDER BY option_name"
12865                                                                           "), E',\n    ') AS ftoptions "
12866                                                                           "FROM pg_catalog.pg_foreign_table ft "
12867                                                                           "JOIN pg_catalog.pg_foreign_server fs "
12868                                                                           "ON (fs.oid = ft.ftserver) "
12869                                                                           "WHERE ft.ftrelid = '%u'",
12870                                                                           tbinfo->dobj.catId.oid);
12871                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12872                                         i_srvname = PQfnumber(res, "srvname");
12873                                         i_ftoptions = PQfnumber(res, "ftoptions");
12874                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12875                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12876                                         PQclear(res);
12877                                         destroyPQExpBuffer(query);
12878                                         break;
12879                                 }
12880                         case (RELKIND_MATVIEW):
12881                                 reltypename = "MATERIALIZED VIEW";
12882                                 srvname = NULL;
12883                                 ftoptions = NULL;
12884                                 break;
12885                         default:
12886                                 reltypename = "TABLE";
12887                                 srvname = NULL;
12888                                 ftoptions = NULL;
12889                 }
12890
12891                 numParents = tbinfo->numParents;
12892                 parents = tbinfo->parents;
12893
12894                 /*
12895                  * DROP must be fully qualified in case same name appears in
12896                  * pg_catalog
12897                  */
12898                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12899                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12900                 appendPQExpBuffer(delq, "%s;\n",
12901                                                   fmtId(tbinfo->dobj.name));
12902
12903                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12904                                                   fmtId(tbinfo->dobj.name));
12905
12906                 if (binary_upgrade)
12907                         binary_upgrade_set_pg_class_oids(fout, q,
12908                                                                                          tbinfo->dobj.catId.oid, false);
12909
12910                 appendPQExpBuffer(q, "CREATE %s%s %s",
12911                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12912                                                   "UNLOGGED " : "",
12913                                                   reltypename,
12914                                                   fmtId(tbinfo->dobj.name));
12915
12916                 /*
12917                  * Attach to type, if reloftype; except in case of a binary upgrade,
12918                  * we dump the table normally and attach it to the type afterward.
12919                  */
12920                 if (tbinfo->reloftype && !binary_upgrade)
12921                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12922
12923                 if (tbinfo->relkind != RELKIND_MATVIEW)
12924                 {
12925                         /* Dump the attributes */
12926                         actual_atts = 0;
12927                         for (j = 0; j < tbinfo->numatts; j++)
12928                         {
12929                                 /*
12930                                  * Normally, dump if it's locally defined in this table, and
12931                                  * not dropped.  But for binary upgrade, we'll dump all the
12932                                  * columns, and then fix up the dropped and nonlocal cases
12933                                  * below.
12934                                  */
12935                                 if (shouldPrintColumn(tbinfo, j))
12936                                 {
12937                                         /*
12938                                          * Default value --- suppress if to be printed separately.
12939                                          */
12940                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12941                                                                                          !tbinfo->attrdefs[j]->separate);
12942
12943                                         /*
12944                                          * Not Null constraint --- suppress if inherited, except
12945                                          * in binary-upgrade case where that won't work.
12946                                          */
12947                                         bool            has_notnull = (tbinfo->notnull[j] &&
12948                                                                                            (!tbinfo->inhNotNull[j] ||
12949                                                                                                 binary_upgrade));
12950
12951                                         /* Skip column if fully defined by reloftype */
12952                                         if (tbinfo->reloftype &&
12953                                                 !has_default && !has_notnull && !binary_upgrade)
12954                                                 continue;
12955
12956                                         /* Format properly if not first attr */
12957                                         if (actual_atts == 0)
12958                                                 appendPQExpBuffer(q, " (");
12959                                         else
12960                                                 appendPQExpBuffer(q, ",");
12961                                         appendPQExpBuffer(q, "\n    ");
12962                                         actual_atts++;
12963
12964                                         /* Attribute name */
12965                                         appendPQExpBuffer(q, "%s",
12966                                                                           fmtId(tbinfo->attnames[j]));
12967
12968                                         if (tbinfo->attisdropped[j])
12969                                         {
12970                                                 /*
12971                                                  * ALTER TABLE DROP COLUMN clears
12972                                                  * pg_attribute.atttypid, so we will not have gotten a
12973                                                  * valid type name; insert INTEGER as a stopgap. We'll
12974                                                  * clean things up later.
12975                                                  */
12976                                                 appendPQExpBuffer(q, " INTEGER /* dummy */");
12977                                                 /* Skip all the rest, too */
12978                                                 continue;
12979                                         }
12980
12981                                         /* Attribute type */
12982                                         if (tbinfo->reloftype && !binary_upgrade)
12983                                         {
12984                                                 appendPQExpBuffer(q, " WITH OPTIONS");
12985                                         }
12986                                         else if (fout->remoteVersion >= 70100)
12987                                         {
12988                                                 appendPQExpBuffer(q, " %s",
12989                                                                                   tbinfo->atttypnames[j]);
12990                                         }
12991                                         else
12992                                         {
12993                                                 /* If no format_type, fake it */
12994                                                 appendPQExpBuffer(q, " %s",
12995                                                                                   myFormatType(tbinfo->atttypnames[j],
12996                                                                                                            tbinfo->atttypmod[j]));
12997                                         }
12998
12999                                         /* Add collation if not default for the type */
13000                                         if (OidIsValid(tbinfo->attcollation[j]))
13001                                         {
13002                                                 CollInfo   *coll;
13003
13004                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
13005                                                 if (coll)
13006                                                 {
13007                                                         /* always schema-qualify, don't try to be smart */
13008                                                         appendPQExpBuffer(q, " COLLATE %s.",
13009                                                                          fmtId(coll->dobj.namespace->dobj.name));
13010                                                         appendPQExpBuffer(q, "%s",
13011                                                                                           fmtId(coll->dobj.name));
13012                                                 }
13013                                         }
13014
13015                                         if (has_default)
13016                                                 appendPQExpBuffer(q, " DEFAULT %s",
13017                                                                                   tbinfo->attrdefs[j]->adef_expr);
13018
13019                                         if (has_notnull)
13020                                                 appendPQExpBuffer(q, " NOT NULL");
13021                                 }
13022                         }
13023
13024                         /*
13025                          * Add non-inherited CHECK constraints, if any.
13026                          */
13027                         for (j = 0; j < tbinfo->ncheck; j++)
13028                         {
13029                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13030
13031                                 if (constr->separate || !constr->conislocal)
13032                                         continue;
13033
13034                                 if (actual_atts == 0)
13035                                         appendPQExpBuffer(q, " (\n    ");
13036                                 else
13037                                         appendPQExpBuffer(q, ",\n    ");
13038
13039                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
13040                                                                   fmtId(constr->dobj.name));
13041                                 appendPQExpBuffer(q, "%s", constr->condef);
13042
13043                                 actual_atts++;
13044                         }
13045
13046                         if (actual_atts)
13047                                 appendPQExpBuffer(q, "\n)");
13048                         else if (!(tbinfo->reloftype && !binary_upgrade))
13049                         {
13050                                 /*
13051                                  * We must have a parenthesized attribute list, even though
13052                                  * empty, when not using the OF TYPE syntax.
13053                                  */
13054                                 appendPQExpBuffer(q, " (\n)");
13055                         }
13056
13057                         if (numParents > 0 && !binary_upgrade)
13058                         {
13059                                 appendPQExpBuffer(q, "\nINHERITS (");
13060                                 for (k = 0; k < numParents; k++)
13061                                 {
13062                                         TableInfo  *parentRel = parents[k];
13063
13064                                         if (k > 0)
13065                                                 appendPQExpBuffer(q, ", ");
13066                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13067                                                 appendPQExpBuffer(q, "%s.",
13068                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
13069                                         appendPQExpBuffer(q, "%s",
13070                                                                           fmtId(parentRel->dobj.name));
13071                                 }
13072                                 appendPQExpBuffer(q, ")");
13073                         }
13074
13075                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
13076                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
13077                 }
13078
13079                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
13080                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
13081                 {
13082                         bool            addcomma = false;
13083
13084                         appendPQExpBuffer(q, "\nWITH (");
13085                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
13086                         {
13087                                 addcomma = true;
13088                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
13089                         }
13090                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
13091                         {
13092                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
13093                                                                   tbinfo->toast_reloptions);
13094                         }
13095                         appendPQExpBuffer(q, ")");
13096                 }
13097
13098                 /* Dump generic options if any */
13099                 if (ftoptions && ftoptions[0])
13100                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
13101
13102                 /*
13103                  * For materialized views, create the AS clause just like a view.
13104                  */
13105                 if (tbinfo->relkind == RELKIND_MATVIEW)
13106                 {
13107                         PQExpBuffer result;
13108
13109                         result = createViewAsClause(fout, tbinfo);
13110                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
13111                                                           result->data);
13112                         destroyPQExpBuffer(result);
13113                 }
13114                 else
13115                         appendPQExpBuffer(q, ";\n");
13116
13117                 /*
13118                  * To create binary-compatible heap files, we have to ensure the same
13119                  * physical column order, including dropped columns, as in the
13120                  * original.  Therefore, we create dropped columns above and drop them
13121                  * here, also updating their attlen/attalign values so that the
13122                  * dropped column can be skipped properly.      (We do not bother with
13123                  * restoring the original attbyval setting.)  Also, inheritance
13124                  * relationships are set up by doing ALTER INHERIT rather than using
13125                  * an INHERITS clause --- the latter would possibly mess up the column
13126                  * order.  That also means we have to take care about setting
13127                  * attislocal correctly, plus fix up any inherited CHECK constraints.
13128                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
13129                  */
13130                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
13131                 {
13132                         for (j = 0; j < tbinfo->numatts; j++)
13133                         {
13134                                 if (tbinfo->attisdropped[j])
13135                                 {
13136                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
13137                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13138                                                                           "SET attlen = %d, "
13139                                                                           "attalign = '%c', attbyval = false\n"
13140                                                                           "WHERE attname = ",
13141                                                                           tbinfo->attlen[j],
13142                                                                           tbinfo->attalign[j]);
13143                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13144                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
13145                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13146                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13147
13148                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13149                                                                           fmtId(tbinfo->dobj.name));
13150                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
13151                                                                           fmtId(tbinfo->attnames[j]));
13152                                 }
13153                                 else if (!tbinfo->attislocal[j])
13154                                 {
13155                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
13156                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13157                                                                           "SET attislocal = false\n"
13158                                                                           "WHERE attname = ");
13159                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13160                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
13161                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13162                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13163                                 }
13164                         }
13165
13166                         for (k = 0; k < tbinfo->ncheck; k++)
13167                         {
13168                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
13169
13170                                 if (constr->separate || constr->conislocal)
13171                                         continue;
13172
13173                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
13174                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13175                                                                   fmtId(tbinfo->dobj.name));
13176                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13177                                                                   fmtId(constr->dobj.name));
13178                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
13179                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
13180                                                                   "SET conislocal = false\n"
13181                                                                   "WHERE contype = 'c' AND conname = ");
13182                                 appendStringLiteralAH(q, constr->dobj.name, fout);
13183                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
13184                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13185                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13186                         }
13187
13188                         if (numParents > 0)
13189                         {
13190                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
13191                                 for (k = 0; k < numParents; k++)
13192                                 {
13193                                         TableInfo  *parentRel = parents[k];
13194
13195                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
13196                                                                           fmtId(tbinfo->dobj.name));
13197                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13198                                                 appendPQExpBuffer(q, "%s.",
13199                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
13200                                         appendPQExpBuffer(q, "%s;\n",
13201                                                                           fmtId(parentRel->dobj.name));
13202                                 }
13203                         }
13204
13205                         if (tbinfo->reloftype)
13206                         {
13207                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
13208                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
13209                                                                   fmtId(tbinfo->dobj.name),
13210                                                                   tbinfo->reloftype);
13211                         }
13212
13213                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
13214                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13215                                                           "SET relfrozenxid = '%u'\n"
13216                                                           "WHERE oid = ",
13217                                                           tbinfo->frozenxid);
13218                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13219                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13220
13221                         if (tbinfo->toast_oid)
13222                         {
13223                                 /* We preserve the toast oids, so we can use it during restore */
13224                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
13225                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13226                                                                   "SET relfrozenxid = '%u'\n"
13227                                                                   "WHERE oid = '%u';\n",
13228                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
13229                         }
13230                 }
13231
13232                 /*
13233                  * Dump additional per-column properties that we can't handle in the
13234                  * main CREATE TABLE command.
13235                  */
13236                 for (j = 0; j < tbinfo->numatts; j++)
13237                 {
13238                         /* None of this applies to dropped columns */
13239                         if (tbinfo->attisdropped[j])
13240                                 continue;
13241
13242                         /*
13243                          * If we didn't dump the column definition explicitly above, and
13244                          * it is NOT NULL and did not inherit that property from a parent,
13245                          * we have to mark it separately.
13246                          */
13247                         if (!shouldPrintColumn(tbinfo, j) &&
13248                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
13249                         {
13250                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13251                                                                   fmtId(tbinfo->dobj.name));
13252                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
13253                                                                   fmtId(tbinfo->attnames[j]));
13254                         }
13255
13256                         /*
13257                          * Dump per-column statistics information. We only issue an ALTER
13258                          * TABLE statement if the attstattarget entry for this column is
13259                          * non-negative (i.e. it's not the default value)
13260                          */
13261                         if (tbinfo->attstattarget[j] >= 0)
13262                         {
13263                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13264                                                                   fmtId(tbinfo->dobj.name));
13265                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13266                                                                   fmtId(tbinfo->attnames[j]));
13267                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
13268                                                                   tbinfo->attstattarget[j]);
13269                         }
13270
13271                         /*
13272                          * Dump per-column storage information.  The statement is only
13273                          * dumped if the storage has been changed from the type's default.
13274                          */
13275                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
13276                         {
13277                                 switch (tbinfo->attstorage[j])
13278                                 {
13279                                         case 'p':
13280                                                 storage = "PLAIN";
13281                                                 break;
13282                                         case 'e':
13283                                                 storage = "EXTERNAL";
13284                                                 break;
13285                                         case 'm':
13286                                                 storage = "MAIN";
13287                                                 break;
13288                                         case 'x':
13289                                                 storage = "EXTENDED";
13290                                                 break;
13291                                         default:
13292                                                 storage = NULL;
13293                                 }
13294
13295                                 /*
13296                                  * Only dump the statement if it's a storage type we recognize
13297                                  */
13298                                 if (storage != NULL)
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 STORAGE %s;\n",
13305                                                                           storage);
13306                                 }
13307                         }
13308
13309                         /*
13310                          * Dump per-column attributes.
13311                          */
13312                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
13313                         {
13314                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13315                                                                   fmtId(tbinfo->dobj.name));
13316                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13317                                                                   fmtId(tbinfo->attnames[j]));
13318                                 appendPQExpBuffer(q, "SET (%s);\n",
13319                                                                   tbinfo->attoptions[j]);
13320                         }
13321
13322                         /*
13323                          * Dump per-column fdw options.
13324                          */
13325                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
13326                                 tbinfo->attfdwoptions[j] &&
13327                                 tbinfo->attfdwoptions[j][0] != '\0')
13328                         {
13329                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13330                                                                   fmtId(tbinfo->dobj.name));
13331                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13332                                                                   fmtId(tbinfo->attnames[j]));
13333                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
13334                                                                   tbinfo->attfdwoptions[j]);
13335                         }
13336                 }
13337         }
13338
13339         if (binary_upgrade)
13340                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
13341
13342         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13343                                  tbinfo->dobj.name,
13344                                  tbinfo->dobj.namespace->dobj.name,
13345                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
13346                                  tbinfo->rolname,
13347                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
13348                                  reltypename, SECTION_PRE_DATA,
13349                                  q->data, delq->data, NULL,
13350                                  NULL, 0,
13351                                  NULL, NULL);
13352
13353
13354         /* Dump Table Comments */
13355         dumpTableComment(fout, tbinfo, reltypename);
13356
13357         /* Dump Table Security Labels */
13358         dumpTableSecLabel(fout, tbinfo, reltypename);
13359
13360         /* Dump comments on inlined table constraints */
13361         for (j = 0; j < tbinfo->ncheck; j++)
13362         {
13363                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13364
13365                 if (constr->separate || !constr->conislocal)
13366                         continue;
13367
13368                 dumpTableConstraintComment(fout, constr);
13369         }
13370
13371         destroyPQExpBuffer(q);
13372         destroyPQExpBuffer(delq);
13373         destroyPQExpBuffer(labelq);
13374 }
13375
13376 /*
13377  * dumpAttrDef --- dump an attribute's default-value declaration
13378  */
13379 static void
13380 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13381 {
13382         TableInfo  *tbinfo = adinfo->adtable;
13383         int                     adnum = adinfo->adnum;
13384         PQExpBuffer q;
13385         PQExpBuffer delq;
13386
13387         /* Skip if table definition not to be dumped */
13388         if (!tbinfo->dobj.dump || dataOnly)
13389                 return;
13390
13391         /* Skip if not "separate"; it was dumped in the table's definition */
13392         if (!adinfo->separate)
13393                 return;
13394
13395         q = createPQExpBuffer();
13396         delq = createPQExpBuffer();
13397
13398         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13399                                           fmtId(tbinfo->dobj.name));
13400         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13401                                           fmtId(tbinfo->attnames[adnum - 1]),
13402                                           adinfo->adef_expr);
13403
13404         /*
13405          * DROP must be fully qualified in case same name appears in pg_catalog
13406          */
13407         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13408                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13409         appendPQExpBuffer(delq, "%s ",
13410                                           fmtId(tbinfo->dobj.name));
13411         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13412                                           fmtId(tbinfo->attnames[adnum - 1]));
13413
13414         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13415                                  tbinfo->attnames[adnum - 1],
13416                                  tbinfo->dobj.namespace->dobj.name,
13417                                  NULL,
13418                                  tbinfo->rolname,
13419                                  false, "DEFAULT", SECTION_PRE_DATA,
13420                                  q->data, delq->data, NULL,
13421                                  NULL, 0,
13422                                  NULL, NULL);
13423
13424         destroyPQExpBuffer(q);
13425         destroyPQExpBuffer(delq);
13426 }
13427
13428 /*
13429  * getAttrName: extract the correct name for an attribute
13430  *
13431  * The array tblInfo->attnames[] only provides names of user attributes;
13432  * if a system attribute number is supplied, we have to fake it.
13433  * We also do a little bit of bounds checking for safety's sake.
13434  */
13435 static const char *
13436 getAttrName(int attrnum, TableInfo *tblInfo)
13437 {
13438         if (attrnum > 0 && attrnum <= tblInfo->numatts)
13439                 return tblInfo->attnames[attrnum - 1];
13440         switch (attrnum)
13441         {
13442                 case SelfItemPointerAttributeNumber:
13443                         return "ctid";
13444                 case ObjectIdAttributeNumber:
13445                         return "oid";
13446                 case MinTransactionIdAttributeNumber:
13447                         return "xmin";
13448                 case MinCommandIdAttributeNumber:
13449                         return "cmin";
13450                 case MaxTransactionIdAttributeNumber:
13451                         return "xmax";
13452                 case MaxCommandIdAttributeNumber:
13453                         return "cmax";
13454                 case TableOidAttributeNumber:
13455                         return "tableoid";
13456         }
13457         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13458                                   attrnum, tblInfo->dobj.name);
13459         return NULL;                            /* keep compiler quiet */
13460 }
13461
13462 /*
13463  * dumpIndex
13464  *        write out to fout a user-defined index
13465  */
13466 static void
13467 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13468 {
13469         TableInfo  *tbinfo = indxinfo->indextable;
13470         PQExpBuffer q;
13471         PQExpBuffer delq;
13472         PQExpBuffer labelq;
13473
13474         if (dataOnly)
13475                 return;
13476
13477         q = createPQExpBuffer();
13478         delq = createPQExpBuffer();
13479         labelq = createPQExpBuffer();
13480
13481         appendPQExpBuffer(labelq, "INDEX %s",
13482                                           fmtId(indxinfo->dobj.name));
13483
13484         /*
13485          * If there's an associated constraint, don't dump the index per se, but
13486          * do dump any comment for it.  (This is safe because dependency ordering
13487          * will have ensured the constraint is emitted first.)
13488          */
13489         if (indxinfo->indexconstraint == 0)
13490         {
13491                 if (binary_upgrade)
13492                         binary_upgrade_set_pg_class_oids(fout, q,
13493                                                                                          indxinfo->dobj.catId.oid, true);
13494
13495                 /* Plain secondary index */
13496                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13497
13498                 /* If the index is clustered, we need to record that. */
13499                 if (indxinfo->indisclustered)
13500                 {
13501                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13502                                                           fmtId(tbinfo->dobj.name));
13503                         appendPQExpBuffer(q, " ON %s;\n",
13504                                                           fmtId(indxinfo->dobj.name));
13505                 }
13506
13507                 /*
13508                  * DROP must be fully qualified in case same name appears in
13509                  * pg_catalog
13510                  */
13511                 appendPQExpBuffer(delq, "DROP INDEX %s.",
13512                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13513                 appendPQExpBuffer(delq, "%s;\n",
13514                                                   fmtId(indxinfo->dobj.name));
13515
13516                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13517                                          indxinfo->dobj.name,
13518                                          tbinfo->dobj.namespace->dobj.name,
13519                                          indxinfo->tablespace,
13520                                          tbinfo->rolname, false,
13521                                          "INDEX", SECTION_POST_DATA,
13522                                          q->data, delq->data, NULL,
13523                                          NULL, 0,
13524                                          NULL, NULL);
13525         }
13526
13527         /* Dump Index Comments */
13528         dumpComment(fout, labelq->data,
13529                                 tbinfo->dobj.namespace->dobj.name,
13530                                 tbinfo->rolname,
13531                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13532
13533         destroyPQExpBuffer(q);
13534         destroyPQExpBuffer(delq);
13535         destroyPQExpBuffer(labelq);
13536 }
13537
13538 /*
13539  * dumpConstraint
13540  *        write out to fout a user-defined constraint
13541  */
13542 static void
13543 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13544 {
13545         TableInfo  *tbinfo = coninfo->contable;
13546         PQExpBuffer q;
13547         PQExpBuffer delq;
13548
13549         /* Skip if not to be dumped */
13550         if (!coninfo->dobj.dump || dataOnly)
13551                 return;
13552
13553         q = createPQExpBuffer();
13554         delq = createPQExpBuffer();
13555
13556         if (coninfo->contype == 'p' ||
13557                 coninfo->contype == 'u' ||
13558                 coninfo->contype == 'x')
13559         {
13560                 /* Index-related constraint */
13561                 IndxInfo   *indxinfo;
13562                 int                     k;
13563
13564                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13565
13566                 if (indxinfo == NULL)
13567                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13568                                                   coninfo->dobj.name);
13569
13570                 if (binary_upgrade)
13571                         binary_upgrade_set_pg_class_oids(fout, q,
13572                                                                                          indxinfo->dobj.catId.oid, true);
13573
13574                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13575                                                   fmtId(tbinfo->dobj.name));
13576                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
13577                                                   fmtId(coninfo->dobj.name));
13578
13579                 if (coninfo->condef)
13580                 {
13581                         /* pg_get_constraintdef should have provided everything */
13582                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13583                 }
13584                 else
13585                 {
13586                         appendPQExpBuffer(q, "%s (",
13587                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13588                         for (k = 0; k < indxinfo->indnkeys; k++)
13589                         {
13590                                 int                     indkey = (int) indxinfo->indkeys[k];
13591                                 const char *attname;
13592
13593                                 if (indkey == InvalidAttrNumber)
13594                                         break;
13595                                 attname = getAttrName(indkey, tbinfo);
13596
13597                                 appendPQExpBuffer(q, "%s%s",
13598                                                                   (k == 0) ? "" : ", ",
13599                                                                   fmtId(attname));
13600                         }
13601
13602                         appendPQExpBuffer(q, ")");
13603
13604                         if (indxinfo->options && strlen(indxinfo->options) > 0)
13605                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13606
13607                         if (coninfo->condeferrable)
13608                         {
13609                                 appendPQExpBuffer(q, " DEFERRABLE");
13610                                 if (coninfo->condeferred)
13611                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
13612                         }
13613
13614                         appendPQExpBuffer(q, ";\n");
13615                 }
13616
13617                 /* If the index is clustered, we need to record that. */
13618                 if (indxinfo->indisclustered)
13619                 {
13620                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13621                                                           fmtId(tbinfo->dobj.name));
13622                         appendPQExpBuffer(q, " ON %s;\n",
13623                                                           fmtId(indxinfo->dobj.name));
13624                 }
13625
13626                 /*
13627                  * DROP must be fully qualified in case same name appears in
13628                  * pg_catalog
13629                  */
13630                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13631                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13632                 appendPQExpBuffer(delq, "%s ",
13633                                                   fmtId(tbinfo->dobj.name));
13634                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13635                                                   fmtId(coninfo->dobj.name));
13636
13637                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13638                                          coninfo->dobj.name,
13639                                          tbinfo->dobj.namespace->dobj.name,
13640                                          indxinfo->tablespace,
13641                                          tbinfo->rolname, false,
13642                                          "CONSTRAINT", SECTION_POST_DATA,
13643                                          q->data, delq->data, NULL,
13644                                          NULL, 0,
13645                                          NULL, NULL);
13646         }
13647         else if (coninfo->contype == 'f')
13648         {
13649                 /*
13650                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13651                  * current table data is not processed
13652                  */
13653                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13654                                                   fmtId(tbinfo->dobj.name));
13655                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13656                                                   fmtId(coninfo->dobj.name),
13657                                                   coninfo->condef);
13658
13659                 /*
13660                  * DROP must be fully qualified in case same name appears in
13661                  * pg_catalog
13662                  */
13663                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13664                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13665                 appendPQExpBuffer(delq, "%s ",
13666                                                   fmtId(tbinfo->dobj.name));
13667                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13668                                                   fmtId(coninfo->dobj.name));
13669
13670                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13671                                          coninfo->dobj.name,
13672                                          tbinfo->dobj.namespace->dobj.name,
13673                                          NULL,
13674                                          tbinfo->rolname, false,
13675                                          "FK CONSTRAINT", SECTION_POST_DATA,
13676                                          q->data, delq->data, NULL,
13677                                          NULL, 0,
13678                                          NULL, NULL);
13679         }
13680         else if (coninfo->contype == 'c' && tbinfo)
13681         {
13682                 /* CHECK constraint on a table */
13683
13684                 /* Ignore if not to be dumped separately */
13685                 if (coninfo->separate)
13686                 {
13687                         /* not ONLY since we want it to propagate to children */
13688                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13689                                                           fmtId(tbinfo->dobj.name));
13690                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13691                                                           fmtId(coninfo->dobj.name),
13692                                                           coninfo->condef);
13693
13694                         /*
13695                          * DROP must be fully qualified in case same name appears in
13696                          * pg_catalog
13697                          */
13698                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13699                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13700                         appendPQExpBuffer(delq, "%s ",
13701                                                           fmtId(tbinfo->dobj.name));
13702                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13703                                                           fmtId(coninfo->dobj.name));
13704
13705                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13706                                                  coninfo->dobj.name,
13707                                                  tbinfo->dobj.namespace->dobj.name,
13708                                                  NULL,
13709                                                  tbinfo->rolname, false,
13710                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13711                                                  q->data, delq->data, NULL,
13712                                                  NULL, 0,
13713                                                  NULL, NULL);
13714                 }
13715         }
13716         else if (coninfo->contype == 'c' && tbinfo == NULL)
13717         {
13718                 /* CHECK constraint on a domain */
13719                 TypeInfo   *tyinfo = coninfo->condomain;
13720
13721                 /* Ignore if not to be dumped separately */
13722                 if (coninfo->separate)
13723                 {
13724                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13725                                                           fmtId(tyinfo->dobj.name));
13726                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13727                                                           fmtId(coninfo->dobj.name),
13728                                                           coninfo->condef);
13729
13730                         /*
13731                          * DROP must be fully qualified in case same name appears in
13732                          * pg_catalog
13733                          */
13734                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13735                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13736                         appendPQExpBuffer(delq, "%s ",
13737                                                           fmtId(tyinfo->dobj.name));
13738                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13739                                                           fmtId(coninfo->dobj.name));
13740
13741                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13742                                                  coninfo->dobj.name,
13743                                                  tyinfo->dobj.namespace->dobj.name,
13744                                                  NULL,
13745                                                  tyinfo->rolname, false,
13746                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13747                                                  q->data, delq->data, NULL,
13748                                                  NULL, 0,
13749                                                  NULL, NULL);
13750                 }
13751         }
13752         else
13753         {
13754                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13755                                           coninfo->contype);
13756         }
13757
13758         /* Dump Constraint Comments --- only works for table constraints */
13759         if (tbinfo && coninfo->separate)
13760                 dumpTableConstraintComment(fout, coninfo);
13761
13762         destroyPQExpBuffer(q);
13763         destroyPQExpBuffer(delq);
13764 }
13765
13766 /*
13767  * dumpTableConstraintComment --- dump a constraint's comment if any
13768  *
13769  * This is split out because we need the function in two different places
13770  * depending on whether the constraint is dumped as part of CREATE TABLE
13771  * or as a separate ALTER command.
13772  */
13773 static void
13774 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13775 {
13776         TableInfo  *tbinfo = coninfo->contable;
13777         PQExpBuffer labelq = createPQExpBuffer();
13778
13779         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13780                                           fmtId(coninfo->dobj.name));
13781         appendPQExpBuffer(labelq, "ON %s",
13782                                           fmtId(tbinfo->dobj.name));
13783         dumpComment(fout, labelq->data,
13784                                 tbinfo->dobj.namespace->dobj.name,
13785                                 tbinfo->rolname,
13786                                 coninfo->dobj.catId, 0,
13787                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13788
13789         destroyPQExpBuffer(labelq);
13790 }
13791
13792 /*
13793  * findLastBuiltInOid -
13794  * find the last built in oid
13795  *
13796  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13797  * pg_database entry for the current database
13798  */
13799 static Oid
13800 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13801 {
13802         PGresult   *res;
13803         Oid                     last_oid;
13804         PQExpBuffer query = createPQExpBuffer();
13805
13806         resetPQExpBuffer(query);
13807         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13808         appendStringLiteralAH(query, dbname, fout);
13809
13810         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13811         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13812         PQclear(res);
13813         destroyPQExpBuffer(query);
13814         return last_oid;
13815 }
13816
13817 /*
13818  * findLastBuiltInOid -
13819  * find the last built in oid
13820  *
13821  * For 7.0, we do this by assuming that the last thing that initdb does is to
13822  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13823  * initdb won't be changing anymore, it'll do.
13824  */
13825 static Oid
13826 findLastBuiltinOid_V70(Archive *fout)
13827 {
13828         PGresult   *res;
13829         int                     last_oid;
13830
13831         res = ExecuteSqlQueryForSingleRow(fout,
13832                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13833         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13834         PQclear(res);
13835         return last_oid;
13836 }
13837
13838 /*
13839  * dumpSequence
13840  *        write the declaration (not data) of one user-defined sequence
13841  */
13842 static void
13843 dumpSequence(Archive *fout, TableInfo *tbinfo)
13844 {
13845         PGresult   *res;
13846         char       *startv,
13847                            *incby,
13848                            *maxv = NULL,
13849                            *minv = NULL,
13850                            *cache;
13851         char            bufm[100],
13852                                 bufx[100];
13853         bool            cycled;
13854         PQExpBuffer query = createPQExpBuffer();
13855         PQExpBuffer delqry = createPQExpBuffer();
13856         PQExpBuffer labelq = createPQExpBuffer();
13857
13858         /* Make sure we are in proper schema */
13859         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13860
13861         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13862         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13863
13864         if (fout->remoteVersion >= 80400)
13865         {
13866                 appendPQExpBuffer(query,
13867                                                   "SELECT sequence_name, "
13868                                                   "start_value, increment_by, "
13869                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13870                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13871                                                   "     ELSE max_value "
13872                                                   "END AS max_value, "
13873                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13874                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13875                                                   "     ELSE min_value "
13876                                                   "END AS min_value, "
13877                                                   "cache_value, is_cycled FROM %s",
13878                                                   bufx, bufm,
13879                                                   fmtId(tbinfo->dobj.name));
13880         }
13881         else
13882         {
13883                 appendPQExpBuffer(query,
13884                                                   "SELECT sequence_name, "
13885                                                   "0 AS start_value, increment_by, "
13886                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13887                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13888                                                   "     ELSE max_value "
13889                                                   "END AS max_value, "
13890                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13891                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13892                                                   "     ELSE min_value "
13893                                                   "END AS min_value, "
13894                                                   "cache_value, is_cycled FROM %s",
13895                                                   bufx, bufm,
13896                                                   fmtId(tbinfo->dobj.name));
13897         }
13898
13899         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13900
13901         if (PQntuples(res) != 1)
13902         {
13903                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13904                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13905                                                                  PQntuples(res)),
13906                                   tbinfo->dobj.name, PQntuples(res));
13907                 exit_nicely(1);
13908         }
13909
13910         /* Disable this check: it fails if sequence has been renamed */
13911 #ifdef NOT_USED
13912         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13913         {
13914                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13915                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13916                 exit_nicely(1);
13917         }
13918 #endif
13919
13920         startv = PQgetvalue(res, 0, 1);
13921         incby = PQgetvalue(res, 0, 2);
13922         if (!PQgetisnull(res, 0, 3))
13923                 maxv = PQgetvalue(res, 0, 3);
13924         if (!PQgetisnull(res, 0, 4))
13925                 minv = PQgetvalue(res, 0, 4);
13926         cache = PQgetvalue(res, 0, 5);
13927         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13928
13929         /*
13930          * DROP must be fully qualified in case same name appears in pg_catalog
13931          */
13932         appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13933                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13934         appendPQExpBuffer(delqry, "%s;\n",
13935                                           fmtId(tbinfo->dobj.name));
13936
13937         resetPQExpBuffer(query);
13938
13939         if (binary_upgrade)
13940         {
13941                 binary_upgrade_set_pg_class_oids(fout, query,
13942                                                                                  tbinfo->dobj.catId.oid, false);
13943                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13944                                                                                                 tbinfo->dobj.catId.oid);
13945         }
13946
13947         appendPQExpBuffer(query,
13948                                           "CREATE SEQUENCE %s\n",
13949                                           fmtId(tbinfo->dobj.name));
13950
13951         if (fout->remoteVersion >= 80400)
13952                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
13953
13954         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13955
13956         if (minv)
13957                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13958         else
13959                 appendPQExpBuffer(query, "    NO MINVALUE\n");
13960
13961         if (maxv)
13962                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13963         else
13964                 appendPQExpBuffer(query, "    NO MAXVALUE\n");
13965
13966         appendPQExpBuffer(query,
13967                                           "    CACHE %s%s",
13968                                           cache, (cycled ? "\n    CYCLE" : ""));
13969
13970         appendPQExpBuffer(query, ";\n");
13971
13972         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13973
13974         /* binary_upgrade:      no need to clear TOAST table oid */
13975
13976         if (binary_upgrade)
13977                 binary_upgrade_extension_member(query, &tbinfo->dobj,
13978                                                                                 labelq->data);
13979
13980         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13981                                  tbinfo->dobj.name,
13982                                  tbinfo->dobj.namespace->dobj.name,
13983                                  NULL,
13984                                  tbinfo->rolname,
13985                                  false, "SEQUENCE", SECTION_PRE_DATA,
13986                                  query->data, delqry->data, NULL,
13987                                  NULL, 0,
13988                                  NULL, NULL);
13989
13990         /*
13991          * If the sequence is owned by a table column, emit the ALTER for it as a
13992          * separate TOC entry immediately following the sequence's own entry. It's
13993          * OK to do this rather than using full sorting logic, because the
13994          * dependency that tells us it's owned will have forced the table to be
13995          * created first.  We can't just include the ALTER in the TOC entry
13996          * because it will fail if we haven't reassigned the sequence owner to
13997          * match the table's owner.
13998          *
13999          * We need not schema-qualify the table reference because both sequence
14000          * and table must be in the same schema.
14001          */
14002         if (OidIsValid(tbinfo->owning_tab))
14003         {
14004                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
14005
14006                 if (owning_tab && owning_tab->dobj.dump)
14007                 {
14008                         resetPQExpBuffer(query);
14009                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
14010                                                           fmtId(tbinfo->dobj.name));
14011                         appendPQExpBuffer(query, " OWNED BY %s",
14012                                                           fmtId(owning_tab->dobj.name));
14013                         appendPQExpBuffer(query, ".%s;\n",
14014                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
14015
14016                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
14017                                                  tbinfo->dobj.name,
14018                                                  tbinfo->dobj.namespace->dobj.name,
14019                                                  NULL,
14020                                                  tbinfo->rolname,
14021                                                  false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
14022                                                  query->data, "", NULL,
14023                                                  &(tbinfo->dobj.dumpId), 1,
14024                                                  NULL, NULL);
14025                 }
14026         }
14027
14028         /* Dump Sequence Comments and Security Labels */
14029         dumpComment(fout, labelq->data,
14030                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14031                                 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14032         dumpSecLabel(fout, labelq->data,
14033                                  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14034                                  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14035
14036         PQclear(res);
14037
14038         destroyPQExpBuffer(query);
14039         destroyPQExpBuffer(delqry);
14040         destroyPQExpBuffer(labelq);
14041 }
14042
14043 /*
14044  * dumpSequenceData
14045  *        write the data of one user-defined sequence
14046  */
14047 static void
14048 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
14049 {
14050         TableInfo  *tbinfo = tdinfo->tdtable;
14051         PGresult   *res;
14052         char       *last;
14053         bool            called;
14054         PQExpBuffer query = createPQExpBuffer();
14055
14056         /* Make sure we are in proper schema */
14057         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14058
14059         appendPQExpBuffer(query,
14060                                           "SELECT last_value, is_called FROM %s",
14061                                           fmtId(tbinfo->dobj.name));
14062
14063         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14064
14065         if (PQntuples(res) != 1)
14066         {
14067                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
14068                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
14069                                                                  PQntuples(res)),
14070                                   tbinfo->dobj.name, PQntuples(res));
14071                 exit_nicely(1);
14072         }
14073
14074         last = PQgetvalue(res, 0, 0);
14075         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
14076
14077         resetPQExpBuffer(query);
14078         appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
14079         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
14080         appendPQExpBuffer(query, ", %s, %s);\n",
14081                                           last, (called ? "true" : "false"));
14082
14083         ArchiveEntry(fout, nilCatalogId, createDumpId(),
14084                                  tbinfo->dobj.name,
14085                                  tbinfo->dobj.namespace->dobj.name,
14086                                  NULL,
14087                                  tbinfo->rolname,
14088                                  false, "SEQUENCE SET", SECTION_DATA,
14089                                  query->data, "", NULL,
14090                                  &(tbinfo->dobj.dumpId), 1,
14091                                  NULL, NULL);
14092
14093         PQclear(res);
14094
14095         destroyPQExpBuffer(query);
14096 }
14097
14098 static void
14099 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
14100 {
14101         TableInfo  *tbinfo = tginfo->tgtable;
14102         PQExpBuffer query;
14103         PQExpBuffer delqry;
14104         PQExpBuffer labelq;
14105         char       *tgargs;
14106         size_t          lentgargs;
14107         const char *p;
14108         int                     findx;
14109
14110         if (dataOnly)
14111                 return;
14112
14113         query = createPQExpBuffer();
14114         delqry = createPQExpBuffer();
14115         labelq = createPQExpBuffer();
14116
14117         /*
14118          * DROP must be fully qualified in case same name appears in pg_catalog
14119          */
14120         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
14121                                           fmtId(tginfo->dobj.name));
14122         appendPQExpBuffer(delqry, "ON %s.",
14123                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14124         appendPQExpBuffer(delqry, "%s;\n",
14125                                           fmtId(tbinfo->dobj.name));
14126
14127         if (tginfo->tgdef)
14128         {
14129                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
14130         }
14131         else
14132         {
14133                 if (tginfo->tgisconstraint)
14134                 {
14135                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
14136                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
14137                 }
14138                 else
14139                 {
14140                         appendPQExpBuffer(query, "CREATE TRIGGER ");
14141                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
14142                 }
14143                 appendPQExpBuffer(query, "\n    ");
14144
14145                 /* Trigger type */
14146                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
14147                         appendPQExpBuffer(query, "BEFORE");
14148                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
14149                         appendPQExpBuffer(query, "AFTER");
14150                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
14151                         appendPQExpBuffer(query, "INSTEAD OF");
14152                 else
14153                 {
14154                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
14155                         exit_nicely(1);
14156                 }
14157
14158                 findx = 0;
14159                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
14160                 {
14161                         appendPQExpBuffer(query, " INSERT");
14162                         findx++;
14163                 }
14164                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
14165                 {
14166                         if (findx > 0)
14167                                 appendPQExpBuffer(query, " OR DELETE");
14168                         else
14169                                 appendPQExpBuffer(query, " DELETE");
14170                         findx++;
14171                 }
14172                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
14173                 {
14174                         if (findx > 0)
14175                                 appendPQExpBuffer(query, " OR UPDATE");
14176                         else
14177                                 appendPQExpBuffer(query, " UPDATE");
14178                         findx++;
14179                 }
14180                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
14181                 {
14182                         if (findx > 0)
14183                                 appendPQExpBuffer(query, " OR TRUNCATE");
14184                         else
14185                                 appendPQExpBuffer(query, " TRUNCATE");
14186                         findx++;
14187                 }
14188                 appendPQExpBuffer(query, " ON %s\n",
14189                                                   fmtId(tbinfo->dobj.name));
14190
14191                 if (tginfo->tgisconstraint)
14192                 {
14193                         if (OidIsValid(tginfo->tgconstrrelid))
14194                         {
14195                                 /* If we are using regclass, name is already quoted */
14196                                 if (fout->remoteVersion >= 70300)
14197                                         appendPQExpBuffer(query, "    FROM %s\n    ",
14198                                                                           tginfo->tgconstrrelname);
14199                                 else
14200                                         appendPQExpBuffer(query, "    FROM %s\n    ",
14201                                                                           fmtId(tginfo->tgconstrrelname));
14202                         }
14203                         if (!tginfo->tgdeferrable)
14204                                 appendPQExpBuffer(query, "NOT ");
14205                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
14206                         if (tginfo->tginitdeferred)
14207                                 appendPQExpBuffer(query, "DEFERRED\n");
14208                         else
14209                                 appendPQExpBuffer(query, "IMMEDIATE\n");
14210                 }
14211
14212                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
14213                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
14214                 else
14215                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
14216
14217                 /* In 7.3, result of regproc is already quoted */
14218                 if (fout->remoteVersion >= 70300)
14219                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14220                                                           tginfo->tgfname);
14221                 else
14222                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14223                                                           fmtId(tginfo->tgfname));
14224
14225                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
14226                                                                                   &lentgargs);
14227                 p = tgargs;
14228                 for (findx = 0; findx < tginfo->tgnargs; findx++)
14229                 {
14230                         /* find the embedded null that terminates this trigger argument */
14231                         size_t          tlen = strlen(p);
14232
14233                         if (p + tlen >= tgargs + lentgargs)
14234                         {
14235                                 /* hm, not found before end of bytea value... */
14236                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
14237                                                   tginfo->tgargs,
14238                                                   tginfo->dobj.name,
14239                                                   tbinfo->dobj.name);
14240                                 exit_nicely(1);
14241                         }
14242
14243                         if (findx > 0)
14244                                 appendPQExpBuffer(query, ", ");
14245                         appendStringLiteralAH(query, p, fout);
14246                         p += tlen + 1;
14247                 }
14248                 free(tgargs);
14249                 appendPQExpBuffer(query, ");\n");
14250         }
14251
14252         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
14253         {
14254                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
14255                                                   fmtId(tbinfo->dobj.name));
14256                 switch (tginfo->tgenabled)
14257                 {
14258                         case 'D':
14259                         case 'f':
14260                                 appendPQExpBuffer(query, "DISABLE");
14261                                 break;
14262                         case 'A':
14263                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
14264                                 break;
14265                         case 'R':
14266                                 appendPQExpBuffer(query, "ENABLE REPLICA");
14267                                 break;
14268                         default:
14269                                 appendPQExpBuffer(query, "ENABLE");
14270                                 break;
14271                 }
14272                 appendPQExpBuffer(query, " TRIGGER %s;\n",
14273                                                   fmtId(tginfo->dobj.name));
14274         }
14275
14276         appendPQExpBuffer(labelq, "TRIGGER %s ",
14277                                           fmtId(tginfo->dobj.name));
14278         appendPQExpBuffer(labelq, "ON %s",
14279                                           fmtId(tbinfo->dobj.name));
14280
14281         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
14282                                  tginfo->dobj.name,
14283                                  tbinfo->dobj.namespace->dobj.name,
14284                                  NULL,
14285                                  tbinfo->rolname, false,
14286                                  "TRIGGER", SECTION_POST_DATA,
14287                                  query->data, delqry->data, NULL,
14288                                  NULL, 0,
14289                                  NULL, NULL);
14290
14291         dumpComment(fout, labelq->data,
14292                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14293                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
14294
14295         destroyPQExpBuffer(query);
14296         destroyPQExpBuffer(delqry);
14297         destroyPQExpBuffer(labelq);
14298 }
14299
14300 static void
14301 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
14302 {
14303         PQExpBuffer query;
14304         PQExpBuffer labelq;
14305
14306         query = createPQExpBuffer();
14307         labelq = createPQExpBuffer();
14308
14309         appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
14310         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
14311         appendPQExpBuffer(query, " ON ");
14312         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
14313         appendPQExpBufferStr(query, " ");
14314
14315         if (strcmp("", evtinfo->evttags) != 0)
14316         {
14317                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
14318                 appendPQExpBufferStr(query, evtinfo->evttags);
14319                 appendPQExpBufferStr(query, ") ");
14320         }
14321
14322         appendPQExpBuffer(query, "\n   EXECUTE PROCEDURE ");
14323         appendPQExpBufferStr(query, evtinfo->evtfname);
14324         appendPQExpBuffer(query, "();\n");
14325
14326         if (evtinfo->evtenabled != 'O')
14327         {
14328                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
14329                                                   fmtId(evtinfo->dobj.name));
14330                 switch (evtinfo->evtenabled)
14331                 {
14332                         case 'D':
14333                                 appendPQExpBuffer(query, "DISABLE");
14334                                 break;
14335                         case 'A':
14336                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
14337                                 break;
14338                         case 'R':
14339                                 appendPQExpBuffer(query, "ENABLE REPLICA");
14340                                 break;
14341                         default:
14342                                 appendPQExpBuffer(query, "ENABLE");
14343                                 break;
14344                 }
14345                 appendPQExpBuffer(query, ";\n");
14346         }
14347         appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
14348                                           fmtId(evtinfo->dobj.name));
14349
14350         ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
14351                                  evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
14352                                  "EVENT TRIGGER", SECTION_POST_DATA,
14353                                  query->data, "", NULL, NULL, 0, NULL, NULL);
14354
14355         dumpComment(fout, labelq->data,
14356                                 NULL, NULL,
14357                                 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
14358
14359         destroyPQExpBuffer(query);
14360         destroyPQExpBuffer(labelq);
14361 }
14362
14363 /*
14364  * dumpRule
14365  *              Dump a rule
14366  */
14367 static void
14368 dumpRule(Archive *fout, RuleInfo *rinfo)
14369 {
14370         TableInfo  *tbinfo = rinfo->ruletable;
14371         PQExpBuffer query;
14372         PQExpBuffer cmd;
14373         PQExpBuffer delcmd;
14374         PQExpBuffer labelq;
14375         PGresult   *res;
14376
14377         /* Skip if not to be dumped */
14378         if (!rinfo->dobj.dump || dataOnly)
14379                 return;
14380
14381         /*
14382          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
14383          * we do not want to dump it as a separate object.
14384          */
14385         if (!rinfo->separate)
14386                 return;
14387
14388         /*
14389          * Make sure we are in proper schema.
14390          */
14391         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14392
14393         query = createPQExpBuffer();
14394         cmd = createPQExpBuffer();
14395         delcmd = createPQExpBuffer();
14396         labelq = createPQExpBuffer();
14397
14398         if (fout->remoteVersion >= 70300)
14399         {
14400                 appendPQExpBuffer(query,
14401                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14402                                                   rinfo->dobj.catId.oid);
14403         }
14404         else
14405         {
14406                 /* Rule name was unique before 7.3 ... */
14407                 appendPQExpBuffer(query,
14408                                                   "SELECT pg_get_ruledef('%s') AS definition",
14409                                                   rinfo->dobj.name);
14410         }
14411
14412         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14413
14414         if (PQntuples(res) != 1)
14415         {
14416                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14417                                   rinfo->dobj.name, tbinfo->dobj.name);
14418                 exit_nicely(1);
14419         }
14420
14421         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14422
14423         /*
14424          * Add the command to alter the rules replication firing semantics if it
14425          * differs from the default.
14426          */
14427         if (rinfo->ev_enabled != 'O')
14428         {
14429                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14430                 switch (rinfo->ev_enabled)
14431                 {
14432                         case 'A':
14433                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14434                                                                   fmtId(rinfo->dobj.name));
14435                                 break;
14436                         case 'R':
14437                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14438                                                                   fmtId(rinfo->dobj.name));
14439                                 break;
14440                         case 'D':
14441                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14442                                                                   fmtId(rinfo->dobj.name));
14443                                 break;
14444                 }
14445         }
14446
14447         /*
14448          * Apply view's reloptions when its ON SELECT rule is separate.
14449          */
14450         if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14451         {
14452                 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14453                                                   fmtId(tbinfo->dobj.name),
14454                                                   rinfo->reloptions);
14455         }
14456
14457         /*
14458          * DROP must be fully qualified in case same name appears in pg_catalog
14459          */
14460         appendPQExpBuffer(delcmd, "DROP RULE %s ",
14461                                           fmtId(rinfo->dobj.name));
14462         appendPQExpBuffer(delcmd, "ON %s.",
14463                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14464         appendPQExpBuffer(delcmd, "%s;\n",
14465                                           fmtId(tbinfo->dobj.name));
14466
14467         appendPQExpBuffer(labelq, "RULE %s",
14468                                           fmtId(rinfo->dobj.name));
14469         appendPQExpBuffer(labelq, " ON %s",
14470                                           fmtId(tbinfo->dobj.name));
14471
14472         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14473                                  rinfo->dobj.name,
14474                                  tbinfo->dobj.namespace->dobj.name,
14475                                  NULL,
14476                                  tbinfo->rolname, false,
14477                                  "RULE", SECTION_POST_DATA,
14478                                  cmd->data, delcmd->data, NULL,
14479                                  NULL, 0,
14480                                  NULL, NULL);
14481
14482         /* Dump rule comments */
14483         dumpComment(fout, labelq->data,
14484                                 tbinfo->dobj.namespace->dobj.name,
14485                                 tbinfo->rolname,
14486                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14487
14488         PQclear(res);
14489
14490         destroyPQExpBuffer(query);
14491         destroyPQExpBuffer(cmd);
14492         destroyPQExpBuffer(delcmd);
14493         destroyPQExpBuffer(labelq);
14494 }
14495
14496 /*
14497  * getExtensionMembership --- obtain extension membership data
14498  */
14499 void
14500 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14501                                            int numExtensions)
14502 {
14503         PQExpBuffer query;
14504         PGresult   *res;
14505         int                     ntups,
14506                                 i;
14507         int                     i_classid,
14508                                 i_objid,
14509                                 i_refclassid,
14510                                 i_refobjid;
14511         DumpableObject *dobj,
14512                            *refdobj;
14513
14514         /* Nothing to do if no extensions */
14515         if (numExtensions == 0)
14516                 return;
14517
14518         /* Make sure we are in proper schema */
14519         selectSourceSchema(fout, "pg_catalog");
14520
14521         query = createPQExpBuffer();
14522
14523         /* refclassid constraint is redundant but may speed the search */
14524         appendPQExpBuffer(query, "SELECT "
14525                                           "classid, objid, refclassid, refobjid "
14526                                           "FROM pg_depend "
14527                                           "WHERE refclassid = 'pg_extension'::regclass "
14528                                           "AND deptype = 'e' "
14529                                           "ORDER BY 3,4");
14530
14531         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14532
14533         ntups = PQntuples(res);
14534
14535         i_classid = PQfnumber(res, "classid");
14536         i_objid = PQfnumber(res, "objid");
14537         i_refclassid = PQfnumber(res, "refclassid");
14538         i_refobjid = PQfnumber(res, "refobjid");
14539
14540         /*
14541          * Since we ordered the SELECT by referenced ID, we can expect that
14542          * multiple entries for the same extension will appear together; this
14543          * saves on searches.
14544          */
14545         refdobj = NULL;
14546
14547         for (i = 0; i < ntups; i++)
14548         {
14549                 CatalogId       objId;
14550                 CatalogId       refobjId;
14551
14552                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14553                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14554                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14555                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14556
14557                 if (refdobj == NULL ||
14558                         refdobj->catId.tableoid != refobjId.tableoid ||
14559                         refdobj->catId.oid != refobjId.oid)
14560                         refdobj = findObjectByCatalogId(refobjId);
14561
14562                 /*
14563                  * Failure to find objects mentioned in pg_depend is not unexpected,
14564                  * since for example we don't collect info about TOAST tables.
14565                  */
14566                 if (refdobj == NULL)
14567                 {
14568 #ifdef NOT_USED
14569                         fprintf(stderr, "no referenced object %u %u\n",
14570                                         refobjId.tableoid, refobjId.oid);
14571 #endif
14572                         continue;
14573                 }
14574
14575                 dobj = findObjectByCatalogId(objId);
14576
14577                 if (dobj == NULL)
14578                 {
14579 #ifdef NOT_USED
14580                         fprintf(stderr, "no referencing object %u %u\n",
14581                                         objId.tableoid, objId.oid);
14582 #endif
14583                         continue;
14584                 }
14585
14586                 /* Record dependency so that getDependencies needn't repeat this */
14587                 addObjectDependency(dobj, refdobj->dumpId);
14588
14589                 dobj->ext_member = true;
14590
14591                 /*
14592                  * Normally, mark the member object as not to be dumped.  But in
14593                  * binary upgrades, we still dump the members individually, since the
14594                  * idea is to exactly reproduce the database contents rather than
14595                  * replace the extension contents with something different.
14596                  */
14597                 if (!binary_upgrade)
14598                         dobj->dump = false;
14599                 else
14600                         dobj->dump = refdobj->dump;
14601         }
14602
14603         PQclear(res);
14604
14605         /*
14606          * Now identify extension configuration tables and create TableDataInfo
14607          * objects for them, ensuring their data will be dumped even though the
14608          * tables themselves won't be.
14609          *
14610          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14611          * user data in a configuration table is treated like schema data. This
14612          * seems appropriate since system data in a config table would get
14613          * reloaded by CREATE EXTENSION.
14614          */
14615         for (i = 0; i < numExtensions; i++)
14616         {
14617                 ExtensionInfo *curext = &(extinfo[i]);
14618                 char       *extconfig = curext->extconfig;
14619                 char       *extcondition = curext->extcondition;
14620                 char      **extconfigarray = NULL;
14621                 char      **extconditionarray = NULL;
14622                 int                     nconfigitems;
14623                 int                     nconditionitems;
14624
14625                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14626                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14627                         nconfigitems == nconditionitems)
14628                 {
14629                         int                     j;
14630
14631                         for (j = 0; j < nconfigitems; j++)
14632                         {
14633                                 TableInfo  *configtbl;
14634                                 Oid                     configtbloid = atooid(extconfigarray[j]);
14635                                 bool            dumpobj = curext->dobj.dump;
14636
14637                                 configtbl = findTableByOid(configtbloid);
14638                                 if (configtbl == NULL)
14639                                         continue;
14640
14641                                 /*
14642                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
14643                                  * unless the table or its schema is explicitly included
14644                                  */
14645                                 if (!curext->dobj.dump)
14646                                 {
14647                                         /* check table explicitly requested */
14648                                         if (table_include_oids.head != NULL &&
14649                                                 simple_oid_list_member(&table_include_oids,
14650                                                                                                 configtbloid))
14651                                                 dumpobj = true;
14652
14653                                         /* check table's schema explicitly requested */
14654                                         if (configtbl->dobj.namespace->dobj.dump)
14655                                                 dumpobj = true;
14656                                 }
14657
14658                                 /* check table excluded by an exclusion switch */
14659                                 if (table_exclude_oids.head != NULL &&
14660                                         simple_oid_list_member(&table_exclude_oids,
14661                                                                                         configtbloid))
14662                                         dumpobj = false;
14663
14664                                 /* check schema excluded by an exclusion switch */
14665                                 if (simple_oid_list_member(&schema_exclude_oids,
14666                                         configtbl->dobj.namespace->dobj.catId.oid))
14667                                         dumpobj = false;
14668
14669                                 if (dumpobj)
14670                                 {
14671                                         /*
14672                                          * Note: config tables are dumped without OIDs regardless of
14673                                          * the --oids setting.  This is because row filtering
14674                                          * conditions aren't compatible with dumping OIDs.
14675                                          */
14676                                         makeTableDataInfo(configtbl, false);
14677                                         if (configtbl->dataObj != NULL)
14678                                         {
14679                                                 if (strlen(extconditionarray[j]) > 0)
14680                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14681                                         }
14682                                 }
14683                         }
14684                 }
14685                 if (extconfigarray)
14686                         free(extconfigarray);
14687                 if (extconditionarray)
14688                         free(extconditionarray);
14689         }
14690
14691         destroyPQExpBuffer(query);
14692 }
14693
14694 /*
14695  * getDependencies --- obtain available dependency data
14696  */
14697 static void
14698 getDependencies(Archive *fout)
14699 {
14700         PQExpBuffer query;
14701         PGresult   *res;
14702         int                     ntups,
14703                                 i;
14704         int                     i_classid,
14705                                 i_objid,
14706                                 i_refclassid,
14707                                 i_refobjid,
14708                                 i_deptype;
14709         DumpableObject *dobj,
14710                            *refdobj;
14711
14712         /* No dependency info available before 7.3 */
14713         if (fout->remoteVersion < 70300)
14714                 return;
14715
14716         if (g_verbose)
14717                 write_msg(NULL, "reading dependency data\n");
14718
14719         /* Make sure we are in proper schema */
14720         selectSourceSchema(fout, "pg_catalog");
14721
14722         query = createPQExpBuffer();
14723
14724         /*
14725          * PIN dependencies aren't interesting, and EXTENSION dependencies were
14726          * already processed by getExtensionMembership.
14727          */
14728         appendPQExpBuffer(query, "SELECT "
14729                                           "classid, objid, refclassid, refobjid, deptype "
14730                                           "FROM pg_depend "
14731                                           "WHERE deptype != 'p' AND deptype != 'e' "
14732                                           "ORDER BY 1,2");
14733
14734         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14735
14736         ntups = PQntuples(res);
14737
14738         i_classid = PQfnumber(res, "classid");
14739         i_objid = PQfnumber(res, "objid");
14740         i_refclassid = PQfnumber(res, "refclassid");
14741         i_refobjid = PQfnumber(res, "refobjid");
14742         i_deptype = PQfnumber(res, "deptype");
14743
14744         /*
14745          * Since we ordered the SELECT by referencing ID, we can expect that
14746          * multiple entries for the same object will appear together; this saves
14747          * on searches.
14748          */
14749         dobj = NULL;
14750
14751         for (i = 0; i < ntups; i++)
14752         {
14753                 CatalogId       objId;
14754                 CatalogId       refobjId;
14755                 char            deptype;
14756
14757                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14758                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14759                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14760                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14761                 deptype = *(PQgetvalue(res, i, i_deptype));
14762
14763                 if (dobj == NULL ||
14764                         dobj->catId.tableoid != objId.tableoid ||
14765                         dobj->catId.oid != objId.oid)
14766                         dobj = findObjectByCatalogId(objId);
14767
14768                 /*
14769                  * Failure to find objects mentioned in pg_depend is not unexpected,
14770                  * since for example we don't collect info about TOAST tables.
14771                  */
14772                 if (dobj == NULL)
14773                 {
14774 #ifdef NOT_USED
14775                         fprintf(stderr, "no referencing object %u %u\n",
14776                                         objId.tableoid, objId.oid);
14777 #endif
14778                         continue;
14779                 }
14780
14781                 refdobj = findObjectByCatalogId(refobjId);
14782
14783                 if (refdobj == NULL)
14784                 {
14785 #ifdef NOT_USED
14786                         fprintf(stderr, "no referenced object %u %u\n",
14787                                         refobjId.tableoid, refobjId.oid);
14788 #endif
14789                         continue;
14790                 }
14791
14792                 /*
14793                  * Ordinarily, table rowtypes have implicit dependencies on their
14794                  * tables.      However, for a composite type the implicit dependency goes
14795                  * the other way in pg_depend; which is the right thing for DROP but
14796                  * it doesn't produce the dependency ordering we need. So in that one
14797                  * case, we reverse the direction of the dependency.
14798                  */
14799                 if (deptype == 'i' &&
14800                         dobj->objType == DO_TABLE &&
14801                         refdobj->objType == DO_TYPE)
14802                         addObjectDependency(refdobj, dobj->dumpId);
14803                 else
14804                         /* normal case */
14805                         addObjectDependency(dobj, refdobj->dumpId);
14806         }
14807
14808         PQclear(res);
14809
14810         destroyPQExpBuffer(query);
14811 }
14812
14813
14814 /*
14815  * createBoundaryObjects - create dummy DumpableObjects to represent
14816  * dump section boundaries.
14817  */
14818 static DumpableObject *
14819 createBoundaryObjects(void)
14820 {
14821         DumpableObject *dobjs;
14822
14823         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14824
14825         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14826         dobjs[0].catId = nilCatalogId;
14827         AssignDumpId(dobjs + 0);
14828         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14829
14830         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14831         dobjs[1].catId = nilCatalogId;
14832         AssignDumpId(dobjs + 1);
14833         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14834
14835         return dobjs;
14836 }
14837
14838 /*
14839  * addBoundaryDependencies - add dependencies as needed to enforce the dump
14840  * section boundaries.
14841  */
14842 static void
14843 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14844                                                 DumpableObject *boundaryObjs)
14845 {
14846         DumpableObject *preDataBound = boundaryObjs + 0;
14847         DumpableObject *postDataBound = boundaryObjs + 1;
14848         int                     i;
14849
14850         for (i = 0; i < numObjs; i++)
14851         {
14852                 DumpableObject *dobj = dobjs[i];
14853
14854                 /*
14855                  * The classification of object types here must match the SECTION_xxx
14856                  * values assigned during subsequent ArchiveEntry calls!
14857                  */
14858                 switch (dobj->objType)
14859                 {
14860                         case DO_NAMESPACE:
14861                         case DO_EXTENSION:
14862                         case DO_TYPE:
14863                         case DO_SHELL_TYPE:
14864                         case DO_FUNC:
14865                         case DO_AGG:
14866                         case DO_OPERATOR:
14867                         case DO_OPCLASS:
14868                         case DO_OPFAMILY:
14869                         case DO_COLLATION:
14870                         case DO_CONVERSION:
14871                         case DO_TABLE:
14872                         case DO_ATTRDEF:
14873                         case DO_PROCLANG:
14874                         case DO_CAST:
14875                         case DO_DUMMY_TYPE:
14876                         case DO_TSPARSER:
14877                         case DO_TSDICT:
14878                         case DO_TSTEMPLATE:
14879                         case DO_TSCONFIG:
14880                         case DO_FDW:
14881                         case DO_FOREIGN_SERVER:
14882                         case DO_BLOB:
14883                                 /* Pre-data objects: must come before the pre-data boundary */
14884                                 addObjectDependency(preDataBound, dobj->dumpId);
14885                                 break;
14886                         case DO_TABLE_DATA:
14887                         case DO_BLOB_DATA:
14888                                 /* Data objects: must come between the boundaries */
14889                                 addObjectDependency(dobj, preDataBound->dumpId);
14890                                 addObjectDependency(postDataBound, dobj->dumpId);
14891                                 break;
14892                         case DO_INDEX:
14893                         case DO_REFRESH_MATVIEW:
14894                         case DO_TRIGGER:
14895                         case DO_EVENT_TRIGGER:
14896                         case DO_DEFAULT_ACL:
14897                                 /* Post-data objects: must come after the post-data boundary */
14898                                 addObjectDependency(dobj, postDataBound->dumpId);
14899                                 break;
14900                         case DO_RULE:
14901                                 /* Rules are post-data, but only if dumped separately */
14902                                 if (((RuleInfo *) dobj)->separate)
14903                                         addObjectDependency(dobj, postDataBound->dumpId);
14904                                 break;
14905                         case DO_CONSTRAINT:
14906                         case DO_FK_CONSTRAINT:
14907                                 /* Constraints are post-data, but only if dumped separately */
14908                                 if (((ConstraintInfo *) dobj)->separate)
14909                                         addObjectDependency(dobj, postDataBound->dumpId);
14910                                 break;
14911                         case DO_PRE_DATA_BOUNDARY:
14912                                 /* nothing to do */
14913                                 break;
14914                         case DO_POST_DATA_BOUNDARY:
14915                                 /* must come after the pre-data boundary */
14916                                 addObjectDependency(dobj, preDataBound->dumpId);
14917                                 break;
14918                 }
14919         }
14920 }
14921
14922
14923 /*
14924  * BuildArchiveDependencies - create dependency data for archive TOC entries
14925  *
14926  * The raw dependency data obtained by getDependencies() is not terribly
14927  * useful in an archive dump, because in many cases there are dependency
14928  * chains linking through objects that don't appear explicitly in the dump.
14929  * For example, a view will depend on its _RETURN rule while the _RETURN rule
14930  * will depend on other objects --- but the rule will not appear as a separate
14931  * object in the dump.  We need to adjust the view's dependencies to include
14932  * whatever the rule depends on that is included in the dump.
14933  *
14934  * Just to make things more complicated, there are also "special" dependencies
14935  * such as the dependency of a TABLE DATA item on its TABLE, which we must
14936  * not rearrange because pg_restore knows that TABLE DATA only depends on
14937  * its table.  In these cases we must leave the dependencies strictly as-is
14938  * even if they refer to not-to-be-dumped objects.
14939  *
14940  * To handle this, the convention is that "special" dependencies are created
14941  * during ArchiveEntry calls, and an archive TOC item that has any such
14942  * entries will not be touched here.  Otherwise, we recursively search the
14943  * DumpableObject data structures to build the correct dependencies for each
14944  * archive TOC item.
14945  */
14946 static void
14947 BuildArchiveDependencies(Archive *fout)
14948 {
14949         ArchiveHandle *AH = (ArchiveHandle *) fout;
14950         TocEntry   *te;
14951
14952         /* Scan all TOC entries in the archive */
14953         for (te = AH->toc->next; te != AH->toc; te = te->next)
14954         {
14955                 DumpableObject *dobj;
14956                 DumpId     *dependencies;
14957                 int                     nDeps;
14958                 int                     allocDeps;
14959
14960                 /* No need to process entries that will not be dumped */
14961                 if (te->reqs == 0)
14962                         continue;
14963                 /* Ignore entries that already have "special" dependencies */
14964                 if (te->nDeps > 0)
14965                         continue;
14966                 /* Otherwise, look up the item's original DumpableObject, if any */
14967                 dobj = findObjectByDumpId(te->dumpId);
14968                 if (dobj == NULL)
14969                         continue;
14970                 /* No work if it has no dependencies */
14971                 if (dobj->nDeps <= 0)
14972                         continue;
14973                 /* Set up work array */
14974                 allocDeps = 64;
14975                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14976                 nDeps = 0;
14977                 /* Recursively find all dumpable dependencies */
14978                 findDumpableDependencies(AH, dobj,
14979                                                                  &dependencies, &nDeps, &allocDeps);
14980                 /* And save 'em ... */
14981                 if (nDeps > 0)
14982                 {
14983                         dependencies = (DumpId *) pg_realloc(dependencies,
14984                                                                                                  nDeps * sizeof(DumpId));
14985                         te->dependencies = dependencies;
14986                         te->nDeps = nDeps;
14987                 }
14988                 else
14989                         free(dependencies);
14990         }
14991 }
14992
14993 /* Recursive search subroutine for BuildArchiveDependencies */
14994 static void
14995 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14996                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
14997 {
14998         int                     i;
14999
15000         /*
15001          * Ignore section boundary objects: if we search through them, we'll
15002          * report lots of bogus dependencies.
15003          */
15004         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
15005                 dobj->objType == DO_POST_DATA_BOUNDARY)
15006                 return;
15007
15008         for (i = 0; i < dobj->nDeps; i++)
15009         {
15010                 DumpId          depid = dobj->dependencies[i];
15011
15012                 if (TocIDRequired(AH, depid) != 0)
15013                 {
15014                         /* Object will be dumped, so just reference it as a dependency */
15015                         if (*nDeps >= *allocDeps)
15016                         {
15017                                 *allocDeps *= 2;
15018                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
15019                                                                                                 *allocDeps * sizeof(DumpId));
15020                         }
15021                         (*dependencies)[*nDeps] = depid;
15022                         (*nDeps)++;
15023                 }
15024                 else
15025                 {
15026                         /*
15027                          * Object will not be dumped, so recursively consider its deps. We
15028                          * rely on the assumption that sortDumpableObjects already broke
15029                          * any dependency loops, else we might recurse infinitely.
15030                          */
15031                         DumpableObject *otherdobj = findObjectByDumpId(depid);
15032
15033                         if (otherdobj)
15034                                 findDumpableDependencies(AH, otherdobj,
15035                                                                                  dependencies, nDeps, allocDeps);
15036                 }
15037         }
15038 }
15039
15040
15041 /*
15042  * selectSourceSchema - make the specified schema the active search path
15043  * in the source database.
15044  *
15045  * NB: pg_catalog is explicitly searched after the specified schema;
15046  * so user names are only qualified if they are cross-schema references,
15047  * and system names are only qualified if they conflict with a user name
15048  * in the current schema.
15049  *
15050  * Whenever the selected schema is not pg_catalog, be careful to qualify
15051  * references to system catalogs and types in our emitted commands!
15052  *
15053  * This function is called only from selectSourceSchemaOnAH and
15054  * selectSourceSchema.
15055  */
15056 static void
15057 selectSourceSchema(Archive *fout, const char *schemaName)
15058 {
15059         PQExpBuffer query;
15060
15061         /* This is checked by the callers already */
15062         Assert(schemaName != NULL && *schemaName != '\0');
15063
15064         /* Not relevant if fetching from pre-7.3 DB */
15065         if (fout->remoteVersion < 70300)
15066                 return;
15067
15068         query = createPQExpBuffer();
15069         appendPQExpBuffer(query, "SET search_path = %s",
15070                                           fmtId(schemaName));
15071         if (strcmp(schemaName, "pg_catalog") != 0)
15072                 appendPQExpBuffer(query, ", pg_catalog");
15073
15074         ExecuteSqlStatement(fout, query->data);
15075
15076         destroyPQExpBuffer(query);
15077 }
15078
15079 /*
15080  * getFormattedTypeName - retrieve a nicely-formatted type name for the
15081  * given type name.
15082  *
15083  * NB: in 7.3 and up the result may depend on the currently-selected
15084  * schema; this is why we don't try to cache the names.
15085  */
15086 static char *
15087 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
15088 {
15089         char       *result;
15090         PQExpBuffer query;
15091         PGresult   *res;
15092
15093         if (oid == 0)
15094         {
15095                 if ((opts & zeroAsOpaque) != 0)
15096                         return pg_strdup(g_opaque_type);
15097                 else if ((opts & zeroAsAny) != 0)
15098                         return pg_strdup("'any'");
15099                 else if ((opts & zeroAsStar) != 0)
15100                         return pg_strdup("*");
15101                 else if ((opts & zeroAsNone) != 0)
15102                         return pg_strdup("NONE");
15103         }
15104
15105         query = createPQExpBuffer();
15106         if (fout->remoteVersion >= 70300)
15107         {
15108                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
15109                                                   oid);
15110         }
15111         else if (fout->remoteVersion >= 70100)
15112         {
15113                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
15114                                                   oid);
15115         }
15116         else
15117         {
15118                 appendPQExpBuffer(query, "SELECT typname "
15119                                                   "FROM pg_type "
15120                                                   "WHERE oid = '%u'::oid",
15121                                                   oid);
15122         }
15123
15124         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15125
15126         if (fout->remoteVersion >= 70100)
15127         {
15128                 /* already quoted */
15129                 result = pg_strdup(PQgetvalue(res, 0, 0));
15130         }
15131         else
15132         {
15133                 /* may need to quote it */
15134                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
15135         }
15136
15137         PQclear(res);
15138         destroyPQExpBuffer(query);
15139
15140         return result;
15141 }
15142
15143 /*
15144  * myFormatType --- local implementation of format_type for use with 7.0.
15145  */
15146 static char *
15147 myFormatType(const char *typname, int32 typmod)
15148 {
15149         char       *result;
15150         bool            isarray = false;
15151         PQExpBuffer buf = createPQExpBuffer();
15152
15153         /* Handle array types */
15154         if (typname[0] == '_')
15155         {
15156                 isarray = true;
15157                 typname++;
15158         }
15159
15160         /* Show lengths on bpchar and varchar */
15161         if (strcmp(typname, "bpchar") == 0)
15162         {
15163                 int                     len = (typmod - VARHDRSZ);
15164
15165                 appendPQExpBuffer(buf, "character");
15166                 if (len > 1)
15167                         appendPQExpBuffer(buf, "(%d)",
15168                                                           typmod - VARHDRSZ);
15169         }
15170         else if (strcmp(typname, "varchar") == 0)
15171         {
15172                 appendPQExpBuffer(buf, "character varying");
15173                 if (typmod != -1)
15174                         appendPQExpBuffer(buf, "(%d)",
15175                                                           typmod - VARHDRSZ);
15176         }
15177         else if (strcmp(typname, "numeric") == 0)
15178         {
15179                 appendPQExpBuffer(buf, "numeric");
15180                 if (typmod != -1)
15181                 {
15182                         int32           tmp_typmod;
15183                         int                     precision;
15184                         int                     scale;
15185
15186                         tmp_typmod = typmod - VARHDRSZ;
15187                         precision = (tmp_typmod >> 16) & 0xffff;
15188                         scale = tmp_typmod & 0xffff;
15189                         appendPQExpBuffer(buf, "(%d,%d)",
15190                                                           precision, scale);
15191                 }
15192         }
15193
15194         /*
15195          * char is an internal single-byte data type; Let's make sure we force it
15196          * through with quotes. - thomas 1998-12-13
15197          */
15198         else if (strcmp(typname, "char") == 0)
15199                 appendPQExpBuffer(buf, "\"char\"");
15200         else
15201                 appendPQExpBuffer(buf, "%s", fmtId(typname));
15202
15203         /* Append array qualifier for array types */
15204         if (isarray)
15205                 appendPQExpBuffer(buf, "[]");
15206
15207         result = pg_strdup(buf->data);
15208         destroyPQExpBuffer(buf);
15209
15210         return result;
15211 }
15212
15213 /*
15214  * Return a column list clause for the given relation.
15215  *
15216  * Special case: if there are no undropped columns in the relation, return
15217  * "", not an invalid "()" column list.
15218  */
15219 static const char *
15220 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
15221 {
15222         int                     numatts = ti->numatts;
15223         char      **attnames = ti->attnames;
15224         bool       *attisdropped = ti->attisdropped;
15225         bool            needComma;
15226         int                     i;
15227
15228         appendPQExpBuffer(buffer, "(");
15229         needComma = false;
15230         for (i = 0; i < numatts; i++)
15231         {
15232                 if (attisdropped[i])
15233                         continue;
15234                 if (needComma)
15235                         appendPQExpBuffer(buffer, ", ");
15236                 appendPQExpBuffer(buffer, "%s", fmtId(attnames[i]));
15237                 needComma = true;
15238         }
15239
15240         if (!needComma)
15241                 return "";                              /* no undropped columns */
15242
15243         appendPQExpBuffer(buffer, ")");
15244         return buffer->data;
15245 }
15246
15247 /*
15248  * Execute an SQL query and verify that we got exactly one row back.
15249  */
15250 static PGresult *
15251 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
15252 {
15253         PGresult   *res;
15254         int                     ntups;
15255
15256         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
15257
15258         /* Expecting a single result only */
15259         ntups = PQntuples(res);
15260         if (ntups != 1)
15261                 exit_horribly(NULL,
15262                                           ngettext("query returned %d row instead of one: %s\n",
15263                                                            "query returned %d rows instead of one: %s\n",
15264                                                            ntups),
15265                                           ntups, query);
15266
15267         return res;
15268 }