]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
1fd43b55e17447da2e2a1b745b344e47ad30d604
[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-2010, 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 serializable transaction, so it sees a
15  *      consistent snapshot of the database including system catalogs.
16  *      However, it relies in part on various specialized backend functions
17  *      like pg_get_indexdef(), and those things tend to run on SnapshotNow
18  *      time, ie they look at the currently committed state.  So it is
19  *      possible to get 'cache lookup failed' error if someone performs DDL
20  *      changes while a dump is happening. The window for this sort of thing
21  *      is from the beginning of the serializable transaction 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  *        $PostgreSQL: pgsql/src/bin/pg_dump/pg_dump.c,v 1.584 2010/08/03 19:24:04 tgl Exp $
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 "catalog/pg_cast.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_default_acl.h"
51 #include "catalog/pg_largeobject.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_trigger.h"
54 #include "catalog/pg_type.h"
55 #include "libpq/libpq-fs.h"
56
57 #include "pg_backup_archiver.h"
58 #include "dumputils.h"
59
60 extern char *optarg;
61 extern int      optind,
62                         opterr;
63
64
65 typedef struct
66 {
67         const char *descr;                      /* comment for an object */
68         Oid                     classoid;               /* object class (catalog OID) */
69         Oid                     objoid;                 /* object OID */
70         int                     objsubid;               /* subobject (table column #) */
71 } CommentItem;
72
73
74 /* global decls */
75 bool            g_verbose;                      /* User wants verbose narration of our
76                                                                  * activities. */
77 Archive    *g_fout;                             /* the script file */
78 PGconn     *g_conn;                             /* the database connection */
79
80 /* various user-settable parameters */
81 bool            schemaOnly;
82 bool            dataOnly;
83 bool            aclsSkip;
84 const char *lockWaitTimeout;
85
86 /* subquery used to convert user ID (eg, datdba) to user name */
87 static const char *username_subquery;
88
89 /* obsolete as of 7.3: */
90 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
91
92 /*
93  * Object inclusion/exclusion lists
94  *
95  * The string lists record the patterns given by command-line switches,
96  * which we then convert to lists of OIDs of matching objects.
97  */
98 static SimpleStringList schema_include_patterns = {NULL, NULL};
99 static SimpleOidList schema_include_oids = {NULL, NULL};
100 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
101 static SimpleOidList schema_exclude_oids = {NULL, NULL};
102
103 static SimpleStringList table_include_patterns = {NULL, NULL};
104 static SimpleOidList table_include_oids = {NULL, NULL};
105 static SimpleStringList table_exclude_patterns = {NULL, NULL};
106 static SimpleOidList table_exclude_oids = {NULL, NULL};
107
108 /* default, if no "inclusion" switches appear, is to dump everything */
109 static bool include_everything = true;
110
111 char            g_opaque_type[10];      /* name for the opaque type */
112
113 /* placeholders for the delimiters for comments */
114 char            g_comment_start[10];
115 char            g_comment_end[10];
116
117 static const CatalogId nilCatalogId = {0, 0};
118
119 /* these are to avoid passing around info for findNamespace() */
120 static NamespaceInfo *g_namespaces;
121 static int      g_numNamespaces;
122
123 /* flags for various command-line long options */
124 static int      binary_upgrade = 0;
125 static int      disable_dollar_quoting = 0;
126 static int      dump_inserts = 0;
127 static int      column_inserts = 0;
128
129
130 static void help(const char *progname);
131 static void expand_schema_name_patterns(SimpleStringList *patterns,
132                                                         SimpleOidList *oids);
133 static void expand_table_name_patterns(SimpleStringList *patterns,
134                                                    SimpleOidList *oids);
135 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
136 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
137 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
138 static void dumpComment(Archive *fout, const char *target,
139                         const char *namespace, const char *owner,
140                         CatalogId catalogId, int subid, DumpId dumpId);
141 static int findComments(Archive *fout, Oid classoid, Oid objoid,
142                          CommentItem **items);
143 static int      collectComments(Archive *fout, CommentItem **items);
144 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
145 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
146 static void dumpType(Archive *fout, TypeInfo *tyinfo);
147 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
148 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
149 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
150 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
151 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
152 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
153 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
154 static void dumpFunc(Archive *fout, FuncInfo *finfo);
155 static void dumpCast(Archive *fout, CastInfo *cast);
156 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
157 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
158 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
159 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
160 static void dumpRule(Archive *fout, RuleInfo *rinfo);
161 static void dumpAgg(Archive *fout, AggInfo *agginfo);
162 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
163 static void dumpTable(Archive *fout, TableInfo *tbinfo);
164 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
165 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
166 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
167 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
168 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
169 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
170 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
171 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
172 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
173 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
174 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
175 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
176 static void dumpUserMappings(Archive *fout,
177                                  const char *servername, const char *namespace,
178                                  const char *owner, CatalogId catalogId, DumpId dumpId);
179 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
180
181 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
182                 const char *type, const char *name, const char *subname,
183                 const char *tag, const char *nspname, const char *owner,
184                 const char *acls);
185
186 static void getDependencies(void);
187 static void getDomainConstraints(TypeInfo *tyinfo);
188 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
189 static void getTableDataFKConstraints(void);
190 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
191 static char *format_function_arguments_old(FuncInfo *finfo, int nallargs,
192                                                           char **allargtypes,
193                                                           char **argmodes,
194                                                           char **argnames);
195 static char *format_function_signature(FuncInfo *finfo, bool honor_quotes);
196 static const char *convertRegProcReference(const char *proc);
197 static const char *convertOperatorReference(const char *opr);
198 static const char *convertTSFunction(Oid funcOid);
199 static Oid      findLastBuiltinOid_V71(const char *);
200 static Oid      findLastBuiltinOid_V70(void);
201 static void selectSourceSchema(const char *schemaName);
202 static char *getFormattedTypeName(Oid oid, OidOptions opts);
203 static char *myFormatType(const char *typname, int32 typmod);
204 static const char *fmtQualifiedId(const char *schema, const char *id);
205 static void getBlobs(Archive *AH);
206 static void dumpBlob(Archive *AH, BlobInfo *binfo);
207 static int      dumpBlobs(Archive *AH, void *arg);
208 static void dumpDatabase(Archive *AH);
209 static void dumpEncoding(Archive *AH);
210 static void dumpStdStrings(Archive *AH);
211 static void binary_upgrade_set_type_oids_by_type_oid(
212                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
213 static bool binary_upgrade_set_type_oids_by_rel_oid(
214                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
215 static void binary_upgrade_set_relfilenodes(PQExpBuffer upgrade_buffer,
216                                                                 Oid pg_class_oid, bool is_index);
217 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
218 static const char *fmtCopyColumnList(const TableInfo *ti);
219 static void do_sql_command(PGconn *conn, const char *query);
220 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
221                                  ExecStatusType expected);
222
223
224 int
225 main(int argc, char **argv)
226 {
227         int                     c;
228         const char *filename = NULL;
229         const char *format = "p";
230         const char *dbname = NULL;
231         const char *pghost = NULL;
232         const char *pgport = NULL;
233         const char *username = NULL;
234         const char *dumpencoding = NULL;
235         const char *std_strings;
236         bool            oids = false;
237         TableInfo  *tblinfo;
238         int                     numTables;
239         DumpableObject **dobjs;
240         int                     numObjs;
241         int                     i;
242         enum trivalue prompt_password = TRI_DEFAULT;
243         int                     compressLevel = -1;
244         int                     plainText = 0;
245         int                     outputClean = 0;
246         int                     outputCreateDB = 0;
247         bool            outputBlobs = false;
248         int                     outputNoOwner = 0;
249         char       *outputSuperuser = NULL;
250         char       *use_role = NULL;
251         int                     my_version;
252         int                     optindex;
253         RestoreOptions *ropt;
254
255         static int      disable_triggers = 0;
256         static int      outputNoTablespaces = 0;
257         static int      use_setsessauth = 0;
258
259         static struct option long_options[] = {
260                 {"data-only", no_argument, NULL, 'a'},
261                 {"blobs", no_argument, NULL, 'b'},
262                 {"clean", no_argument, NULL, 'c'},
263                 {"create", no_argument, NULL, 'C'},
264                 {"file", required_argument, NULL, 'f'},
265                 {"format", required_argument, NULL, 'F'},
266                 {"host", required_argument, NULL, 'h'},
267                 {"ignore-version", no_argument, NULL, 'i'},
268                 {"no-reconnect", no_argument, NULL, 'R'},
269                 {"oids", no_argument, NULL, 'o'},
270                 {"no-owner", no_argument, NULL, 'O'},
271                 {"port", required_argument, NULL, 'p'},
272                 {"schema", required_argument, NULL, 'n'},
273                 {"exclude-schema", required_argument, NULL, 'N'},
274                 {"schema-only", no_argument, NULL, 's'},
275                 {"superuser", required_argument, NULL, 'S'},
276                 {"table", required_argument, NULL, 't'},
277                 {"exclude-table", required_argument, NULL, 'T'},
278                 {"no-password", no_argument, NULL, 'w'},
279                 {"password", no_argument, NULL, 'W'},
280                 {"username", required_argument, NULL, 'U'},
281                 {"verbose", no_argument, NULL, 'v'},
282                 {"no-privileges", no_argument, NULL, 'x'},
283                 {"no-acl", no_argument, NULL, 'x'},
284                 {"compress", required_argument, NULL, 'Z'},
285                 {"encoding", required_argument, NULL, 'E'},
286                 {"help", no_argument, NULL, '?'},
287                 {"version", no_argument, NULL, 'V'},
288
289                 /*
290                  * the following options don't have an equivalent short option letter
291                  */
292                 {"attribute-inserts", no_argument, &column_inserts, 1},
293                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
294                 {"column-inserts", no_argument, &column_inserts, 1},
295                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
296                 {"disable-triggers", no_argument, &disable_triggers, 1},
297                 {"inserts", no_argument, &dump_inserts, 1},
298                 {"lock-wait-timeout", required_argument, NULL, 2},
299                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
300                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
301                 {"role", required_argument, NULL, 3},
302                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
303
304                 {NULL, 0, NULL, 0}
305         };
306
307         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
308
309         g_verbose = false;
310
311         strcpy(g_comment_start, "-- ");
312         g_comment_end[0] = '\0';
313         strcpy(g_opaque_type, "opaque");
314
315         dataOnly = schemaOnly = false;
316         lockWaitTimeout = NULL;
317
318         progname = get_progname(argv[0]);
319
320         /* Set default options based on progname */
321         if (strcmp(progname, "pg_backup") == 0)
322                 format = "c";
323
324         if (argc > 1)
325         {
326                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
327                 {
328                         help(progname);
329                         exit(0);
330                 }
331                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
332                 {
333                         puts("pg_dump (PostgreSQL) " PG_VERSION);
334                         exit(0);
335                 }
336         }
337
338         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxX:Z:",
339                                                         long_options, &optindex)) != -1)
340         {
341                 switch (c)
342                 {
343                         case 'a':                       /* Dump data only */
344                                 dataOnly = true;
345                                 break;
346
347                         case 'b':                       /* Dump blobs */
348                                 outputBlobs = true;
349                                 break;
350
351                         case 'c':                       /* clean (i.e., drop) schema prior to create */
352                                 outputClean = 1;
353                                 break;
354
355                         case 'C':                       /* Create DB */
356                                 outputCreateDB = 1;
357                                 break;
358
359                         case 'E':                       /* Dump encoding */
360                                 dumpencoding = optarg;
361                                 break;
362
363                         case 'f':
364                                 filename = optarg;
365                                 break;
366
367                         case 'F':
368                                 format = optarg;
369                                 break;
370
371                         case 'h':                       /* server host */
372                                 pghost = optarg;
373                                 break;
374
375                         case 'i':
376                                 /* ignored, deprecated option */
377                                 break;
378
379                         case 'n':                       /* include schema(s) */
380                                 simple_string_list_append(&schema_include_patterns, optarg);
381                                 include_everything = false;
382                                 break;
383
384                         case 'N':                       /* exclude schema(s) */
385                                 simple_string_list_append(&schema_exclude_patterns, optarg);
386                                 break;
387
388                         case 'o':                       /* Dump oids */
389                                 oids = true;
390                                 break;
391
392                         case 'O':                       /* Don't reconnect to match owner */
393                                 outputNoOwner = 1;
394                                 break;
395
396                         case 'p':                       /* server port */
397                                 pgport = optarg;
398                                 break;
399
400                         case 'R':
401                                 /* no-op, still accepted for backwards compatibility */
402                                 break;
403
404                         case 's':                       /* dump schema only */
405                                 schemaOnly = true;
406                                 break;
407
408                         case 'S':                       /* Username for superuser in plain text output */
409                                 outputSuperuser = strdup(optarg);
410                                 break;
411
412                         case 't':                       /* include table(s) */
413                                 simple_string_list_append(&table_include_patterns, optarg);
414                                 include_everything = false;
415                                 break;
416
417                         case 'T':                       /* exclude table(s) */
418                                 simple_string_list_append(&table_exclude_patterns, optarg);
419                                 break;
420
421                         case 'U':
422                                 username = optarg;
423                                 break;
424
425                         case 'v':                       /* verbose */
426                                 g_verbose = true;
427                                 break;
428
429                         case 'w':
430                                 prompt_password = TRI_NO;
431                                 break;
432
433                         case 'W':
434                                 prompt_password = TRI_YES;
435                                 break;
436
437                         case 'x':                       /* skip ACL dump */
438                                 aclsSkip = true;
439                                 break;
440
441                         case 'X':
442                                 /* -X is a deprecated alternative to long options */
443                                 if (strcmp(optarg, "disable-dollar-quoting") == 0)
444                                         disable_dollar_quoting = 1;
445                                 else if (strcmp(optarg, "disable-triggers") == 0)
446                                         disable_triggers = 1;
447                                 else if (strcmp(optarg, "no-tablespaces") == 0)
448                                         outputNoTablespaces = 1;
449                                 else if (strcmp(optarg, "use-set-session-authorization") == 0)
450                                         use_setsessauth = 1;
451                                 else
452                                 {
453                                         fprintf(stderr,
454                                                         _("%s: invalid -X option -- %s\n"),
455                                                         progname, optarg);
456                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
457                                         exit(1);
458                                 }
459                                 break;
460
461                         case 'Z':                       /* Compression Level */
462                                 compressLevel = atoi(optarg);
463                                 break;
464
465                         case 0:
466                                 /* This covers the long options equivalent to -X xxx. */
467                                 break;
468
469                         case 2:                         /* lock-wait-timeout */
470                                 lockWaitTimeout = optarg;
471                                 break;
472
473                         case 3:                         /* SET ROLE */
474                                 use_role = optarg;
475                                 break;
476
477                         default:
478                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
479                                 exit(1);
480                 }
481         }
482
483         if (optind < (argc - 1))
484         {
485                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
486                                 progname, argv[optind + 1]);
487                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
488                                 progname);
489                 exit(1);
490         }
491
492         /* Get database name from command line */
493         if (optind < argc)
494                 dbname = argv[optind];
495
496         /* --column-inserts implies --inserts */
497         if (column_inserts)
498                 dump_inserts = 1;
499
500         if (dataOnly && schemaOnly)
501         {
502                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
503                 exit(1);
504         }
505
506         if (dataOnly && outputClean)
507         {
508                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
509                 exit(1);
510         }
511
512         if (dump_inserts && oids)
513         {
514                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
515                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
516                 exit(1);
517         }
518
519         /* open the output file */
520         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
521         {
522                 /* This is used by pg_dumpall, and is not documented */
523                 plainText = 1;
524                 g_fout = CreateArchive(filename, archNull, 0, archModeAppend);
525         }
526         else if (pg_strcasecmp(format, "c") == 0 || pg_strcasecmp(format, "custom") == 0)
527                 g_fout = CreateArchive(filename, archCustom, compressLevel, archModeWrite);
528         else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
529         {
530                 /*
531                  * Dump files into the current directory; for demonstration only, not
532                  * documented.
533                  */
534                 g_fout = CreateArchive(filename, archFiles, compressLevel, archModeWrite);
535         }
536         else if (pg_strcasecmp(format, "p") == 0 || pg_strcasecmp(format, "plain") == 0)
537         {
538                 plainText = 1;
539                 g_fout = CreateArchive(filename, archNull, 0, archModeWrite);
540         }
541         else if (pg_strcasecmp(format, "t") == 0 || pg_strcasecmp(format, "tar") == 0)
542                 g_fout = CreateArchive(filename, archTar, compressLevel, archModeWrite);
543         else
544         {
545                 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
546                 exit(1);
547         }
548
549         if (g_fout == NULL)
550         {
551                 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
552                 exit(1);
553         }
554
555         /* Let the archiver know how noisy to be */
556         g_fout->verbose = g_verbose;
557
558         my_version = parse_version(PG_VERSION);
559         if (my_version < 0)
560         {
561                 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
562                 exit(1);
563         }
564
565         /*
566          * We allow the server to be back to 7.0, and up to any minor release of
567          * our own major version.  (See also version check in pg_dumpall.c.)
568          */
569         g_fout->minRemoteVersion = 70000;
570         g_fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
571
572         /*
573          * Open the database using the Archiver, so it knows about it. Errors mean
574          * death.
575          */
576         g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
577                                                          username, prompt_password);
578
579         /* Set the client encoding if requested */
580         if (dumpencoding)
581         {
582                 if (PQsetClientEncoding(g_conn, dumpencoding) < 0)
583                 {
584                         write_msg(NULL, "invalid client encoding \"%s\" specified\n",
585                                           dumpencoding);
586                         exit(1);
587                 }
588         }
589
590         /*
591          * Get the active encoding and the standard_conforming_strings setting, so
592          * we know how to escape strings.
593          */
594         g_fout->encoding = PQclientEncoding(g_conn);
595
596         std_strings = PQparameterStatus(g_conn, "standard_conforming_strings");
597         g_fout->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
598
599         /* Set the role if requested */
600         if (use_role && g_fout->remoteVersion >= 80100)
601         {
602                 PQExpBuffer query = createPQExpBuffer();
603
604                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
605                 do_sql_command(g_conn, query->data);
606                 destroyPQExpBuffer(query);
607         }
608
609         /* Set the datestyle to ISO to ensure the dump's portability */
610         do_sql_command(g_conn, "SET DATESTYLE = ISO");
611
612         /* Likewise, avoid using sql_standard intervalstyle */
613         if (g_fout->remoteVersion >= 80400)
614                 do_sql_command(g_conn, "SET INTERVALSTYLE = POSTGRES");
615
616         /*
617          * If supported, set extra_float_digits so that we can dump float data
618          * exactly (given correctly implemented float I/O code, anyway)
619          */
620         if (g_fout->remoteVersion >= 90000)
621                 do_sql_command(g_conn, "SET extra_float_digits TO 3");
622         else if (g_fout->remoteVersion >= 70400)
623                 do_sql_command(g_conn, "SET extra_float_digits TO 2");
624
625         /*
626          * If synchronized scanning is supported, disable it, to prevent
627          * unpredictable changes in row ordering across a dump and reload.
628          */
629         if (g_fout->remoteVersion >= 80300)
630                 do_sql_command(g_conn, "SET synchronize_seqscans TO off");
631
632         /*
633          * Disable timeouts if supported.
634          */
635         if (g_fout->remoteVersion >= 70300)
636                 do_sql_command(g_conn, "SET statement_timeout = 0");
637
638         /*
639          * Quote all identifiers, if requested.
640          */
641         if (quote_all_identifiers && g_fout->remoteVersion >= 90100)
642                 do_sql_command(g_conn, "SET quote_all_identifiers = true");
643
644         /*
645          * Start serializable transaction to dump consistent data.
646          */
647         do_sql_command(g_conn, "BEGIN");
648
649         do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
650
651         /* Select the appropriate subquery to convert user IDs to names */
652         if (g_fout->remoteVersion >= 80100)
653                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
654         else if (g_fout->remoteVersion >= 70300)
655                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
656         else
657                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
658
659         /* Find the last built-in OID, if needed */
660         if (g_fout->remoteVersion < 70300)
661         {
662                 if (g_fout->remoteVersion >= 70100)
663                         g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
664                 else
665                         g_last_builtin_oid = findLastBuiltinOid_V70();
666                 if (g_verbose)
667                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
668         }
669
670         /* Expand schema selection patterns into OID lists */
671         if (schema_include_patterns.head != NULL)
672         {
673                 expand_schema_name_patterns(&schema_include_patterns,
674                                                                         &schema_include_oids);
675                 if (schema_include_oids.head == NULL)
676                 {
677                         write_msg(NULL, "No matching schemas were found\n");
678                         exit_nicely();
679                 }
680         }
681         expand_schema_name_patterns(&schema_exclude_patterns,
682                                                                 &schema_exclude_oids);
683         /* non-matching exclusion patterns aren't an error */
684
685         /* Expand table selection patterns into OID lists */
686         if (table_include_patterns.head != NULL)
687         {
688                 expand_table_name_patterns(&table_include_patterns,
689                                                                    &table_include_oids);
690                 if (table_include_oids.head == NULL)
691                 {
692                         write_msg(NULL, "No matching tables were found\n");
693                         exit_nicely();
694                 }
695         }
696         expand_table_name_patterns(&table_exclude_patterns,
697                                                            &table_exclude_oids);
698         /* non-matching exclusion patterns aren't an error */
699
700         /*
701          * Dumping blobs is now default unless we saw an inclusion switch or -s
702          * ... but even if we did see one of these, -b turns it back on.
703          */
704         if (include_everything && !schemaOnly)
705                 outputBlobs = true;
706
707         /*
708          * Now scan the database and create DumpableObject structs for all the
709          * objects we intend to dump.
710          */
711         tblinfo = getSchemaData(&numTables);
712
713         if (g_fout->remoteVersion < 80400)
714                 guessConstraintInheritance(tblinfo, numTables);
715
716         if (!schemaOnly)
717         {
718                 getTableData(tblinfo, numTables, oids);
719                 if (dataOnly)
720                         getTableDataFKConstraints();
721         }
722
723         if (outputBlobs)
724                 getBlobs(g_fout);
725
726         /*
727          * Collect dependency data to assist in ordering the objects.
728          */
729         getDependencies();
730
731         /*
732          * Sort the objects into a safe dump order (no forward references).
733          *
734          * In 7.3 or later, we can rely on dependency information to help us
735          * determine a safe order, so the initial sort is mostly for cosmetic
736          * purposes: we sort by name to ensure that logically identical schemas
737          * will dump identically.  Before 7.3 we don't have dependencies and we
738          * use OID ordering as an (unreliable) guide to creation order.
739          */
740         getDumpableObjects(&dobjs, &numObjs);
741
742         if (g_fout->remoteVersion >= 70300)
743                 sortDumpableObjectsByTypeName(dobjs, numObjs);
744         else
745                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
746
747         sortDumpableObjects(dobjs, numObjs);
748
749         /*
750          * Create archive TOC entries for all the objects to be dumped, in a safe
751          * order.
752          */
753
754         /* First the special ENCODING and STDSTRINGS entries. */
755         dumpEncoding(g_fout);
756         dumpStdStrings(g_fout);
757
758         /* The database item is always next, unless we don't want it at all */
759         if (include_everything && !dataOnly)
760                 dumpDatabase(g_fout);
761
762         /* Now the rearrangeable objects. */
763         for (i = 0; i < numObjs; i++)
764                 dumpDumpableObject(g_fout, dobjs[i]);
765
766         /*
767          * And finally we can do the actual output.
768          */
769         if (plainText)
770         {
771                 ropt = NewRestoreOptions();
772                 ropt->filename = (char *) filename;
773                 ropt->dropSchema = outputClean;
774                 ropt->aclsSkip = aclsSkip;
775                 ropt->superuser = outputSuperuser;
776                 ropt->createDB = outputCreateDB;
777                 ropt->noOwner = outputNoOwner;
778                 ropt->noTablespace = outputNoTablespaces;
779                 ropt->disable_triggers = disable_triggers;
780                 ropt->use_setsessauth = use_setsessauth;
781                 ropt->dataOnly = dataOnly;
782
783                 if (compressLevel == -1)
784                         ropt->compression = 0;
785                 else
786                         ropt->compression = compressLevel;
787
788                 ropt->suppressDumpWarnings = true;              /* We've already shown them */
789
790                 RestoreArchive(g_fout, ropt);
791         }
792
793         CloseArchive(g_fout);
794
795         PQfinish(g_conn);
796
797         exit(0);
798 }
799
800
801 static void
802 help(const char *progname)
803 {
804         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
805         printf(_("Usage:\n"));
806         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
807
808         printf(_("\nGeneral options:\n"));
809         printf(_("  -f, --file=FILENAME         output file name\n"));
810         printf(_("  -F, --format=c|t|p          output file format (custom, tar, plain text)\n"));
811         printf(_("  -v, --verbose               verbose mode\n"));
812         printf(_("  -Z, --compress=0-9          compression level for compressed formats\n"));
813         printf(_("  --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
814         printf(_("  --help                      show this help, then exit\n"));
815         printf(_("  --version                   output version information, then exit\n"));
816
817         printf(_("\nOptions controlling the output content:\n"));
818         printf(_("  -a, --data-only             dump only the data, not the schema\n"));
819         printf(_("  -b, --blobs                 include large objects in dump\n"));
820         printf(_("  -c, --clean                 clean (drop) database objects before recreating\n"));
821         printf(_("  -C, --create                include commands to create database in dump\n"));
822         printf(_("  -E, --encoding=ENCODING     dump the data in encoding ENCODING\n"));
823         printf(_("  -n, --schema=SCHEMA         dump the named schema(s) only\n"));
824         printf(_("  -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
825         printf(_("  -o, --oids                  include OIDs in dump\n"));
826         printf(_("  -O, --no-owner              skip restoration of object ownership in\n"
827                          "                              plain-text format\n"));
828         printf(_("  -s, --schema-only           dump only the schema, no data\n"));
829         printf(_("  -S, --superuser=NAME        superuser user name to use in plain-text format\n"));
830         printf(_("  -t, --table=TABLE           dump the named table(s) only\n"));
831         printf(_("  -T, --exclude-table=TABLE   do NOT dump the named table(s)\n"));
832         printf(_("  -x, --no-privileges         do not dump privileges (grant/revoke)\n"));
833         printf(_("  --binary-upgrade            for use by upgrade utilities only\n"));
834         printf(_("  --inserts                   dump data as INSERT commands, rather than COPY\n"));
835         printf(_("  --column-inserts            dump data as INSERT commands with column names\n"));
836         printf(_("  --disable-dollar-quoting    disable dollar quoting, use SQL standard quoting\n"));
837         printf(_("  --disable-triggers          disable triggers during data-only restore\n"));
838         printf(_("  --no-tablespaces            do not dump tablespace assignments\n"));
839         printf(_("  --quote-all-identifiers     quote all identifiers, even if not keywords\n"));
840         printf(_("  --role=ROLENAME             do SET ROLE before dump\n"));
841         printf(_("  --use-set-session-authorization\n"
842                          "                              use SET SESSION AUTHORIZATION commands instead of\n"
843         "                              ALTER OWNER commands to set ownership\n"));
844
845         printf(_("\nConnection options:\n"));
846         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
847         printf(_("  -p, --port=PORT          database server port number\n"));
848         printf(_("  -U, --username=NAME      connect as specified database user\n"));
849         printf(_("  -w, --no-password        never prompt for password\n"));
850         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
851
852         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
853                          "variable value is used.\n\n"));
854         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
855 }
856
857 void
858 exit_nicely(void)
859 {
860         PQfinish(g_conn);
861         if (g_verbose)
862                 write_msg(NULL, "*** aborted because of error\n");
863         exit(1);
864 }
865
866 /*
867  * Find the OIDs of all schemas matching the given list of patterns,
868  * and append them to the given OID list.
869  */
870 static void
871 expand_schema_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
872 {
873         PQExpBuffer query;
874         PGresult   *res;
875         SimpleStringListCell *cell;
876         int                     i;
877
878         if (patterns->head == NULL)
879                 return;                                 /* nothing to do */
880
881         if (g_fout->remoteVersion < 70300)
882         {
883                 write_msg(NULL, "server version must be at least 7.3 to use schema selection switches\n");
884                 exit_nicely();
885         }
886
887         query = createPQExpBuffer();
888
889         /*
890          * We use UNION ALL rather than UNION; this might sometimes result in
891          * duplicate entries in the OID list, but we don't care.
892          */
893
894         for (cell = patterns->head; cell; cell = cell->next)
895         {
896                 if (cell != patterns->head)
897                         appendPQExpBuffer(query, "UNION ALL\n");
898                 appendPQExpBuffer(query,
899                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
900                 processSQLNamePattern(g_conn, query, cell->val, false, false,
901                                                           NULL, "n.nspname", NULL,
902                                                           NULL);
903         }
904
905         res = PQexec(g_conn, query->data);
906         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
907
908         for (i = 0; i < PQntuples(res); i++)
909         {
910                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
911         }
912
913         PQclear(res);
914         destroyPQExpBuffer(query);
915 }
916
917 /*
918  * Find the OIDs of all tables matching the given list of patterns,
919  * and append them to the given OID list.
920  */
921 static void
922 expand_table_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
923 {
924         PQExpBuffer query;
925         PGresult   *res;
926         SimpleStringListCell *cell;
927         int                     i;
928
929         if (patterns->head == NULL)
930                 return;                                 /* nothing to do */
931
932         query = createPQExpBuffer();
933
934         /*
935          * We use UNION ALL rather than UNION; this might sometimes result in
936          * duplicate entries in the OID list, but we don't care.
937          */
938
939         for (cell = patterns->head; cell; cell = cell->next)
940         {
941                 if (cell != patterns->head)
942                         appendPQExpBuffer(query, "UNION ALL\n");
943                 appendPQExpBuffer(query,
944                                                   "SELECT c.oid"
945                                                   "\nFROM pg_catalog.pg_class c"
946                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
947                                                   "\nWHERE c.relkind in ('%c', '%c', '%c')\n",
948                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
949                 processSQLNamePattern(g_conn, query, cell->val, true, false,
950                                                           "n.nspname", "c.relname", NULL,
951                                                           "pg_catalog.pg_table_is_visible(c.oid)");
952         }
953
954         res = PQexec(g_conn, query->data);
955         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
956
957         for (i = 0; i < PQntuples(res); i++)
958         {
959                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
960         }
961
962         PQclear(res);
963         destroyPQExpBuffer(query);
964 }
965
966 /*
967  * selectDumpableNamespace: policy-setting subroutine
968  *              Mark a namespace as to be dumped or not
969  */
970 static void
971 selectDumpableNamespace(NamespaceInfo *nsinfo)
972 {
973         /*
974          * If specific tables are being dumped, do not dump any complete
975          * namespaces. If specific namespaces are being dumped, dump just those
976          * namespaces. Otherwise, dump all non-system namespaces.
977          */
978         if (table_include_oids.head != NULL)
979                 nsinfo->dobj.dump = false;
980         else if (schema_include_oids.head != NULL)
981                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
982                                                                                                    nsinfo->dobj.catId.oid);
983         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
984                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
985                 nsinfo->dobj.dump = false;
986         else
987                 nsinfo->dobj.dump = true;
988
989         /*
990          * In any case, a namespace can be excluded by an exclusion switch
991          */
992         if (nsinfo->dobj.dump &&
993                 simple_oid_list_member(&schema_exclude_oids,
994                                                            nsinfo->dobj.catId.oid))
995                 nsinfo->dobj.dump = false;
996 }
997
998 /*
999  * selectDumpableTable: policy-setting subroutine
1000  *              Mark a table as to be dumped or not
1001  */
1002 static void
1003 selectDumpableTable(TableInfo *tbinfo)
1004 {
1005         /*
1006          * If specific tables are being dumped, dump just those tables; else, dump
1007          * according to the parent namespace's dump flag.
1008          */
1009         if (table_include_oids.head != NULL)
1010                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1011                                                                                                    tbinfo->dobj.catId.oid);
1012         else
1013                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1014
1015         /*
1016          * In any case, a table can be excluded by an exclusion switch
1017          */
1018         if (tbinfo->dobj.dump &&
1019                 simple_oid_list_member(&table_exclude_oids,
1020                                                            tbinfo->dobj.catId.oid))
1021                 tbinfo->dobj.dump = false;
1022 }
1023
1024 /*
1025  * selectDumpableType: policy-setting subroutine
1026  *              Mark a type as to be dumped or not
1027  *
1028  * If it's a table's rowtype or an autogenerated array type, we also apply a
1029  * special type code to facilitate sorting into the desired order.      (We don't
1030  * want to consider those to be ordinary types because that would bring tables
1031  * up into the datatype part of the dump order.)  Those tests should be made
1032  * first to ensure the objType change is applied regardless of namespace etc.
1033  */
1034 static void
1035 selectDumpableType(TypeInfo *tyinfo)
1036 {
1037         /* skip complex types, except for standalone composite types */
1038         if (OidIsValid(tyinfo->typrelid) &&
1039                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1040         {
1041                 tyinfo->dobj.dump = false;
1042                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1043         }
1044
1045         /* skip auto-generated array types */
1046         else if (tyinfo->isArray)
1047         {
1048                 tyinfo->dobj.dump = false;
1049                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1050         }
1051
1052         /* dump only types in dumpable namespaces */
1053         else if (!tyinfo->dobj.namespace->dobj.dump)
1054                 tyinfo->dobj.dump = false;
1055
1056         /* skip undefined placeholder types */
1057         else if (!tyinfo->isDefined)
1058                 tyinfo->dobj.dump = false;
1059
1060         else
1061                 tyinfo->dobj.dump = true;
1062 }
1063
1064 /*
1065  * selectDumpableDefaultACL: policy-setting subroutine
1066  *              Mark a default ACL as to be dumped or not
1067  *
1068  * For per-schema default ACLs, dump if the schema is to be dumped.
1069  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1070  * and aclsSkip are checked separately.
1071  */
1072 static void
1073 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1074 {
1075         if (dinfo->dobj.namespace)
1076                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1077         else
1078                 dinfo->dobj.dump = include_everything;
1079 }
1080
1081 /*
1082  * selectDumpableObject: policy-setting subroutine
1083  *              Mark a generic dumpable object as to be dumped or not
1084  *
1085  * Use this only for object types without a special-case routine above.
1086  */
1087 static void
1088 selectDumpableObject(DumpableObject *dobj)
1089 {
1090         /*
1091          * Default policy is to dump if parent namespace is dumpable, or always
1092          * for non-namespace-associated items.
1093          */
1094         if (dobj->namespace)
1095                 dobj->dump = dobj->namespace->dobj.dump;
1096         else
1097                 dobj->dump = true;
1098 }
1099
1100 /*
1101  *      Dump a table's contents for loading using the COPY command
1102  *      - this routine is called by the Archiver when it wants the table
1103  *        to be dumped.
1104  */
1105
1106 static int
1107 dumpTableData_copy(Archive *fout, void *dcontext)
1108 {
1109         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1110         TableInfo  *tbinfo = tdinfo->tdtable;
1111         const char *classname = tbinfo->dobj.name;
1112         const bool      hasoids = tbinfo->hasoids;
1113         const bool      oids = tdinfo->oids;
1114         PQExpBuffer q = createPQExpBuffer();
1115         PGresult   *res;
1116         int                     ret;
1117         char       *copybuf;
1118         const char *column_list;
1119
1120         if (g_verbose)
1121                 write_msg(NULL, "dumping contents of table %s\n", classname);
1122
1123         /*
1124          * Make sure we are in proper schema.  We will qualify the table name
1125          * below anyway (in case its name conflicts with a pg_catalog table); but
1126          * this ensures reproducible results in case the table contains regproc,
1127          * regclass, etc columns.
1128          */
1129         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1130
1131         /*
1132          * If possible, specify the column list explicitly so that we have no
1133          * possibility of retrieving data in the wrong column order.  (The default
1134          * column ordering of COPY will not be what we want in certain corner
1135          * cases involving ADD COLUMN and inheritance.)
1136          */
1137         if (g_fout->remoteVersion >= 70300)
1138                 column_list = fmtCopyColumnList(tbinfo);
1139         else
1140                 column_list = "";               /* can't select columns in COPY */
1141
1142         if (oids && hasoids)
1143         {
1144                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1145                                                   fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1146                                                                                  classname),
1147                                                   column_list);
1148         }
1149         else
1150         {
1151                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1152                                                   fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1153                                                                                  classname),
1154                                                   column_list);
1155         }
1156         res = PQexec(g_conn, q->data);
1157         check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
1158         PQclear(res);
1159
1160         for (;;)
1161         {
1162                 ret = PQgetCopyData(g_conn, &copybuf, 0);
1163
1164                 if (ret < 0)
1165                         break;                          /* done or error */
1166
1167                 if (copybuf)
1168                 {
1169                         WriteData(fout, copybuf, ret);
1170                         PQfreemem(copybuf);
1171                 }
1172
1173                 /* ----------
1174                  * THROTTLE:
1175                  *
1176                  * There was considerable discussion in late July, 2000 regarding
1177                  * slowing down pg_dump when backing up large tables. Users with both
1178                  * slow & fast (multi-processor) machines experienced performance
1179                  * degradation when doing a backup.
1180                  *
1181                  * Initial attempts based on sleeping for a number of ms for each ms
1182                  * of work were deemed too complex, then a simple 'sleep in each loop'
1183                  * implementation was suggested. The latter failed because the loop
1184                  * was too tight. Finally, the following was implemented:
1185                  *
1186                  * If throttle is non-zero, then
1187                  *              See how long since the last sleep.
1188                  *              Work out how long to sleep (based on ratio).
1189                  *              If sleep is more than 100ms, then
1190                  *                      sleep
1191                  *                      reset timer
1192                  *              EndIf
1193                  * EndIf
1194                  *
1195                  * where the throttle value was the number of ms to sleep per ms of
1196                  * work. The calculation was done in each loop.
1197                  *
1198                  * Most of the hard work is done in the backend, and this solution
1199                  * still did not work particularly well: on slow machines, the ratio
1200                  * was 50:1, and on medium paced machines, 1:1, and on fast
1201                  * multi-processor machines, it had little or no effect, for reasons
1202                  * that were unclear.
1203                  *
1204                  * Further discussion ensued, and the proposal was dropped.
1205                  *
1206                  * For those people who want this feature, it can be implemented using
1207                  * gettimeofday in each loop, calculating the time since last sleep,
1208                  * multiplying that by the sleep ratio, then if the result is more
1209                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1210                  * function to sleep for a subsecond period ie.
1211                  *
1212                  * select(0, NULL, NULL, NULL, &tvi);
1213                  *
1214                  * This will return after the interval specified in the structure tvi.
1215                  * Finally, call gettimeofday again to save the 'last sleep time'.
1216                  * ----------
1217                  */
1218         }
1219         archprintf(fout, "\\.\n\n\n");
1220
1221         if (ret == -2)
1222         {
1223                 /* copy data transfer failed */
1224                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1225                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1226                 write_msg(NULL, "The command was: %s\n", q->data);
1227                 exit_nicely();
1228         }
1229
1230         /* Check command status and return to normal libpq state */
1231         res = PQgetResult(g_conn);
1232         check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1233         PQclear(res);
1234
1235         destroyPQExpBuffer(q);
1236         return 1;
1237 }
1238
1239 static int
1240 dumpTableData_insert(Archive *fout, void *dcontext)
1241 {
1242         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1243         TableInfo  *tbinfo = tdinfo->tdtable;
1244         const char *classname = tbinfo->dobj.name;
1245         PQExpBuffer q = createPQExpBuffer();
1246         PGresult   *res;
1247         int                     tuple;
1248         int                     nfields;
1249         int                     field;
1250
1251         /*
1252          * Make sure we are in proper schema.  We will qualify the table name
1253          * below anyway (in case its name conflicts with a pg_catalog table); but
1254          * this ensures reproducible results in case the table contains regproc,
1255          * regclass, etc columns.
1256          */
1257         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1258
1259         if (fout->remoteVersion >= 70100)
1260         {
1261                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1262                                                   "SELECT * FROM ONLY %s",
1263                                                   fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1264                                                                                  classname));
1265         }
1266         else
1267         {
1268                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1269                                                   "SELECT * FROM %s",
1270                                                   fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1271                                                                                  classname));
1272         }
1273
1274         res = PQexec(g_conn, q->data);
1275         check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1276
1277         do
1278         {
1279                 PQclear(res);
1280
1281                 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
1282                 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
1283                                                  PGRES_TUPLES_OK);
1284                 nfields = PQnfields(res);
1285                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1286                 {
1287                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1288                         if (nfields == 0)
1289                         {
1290                                 /* corner case for zero-column table */
1291                                 archprintf(fout, "DEFAULT VALUES;\n");
1292                                 continue;
1293                         }
1294                         if (column_inserts)
1295                         {
1296                                 resetPQExpBuffer(q);
1297                                 appendPQExpBuffer(q, "(");
1298                                 for (field = 0; field < nfields; field++)
1299                                 {
1300                                         if (field > 0)
1301                                                 appendPQExpBuffer(q, ", ");
1302                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1303                                 }
1304                                 appendPQExpBuffer(q, ") ");
1305                                 archputs(q->data, fout);
1306                         }
1307                         archprintf(fout, "VALUES (");
1308                         for (field = 0; field < nfields; field++)
1309                         {
1310                                 if (field > 0)
1311                                         archprintf(fout, ", ");
1312                                 if (PQgetisnull(res, tuple, field))
1313                                 {
1314                                         archprintf(fout, "NULL");
1315                                         continue;
1316                                 }
1317
1318                                 /* XXX This code is partially duplicated in ruleutils.c */
1319                                 switch (PQftype(res, field))
1320                                 {
1321                                         case INT2OID:
1322                                         case INT4OID:
1323                                         case INT8OID:
1324                                         case OIDOID:
1325                                         case FLOAT4OID:
1326                                         case FLOAT8OID:
1327                                         case NUMERICOID:
1328                                                 {
1329                                                         /*
1330                                                          * These types are printed without quotes unless
1331                                                          * they contain values that aren't accepted by the
1332                                                          * scanner unquoted (e.g., 'NaN').      Note that
1333                                                          * strtod() and friends might accept NaN, so we
1334                                                          * can't use that to test.
1335                                                          *
1336                                                          * In reality we only need to defend against
1337                                                          * infinity and NaN, so we need not get too crazy
1338                                                          * about pattern matching here.
1339                                                          */
1340                                                         const char *s = PQgetvalue(res, tuple, field);
1341
1342                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1343                                                                 archprintf(fout, "%s", s);
1344                                                         else
1345                                                                 archprintf(fout, "'%s'", s);
1346                                                 }
1347                                                 break;
1348
1349                                         case BITOID:
1350                                         case VARBITOID:
1351                                                 archprintf(fout, "B'%s'",
1352                                                                    PQgetvalue(res, tuple, field));
1353                                                 break;
1354
1355                                         case BOOLOID:
1356                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1357                                                         archprintf(fout, "true");
1358                                                 else
1359                                                         archprintf(fout, "false");
1360                                                 break;
1361
1362                                         default:
1363                                                 /* All other types are printed as string literals. */
1364                                                 resetPQExpBuffer(q);
1365                                                 appendStringLiteralAH(q,
1366                                                                                           PQgetvalue(res, tuple, field),
1367                                                                                           fout);
1368                                                 archputs(q->data, fout);
1369                                                 break;
1370                                 }
1371                         }
1372                         archprintf(fout, ");\n");
1373                 }
1374         } while (PQntuples(res) > 0);
1375
1376         PQclear(res);
1377
1378         archprintf(fout, "\n\n");
1379
1380         do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1381
1382         destroyPQExpBuffer(q);
1383         return 1;
1384 }
1385
1386
1387 /*
1388  * dumpTableData -
1389  *        dump the contents of a single table
1390  *
1391  * Actually, this just makes an ArchiveEntry for the table contents.
1392  */
1393 static void
1394 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1395 {
1396         TableInfo  *tbinfo = tdinfo->tdtable;
1397         PQExpBuffer copyBuf = createPQExpBuffer();
1398         DataDumperPtr dumpFn;
1399         char       *copyStmt;
1400
1401         if (!dump_inserts)
1402         {
1403                 /* Dump/restore using COPY */
1404                 dumpFn = dumpTableData_copy;
1405                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1406                 appendPQExpBuffer(copyBuf, "COPY %s ",
1407                                                   fmtId(tbinfo->dobj.name));
1408                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1409                                                   fmtCopyColumnList(tbinfo),
1410                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1411                 copyStmt = copyBuf->data;
1412         }
1413         else
1414         {
1415                 /* Restore using INSERT */
1416                 dumpFn = dumpTableData_insert;
1417                 copyStmt = NULL;
1418         }
1419
1420         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1421                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1422                                  NULL, tbinfo->rolname,
1423                                  false, "TABLE DATA", SECTION_DATA,
1424                                  "", "", copyStmt,
1425                                  tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1426                                  dumpFn, tdinfo);
1427
1428         destroyPQExpBuffer(copyBuf);
1429 }
1430
1431 /*
1432  * getTableData -
1433  *        set up dumpable objects representing the contents of tables
1434  */
1435 static void
1436 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1437 {
1438         int                     i;
1439
1440         for (i = 0; i < numTables; i++)
1441         {
1442                 /* Skip VIEWs (no data to dump) */
1443                 if (tblinfo[i].relkind == RELKIND_VIEW)
1444                         continue;
1445                 /* Skip SEQUENCEs (handled elsewhere) */
1446                 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1447                         continue;
1448
1449                 if (tblinfo[i].dobj.dump)
1450                 {
1451                         TableDataInfo *tdinfo;
1452
1453                         tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1454
1455                         tdinfo->dobj.objType = DO_TABLE_DATA;
1456
1457                         /*
1458                          * Note: use tableoid 0 so that this object won't be mistaken for
1459                          * something that pg_depend entries apply to.
1460                          */
1461                         tdinfo->dobj.catId.tableoid = 0;
1462                         tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1463                         AssignDumpId(&tdinfo->dobj);
1464                         tdinfo->dobj.name = tblinfo[i].dobj.name;
1465                         tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1466                         tdinfo->tdtable = &(tblinfo[i]);
1467                         tdinfo->oids = oids;
1468                         addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1469
1470                         tblinfo[i].dataObj = tdinfo;
1471                 }
1472         }
1473 }
1474
1475 /*
1476  * getTableDataFKConstraints -
1477  *        add dump-order dependencies reflecting foreign key constraints
1478  *
1479  * This code is executed only in a data-only dump --- in schema+data dumps
1480  * we handle foreign key issues by not creating the FK constraints until
1481  * after the data is loaded.  In a data-only dump, however, we want to
1482  * order the table data objects in such a way that a table's referenced
1483  * tables are restored first.  (In the presence of circular references or
1484  * self-references this may be impossible; we'll detect and complain about
1485  * that during the dependency sorting step.)
1486  */
1487 static void
1488 getTableDataFKConstraints(void)
1489 {
1490         DumpableObject **dobjs;
1491         int                     numObjs;
1492         int                     i;
1493
1494         /* Search through all the dumpable objects for FK constraints */
1495         getDumpableObjects(&dobjs, &numObjs);
1496         for (i = 0; i < numObjs; i++)
1497         {
1498                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1499                 {
1500                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1501                         TableInfo  *ftable;
1502
1503                         /* Not interesting unless both tables are to be dumped */
1504                         if (cinfo->contable == NULL ||
1505                                 cinfo->contable->dataObj == NULL)
1506                                 continue;
1507                         ftable = findTableByOid(cinfo->confrelid);
1508                         if (ftable == NULL ||
1509                                 ftable->dataObj == NULL)
1510                                 continue;
1511
1512                         /*
1513                          * Okay, make referencing table's TABLE_DATA object depend on the
1514                          * referenced table's TABLE_DATA object.
1515                          */
1516                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1517                                                                 ftable->dataObj->dobj.dumpId);
1518                 }
1519         }
1520         free(dobjs);
1521 }
1522
1523
1524 /*
1525  * guessConstraintInheritance:
1526  *      In pre-8.4 databases, we can't tell for certain which constraints
1527  *      are inherited.  We assume a CHECK constraint is inherited if its name
1528  *      matches the name of any constraint in the parent.  Originally this code
1529  *      tried to compare the expression texts, but that can fail for various
1530  *      reasons --- for example, if the parent and child tables are in different
1531  *      schemas, reverse-listing of function calls may produce different text
1532  *      (schema-qualified or not) depending on search path.
1533  *
1534  *      In 8.4 and up we can rely on the conislocal field to decide which
1535  *      constraints must be dumped; much safer.
1536  *
1537  *      This function assumes all conislocal flags were initialized to TRUE.
1538  *      It clears the flag on anything that seems to be inherited.
1539  */
1540 static void
1541 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1542 {
1543         int                     i,
1544                                 j,
1545                                 k;
1546
1547         for (i = 0; i < numTables; i++)
1548         {
1549                 TableInfo  *tbinfo = &(tblinfo[i]);
1550                 int                     numParents;
1551                 TableInfo **parents;
1552                 TableInfo  *parent;
1553
1554                 /* Sequences and views never have parents */
1555                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1556                         tbinfo->relkind == RELKIND_VIEW)
1557                         continue;
1558
1559                 /* Don't bother computing anything for non-target tables, either */
1560                 if (!tbinfo->dobj.dump)
1561                         continue;
1562
1563                 numParents = tbinfo->numParents;
1564                 parents = tbinfo->parents;
1565
1566                 if (numParents == 0)
1567                         continue;                       /* nothing to see here, move along */
1568
1569                 /* scan for inherited CHECK constraints */
1570                 for (j = 0; j < tbinfo->ncheck; j++)
1571                 {
1572                         ConstraintInfo *constr;
1573
1574                         constr = &(tbinfo->checkexprs[j]);
1575
1576                         for (k = 0; k < numParents; k++)
1577                         {
1578                                 int                     l;
1579
1580                                 parent = parents[k];
1581                                 for (l = 0; l < parent->ncheck; l++)
1582                                 {
1583                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1584
1585                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1586                                         {
1587                                                 constr->conislocal = false;
1588                                                 break;
1589                                         }
1590                                 }
1591                                 if (!constr->conislocal)
1592                                         break;
1593                         }
1594                 }
1595         }
1596 }
1597
1598
1599 /*
1600  * dumpDatabase:
1601  *      dump the database definition
1602  */
1603 static void
1604 dumpDatabase(Archive *AH)
1605 {
1606         PQExpBuffer dbQry = createPQExpBuffer();
1607         PQExpBuffer delQry = createPQExpBuffer();
1608         PQExpBuffer creaQry = createPQExpBuffer();
1609         PGresult   *res;
1610         int                     ntups;
1611         int                     i_tableoid,
1612                                 i_oid,
1613                                 i_dba,
1614                                 i_encoding,
1615                                 i_collate,
1616                                 i_ctype,
1617                                 i_frozenxid,
1618                                 i_tablespace;
1619         CatalogId       dbCatId;
1620         DumpId          dbDumpId;
1621         const char *datname,
1622                            *dba,
1623                            *encoding,
1624                            *collate,
1625                            *ctype,
1626                            *tablespace;
1627         uint32          frozenxid;
1628
1629         datname = PQdb(g_conn);
1630
1631         if (g_verbose)
1632                 write_msg(NULL, "saving database definition\n");
1633
1634         /* Make sure we are in proper schema */
1635         selectSourceSchema("pg_catalog");
1636
1637         /* Get the database owner and parameters from pg_database */
1638         if (g_fout->remoteVersion >= 80400)
1639         {
1640                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1641                                                   "(%s datdba) AS dba, "
1642                                                   "pg_encoding_to_char(encoding) AS encoding, "
1643                                                   "datcollate, datctype, datfrozenxid, "
1644                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1645                                           "shobj_description(oid, 'pg_database') AS description "
1646
1647                                                   "FROM pg_database "
1648                                                   "WHERE datname = ",
1649                                                   username_subquery);
1650                 appendStringLiteralAH(dbQry, datname, AH);
1651         }
1652         else if (g_fout->remoteVersion >= 80200)
1653         {
1654                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1655                                                   "(%s datdba) AS dba, "
1656                                                   "pg_encoding_to_char(encoding) AS encoding, "
1657                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1658                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1659                                           "shobj_description(oid, 'pg_database') AS description "
1660
1661                                                   "FROM pg_database "
1662                                                   "WHERE datname = ",
1663                                                   username_subquery);
1664                 appendStringLiteralAH(dbQry, datname, AH);
1665         }
1666         else if (g_fout->remoteVersion >= 80000)
1667         {
1668                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1669                                                   "(%s datdba) AS dba, "
1670                                                   "pg_encoding_to_char(encoding) AS encoding, "
1671                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1672                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1673                                                   "FROM pg_database "
1674                                                   "WHERE datname = ",
1675                                                   username_subquery);
1676                 appendStringLiteralAH(dbQry, datname, AH);
1677         }
1678         else if (g_fout->remoteVersion >= 70100)
1679         {
1680                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1681                                                   "(%s datdba) AS dba, "
1682                                                   "pg_encoding_to_char(encoding) AS encoding, "
1683                                                   "NULL AS datcollate, NULL AS datctype, "
1684                                                   "0 AS datfrozenxid, "
1685                                                   "NULL AS tablespace "
1686                                                   "FROM pg_database "
1687                                                   "WHERE datname = ",
1688                                                   username_subquery);
1689                 appendStringLiteralAH(dbQry, datname, AH);
1690         }
1691         else
1692         {
1693                 appendPQExpBuffer(dbQry, "SELECT "
1694                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1695                                                   "oid, "
1696                                                   "(%s datdba) AS dba, "
1697                                                   "pg_encoding_to_char(encoding) AS encoding, "
1698                                                   "NULL AS datcollate, NULL AS datctype, "
1699                                                   "0 AS datfrozenxid, "
1700                                                   "NULL AS tablespace "
1701                                                   "FROM pg_database "
1702                                                   "WHERE datname = ",
1703                                                   username_subquery);
1704                 appendStringLiteralAH(dbQry, datname, AH);
1705         }
1706
1707         res = PQexec(g_conn, dbQry->data);
1708         check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1709
1710         ntups = PQntuples(res);
1711
1712         if (ntups <= 0)
1713         {
1714                 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1715                                   datname);
1716                 exit_nicely();
1717         }
1718
1719         if (ntups != 1)
1720         {
1721                 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1722                                   ntups, datname);
1723                 exit_nicely();
1724         }
1725
1726         i_tableoid = PQfnumber(res, "tableoid");
1727         i_oid = PQfnumber(res, "oid");
1728         i_dba = PQfnumber(res, "dba");
1729         i_encoding = PQfnumber(res, "encoding");
1730         i_collate = PQfnumber(res, "datcollate");
1731         i_ctype = PQfnumber(res, "datctype");
1732         i_frozenxid = PQfnumber(res, "datfrozenxid");
1733         i_tablespace = PQfnumber(res, "tablespace");
1734
1735         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1736         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1737         dba = PQgetvalue(res, 0, i_dba);
1738         encoding = PQgetvalue(res, 0, i_encoding);
1739         collate = PQgetvalue(res, 0, i_collate);
1740         ctype = PQgetvalue(res, 0, i_ctype);
1741         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1742         tablespace = PQgetvalue(res, 0, i_tablespace);
1743
1744         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1745                                           fmtId(datname));
1746         if (strlen(encoding) > 0)
1747         {
1748                 appendPQExpBuffer(creaQry, " ENCODING = ");
1749                 appendStringLiteralAH(creaQry, encoding, AH);
1750         }
1751         if (strlen(collate) > 0)
1752         {
1753                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1754                 appendStringLiteralAH(creaQry, collate, AH);
1755         }
1756         if (strlen(ctype) > 0)
1757         {
1758                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1759                 appendStringLiteralAH(creaQry, ctype, AH);
1760         }
1761         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1762                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1763                                                   fmtId(tablespace));
1764         appendPQExpBuffer(creaQry, ";\n");
1765
1766         if (binary_upgrade)
1767         {
1768                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1769                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1770                                                   "SET datfrozenxid = '%u'\n"
1771                                                   "WHERE        datname = ",
1772                                                   frozenxid);
1773                 appendStringLiteralAH(creaQry, datname, AH);
1774                 appendPQExpBuffer(creaQry, ";\n");
1775
1776         }
1777
1778         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1779                                           fmtId(datname));
1780
1781         dbDumpId = createDumpId();
1782
1783         ArchiveEntry(AH,
1784                                  dbCatId,               /* catalog ID */
1785                                  dbDumpId,              /* dump ID */
1786                                  datname,               /* Name */
1787                                  NULL,                  /* Namespace */
1788                                  NULL,                  /* Tablespace */
1789                                  dba,                   /* Owner */
1790                                  false,                 /* with oids */
1791                                  "DATABASE",    /* Desc */
1792                                  SECTION_PRE_DATA,              /* Section */
1793                                  creaQry->data, /* Create */
1794                                  delQry->data,  /* Del */
1795                                  NULL,                  /* Copy */
1796                                  NULL,                  /* Deps */
1797                                  0,                             /* # Deps */
1798                                  NULL,                  /* Dumper */
1799                                  NULL);                 /* Dumper Arg */
1800
1801         /*
1802          * pg_largeobject comes from the old system intact, so set its
1803          * relfrozenxid.
1804          */
1805         if (binary_upgrade)
1806         {
1807                 PGresult   *lo_res;
1808                 PQExpBuffer loFrozenQry = createPQExpBuffer();
1809                 PQExpBuffer loOutQry = createPQExpBuffer();
1810                 int                     i_relfrozenxid;
1811
1812                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1813                                                   "FROM pg_catalog.pg_class\n"
1814                                                   "WHERE oid = %u;\n",
1815                                                   LargeObjectRelationId);
1816
1817                 lo_res = PQexec(g_conn, loFrozenQry->data);
1818                 check_sql_result(lo_res, g_conn, loFrozenQry->data, PGRES_TUPLES_OK);
1819
1820                 if (PQntuples(lo_res) != 1)
1821                 {
1822                         write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
1823                         exit_nicely();
1824                 }
1825
1826                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1827
1828                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid.\n");
1829                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1830                                                   "SET relfrozenxid = '%u'\n"
1831                                                   "WHERE oid = %u;\n",
1832                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1833                                                   LargeObjectRelationId);
1834                 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1835                                          "pg_largeobject", NULL, NULL, "",
1836                                          false, "pg_largeobject", SECTION_PRE_DATA,
1837                                          loOutQry->data, "", NULL,
1838                                          NULL, 0,
1839                                          NULL, NULL);
1840
1841                 PQclear(lo_res);
1842                 destroyPQExpBuffer(loFrozenQry);
1843                 destroyPQExpBuffer(loOutQry);
1844         }
1845
1846         /* Dump DB comment if any */
1847         if (g_fout->remoteVersion >= 80200)
1848         {
1849                 /*
1850                  * 8.2 keeps comments on shared objects in a shared table, so we
1851                  * cannot use the dumpComment used for other database objects.
1852                  */
1853                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
1854
1855                 if (comment && strlen(comment))
1856                 {
1857                         resetPQExpBuffer(dbQry);
1858
1859                         /*
1860                          * Generates warning when loaded into a differently-named
1861                          * database.
1862                          */
1863                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
1864                         appendStringLiteralAH(dbQry, comment, AH);
1865                         appendPQExpBuffer(dbQry, ";\n");
1866
1867                         ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
1868                                                  dba, false, "COMMENT", SECTION_NONE,
1869                                                  dbQry->data, "", NULL,
1870                                                  &dbDumpId, 1, NULL, NULL);
1871                 }
1872         }
1873         else
1874         {
1875                 resetPQExpBuffer(dbQry);
1876                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1877                 dumpComment(AH, dbQry->data, NULL, "",
1878                                         dbCatId, 0, dbDumpId);
1879         }
1880
1881         PQclear(res);
1882
1883         destroyPQExpBuffer(dbQry);
1884         destroyPQExpBuffer(delQry);
1885         destroyPQExpBuffer(creaQry);
1886 }
1887
1888
1889 /*
1890  * dumpEncoding: put the correct encoding into the archive
1891  */
1892 static void
1893 dumpEncoding(Archive *AH)
1894 {
1895         const char *encname = pg_encoding_to_char(AH->encoding);
1896         PQExpBuffer qry = createPQExpBuffer();
1897
1898         if (g_verbose)
1899                 write_msg(NULL, "saving encoding = %s\n", encname);
1900
1901         appendPQExpBuffer(qry, "SET client_encoding = ");
1902         appendStringLiteralAH(qry, encname, AH);
1903         appendPQExpBuffer(qry, ";\n");
1904
1905         ArchiveEntry(AH, nilCatalogId, createDumpId(),
1906                                  "ENCODING", NULL, NULL, "",
1907                                  false, "ENCODING", SECTION_PRE_DATA,
1908                                  qry->data, "", NULL,
1909                                  NULL, 0,
1910                                  NULL, NULL);
1911
1912         destroyPQExpBuffer(qry);
1913 }
1914
1915
1916 /*
1917  * dumpStdStrings: put the correct escape string behavior into the archive
1918  */
1919 static void
1920 dumpStdStrings(Archive *AH)
1921 {
1922         const char *stdstrings = AH->std_strings ? "on" : "off";
1923         PQExpBuffer qry = createPQExpBuffer();
1924
1925         if (g_verbose)
1926                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
1927                                   stdstrings);
1928
1929         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
1930                                           stdstrings);
1931
1932         ArchiveEntry(AH, nilCatalogId, createDumpId(),
1933                                  "STDSTRINGS", NULL, NULL, "",
1934                                  false, "STDSTRINGS", SECTION_PRE_DATA,
1935                                  qry->data, "", NULL,
1936                                  NULL, 0,
1937                                  NULL, NULL);
1938
1939         destroyPQExpBuffer(qry);
1940 }
1941
1942
1943 /*
1944  * getBlobs:
1945  *      Collect schema-level data about large objects
1946  */
1947 static void
1948 getBlobs(Archive *AH)
1949 {
1950         PQExpBuffer blobQry = createPQExpBuffer();
1951         BlobInfo   *binfo;
1952         DumpableObject *bdata;
1953         PGresult   *res;
1954         int                     ntups;
1955         int                     i;
1956
1957         /* Verbose message */
1958         if (g_verbose)
1959                 write_msg(NULL, "reading large objects\n");
1960
1961         /* Make sure we are in proper schema */
1962         selectSourceSchema("pg_catalog");
1963
1964         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
1965         if (AH->remoteVersion >= 90000)
1966                 appendPQExpBuffer(blobQry,
1967                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
1968                                                   " FROM pg_largeobject_metadata",
1969                                                   username_subquery);
1970         else if (AH->remoteVersion >= 70100)
1971                 appendPQExpBuffer(blobQry,
1972                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
1973                                                   " FROM pg_largeobject");
1974         else
1975                 appendPQExpBuffer(blobQry,
1976                                                   "SELECT oid, NULL::oid, NULL::oid"
1977                                                   " FROM pg_class WHERE relkind = 'l'");
1978
1979         res = PQexec(g_conn, blobQry->data);
1980         check_sql_result(res, g_conn, blobQry->data, PGRES_TUPLES_OK);
1981
1982         ntups = PQntuples(res);
1983         if (ntups > 0)
1984         {
1985                 /*
1986                  * Each large object has its own BLOB archive entry.
1987                  */
1988                 binfo = (BlobInfo *) malloc(ntups * sizeof(BlobInfo));
1989
1990                 for (i = 0; i < ntups; i++)
1991                 {
1992                         binfo[i].dobj.objType = DO_BLOB;
1993                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
1994                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
1995                         AssignDumpId(&binfo[i].dobj);
1996
1997                         binfo[i].dobj.name = strdup(PQgetvalue(res, i, 0));
1998                         if (!PQgetisnull(res, i, 1))
1999                                 binfo[i].rolname = strdup(PQgetvalue(res, i, 1));
2000                         else
2001                                 binfo[i].rolname = "";
2002                         if (!PQgetisnull(res, i, 2))
2003                                 binfo[i].blobacl = strdup(PQgetvalue(res, i, 2));
2004                         else
2005                                 binfo[i].blobacl = NULL;
2006                 }
2007
2008                 /*
2009                  * If we have any large objects, a "BLOBS" archive entry is needed.
2010                  * This is just a placeholder for sorting; it carries no data now.
2011                  */
2012                 bdata = (DumpableObject *) malloc(sizeof(DumpableObject));
2013                 bdata->objType = DO_BLOB_DATA;
2014                 bdata->catId = nilCatalogId;
2015                 AssignDumpId(bdata);
2016                 bdata->name = strdup("BLOBS");
2017         }
2018
2019         PQclear(res);
2020         destroyPQExpBuffer(blobQry);
2021 }
2022
2023 /*
2024  * dumpBlob
2025  *
2026  * dump the definition (metadata) of the given large object
2027  */
2028 static void
2029 dumpBlob(Archive *AH, BlobInfo *binfo)
2030 {
2031         PQExpBuffer cquery = createPQExpBuffer();
2032         PQExpBuffer dquery = createPQExpBuffer();
2033
2034         appendPQExpBuffer(cquery,
2035                                           "SELECT pg_catalog.lo_create('%s');\n",
2036                                           binfo->dobj.name);
2037
2038         appendPQExpBuffer(dquery,
2039                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2040                                           binfo->dobj.name);
2041
2042         ArchiveEntry(AH, binfo->dobj.catId, binfo->dobj.dumpId,
2043                                  binfo->dobj.name,
2044                                  NULL, NULL,
2045                                  binfo->rolname, false,
2046                                  "BLOB", SECTION_PRE_DATA,
2047                                  cquery->data, dquery->data, NULL,
2048                                  binfo->dobj.dependencies, binfo->dobj.nDeps,
2049                                  NULL, NULL);
2050
2051         /* set up tag for comment and/or ACL */
2052         resetPQExpBuffer(cquery);
2053         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2054
2055         /* Dump comment if any */
2056         dumpComment(AH, cquery->data,
2057                                 NULL, binfo->rolname,
2058                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2059
2060         /* Dump ACL if any */
2061         if (binfo->blobacl)
2062                 dumpACL(AH, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2063                                 binfo->dobj.name, NULL, cquery->data,
2064                                 NULL, binfo->rolname, binfo->blobacl);
2065
2066         destroyPQExpBuffer(cquery);
2067         destroyPQExpBuffer(dquery);
2068 }
2069
2070 /*
2071  * dumpBlobs:
2072  *      dump the data contents of all large objects
2073  */
2074 static int
2075 dumpBlobs(Archive *AH, void *arg)
2076 {
2077         const char *blobQry;
2078         const char *blobFetchQry;
2079         PGresult   *res;
2080         char            buf[LOBBUFSIZE];
2081         int                     ntups;
2082         int                     i;
2083         int                     cnt;
2084
2085         if (g_verbose)
2086                 write_msg(NULL, "saving large objects\n");
2087
2088         /* Make sure we are in proper schema */
2089         selectSourceSchema("pg_catalog");
2090
2091         /*
2092          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2093          * the already-in-memory dumpable objects instead...
2094          */
2095         if (AH->remoteVersion >= 90000)
2096                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2097         else if (AH->remoteVersion >= 70100)
2098                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2099         else
2100                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2101
2102         res = PQexec(g_conn, blobQry);
2103         check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
2104
2105         /* Command to fetch from cursor */
2106         blobFetchQry = "FETCH 1000 IN bloboid";
2107
2108         do
2109         {
2110                 PQclear(res);
2111
2112                 /* Do a fetch */
2113                 res = PQexec(g_conn, blobFetchQry);
2114                 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
2115
2116                 /* Process the tuples, if any */
2117                 ntups = PQntuples(res);
2118                 for (i = 0; i < ntups; i++)
2119                 {
2120                         Oid                     blobOid;
2121                         int                     loFd;
2122
2123                         blobOid = atooid(PQgetvalue(res, i, 0));
2124                         /* Open the BLOB */
2125                         loFd = lo_open(g_conn, blobOid, INV_READ);
2126                         if (loFd == -1)
2127                         {
2128                                 write_msg(NULL, "could not open large object %u: %s",
2129                                                   blobOid, PQerrorMessage(g_conn));
2130                                 exit_nicely();
2131                         }
2132
2133                         StartBlob(AH, blobOid);
2134
2135                         /* Now read it in chunks, sending data to archive */
2136                         do
2137                         {
2138                                 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2139                                 if (cnt < 0)
2140                                 {
2141                                         write_msg(NULL, "error reading large object %u: %s",
2142                                                           blobOid, PQerrorMessage(g_conn));
2143                                         exit_nicely();
2144                                 }
2145
2146                                 WriteData(AH, buf, cnt);
2147                         } while (cnt > 0);
2148
2149                         lo_close(g_conn, loFd);
2150
2151                         EndBlob(AH, blobOid);
2152                 }
2153         } while (ntups > 0);
2154
2155         PQclear(res);
2156
2157         return 1;
2158 }
2159
2160 static void
2161 binary_upgrade_set_type_oids_by_type_oid(PQExpBuffer upgrade_buffer,
2162                                                                                  Oid pg_type_oid)
2163 {
2164         PQExpBuffer upgrade_query = createPQExpBuffer();
2165         int                     ntups;
2166         PGresult   *upgrade_res;
2167         Oid                     pg_type_array_oid;
2168
2169         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2170         appendPQExpBuffer(upgrade_buffer,
2171          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2172                                           pg_type_oid);
2173
2174         /* we only support old >= 8.3 for binary upgrades */
2175         appendPQExpBuffer(upgrade_query,
2176                                           "SELECT typarray "
2177                                           "FROM pg_catalog.pg_type "
2178                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2179                                           pg_type_oid);
2180
2181         upgrade_res = PQexec(g_conn, upgrade_query->data);
2182         check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2183
2184         /* Expecting a single result only */
2185         ntups = PQntuples(upgrade_res);
2186         if (ntups != 1)
2187         {
2188                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2189                                                            "query returned %d rows instead of one: %s\n",
2190                                                                  ntups),
2191                                   ntups, upgrade_query->data);
2192                 exit_nicely();
2193         }
2194
2195         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2196
2197         if (OidIsValid(pg_type_array_oid))
2198         {
2199                 appendPQExpBuffer(upgrade_buffer,
2200                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2201                 appendPQExpBuffer(upgrade_buffer,
2202                                                   "SELECT binary_upgrade.set_next_pg_type_array_oid('%u'::pg_catalog.oid);\n\n",
2203                                                   pg_type_array_oid);
2204         }
2205
2206         PQclear(upgrade_res);
2207         destroyPQExpBuffer(upgrade_query);
2208 }
2209
2210 static bool
2211 binary_upgrade_set_type_oids_by_rel_oid(PQExpBuffer upgrade_buffer,
2212                                                                                 Oid pg_rel_oid)
2213 {
2214         PQExpBuffer upgrade_query = createPQExpBuffer();
2215         int                     ntups;
2216         PGresult   *upgrade_res;
2217         Oid                     pg_type_oid;
2218         bool            toast_set = false;
2219
2220         /* we only support old >= 8.3 for binary upgrades */
2221         appendPQExpBuffer(upgrade_query,
2222                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2223                                           "FROM pg_catalog.pg_class c "
2224                                           "LEFT JOIN pg_catalog.pg_class t ON "
2225                                           "  (c.reltoastrelid = t.oid) "
2226                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2227                                           pg_rel_oid);
2228
2229         upgrade_res = PQexec(g_conn, upgrade_query->data);
2230         check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2231
2232         /* Expecting a single result only */
2233         ntups = PQntuples(upgrade_res);
2234         if (ntups != 1)
2235         {
2236                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2237                                                            "query returned %d rows instead of one: %s\n",
2238                                                                  ntups),
2239                                   ntups, upgrade_query->data);
2240                 exit_nicely();
2241         }
2242
2243         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2244
2245         binary_upgrade_set_type_oids_by_type_oid(upgrade_buffer, pg_type_oid);
2246
2247         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2248         {
2249                 /* Toast tables do not have pg_type array rows */
2250                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2251                                                                                         PQfnumber(upgrade_res, "trel")));
2252
2253                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2254                 appendPQExpBuffer(upgrade_buffer,
2255                                                   "SELECT binary_upgrade.set_next_pg_type_toast_oid('%u'::pg_catalog.oid);\n\n",
2256                                                   pg_type_toast_oid);
2257
2258                 toast_set = true;
2259         }
2260
2261         PQclear(upgrade_res);
2262         destroyPQExpBuffer(upgrade_query);
2263
2264         return toast_set;
2265 }
2266
2267 static void
2268 binary_upgrade_set_relfilenodes(PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2269                                                                 bool is_index)
2270 {
2271         PQExpBuffer upgrade_query = createPQExpBuffer();
2272         int                     ntups;
2273         PGresult   *upgrade_res;
2274         Oid                     pg_class_relfilenode;
2275         Oid                     pg_class_reltoastrelid;
2276         Oid                     pg_class_reltoastidxid;
2277
2278         /*
2279          * Note: we don't need to use pg_relation_filenode() here because this
2280          * function is not intended to be used against system catalogs. Otherwise
2281          * we'd have to worry about which versions pg_relation_filenode is
2282          * available in.
2283          */
2284         appendPQExpBuffer(upgrade_query,
2285                                         "SELECT c.relfilenode, c.reltoastrelid, t.reltoastidxid "
2286                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2287                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2288                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2289                                           pg_class_oid);
2290
2291         upgrade_res = PQexec(g_conn, upgrade_query->data);
2292         check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2293
2294         /* Expecting a single result only */
2295         ntups = PQntuples(upgrade_res);
2296         if (ntups != 1)
2297         {
2298                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2299                                                            "query returned %d rows instead of one: %s\n",
2300                                                                  ntups),
2301                                   ntups, upgrade_query->data);
2302                 exit_nicely();
2303         }
2304
2305         pg_class_relfilenode = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "relfilenode")));
2306         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2307         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2308
2309         appendPQExpBuffer(upgrade_buffer,
2310                                         "\n-- For binary upgrade, must preserve relfilenodes\n");
2311
2312         if (!is_index)
2313                 appendPQExpBuffer(upgrade_buffer,
2314                                                   "SELECT binary_upgrade.set_next_heap_relfilenode('%u'::pg_catalog.oid);\n",
2315                                                   pg_class_relfilenode);
2316         else
2317                 appendPQExpBuffer(upgrade_buffer,
2318                                                   "SELECT binary_upgrade.set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
2319                                                   pg_class_relfilenode);
2320
2321         if (OidIsValid(pg_class_reltoastrelid))
2322         {
2323                 /*
2324                  * One complexity is that the table definition might not require the
2325                  * creation of a TOAST table, and the TOAST table might have been
2326                  * created long after table creation, when the table was loaded with
2327                  * wide data.  By setting the TOAST relfilenode we force creation of
2328                  * the TOAST heap and TOAST index by the backend so we can cleanly
2329                  * migrate the files during binary migration.
2330                  */
2331
2332                 appendPQExpBuffer(upgrade_buffer,
2333                                                   "SELECT binary_upgrade.set_next_toast_relfilenode('%u'::pg_catalog.oid);\n",
2334                                                   pg_class_reltoastrelid);
2335
2336                 /* every toast table has an index */
2337                 appendPQExpBuffer(upgrade_buffer,
2338                                                   "SELECT binary_upgrade.set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
2339                                                   pg_class_reltoastidxid);
2340         }
2341         appendPQExpBuffer(upgrade_buffer, "\n");
2342
2343         PQclear(upgrade_res);
2344         destroyPQExpBuffer(upgrade_query);
2345 }
2346
2347 /*
2348  * getNamespaces:
2349  *        read all namespaces in the system catalogs and return them in the
2350  * NamespaceInfo* structure
2351  *
2352  *      numNamespaces is set to the number of namespaces read in
2353  */
2354 NamespaceInfo *
2355 getNamespaces(int *numNamespaces)
2356 {
2357         PGresult   *res;
2358         int                     ntups;
2359         int                     i;
2360         PQExpBuffer query;
2361         NamespaceInfo *nsinfo;
2362         int                     i_tableoid;
2363         int                     i_oid;
2364         int                     i_nspname;
2365         int                     i_rolname;
2366         int                     i_nspacl;
2367
2368         /*
2369          * Before 7.3, there are no real namespaces; create two dummy entries, one
2370          * for user stuff and one for system stuff.
2371          */
2372         if (g_fout->remoteVersion < 70300)
2373         {
2374                 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
2375
2376                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2377                 nsinfo[0].dobj.catId.tableoid = 0;
2378                 nsinfo[0].dobj.catId.oid = 0;
2379                 AssignDumpId(&nsinfo[0].dobj);
2380                 nsinfo[0].dobj.name = strdup("public");
2381                 nsinfo[0].rolname = strdup("");
2382                 nsinfo[0].nspacl = strdup("");
2383
2384                 selectDumpableNamespace(&nsinfo[0]);
2385
2386                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2387                 nsinfo[1].dobj.catId.tableoid = 0;
2388                 nsinfo[1].dobj.catId.oid = 1;
2389                 AssignDumpId(&nsinfo[1].dobj);
2390                 nsinfo[1].dobj.name = strdup("pg_catalog");
2391                 nsinfo[1].rolname = strdup("");
2392                 nsinfo[1].nspacl = strdup("");
2393
2394                 selectDumpableNamespace(&nsinfo[1]);
2395
2396                 g_namespaces = nsinfo;
2397                 g_numNamespaces = *numNamespaces = 2;
2398
2399                 return nsinfo;
2400         }
2401
2402         query = createPQExpBuffer();
2403
2404         /* Make sure we are in proper schema */
2405         selectSourceSchema("pg_catalog");
2406
2407         /*
2408          * we fetch all namespaces including system ones, so that every object we
2409          * read in can be linked to a containing namespace.
2410          */
2411         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2412                                           "(%s nspowner) AS rolname, "
2413                                           "nspacl FROM pg_namespace",
2414                                           username_subquery);
2415
2416         res = PQexec(g_conn, query->data);
2417         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2418
2419         ntups = PQntuples(res);
2420
2421         nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
2422
2423         i_tableoid = PQfnumber(res, "tableoid");
2424         i_oid = PQfnumber(res, "oid");
2425         i_nspname = PQfnumber(res, "nspname");
2426         i_rolname = PQfnumber(res, "rolname");
2427         i_nspacl = PQfnumber(res, "nspacl");
2428
2429         for (i = 0; i < ntups; i++)
2430         {
2431                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2432                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2433                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2434                 AssignDumpId(&nsinfo[i].dobj);
2435                 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
2436                 nsinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2437                 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
2438
2439                 /* Decide whether to dump this namespace */
2440                 selectDumpableNamespace(&nsinfo[i]);
2441
2442                 if (strlen(nsinfo[i].rolname) == 0)
2443                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2444                                           nsinfo[i].dobj.name);
2445         }
2446
2447         PQclear(res);
2448         destroyPQExpBuffer(query);
2449
2450         g_namespaces = nsinfo;
2451         g_numNamespaces = *numNamespaces = ntups;
2452
2453         return nsinfo;
2454 }
2455
2456 /*
2457  * findNamespace:
2458  *              given a namespace OID and an object OID, look up the info read by
2459  *              getNamespaces
2460  *
2461  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2462  * a system object or not.      In 7.3 and later there is no guessing.
2463  */
2464 static NamespaceInfo *
2465 findNamespace(Oid nsoid, Oid objoid)
2466 {
2467         int                     i;
2468
2469         if (g_fout->remoteVersion >= 70300)
2470         {
2471                 for (i = 0; i < g_numNamespaces; i++)
2472                 {
2473                         NamespaceInfo *nsinfo = &g_namespaces[i];
2474
2475                         if (nsoid == nsinfo->dobj.catId.oid)
2476                                 return nsinfo;
2477                 }
2478                 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2479                 exit_nicely();
2480         }
2481         else
2482         {
2483                 /* This code depends on the layout set up by getNamespaces. */
2484                 if (objoid > g_last_builtin_oid)
2485                         i = 0;                          /* user object */
2486                 else
2487                         i = 1;                          /* system object */
2488                 return &g_namespaces[i];
2489         }
2490
2491         return NULL;                            /* keep compiler quiet */
2492 }
2493
2494 /*
2495  * getTypes:
2496  *        read all types in the system catalogs and return them in the
2497  * TypeInfo* structure
2498  *
2499  *      numTypes is set to the number of types read in
2500  *
2501  * NB: this must run after getFuncs() because we assume we can do
2502  * findFuncByOid().
2503  */
2504 TypeInfo *
2505 getTypes(int *numTypes)
2506 {
2507         PGresult   *res;
2508         int                     ntups;
2509         int                     i;
2510         PQExpBuffer query = createPQExpBuffer();
2511         TypeInfo   *tyinfo;
2512         ShellTypeInfo *stinfo;
2513         int                     i_tableoid;
2514         int                     i_oid;
2515         int                     i_typname;
2516         int                     i_typnamespace;
2517         int                     i_rolname;
2518         int                     i_typinput;
2519         int                     i_typoutput;
2520         int                     i_typelem;
2521         int                     i_typrelid;
2522         int                     i_typrelkind;
2523         int                     i_typtype;
2524         int                     i_typisdefined;
2525         int                     i_isarray;
2526
2527         /*
2528          * we include even the built-in types because those may be used as array
2529          * elements by user-defined types
2530          *
2531          * we filter out the built-in types when we dump out the types
2532          *
2533          * same approach for undefined (shell) types and array types
2534          *
2535          * Note: as of 8.3 we can reliably detect whether a type is an
2536          * auto-generated array type by checking the element type's typarray.
2537          * (Before that the test is capable of generating false positives.) We
2538          * still check for name beginning with '_', though, so as to avoid the
2539          * cost of the subselect probe for all standard types.  This would have to
2540          * be revisited if the backend ever allows renaming of array types.
2541          */
2542
2543         /* Make sure we are in proper schema */
2544         selectSourceSchema("pg_catalog");
2545
2546         if (g_fout->remoteVersion >= 80300)
2547         {
2548                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2549                                                   "typnamespace, "
2550                                                   "(%s typowner) AS rolname, "
2551                                                   "typinput::oid AS typinput, "
2552                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2553                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2554                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2555                                                   "typtype, typisdefined, "
2556                                                   "typname[0] = '_' AND typelem != 0 AND "
2557                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2558                                                   "FROM pg_type",
2559                                                   username_subquery);
2560         }
2561         else if (g_fout->remoteVersion >= 70300)
2562         {
2563                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2564                                                   "typnamespace, "
2565                                                   "(%s typowner) AS rolname, "
2566                                                   "typinput::oid AS typinput, "
2567                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2568                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2569                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2570                                                   "typtype, typisdefined, "
2571                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2572                                                   "FROM pg_type",
2573                                                   username_subquery);
2574         }
2575         else if (g_fout->remoteVersion >= 70100)
2576         {
2577                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2578                                                   "0::oid AS typnamespace, "
2579                                                   "(%s typowner) AS rolname, "
2580                                                   "typinput::oid AS typinput, "
2581                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2582                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2583                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2584                                                   "typtype, typisdefined, "
2585                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2586                                                   "FROM pg_type",
2587                                                   username_subquery);
2588         }
2589         else
2590         {
2591                 appendPQExpBuffer(query, "SELECT "
2592                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2593                                                   "oid, typname, "
2594                                                   "0::oid AS typnamespace, "
2595                                                   "(%s typowner) AS rolname, "
2596                                                   "typinput::oid AS typinput, "
2597                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2598                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2599                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2600                                                   "typtype, typisdefined, "
2601                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2602                                                   "FROM pg_type",
2603                                                   username_subquery);
2604         }
2605
2606         res = PQexec(g_conn, query->data);
2607         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2608
2609         ntups = PQntuples(res);
2610
2611         tyinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
2612
2613         i_tableoid = PQfnumber(res, "tableoid");
2614         i_oid = PQfnumber(res, "oid");
2615         i_typname = PQfnumber(res, "typname");
2616         i_typnamespace = PQfnumber(res, "typnamespace");
2617         i_rolname = PQfnumber(res, "rolname");
2618         i_typinput = PQfnumber(res, "typinput");
2619         i_typoutput = PQfnumber(res, "typoutput");
2620         i_typelem = PQfnumber(res, "typelem");
2621         i_typrelid = PQfnumber(res, "typrelid");
2622         i_typrelkind = PQfnumber(res, "typrelkind");
2623         i_typtype = PQfnumber(res, "typtype");
2624         i_typisdefined = PQfnumber(res, "typisdefined");
2625         i_isarray = PQfnumber(res, "isarray");
2626
2627         for (i = 0; i < ntups; i++)
2628         {
2629                 tyinfo[i].dobj.objType = DO_TYPE;
2630                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2631                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2632                 AssignDumpId(&tyinfo[i].dobj);
2633                 tyinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
2634                 tyinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
2635                                                                                                  tyinfo[i].dobj.catId.oid);
2636                 tyinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2637                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2638                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2639                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2640                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2641                 tyinfo[i].shellType = NULL;
2642
2643                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2644                         tyinfo[i].isDefined = true;
2645                 else
2646                         tyinfo[i].isDefined = false;
2647
2648                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2649                         tyinfo[i].isArray = true;
2650                 else
2651                         tyinfo[i].isArray = false;
2652
2653                 /* Decide whether we want to dump it */
2654                 selectDumpableType(&tyinfo[i]);
2655
2656                 /*
2657                  * If it's a domain, fetch info about its constraints, if any
2658                  */
2659                 tyinfo[i].nDomChecks = 0;
2660                 tyinfo[i].domChecks = NULL;
2661                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2662                         getDomainConstraints(&(tyinfo[i]));
2663
2664                 /*
2665                  * If it's a base type, make a DumpableObject representing a shell
2666                  * definition of the type.      We will need to dump that ahead of the I/O
2667                  * functions for the type.
2668                  *
2669                  * Note: the shell type doesn't have a catId.  You might think it
2670                  * should copy the base type's catId, but then it might capture the
2671                  * pg_depend entries for the type, which we don't want.
2672                  */
2673                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_BASE)
2674                 {
2675                         stinfo = (ShellTypeInfo *) malloc(sizeof(ShellTypeInfo));
2676                         stinfo->dobj.objType = DO_SHELL_TYPE;
2677                         stinfo->dobj.catId = nilCatalogId;
2678                         AssignDumpId(&stinfo->dobj);
2679                         stinfo->dobj.name = strdup(tyinfo[i].dobj.name);
2680                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2681                         stinfo->baseType = &(tyinfo[i]);
2682                         tyinfo[i].shellType = stinfo;
2683
2684                         /*
2685                          * Initially mark the shell type as not to be dumped.  We'll only
2686                          * dump it if the I/O functions need to be dumped; this is taken
2687                          * care of while sorting dependencies.
2688                          */
2689                         stinfo->dobj.dump = false;
2690
2691                         /*
2692                          * However, if dumping from pre-7.3, there will be no dependency
2693                          * info so we have to fake it here.  We only need to worry about
2694                          * typinput and typoutput since the other functions only exist
2695                          * post-7.3.
2696                          */
2697                         if (g_fout->remoteVersion < 70300)
2698                         {
2699                                 Oid                     typinput;
2700                                 Oid                     typoutput;
2701                                 FuncInfo   *funcInfo;
2702
2703                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
2704                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
2705
2706                                 funcInfo = findFuncByOid(typinput);
2707                                 if (funcInfo && funcInfo->dobj.dump)
2708                                 {
2709                                         /* base type depends on function */
2710                                         addObjectDependency(&tyinfo[i].dobj,
2711                                                                                 funcInfo->dobj.dumpId);
2712                                         /* function depends on shell type */
2713                                         addObjectDependency(&funcInfo->dobj,
2714                                                                                 stinfo->dobj.dumpId);
2715                                         /* mark shell type as to be dumped */
2716                                         stinfo->dobj.dump = true;
2717                                 }
2718
2719                                 funcInfo = findFuncByOid(typoutput);
2720                                 if (funcInfo && funcInfo->dobj.dump)
2721                                 {
2722                                         /* base type depends on function */
2723                                         addObjectDependency(&tyinfo[i].dobj,
2724                                                                                 funcInfo->dobj.dumpId);
2725                                         /* function depends on shell type */
2726                                         addObjectDependency(&funcInfo->dobj,
2727                                                                                 stinfo->dobj.dumpId);
2728                                         /* mark shell type as to be dumped */
2729                                         stinfo->dobj.dump = true;
2730                                 }
2731                         }
2732                 }
2733
2734                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
2735                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
2736                                           tyinfo[i].dobj.name);
2737         }
2738
2739         *numTypes = ntups;
2740
2741         PQclear(res);
2742
2743         destroyPQExpBuffer(query);
2744
2745         return tyinfo;
2746 }
2747
2748 /*
2749  * getOperators:
2750  *        read all operators in the system catalogs and return them in the
2751  * OprInfo* structure
2752  *
2753  *      numOprs is set to the number of operators read in
2754  */
2755 OprInfo *
2756 getOperators(int *numOprs)
2757 {
2758         PGresult   *res;
2759         int                     ntups;
2760         int                     i;
2761         PQExpBuffer query = createPQExpBuffer();
2762         OprInfo    *oprinfo;
2763         int                     i_tableoid;
2764         int                     i_oid;
2765         int                     i_oprname;
2766         int                     i_oprnamespace;
2767         int                     i_rolname;
2768         int                     i_oprcode;
2769
2770         /*
2771          * find all operators, including builtin operators; we filter out
2772          * system-defined operators at dump-out time.
2773          */
2774
2775         /* Make sure we are in proper schema */
2776         selectSourceSchema("pg_catalog");
2777
2778         if (g_fout->remoteVersion >= 70300)
2779         {
2780                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
2781                                                   "oprnamespace, "
2782                                                   "(%s oprowner) AS rolname, "
2783                                                   "oprcode::oid AS oprcode "
2784                                                   "FROM pg_operator",
2785                                                   username_subquery);
2786         }
2787         else if (g_fout->remoteVersion >= 70100)
2788         {
2789                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
2790                                                   "0::oid AS oprnamespace, "
2791                                                   "(%s oprowner) AS rolname, "
2792                                                   "oprcode::oid AS oprcode "
2793                                                   "FROM pg_operator",
2794                                                   username_subquery);
2795         }
2796         else
2797         {
2798                 appendPQExpBuffer(query, "SELECT "
2799                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
2800                                                   "oid, oprname, "
2801                                                   "0::oid AS oprnamespace, "
2802                                                   "(%s oprowner) AS rolname, "
2803                                                   "oprcode::oid AS oprcode "
2804                                                   "FROM pg_operator",
2805                                                   username_subquery);
2806         }
2807
2808         res = PQexec(g_conn, query->data);
2809         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2810
2811         ntups = PQntuples(res);
2812         *numOprs = ntups;
2813
2814         oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
2815
2816         i_tableoid = PQfnumber(res, "tableoid");
2817         i_oid = PQfnumber(res, "oid");
2818         i_oprname = PQfnumber(res, "oprname");
2819         i_oprnamespace = PQfnumber(res, "oprnamespace");
2820         i_rolname = PQfnumber(res, "rolname");
2821         i_oprcode = PQfnumber(res, "oprcode");
2822
2823         for (i = 0; i < ntups; i++)
2824         {
2825                 oprinfo[i].dobj.objType = DO_OPERATOR;
2826                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2827                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2828                 AssignDumpId(&oprinfo[i].dobj);
2829                 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
2830                 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
2831                                                                                                   oprinfo[i].dobj.catId.oid);
2832                 oprinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2833                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
2834
2835                 /* Decide whether we want to dump it */
2836                 selectDumpableObject(&(oprinfo[i].dobj));
2837
2838                 if (strlen(oprinfo[i].rolname) == 0)
2839                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
2840                                           oprinfo[i].dobj.name);
2841         }
2842
2843         PQclear(res);
2844
2845         destroyPQExpBuffer(query);
2846
2847         return oprinfo;
2848 }
2849
2850 /*
2851  * getConversions:
2852  *        read all conversions in the system catalogs and return them in the
2853  * ConvInfo* structure
2854  *
2855  *      numConversions is set to the number of conversions read in
2856  */
2857 ConvInfo *
2858 getConversions(int *numConversions)
2859 {
2860         PGresult   *res;
2861         int                     ntups;
2862         int                     i;
2863         PQExpBuffer query = createPQExpBuffer();
2864         ConvInfo   *convinfo;
2865         int                     i_tableoid;
2866         int                     i_oid;
2867         int                     i_conname;
2868         int                     i_connamespace;
2869         int                     i_rolname;
2870
2871         /* Conversions didn't exist pre-7.3 */
2872         if (g_fout->remoteVersion < 70300)
2873         {
2874                 *numConversions = 0;
2875                 return NULL;
2876         }
2877
2878         /*
2879          * find all conversions, including builtin conversions; we filter out
2880          * system-defined conversions at dump-out time.
2881          */
2882
2883         /* Make sure we are in proper schema */
2884         selectSourceSchema("pg_catalog");
2885
2886         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
2887                                           "connamespace, "
2888                                           "(%s conowner) AS rolname "
2889                                           "FROM pg_conversion",
2890                                           username_subquery);
2891
2892         res = PQexec(g_conn, query->data);
2893         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2894
2895         ntups = PQntuples(res);
2896         *numConversions = ntups;
2897
2898         convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
2899
2900         i_tableoid = PQfnumber(res, "tableoid");
2901         i_oid = PQfnumber(res, "oid");
2902         i_conname = PQfnumber(res, "conname");
2903         i_connamespace = PQfnumber(res, "connamespace");
2904         i_rolname = PQfnumber(res, "rolname");
2905
2906         for (i = 0; i < ntups; i++)
2907         {
2908                 convinfo[i].dobj.objType = DO_CONVERSION;
2909                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2910                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2911                 AssignDumpId(&convinfo[i].dobj);
2912                 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
2913                 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
2914                                                                                                  convinfo[i].dobj.catId.oid);
2915                 convinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2916
2917                 /* Decide whether we want to dump it */
2918                 selectDumpableObject(&(convinfo[i].dobj));
2919         }
2920
2921         PQclear(res);
2922
2923         destroyPQExpBuffer(query);
2924
2925         return convinfo;
2926 }
2927
2928 /*
2929  * getOpclasses:
2930  *        read all opclasses in the system catalogs and return them in the
2931  * OpclassInfo* structure
2932  *
2933  *      numOpclasses is set to the number of opclasses read in
2934  */
2935 OpclassInfo *
2936 getOpclasses(int *numOpclasses)
2937 {
2938         PGresult   *res;
2939         int                     ntups;
2940         int                     i;
2941         PQExpBuffer query = createPQExpBuffer();
2942         OpclassInfo *opcinfo;
2943         int                     i_tableoid;
2944         int                     i_oid;
2945         int                     i_opcname;
2946         int                     i_opcnamespace;
2947         int                     i_rolname;
2948
2949         /*
2950          * find all opclasses, including builtin opclasses; we filter out
2951          * system-defined opclasses at dump-out time.
2952          */
2953
2954         /* Make sure we are in proper schema */
2955         selectSourceSchema("pg_catalog");
2956
2957         if (g_fout->remoteVersion >= 70300)
2958         {
2959                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2960                                                   "opcnamespace, "
2961                                                   "(%s opcowner) AS rolname "
2962                                                   "FROM pg_opclass",
2963                                                   username_subquery);
2964         }
2965         else if (g_fout->remoteVersion >= 70100)
2966         {
2967                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2968                                                   "0::oid AS opcnamespace, "
2969                                                   "''::name AS rolname "
2970                                                   "FROM pg_opclass");
2971         }
2972         else
2973         {
2974                 appendPQExpBuffer(query, "SELECT "
2975                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2976                                                   "oid, opcname, "
2977                                                   "0::oid AS opcnamespace, "
2978                                                   "''::name AS rolname "
2979                                                   "FROM pg_opclass");
2980         }
2981
2982         res = PQexec(g_conn, query->data);
2983         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2984
2985         ntups = PQntuples(res);
2986         *numOpclasses = ntups;
2987
2988         opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2989
2990         i_tableoid = PQfnumber(res, "tableoid");
2991         i_oid = PQfnumber(res, "oid");
2992         i_opcname = PQfnumber(res, "opcname");
2993         i_opcnamespace = PQfnumber(res, "opcnamespace");
2994         i_rolname = PQfnumber(res, "rolname");
2995
2996         for (i = 0; i < ntups; i++)
2997         {
2998                 opcinfo[i].dobj.objType = DO_OPCLASS;
2999                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3000                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3001                 AssignDumpId(&opcinfo[i].dobj);
3002                 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
3003                 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
3004                                                                                                   opcinfo[i].dobj.catId.oid);
3005                 opcinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3006
3007                 /* Decide whether we want to dump it */
3008                 selectDumpableObject(&(opcinfo[i].dobj));
3009
3010                 if (g_fout->remoteVersion >= 70300)
3011                 {
3012                         if (strlen(opcinfo[i].rolname) == 0)
3013                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3014                                                   opcinfo[i].dobj.name);
3015                 }
3016         }
3017
3018         PQclear(res);
3019
3020         destroyPQExpBuffer(query);
3021
3022         return opcinfo;
3023 }
3024
3025 /*
3026  * getOpfamilies:
3027  *        read all opfamilies in the system catalogs and return them in the
3028  * OpfamilyInfo* structure
3029  *
3030  *      numOpfamilies is set to the number of opfamilies read in
3031  */
3032 OpfamilyInfo *
3033 getOpfamilies(int *numOpfamilies)
3034 {
3035         PGresult   *res;
3036         int                     ntups;
3037         int                     i;
3038         PQExpBuffer query;
3039         OpfamilyInfo *opfinfo;
3040         int                     i_tableoid;
3041         int                     i_oid;
3042         int                     i_opfname;
3043         int                     i_opfnamespace;
3044         int                     i_rolname;
3045
3046         /* Before 8.3, there is no separate concept of opfamilies */
3047         if (g_fout->remoteVersion < 80300)
3048         {
3049                 *numOpfamilies = 0;
3050                 return NULL;
3051         }
3052
3053         query = createPQExpBuffer();
3054
3055         /*
3056          * find all opfamilies, including builtin opfamilies; we filter out
3057          * system-defined opfamilies at dump-out time.
3058          */
3059
3060         /* Make sure we are in proper schema */
3061         selectSourceSchema("pg_catalog");
3062
3063         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3064                                           "opfnamespace, "
3065                                           "(%s opfowner) AS rolname "
3066                                           "FROM pg_opfamily",
3067                                           username_subquery);
3068
3069         res = PQexec(g_conn, query->data);
3070         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3071
3072         ntups = PQntuples(res);
3073         *numOpfamilies = ntups;
3074
3075         opfinfo = (OpfamilyInfo *) malloc(ntups * sizeof(OpfamilyInfo));
3076
3077         i_tableoid = PQfnumber(res, "tableoid");
3078         i_oid = PQfnumber(res, "oid");
3079         i_opfname = PQfnumber(res, "opfname");
3080         i_opfnamespace = PQfnumber(res, "opfnamespace");
3081         i_rolname = PQfnumber(res, "rolname");
3082
3083         for (i = 0; i < ntups; i++)
3084         {
3085                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3086                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3087                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3088                 AssignDumpId(&opfinfo[i].dobj);
3089                 opfinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opfname));
3090                 opfinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opfnamespace)),
3091                                                                                                   opfinfo[i].dobj.catId.oid);
3092                 opfinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3093
3094                 /* Decide whether we want to dump it */
3095                 selectDumpableObject(&(opfinfo[i].dobj));
3096
3097                 if (g_fout->remoteVersion >= 70300)
3098                 {
3099                         if (strlen(opfinfo[i].rolname) == 0)
3100                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3101                                                   opfinfo[i].dobj.name);
3102                 }
3103         }
3104
3105         PQclear(res);
3106
3107         destroyPQExpBuffer(query);
3108
3109         return opfinfo;
3110 }
3111
3112 /*
3113  * getAggregates:
3114  *        read all the user-defined aggregates in the system catalogs and
3115  * return them in the AggInfo* structure
3116  *
3117  * numAggs is set to the number of aggregates read in
3118  */
3119 AggInfo *
3120 getAggregates(int *numAggs)
3121 {
3122         PGresult   *res;
3123         int                     ntups;
3124         int                     i;
3125         PQExpBuffer query = createPQExpBuffer();
3126         AggInfo    *agginfo;
3127         int                     i_tableoid;
3128         int                     i_oid;
3129         int                     i_aggname;
3130         int                     i_aggnamespace;
3131         int                     i_pronargs;
3132         int                     i_proargtypes;
3133         int                     i_rolname;
3134         int                     i_aggacl;
3135
3136         /* Make sure we are in proper schema */
3137         selectSourceSchema("pg_catalog");
3138
3139         /* find all user-defined aggregates */
3140
3141         if (g_fout->remoteVersion >= 80200)
3142         {
3143                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3144                                                   "pronamespace AS aggnamespace, "
3145                                                   "pronargs, proargtypes, "
3146                                                   "(%s proowner) AS rolname, "
3147                                                   "proacl AS aggacl "
3148                                                   "FROM pg_proc "
3149                                                   "WHERE proisagg "
3150                                                   "AND pronamespace != "
3151                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3152                                                   username_subquery);
3153         }
3154         else if (g_fout->remoteVersion >= 70300)
3155         {
3156                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3157                                                   "pronamespace AS aggnamespace, "
3158                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3159                                                   "proargtypes, "
3160                                                   "(%s proowner) AS rolname, "
3161                                                   "proacl AS aggacl "
3162                                                   "FROM pg_proc "
3163                                                   "WHERE proisagg "
3164                                                   "AND pronamespace != "
3165                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3166                                                   username_subquery);
3167         }
3168         else if (g_fout->remoteVersion >= 70100)
3169         {
3170                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3171                                                   "0::oid AS aggnamespace, "
3172                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3173                                                   "aggbasetype AS proargtypes, "
3174                                                   "(%s aggowner) AS rolname, "
3175                                                   "'{=X}' AS aggacl "
3176                                                   "FROM pg_aggregate "
3177                                                   "where oid > '%u'::oid",
3178                                                   username_subquery,
3179                                                   g_last_builtin_oid);
3180         }
3181         else
3182         {
3183                 appendPQExpBuffer(query, "SELECT "
3184                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3185                                                   "oid, aggname, "
3186                                                   "0::oid AS aggnamespace, "
3187                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3188                                                   "aggbasetype AS proargtypes, "
3189                                                   "(%s aggowner) AS rolname, "
3190                                                   "'{=X}' AS aggacl "
3191                                                   "FROM pg_aggregate "
3192                                                   "where oid > '%u'::oid",
3193                                                   username_subquery,
3194                                                   g_last_builtin_oid);
3195         }
3196
3197         res = PQexec(g_conn, query->data);
3198         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3199
3200         ntups = PQntuples(res);
3201         *numAggs = ntups;
3202
3203         agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
3204
3205         i_tableoid = PQfnumber(res, "tableoid");
3206         i_oid = PQfnumber(res, "oid");
3207         i_aggname = PQfnumber(res, "aggname");
3208         i_aggnamespace = PQfnumber(res, "aggnamespace");
3209         i_pronargs = PQfnumber(res, "pronargs");
3210         i_proargtypes = PQfnumber(res, "proargtypes");
3211         i_rolname = PQfnumber(res, "rolname");
3212         i_aggacl = PQfnumber(res, "aggacl");
3213
3214         for (i = 0; i < ntups; i++)
3215         {
3216                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3217                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3218                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3219                 AssignDumpId(&agginfo[i].aggfn.dobj);
3220                 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
3221                 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
3222                                                                                         agginfo[i].aggfn.dobj.catId.oid);
3223                 agginfo[i].aggfn.rolname = strdup(PQgetvalue(res, i, i_rolname));
3224                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3225                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3226                                           agginfo[i].aggfn.dobj.name);
3227                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3228                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3229                 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
3230                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3231                 if (agginfo[i].aggfn.nargs == 0)
3232                         agginfo[i].aggfn.argtypes = NULL;
3233                 else
3234                 {
3235                         agginfo[i].aggfn.argtypes = (Oid *) malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3236                         if (g_fout->remoteVersion >= 70300)
3237                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3238                                                           agginfo[i].aggfn.argtypes,
3239                                                           agginfo[i].aggfn.nargs);
3240                         else
3241                                 /* it's just aggbasetype */
3242                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3243                 }
3244
3245                 /* Decide whether we want to dump it */
3246                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3247         }
3248
3249         PQclear(res);
3250
3251         destroyPQExpBuffer(query);
3252
3253         return agginfo;
3254 }
3255
3256 /*
3257  * getFuncs:
3258  *        read all the user-defined functions in the system catalogs and
3259  * return them in the FuncInfo* structure
3260  *
3261  * numFuncs is set to the number of functions read in
3262  */
3263 FuncInfo *
3264 getFuncs(int *numFuncs)
3265 {
3266         PGresult   *res;
3267         int                     ntups;
3268         int                     i;
3269         PQExpBuffer query = createPQExpBuffer();
3270         FuncInfo   *finfo;
3271         int                     i_tableoid;
3272         int                     i_oid;
3273         int                     i_proname;
3274         int                     i_pronamespace;
3275         int                     i_rolname;
3276         int                     i_prolang;
3277         int                     i_pronargs;
3278         int                     i_proargtypes;
3279         int                     i_prorettype;
3280         int                     i_proacl;
3281
3282         /* Make sure we are in proper schema */
3283         selectSourceSchema("pg_catalog");
3284
3285         /* find all user-defined funcs */
3286
3287         if (g_fout->remoteVersion >= 70300)
3288         {
3289                 appendPQExpBuffer(query,
3290                                                   "SELECT tableoid, oid, proname, prolang, "
3291                                                   "pronargs, proargtypes, prorettype, proacl, "
3292                                                   "pronamespace, "
3293                                                   "(%s proowner) AS rolname "
3294                                                   "FROM pg_proc "
3295                                                   "WHERE NOT proisagg "
3296                                                   "AND pronamespace != "
3297                                                   "(SELECT oid FROM pg_namespace "
3298                                                   "WHERE nspname = 'pg_catalog')",
3299                                                   username_subquery);
3300         }
3301         else if (g_fout->remoteVersion >= 70100)
3302         {
3303                 appendPQExpBuffer(query,
3304                                                   "SELECT tableoid, oid, proname, prolang, "
3305                                                   "pronargs, proargtypes, prorettype, "
3306                                                   "'{=X}' AS proacl, "
3307                                                   "0::oid AS pronamespace, "
3308                                                   "(%s proowner) AS rolname "
3309                                                   "FROM pg_proc "
3310                                                   "WHERE pg_proc.oid > '%u'::oid",
3311                                                   username_subquery,
3312                                                   g_last_builtin_oid);
3313         }
3314         else
3315         {
3316                 appendPQExpBuffer(query,
3317                                                   "SELECT "
3318                                                   "(SELECT oid FROM pg_class "
3319                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3320                                                   "oid, proname, prolang, "
3321                                                   "pronargs, proargtypes, prorettype, "
3322                                                   "'{=X}' AS proacl, "
3323                                                   "0::oid AS pronamespace, "
3324                                                   "(%s proowner) AS rolname "
3325                                                   "FROM pg_proc "
3326                                                   "where pg_proc.oid > '%u'::oid",
3327                                                   username_subquery,
3328                                                   g_last_builtin_oid);
3329         }
3330
3331         res = PQexec(g_conn, query->data);
3332         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3333
3334         ntups = PQntuples(res);
3335
3336         *numFuncs = ntups;
3337
3338         finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
3339
3340         i_tableoid = PQfnumber(res, "tableoid");
3341         i_oid = PQfnumber(res, "oid");
3342         i_proname = PQfnumber(res, "proname");
3343         i_pronamespace = PQfnumber(res, "pronamespace");
3344         i_rolname = PQfnumber(res, "rolname");
3345         i_prolang = PQfnumber(res, "prolang");
3346         i_pronargs = PQfnumber(res, "pronargs");
3347         i_proargtypes = PQfnumber(res, "proargtypes");
3348         i_prorettype = PQfnumber(res, "prorettype");
3349         i_proacl = PQfnumber(res, "proacl");
3350
3351         for (i = 0; i < ntups; i++)
3352         {
3353                 finfo[i].dobj.objType = DO_FUNC;
3354                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3355                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3356                 AssignDumpId(&finfo[i].dobj);
3357                 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
3358                 finfo[i].dobj.namespace =
3359                         findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
3360                                                   finfo[i].dobj.catId.oid);
3361                 finfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3362                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3363                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3364                 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
3365                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3366                 if (finfo[i].nargs == 0)
3367                         finfo[i].argtypes = NULL;
3368                 else
3369                 {
3370                         finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
3371                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3372                                                   finfo[i].argtypes, finfo[i].nargs);
3373                 }
3374
3375                 /* Decide whether we want to dump it */
3376                 selectDumpableObject(&(finfo[i].dobj));
3377
3378                 if (strlen(finfo[i].rolname) == 0)
3379                         write_msg(NULL,
3380                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3381                                           finfo[i].dobj.name);
3382         }
3383
3384         PQclear(res);
3385
3386         destroyPQExpBuffer(query);
3387
3388         return finfo;
3389 }
3390
3391 /*
3392  * getTables
3393  *        read all the user-defined tables (no indexes, no catalogs)
3394  * in the system catalogs return them in the TableInfo* structure
3395  *
3396  * numTables is set to the number of tables read in
3397  */
3398 TableInfo *
3399 getTables(int *numTables)
3400 {
3401         PGresult   *res;
3402         int                     ntups;
3403         int                     i;
3404         PQExpBuffer query = createPQExpBuffer();
3405         TableInfo  *tblinfo;
3406         int                     i_reltableoid;
3407         int                     i_reloid;
3408         int                     i_relname;
3409         int                     i_relnamespace;
3410         int                     i_relkind;
3411         int                     i_relacl;
3412         int                     i_rolname;
3413         int                     i_relchecks;
3414         int                     i_relhastriggers;
3415         int                     i_relhasindex;
3416         int                     i_relhasrules;
3417         int                     i_relhasoids;
3418         int                     i_relfrozenxid;
3419         int                     i_owning_tab;
3420         int                     i_owning_col;
3421         int                     i_reltablespace;
3422         int                     i_reloptions;
3423         int                     i_toastreloptions;
3424         int                     i_reloftype;
3425
3426         /* Make sure we are in proper schema */
3427         selectSourceSchema("pg_catalog");
3428
3429         /*
3430          * Find all the tables (including views and sequences).
3431          *
3432          * We include system catalogs, so that we can work if a user table is
3433          * defined to inherit from a system catalog (pretty weird, but...)
3434          *
3435          * We ignore tables that are not type 'r' (ordinary relation), 'S'
3436          * (sequence), 'v' (view), or 'c' (composite type).
3437          *
3438          * Composite-type table entries won't be dumped as such, but we have to
3439          * make a DumpableObject for them so that we can track dependencies of the
3440          * composite type (pg_depend entries for columns of the composite type
3441          * link to the pg_class entry not the pg_type entry).
3442          *
3443          * Note: in this phase we should collect only a minimal amount of
3444          * information about each table, basically just enough to decide if it is
3445          * interesting. We must fetch all tables in this phase because otherwise
3446          * we cannot correctly identify inherited columns, owned sequences, etc.
3447          */
3448
3449         if (g_fout->remoteVersion >= 90000)
3450         {
3451                 /*
3452                  * Left join to pick up dependency info linking sequences to their
3453                  * owning column, if any (note this dependency is AUTO as of 8.2)
3454                  */
3455                 appendPQExpBuffer(query,
3456                                                   "SELECT c.tableoid, c.oid, c.relname, "
3457                                                   "c.relacl, c.relkind, c.relnamespace, "
3458                                                   "(%s c.relowner) AS rolname, "
3459                                                   "c.relchecks, c.relhastriggers, "
3460                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3461                                                   "c.relfrozenxid, "
3462                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3463                                                   "d.refobjid AS owning_tab, "
3464                                                   "d.refobjsubid AS owning_col, "
3465                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3466                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3467                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3468                                                   "FROM pg_class c "
3469                                                   "LEFT JOIN pg_depend d ON "
3470                                                   "(c.relkind = '%c' AND "
3471                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3472                                                   "d.objsubid = 0 AND "
3473                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3474                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3475                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3476                                                   "ORDER BY c.oid",
3477                                                   username_subquery,
3478                                                   RELKIND_SEQUENCE,
3479                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3480                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3481         }
3482         else if (g_fout->remoteVersion >= 80400)
3483         {
3484                 /*
3485                  * Left join to pick up dependency info linking sequences to their
3486                  * owning column, if any (note this dependency is AUTO as of 8.2)
3487                  */
3488                 appendPQExpBuffer(query,
3489                                                   "SELECT c.tableoid, c.oid, c.relname, "
3490                                                   "c.relacl, c.relkind, c.relnamespace, "
3491                                                   "(%s c.relowner) AS rolname, "
3492                                                   "c.relchecks, c.relhastriggers, "
3493                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3494                                                   "c.relfrozenxid, "
3495                                                   "NULL AS reloftype, "
3496                                                   "d.refobjid AS owning_tab, "
3497                                                   "d.refobjsubid AS owning_col, "
3498                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3499                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3500                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3501                                                   "FROM pg_class c "
3502                                                   "LEFT JOIN pg_depend d ON "
3503                                                   "(c.relkind = '%c' AND "
3504                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3505                                                   "d.objsubid = 0 AND "
3506                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3507                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3508                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3509                                                   "ORDER BY c.oid",
3510                                                   username_subquery,
3511                                                   RELKIND_SEQUENCE,
3512                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3513                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3514         }
3515         else if (g_fout->remoteVersion >= 80200)
3516         {
3517                 /*
3518                  * Left join to pick up dependency info linking sequences to their
3519                  * owning column, if any (note this dependency is AUTO as of 8.2)
3520                  */
3521                 appendPQExpBuffer(query,
3522                                                   "SELECT c.tableoid, c.oid, relname, "
3523                                                   "relacl, relkind, relnamespace, "
3524                                                   "(%s relowner) AS rolname, "
3525                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
3526                                                   "relhasindex, relhasrules, relhasoids, "
3527                                                   "relfrozenxid, "
3528                                                   "NULL AS reloftype, "
3529                                                   "d.refobjid AS owning_tab, "
3530                                                   "d.refobjsubid AS owning_col, "
3531                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3532                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3533                                                   "NULL AS toast_reloptions "
3534                                                   "FROM pg_class c "
3535                                                   "LEFT JOIN pg_depend d ON "
3536                                                   "(c.relkind = '%c' AND "
3537                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3538                                                   "d.objsubid = 0 AND "
3539                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3540                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
3541                                                   "ORDER BY c.oid",
3542                                                   username_subquery,
3543                                                   RELKIND_SEQUENCE,
3544                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3545                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3546         }
3547         else if (g_fout->remoteVersion >= 80000)
3548         {
3549                 /*
3550                  * Left join to pick up dependency info linking sequences to their
3551                  * owning column, if any
3552                  */
3553                 appendPQExpBuffer(query,
3554                                                   "SELECT c.tableoid, c.oid, relname, "
3555                                                   "relacl, relkind, relnamespace, "
3556                                                   "(%s relowner) AS rolname, "
3557                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
3558                                                   "relhasindex, relhasrules, relhasoids, "
3559                                                   "0 AS relfrozenxid, "
3560                                                   "NULL AS reloftype, "
3561                                                   "d.refobjid AS owning_tab, "
3562                                                   "d.refobjsubid AS owning_col, "
3563                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3564                                                   "NULL AS reloptions, "
3565                                                   "NULL AS toast_reloptions "
3566                                                   "FROM pg_class c "
3567                                                   "LEFT JOIN pg_depend d ON "
3568                                                   "(c.relkind = '%c' AND "
3569                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3570                                                   "d.objsubid = 0 AND "
3571                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
3572                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
3573                                                   "ORDER BY c.oid",
3574                                                   username_subquery,
3575                                                   RELKIND_SEQUENCE,
3576                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3577                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3578         }
3579         else if (g_fout->remoteVersion >= 70300)
3580         {
3581                 /*
3582                  * Left join to pick up dependency info linking sequences to their
3583                  * owning column, if any
3584                  */
3585                 appendPQExpBuffer(query,
3586                                                   "SELECT c.tableoid, c.oid, relname, "
3587                                                   "relacl, relkind, relnamespace, "
3588                                                   "(%s relowner) AS rolname, "
3589                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
3590                                                   "relhasindex, relhasrules, relhasoids, "
3591                                                   "0 AS relfrozenxid, "
3592                                                   "NULL AS reloftype, "
3593                                                   "d.refobjid AS owning_tab, "
3594                                                   "d.refobjsubid AS owning_col, "
3595                                                   "NULL AS reltablespace, "
3596                                                   "NULL AS reloptions, "
3597                                                   "NULL AS toast_reloptions "
3598                                                   "FROM pg_class c "
3599                                                   "LEFT JOIN pg_depend d ON "
3600                                                   "(c.relkind = '%c' AND "
3601                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3602                                                   "d.objsubid = 0 AND "
3603                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
3604                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
3605                                                   "ORDER BY c.oid",
3606                                                   username_subquery,
3607                                                   RELKIND_SEQUENCE,
3608                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3609                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3610         }
3611         else if (g_fout->remoteVersion >= 70200)
3612         {
3613                 appendPQExpBuffer(query,
3614                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
3615                                                   "0::oid AS relnamespace, "
3616                                                   "(%s relowner) AS rolname, "
3617                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
3618                                                   "relhasindex, relhasrules, relhasoids, "
3619                                                   "0 AS relfrozenxid, "
3620                                                   "NULL AS reloftype, "
3621                                                   "NULL::oid AS owning_tab, "
3622                                                   "NULL::int4 AS owning_col, "
3623                                                   "NULL AS reltablespace, "
3624                                                   "NULL AS reloptions, "
3625                                                   "NULL AS toast_reloptions "
3626                                                   "FROM pg_class "
3627                                                   "WHERE relkind IN ('%c', '%c', '%c') "
3628                                                   "ORDER BY oid",
3629                                                   username_subquery,
3630                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
3631         }
3632         else if (g_fout->remoteVersion >= 70100)
3633         {
3634                 /* all tables have oids in 7.1 */
3635                 appendPQExpBuffer(query,
3636                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
3637                                                   "0::oid AS relnamespace, "
3638                                                   "(%s relowner) AS rolname, "
3639                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
3640                                                   "relhasindex, relhasrules, "
3641                                                   "'t'::bool AS relhasoids, "
3642                                                   "0 AS relfrozenxid, "
3643                                                   "NULL AS reloftype, "
3644                                                   "NULL::oid AS owning_tab, "
3645                                                   "NULL::int4 AS owning_col, "
3646                                                   "NULL AS reltablespace, "
3647                                                   "NULL AS reloptions, "
3648                                                   "NULL AS toast_reloptions "
3649                                                   "FROM pg_class "
3650                                                   "WHERE relkind IN ('%c', '%c', '%c') "
3651                                                   "ORDER BY oid",
3652                                                   username_subquery,
3653                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
3654         }
3655         else
3656         {
3657                 /*
3658                  * Before 7.1, view relkind was not set to 'v', so we must check if we
3659                  * have a view by looking for a rule in pg_rewrite.
3660                  */
3661                 appendPQExpBuffer(query,
3662                                                   "SELECT "
3663                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
3664                                                   "oid, relname, relacl, "
3665                                                   "CASE WHEN relhasrules and relkind = 'r' "
3666                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
3667                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
3668                                                   "THEN '%c'::\"char\" "
3669                                                   "ELSE relkind END AS relkind,"
3670                                                   "0::oid AS relnamespace, "
3671                                                   "(%s relowner) AS rolname, "
3672                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
3673                                                   "relhasindex, relhasrules, "
3674                                                   "'t'::bool AS relhasoids, "
3675                                                   "0 as relfrozenxid, "
3676                                                   "NULL AS reloftype, "
3677                                                   "NULL::oid AS owning_tab, "
3678                                                   "NULL::int4 AS owning_col, "
3679                                                   "NULL AS reltablespace, "
3680                                                   "NULL AS reloptions, "
3681                                                   "NULL AS toast_reloptions "
3682                                                   "FROM pg_class c "
3683                                                   "WHERE relkind IN ('%c', '%c') "
3684                                                   "ORDER BY oid",
3685                                                   RELKIND_VIEW,
3686                                                   username_subquery,
3687                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
3688         }
3689
3690         res = PQexec(g_conn, query->data);
3691         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3692
3693         ntups = PQntuples(res);
3694
3695         *numTables = ntups;
3696
3697         /*
3698          * Extract data from result and lock dumpable tables.  We do the locking
3699          * before anything else, to minimize the window wherein a table could
3700          * disappear under us.
3701          *
3702          * Note that we have to save info about all tables here, even when dumping
3703          * only one, because we don't yet know which tables might be inheritance
3704          * ancestors of the target table.
3705          */
3706         tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
3707
3708         i_reltableoid = PQfnumber(res, "tableoid");
3709         i_reloid = PQfnumber(res, "oid");
3710         i_relname = PQfnumber(res, "relname");
3711         i_relnamespace = PQfnumber(res, "relnamespace");
3712         i_relacl = PQfnumber(res, "relacl");
3713         i_relkind = PQfnumber(res, "relkind");
3714         i_rolname = PQfnumber(res, "rolname");
3715         i_relchecks = PQfnumber(res, "relchecks");
3716         i_relhastriggers = PQfnumber(res, "relhastriggers");
3717         i_relhasindex = PQfnumber(res, "relhasindex");
3718         i_relhasrules = PQfnumber(res, "relhasrules");
3719         i_relhasoids = PQfnumber(res, "relhasoids");
3720         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
3721         i_owning_tab = PQfnumber(res, "owning_tab");
3722         i_owning_col = PQfnumber(res, "owning_col");
3723         i_reltablespace = PQfnumber(res, "reltablespace");
3724         i_reloptions = PQfnumber(res, "reloptions");
3725         i_toastreloptions = PQfnumber(res, "toast_reloptions");
3726         i_reloftype = PQfnumber(res, "reloftype");
3727
3728         if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
3729         {
3730                 /*
3731                  * Arrange to fail instead of waiting forever for a table lock.
3732                  *
3733                  * NB: this coding assumes that the only queries issued within the
3734                  * following loop are LOCK TABLEs; else the timeout may be undesirably
3735                  * applied to other things too.
3736                  */
3737                 resetPQExpBuffer(query);
3738                 appendPQExpBuffer(query, "SET statement_timeout = ");
3739                 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
3740                 do_sql_command(g_conn, query->data);
3741         }
3742
3743         for (i = 0; i < ntups; i++)
3744         {
3745                 tblinfo[i].dobj.objType = DO_TABLE;
3746                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
3747                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
3748                 AssignDumpId(&tblinfo[i].dobj);
3749                 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
3750                 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
3751                                                                                                   tblinfo[i].dobj.catId.oid);
3752                 tblinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3753                 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
3754                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
3755                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
3756                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
3757                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
3758                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
3759                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
3760                 if (PQgetisnull(res, i, i_reloftype))
3761                         tblinfo[i].reloftype = NULL;
3762                 else
3763                         tblinfo[i].reloftype = strdup(PQgetvalue(res, i, i_reloftype));
3764                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
3765                 if (PQgetisnull(res, i, i_owning_tab))
3766                 {
3767                         tblinfo[i].owning_tab = InvalidOid;
3768                         tblinfo[i].owning_col = 0;
3769                 }
3770                 else
3771                 {
3772                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
3773                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
3774                 }
3775                 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
3776                 tblinfo[i].reloptions = strdup(PQgetvalue(res, i, i_reloptions));
3777                 tblinfo[i].toast_reloptions = strdup(PQgetvalue(res, i, i_toastreloptions));
3778
3779                 /* other fields were zeroed above */
3780
3781                 /*
3782                  * Decide whether we want to dump this table.
3783                  */
3784                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
3785                         tblinfo[i].dobj.dump = false;
3786                 else
3787                         selectDumpableTable(&tblinfo[i]);
3788                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
3789
3790                 /*
3791                  * Read-lock target tables to make sure they aren't DROPPED or altered
3792                  * in schema before we get around to dumping them.
3793                  *
3794                  * Note that we don't explicitly lock parents of the target tables; we
3795                  * assume our lock on the child is enough to prevent schema
3796                  * alterations to parent tables.
3797                  *
3798                  * NOTE: it'd be kinda nice to lock views and sequences too, not only
3799                  * plain tables, but the backend doesn't presently allow that.
3800                  */
3801                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
3802                 {
3803                         resetPQExpBuffer(query);
3804                         appendPQExpBuffer(query,
3805                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
3806                                                  fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
3807                                                                                 tblinfo[i].dobj.name));
3808                         do_sql_command(g_conn, query->data);
3809                 }
3810
3811                 /* Emit notice if join for owner failed */
3812                 if (strlen(tblinfo[i].rolname) == 0)
3813                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
3814                                           tblinfo[i].dobj.name);
3815         }
3816
3817         if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
3818         {
3819                 do_sql_command(g_conn, "SET statement_timeout = 0");
3820         }
3821
3822         PQclear(res);
3823
3824         /*
3825          * Force sequences that are "owned" by table columns to be dumped whenever
3826          * their owning table is being dumped.
3827          */
3828         for (i = 0; i < ntups; i++)
3829         {
3830                 TableInfo  *seqinfo = &tblinfo[i];
3831                 int                     j;
3832
3833                 if (!OidIsValid(seqinfo->owning_tab))
3834                         continue;                       /* not an owned sequence */
3835                 if (seqinfo->dobj.dump)
3836                         continue;                       /* no need to search */
3837
3838                 /* can't use findTableByOid yet, unfortunately */
3839                 for (j = 0; j < ntups; j++)
3840                 {
3841                         if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
3842                         {
3843                                 if (tblinfo[j].dobj.dump)
3844                                 {
3845                                         seqinfo->interesting = true;
3846                                         seqinfo->dobj.dump = true;
3847                                 }
3848                                 break;
3849                         }
3850                 }
3851         }
3852
3853         destroyPQExpBuffer(query);
3854
3855         return tblinfo;
3856 }
3857
3858 /*
3859  * getInherits
3860  *        read all the inheritance information
3861  * from the system catalogs return them in the InhInfo* structure
3862  *
3863  * numInherits is set to the number of pairs read in
3864  */
3865 InhInfo *
3866 getInherits(int *numInherits)
3867 {
3868         PGresult   *res;
3869         int                     ntups;
3870         int                     i;
3871         PQExpBuffer query = createPQExpBuffer();
3872         InhInfo    *inhinfo;
3873
3874         int                     i_inhrelid;
3875         int                     i_inhparent;
3876
3877         /* Make sure we are in proper schema */
3878         selectSourceSchema("pg_catalog");
3879
3880         /* find all the inheritance information */
3881
3882         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
3883
3884         res = PQexec(g_conn, query->data);
3885         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3886
3887         ntups = PQntuples(res);
3888
3889         *numInherits = ntups;
3890
3891         inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
3892
3893         i_inhrelid = PQfnumber(res, "inhrelid");
3894         i_inhparent = PQfnumber(res, "inhparent");
3895
3896         for (i = 0; i < ntups; i++)
3897         {
3898                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
3899                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
3900         }
3901
3902         PQclear(res);
3903
3904         destroyPQExpBuffer(query);
3905
3906         return inhinfo;
3907 }
3908
3909 /*
3910  * getIndexes
3911  *        get information about every index on a dumpable table
3912  *
3913  * Note: index data is not returned directly to the caller, but it
3914  * does get entered into the DumpableObject tables.
3915  */
3916 void
3917 getIndexes(TableInfo tblinfo[], int numTables)
3918 {
3919         int                     i,
3920                                 j;
3921         PQExpBuffer query = createPQExpBuffer();
3922         PGresult   *res;
3923         IndxInfo   *indxinfo;
3924         ConstraintInfo *constrinfo;
3925         int                     i_tableoid,
3926                                 i_oid,
3927                                 i_indexname,
3928                                 i_indexdef,
3929                                 i_indnkeys,
3930                                 i_indkey,
3931                                 i_indisclustered,
3932                                 i_contype,
3933                                 i_conname,
3934                                 i_condeferrable,
3935                                 i_condeferred,
3936                                 i_contableoid,
3937                                 i_conoid,
3938                                 i_condef,
3939                                 i_tablespace,
3940                                 i_options;
3941         int                     ntups;
3942
3943         for (i = 0; i < numTables; i++)
3944         {
3945                 TableInfo  *tbinfo = &tblinfo[i];
3946
3947                 /* Only plain tables have indexes */
3948                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
3949                         continue;
3950
3951                 /* Ignore indexes of tables not to be dumped */
3952                 if (!tbinfo->dobj.dump)
3953                         continue;
3954
3955                 if (g_verbose)
3956                         write_msg(NULL, "reading indexes for table \"%s\"\n",
3957                                           tbinfo->dobj.name);
3958
3959                 /* Make sure we are in proper schema so indexdef is right */
3960                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3961
3962                 /*
3963                  * The point of the messy-looking outer join is to find a constraint
3964                  * that is related by an internal dependency link to the index. If we
3965                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
3966                  * assume an index won't have more than one internal dependency.
3967                  *
3968                  * As of 9.0 we don't need to look at pg_depend but can check for a
3969                  * match to pg_constraint.conindid.  The check on conrelid is
3970                  * redundant but useful because that column is indexed while conindid
3971                  * is not.
3972                  */
3973                 resetPQExpBuffer(query);
3974                 if (g_fout->remoteVersion >= 90000)
3975                 {
3976                         appendPQExpBuffer(query,
3977                                                           "SELECT t.tableoid, t.oid, "
3978                                                           "t.relname AS indexname, "
3979                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
3980                                                           "t.relnatts AS indnkeys, "
3981                                                           "i.indkey, i.indisclustered, "
3982                                                           "c.contype, c.conname, "
3983                                                           "c.condeferrable, c.condeferred, "
3984                                                           "c.tableoid AS contableoid, "
3985                                                           "c.oid AS conoid, "
3986                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
3987                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
3988                                                         "array_to_string(t.reloptions, ', ') AS options "
3989                                                           "FROM pg_catalog.pg_index i "
3990                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
3991                                                           "LEFT JOIN pg_catalog.pg_constraint c "
3992                                                           "ON (i.indrelid = c.conrelid AND "
3993                                                           "i.indexrelid = c.conindid AND "
3994                                                           "c.contype IN ('p','u','x')) "
3995                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
3996                                                           "ORDER BY indexname",
3997                                                           tbinfo->dobj.catId.oid);
3998                 }
3999                 else if (g_fout->remoteVersion >= 80200)
4000                 {
4001                         appendPQExpBuffer(query,
4002                                                           "SELECT t.tableoid, t.oid, "
4003                                                           "t.relname AS indexname, "
4004                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4005                                                           "t.relnatts AS indnkeys, "
4006                                                           "i.indkey, i.indisclustered, "
4007                                                           "c.contype, c.conname, "
4008                                                           "c.condeferrable, c.condeferred, "
4009                                                           "c.tableoid AS contableoid, "
4010                                                           "c.oid AS conoid, "
4011                                                           "null AS condef, "
4012                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4013                                                         "array_to_string(t.reloptions, ', ') AS options "
4014                                                           "FROM pg_catalog.pg_index i "
4015                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4016                                                           "LEFT JOIN pg_catalog.pg_depend d "
4017                                                           "ON (d.classid = t.tableoid "
4018                                                           "AND d.objid = t.oid "
4019                                                           "AND d.deptype = 'i') "
4020                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4021                                                           "ON (d.refclassid = c.tableoid "
4022                                                           "AND d.refobjid = c.oid) "
4023                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4024                                                           "ORDER BY indexname",
4025                                                           tbinfo->dobj.catId.oid);
4026                 }
4027                 else if (g_fout->remoteVersion >= 80000)
4028                 {
4029                         appendPQExpBuffer(query,
4030                                                           "SELECT t.tableoid, t.oid, "
4031                                                           "t.relname AS indexname, "
4032                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4033                                                           "t.relnatts AS indnkeys, "
4034                                                           "i.indkey, i.indisclustered, "
4035                                                           "c.contype, c.conname, "
4036                                                           "c.condeferrable, c.condeferred, "
4037                                                           "c.tableoid AS contableoid, "
4038                                                           "c.oid AS conoid, "
4039                                                           "null AS condef, "
4040                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4041                                                           "null AS options "
4042                                                           "FROM pg_catalog.pg_index i "
4043                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4044                                                           "LEFT JOIN pg_catalog.pg_depend d "
4045                                                           "ON (d.classid = t.tableoid "
4046                                                           "AND d.objid = t.oid "
4047                                                           "AND d.deptype = 'i') "
4048                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4049                                                           "ON (d.refclassid = c.tableoid "
4050                                                           "AND d.refobjid = c.oid) "
4051                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4052                                                           "ORDER BY indexname",
4053                                                           tbinfo->dobj.catId.oid);
4054                 }
4055                 else if (g_fout->remoteVersion >= 70300)
4056                 {
4057                         appendPQExpBuffer(query,
4058                                                           "SELECT t.tableoid, t.oid, "
4059                                                           "t.relname AS indexname, "
4060                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4061                                                           "t.relnatts AS indnkeys, "
4062                                                           "i.indkey, i.indisclustered, "
4063                                                           "c.contype, c.conname, "
4064                                                           "c.condeferrable, c.condeferred, "
4065                                                           "c.tableoid AS contableoid, "
4066                                                           "c.oid AS conoid, "
4067                                                           "null AS condef, "
4068                                                           "NULL AS tablespace, "
4069                                                           "null AS options "
4070                                                           "FROM pg_catalog.pg_index i "
4071                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4072                                                           "LEFT JOIN pg_catalog.pg_depend d "
4073                                                           "ON (d.classid = t.tableoid "
4074                                                           "AND d.objid = t.oid "
4075                                                           "AND d.deptype = 'i') "
4076                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4077                                                           "ON (d.refclassid = c.tableoid "
4078                                                           "AND d.refobjid = c.oid) "
4079                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4080                                                           "ORDER BY indexname",
4081                                                           tbinfo->dobj.catId.oid);
4082                 }
4083                 else if (g_fout->remoteVersion >= 70100)
4084                 {
4085                         appendPQExpBuffer(query,
4086                                                           "SELECT t.tableoid, t.oid, "
4087                                                           "t.relname AS indexname, "
4088                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4089                                                           "t.relnatts AS indnkeys, "
4090                                                           "i.indkey, false AS indisclustered, "
4091                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4092                                                           "ELSE '0'::char END AS contype, "
4093                                                           "t.relname AS conname, "
4094                                                           "false AS condeferrable, "
4095                                                           "false AS condeferred, "
4096                                                           "0::oid AS contableoid, "
4097                                                           "t.oid AS conoid, "
4098                                                           "null AS condef, "
4099                                                           "NULL AS tablespace, "
4100                                                           "null AS options "
4101                                                           "FROM pg_index i, pg_class t "
4102                                                           "WHERE t.oid = i.indexrelid "
4103                                                           "AND i.indrelid = '%u'::oid "
4104                                                           "ORDER BY indexname",
4105                                                           tbinfo->dobj.catId.oid);
4106                 }
4107                 else
4108                 {
4109                         appendPQExpBuffer(query,
4110                                                           "SELECT "
4111                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4112                                                           "t.oid, "
4113                                                           "t.relname AS indexname, "
4114                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4115                                                           "t.relnatts AS indnkeys, "
4116                                                           "i.indkey, false AS indisclustered, "
4117                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4118                                                           "ELSE '0'::char END AS contype, "
4119                                                           "t.relname AS conname, "
4120                                                           "false AS condeferrable, "
4121                                                           "false AS condeferred, "
4122                                                           "0::oid AS contableoid, "
4123                                                           "t.oid AS conoid, "
4124                                                           "null AS condef, "
4125                                                           "NULL AS tablespace, "
4126                                                           "null AS options "
4127                                                           "FROM pg_index i, pg_class t "
4128                                                           "WHERE t.oid = i.indexrelid "
4129                                                           "AND i.indrelid = '%u'::oid "
4130                                                           "ORDER BY indexname",
4131                                                           tbinfo->dobj.catId.oid);
4132                 }
4133
4134                 res = PQexec(g_conn, query->data);
4135                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4136
4137                 ntups = PQntuples(res);
4138
4139                 i_tableoid = PQfnumber(res, "tableoid");
4140                 i_oid = PQfnumber(res, "oid");
4141                 i_indexname = PQfnumber(res, "indexname");
4142                 i_indexdef = PQfnumber(res, "indexdef");
4143                 i_indnkeys = PQfnumber(res, "indnkeys");
4144                 i_indkey = PQfnumber(res, "indkey");
4145                 i_indisclustered = PQfnumber(res, "indisclustered");
4146                 i_contype = PQfnumber(res, "contype");
4147                 i_conname = PQfnumber(res, "conname");
4148                 i_condeferrable = PQfnumber(res, "condeferrable");
4149                 i_condeferred = PQfnumber(res, "condeferred");
4150                 i_contableoid = PQfnumber(res, "contableoid");
4151                 i_conoid = PQfnumber(res, "conoid");
4152                 i_condef = PQfnumber(res, "condef");
4153                 i_tablespace = PQfnumber(res, "tablespace");
4154                 i_options = PQfnumber(res, "options");
4155
4156                 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
4157                 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
4158
4159                 for (j = 0; j < ntups; j++)
4160                 {
4161                         char            contype;
4162
4163                         indxinfo[j].dobj.objType = DO_INDEX;
4164                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4165                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4166                         AssignDumpId(&indxinfo[j].dobj);
4167                         indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
4168                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4169                         indxinfo[j].indextable = tbinfo;
4170                         indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
4171                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4172                         indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
4173                         indxinfo[j].options = strdup(PQgetvalue(res, j, i_options));
4174
4175                         /*
4176                          * In pre-7.4 releases, indkeys may contain more entries than
4177                          * indnkeys says (since indnkeys will be 1 for a functional
4178                          * index).      We don't actually care about this case since we don't
4179                          * examine indkeys except for indexes associated with PRIMARY and
4180                          * UNIQUE constraints, which are never functional indexes. But we
4181                          * have to allocate enough space to keep parseOidArray from
4182                          * complaining.
4183                          */
4184                         indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
4185                         parseOidArray(PQgetvalue(res, j, i_indkey),
4186                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4187                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4188                         contype = *(PQgetvalue(res, j, i_contype));
4189
4190                         if (contype == 'p' || contype == 'u' || contype == 'x')
4191                         {
4192                                 /*
4193                                  * If we found a constraint matching the index, create an
4194                                  * entry for it.
4195                                  *
4196                                  * In a pre-7.3 database, we take this path iff the index was
4197                                  * marked indisprimary.
4198                                  */
4199                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4200                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4201                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4202                                 AssignDumpId(&constrinfo[j].dobj);
4203                                 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
4204                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4205                                 constrinfo[j].contable = tbinfo;
4206                                 constrinfo[j].condomain = NULL;
4207                                 constrinfo[j].contype = contype;
4208                                 if (contype == 'x')
4209                                         constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
4210                                 else
4211                                         constrinfo[j].condef = NULL;
4212                                 constrinfo[j].confrelid = InvalidOid;
4213                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4214                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4215                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4216                                 constrinfo[j].conislocal = true;
4217                                 constrinfo[j].separate = true;
4218
4219                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4220
4221                                 /* If pre-7.3 DB, better make sure table comes first */
4222                                 addObjectDependency(&constrinfo[j].dobj,
4223                                                                         tbinfo->dobj.dumpId);
4224                         }
4225                         else
4226                         {
4227                                 /* Plain secondary index */
4228                                 indxinfo[j].indexconstraint = 0;
4229                         }
4230                 }
4231
4232                 PQclear(res);
4233         }
4234
4235         destroyPQExpBuffer(query);
4236 }
4237
4238 /*
4239  * getConstraints
4240  *
4241  * Get info about constraints on dumpable tables.
4242  *
4243  * Currently handles foreign keys only.
4244  * Unique and primary key constraints are handled with indexes,
4245  * while check constraints are processed in getTableAttrs().
4246  */
4247 void
4248 getConstraints(TableInfo tblinfo[], int numTables)
4249 {
4250         int                     i,
4251                                 j;
4252         ConstraintInfo *constrinfo;
4253         PQExpBuffer query;
4254         PGresult   *res;
4255         int                     i_contableoid,
4256                                 i_conoid,
4257                                 i_conname,
4258                                 i_confrelid,
4259                                 i_condef;
4260         int                     ntups;
4261
4262         /* pg_constraint was created in 7.3, so nothing to do if older */
4263         if (g_fout->remoteVersion < 70300)
4264                 return;
4265
4266         query = createPQExpBuffer();
4267
4268         for (i = 0; i < numTables; i++)
4269         {
4270                 TableInfo  *tbinfo = &tblinfo[i];
4271
4272                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4273                         continue;
4274
4275                 if (g_verbose)
4276                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4277                                           tbinfo->dobj.name);
4278
4279                 /*
4280                  * select table schema to ensure constraint expr is qualified if
4281                  * needed
4282                  */
4283                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4284
4285                 resetPQExpBuffer(query);
4286                 appendPQExpBuffer(query,
4287                                                   "SELECT tableoid, oid, conname, confrelid, "
4288                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4289                                                   "FROM pg_catalog.pg_constraint "
4290                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4291                                                   "AND contype = 'f'",
4292                                                   tbinfo->dobj.catId.oid);
4293                 res = PQexec(g_conn, query->data);
4294                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4295
4296                 ntups = PQntuples(res);
4297
4298                 i_contableoid = PQfnumber(res, "tableoid");
4299                 i_conoid = PQfnumber(res, "oid");
4300                 i_conname = PQfnumber(res, "conname");
4301                 i_confrelid = PQfnumber(res, "confrelid");
4302                 i_condef = PQfnumber(res, "condef");
4303
4304                 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
4305
4306                 for (j = 0; j < ntups; j++)
4307                 {
4308                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4309                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4310                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4311                         AssignDumpId(&constrinfo[j].dobj);
4312                         constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
4313                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4314                         constrinfo[j].contable = tbinfo;
4315                         constrinfo[j].condomain = NULL;
4316                         constrinfo[j].contype = 'f';
4317                         constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
4318                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4319                         constrinfo[j].conindex = 0;
4320                         constrinfo[j].condeferrable = false;
4321                         constrinfo[j].condeferred = false;
4322                         constrinfo[j].conislocal = true;
4323                         constrinfo[j].separate = true;
4324                 }
4325
4326                 PQclear(res);
4327         }
4328
4329         destroyPQExpBuffer(query);
4330 }
4331
4332 /*
4333  * getDomainConstraints
4334  *
4335  * Get info about constraints on a domain.
4336  */
4337 static void
4338 getDomainConstraints(TypeInfo *tyinfo)
4339 {
4340         int                     i;
4341         ConstraintInfo *constrinfo;
4342         PQExpBuffer query;
4343         PGresult   *res;
4344         int                     i_tableoid,
4345                                 i_oid,
4346                                 i_conname,
4347                                 i_consrc;
4348         int                     ntups;
4349
4350         /* pg_constraint was created in 7.3, so nothing to do if older */
4351         if (g_fout->remoteVersion < 70300)
4352                 return;
4353
4354         /*
4355          * select appropriate schema to ensure names in constraint are properly
4356          * qualified
4357          */
4358         selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
4359
4360         query = createPQExpBuffer();
4361
4362         if (g_fout->remoteVersion >= 70400)
4363                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4364                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc "
4365                                                   "FROM pg_catalog.pg_constraint "
4366                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4367                                                   "ORDER BY conname",
4368                                                   tyinfo->dobj.catId.oid);
4369         else
4370                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4371                                                   "'CHECK (' || consrc || ')' AS consrc "
4372                                                   "FROM pg_catalog.pg_constraint "
4373                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4374                                                   "ORDER BY conname",
4375                                                   tyinfo->dobj.catId.oid);
4376
4377         res = PQexec(g_conn, query->data);
4378         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4379
4380         ntups = PQntuples(res);
4381
4382         i_tableoid = PQfnumber(res, "tableoid");
4383         i_oid = PQfnumber(res, "oid");
4384         i_conname = PQfnumber(res, "conname");
4385         i_consrc = PQfnumber(res, "consrc");
4386
4387         constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
4388
4389         tyinfo->nDomChecks = ntups;
4390         tyinfo->domChecks = constrinfo;
4391
4392         for (i = 0; i < ntups; i++)
4393         {
4394                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4395                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4396                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4397                 AssignDumpId(&constrinfo[i].dobj);
4398                 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
4399                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4400                 constrinfo[i].contable = NULL;
4401                 constrinfo[i].condomain = tyinfo;
4402                 constrinfo[i].contype = 'c';
4403                 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
4404                 constrinfo[i].confrelid = InvalidOid;
4405                 constrinfo[i].conindex = 0;
4406                 constrinfo[i].condeferrable = false;
4407                 constrinfo[i].condeferred = false;
4408                 constrinfo[i].conislocal = true;
4409                 constrinfo[i].separate = false;
4410
4411                 /*
4412                  * Make the domain depend on the constraint, ensuring it won't be
4413                  * output till any constraint dependencies are OK.
4414                  */
4415                 addObjectDependency(&tyinfo->dobj,
4416                                                         constrinfo[i].dobj.dumpId);
4417         }
4418
4419         PQclear(res);
4420
4421         destroyPQExpBuffer(query);
4422 }
4423
4424 /*
4425  * getRules
4426  *        get basic information about every rule in the system
4427  *
4428  * numRules is set to the number of rules read in
4429  */
4430 RuleInfo *
4431 getRules(int *numRules)
4432 {
4433         PGresult   *res;
4434         int                     ntups;
4435         int                     i;
4436         PQExpBuffer query = createPQExpBuffer();
4437         RuleInfo   *ruleinfo;
4438         int                     i_tableoid;
4439         int                     i_oid;
4440         int                     i_rulename;
4441         int                     i_ruletable;
4442         int                     i_ev_type;
4443         int                     i_is_instead;
4444         int                     i_ev_enabled;
4445
4446         /* Make sure we are in proper schema */
4447         selectSourceSchema("pg_catalog");
4448
4449         if (g_fout->remoteVersion >= 80300)
4450         {
4451                 appendPQExpBuffer(query, "SELECT "
4452                                                   "tableoid, oid, rulename, "
4453                                                   "ev_class AS ruletable, ev_type, is_instead, "
4454                                                   "ev_enabled "
4455                                                   "FROM pg_rewrite "
4456                                                   "ORDER BY oid");
4457         }
4458         else if (g_fout->remoteVersion >= 70100)
4459         {
4460                 appendPQExpBuffer(query, "SELECT "
4461                                                   "tableoid, oid, rulename, "
4462                                                   "ev_class AS ruletable, ev_type, is_instead, "
4463                                                   "'O'::char AS ev_enabled "
4464                                                   "FROM pg_rewrite "
4465                                                   "ORDER BY oid");
4466         }
4467         else
4468         {
4469                 appendPQExpBuffer(query, "SELECT "
4470                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4471                                                   "oid, rulename, "
4472                                                   "ev_class AS ruletable, ev_type, is_instead, "
4473                                                   "'O'::char AS ev_enabled "
4474                                                   "FROM pg_rewrite "
4475                                                   "ORDER BY oid");
4476         }
4477
4478         res = PQexec(g_conn, query->data);
4479         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4480
4481         ntups = PQntuples(res);
4482
4483         *numRules = ntups;
4484
4485         ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
4486
4487         i_tableoid = PQfnumber(res, "tableoid");
4488         i_oid = PQfnumber(res, "oid");
4489         i_rulename = PQfnumber(res, "rulename");
4490         i_ruletable = PQfnumber(res, "ruletable");
4491         i_ev_type = PQfnumber(res, "ev_type");
4492         i_is_instead = PQfnumber(res, "is_instead");
4493         i_ev_enabled = PQfnumber(res, "ev_enabled");
4494
4495         for (i = 0; i < ntups; i++)
4496         {
4497                 Oid                     ruletableoid;
4498
4499                 ruleinfo[i].dobj.objType = DO_RULE;
4500                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4501                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4502                 AssignDumpId(&ruleinfo[i].dobj);
4503                 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
4504                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
4505                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
4506                 if (ruleinfo[i].ruletable == NULL)
4507                 {
4508                         write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
4509                                           ruletableoid,
4510                                           ruleinfo[i].dobj.catId.oid);
4511                         exit_nicely();
4512                 }
4513                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
4514                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
4515                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
4516                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
4517                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
4518                 if (ruleinfo[i].ruletable)
4519                 {
4520                         /*
4521                          * If the table is a view, force its ON SELECT rule to be sorted
4522                          * before the view itself --- this ensures that any dependencies
4523                          * for the rule affect the table's positioning. Other rules are
4524                          * forced to appear after their table.
4525                          */
4526                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
4527                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
4528                         {
4529                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
4530                                                                         ruleinfo[i].dobj.dumpId);
4531                                 /* We'll merge the rule into CREATE VIEW, if possible */
4532                                 ruleinfo[i].separate = false;
4533                         }
4534                         else
4535                         {
4536                                 addObjectDependency(&ruleinfo[i].dobj,
4537                                                                         ruleinfo[i].ruletable->dobj.dumpId);
4538                                 ruleinfo[i].separate = true;
4539                         }
4540                 }
4541                 else
4542                         ruleinfo[i].separate = true;
4543         }
4544
4545         PQclear(res);
4546
4547         destroyPQExpBuffer(query);
4548
4549         return ruleinfo;
4550 }
4551
4552 /*
4553  * getTriggers
4554  *        get information about every trigger on a dumpable table
4555  *
4556  * Note: trigger data is not returned directly to the caller, but it
4557  * does get entered into the DumpableObject tables.
4558  */
4559 void
4560 getTriggers(TableInfo tblinfo[], int numTables)
4561 {
4562         int                     i,
4563                                 j;
4564         PQExpBuffer query = createPQExpBuffer();
4565         PGresult   *res;
4566         TriggerInfo *tginfo;
4567         int                     i_tableoid,
4568                                 i_oid,
4569                                 i_tgname,
4570                                 i_tgfname,
4571                                 i_tgtype,
4572                                 i_tgnargs,
4573                                 i_tgargs,
4574                                 i_tgisconstraint,
4575                                 i_tgconstrname,
4576                                 i_tgconstrrelid,
4577                                 i_tgconstrrelname,
4578                                 i_tgenabled,
4579                                 i_tgdeferrable,
4580                                 i_tginitdeferred,
4581                                 i_tgdef;
4582         int                     ntups;
4583
4584         for (i = 0; i < numTables; i++)
4585         {
4586                 TableInfo  *tbinfo = &tblinfo[i];
4587
4588                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4589                         continue;
4590
4591                 if (g_verbose)
4592                         write_msg(NULL, "reading triggers for table \"%s\"\n",
4593                                           tbinfo->dobj.name);
4594
4595                 /*
4596                  * select table schema to ensure regproc name is qualified if needed
4597                  */
4598                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4599
4600                 resetPQExpBuffer(query);
4601                 if (g_fout->remoteVersion >= 90000)
4602                 {
4603                         /*
4604                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
4605                          * could result in non-forward-compatible dumps of WHEN clauses
4606                          * due to under-parenthesization.
4607                          */
4608                         appendPQExpBuffer(query,
4609                                                           "SELECT tgname, "
4610                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
4611                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
4612                                                           "tgenabled, tableoid, oid "
4613                                                           "FROM pg_catalog.pg_trigger t "
4614                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
4615                                                           "AND NOT tgisinternal",
4616                                                           tbinfo->dobj.catId.oid);
4617                 }
4618                 else if (g_fout->remoteVersion >= 80300)
4619                 {
4620                         /*
4621                          * We ignore triggers that are tied to a foreign-key constraint
4622                          */
4623                         appendPQExpBuffer(query,
4624                                                           "SELECT tgname, "
4625                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
4626                                                           "tgtype, tgnargs, tgargs, tgenabled, "
4627                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
4628                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
4629                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
4630                                                           "FROM pg_catalog.pg_trigger t "
4631                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
4632                                                           "AND tgconstraint = 0",
4633                                                           tbinfo->dobj.catId.oid);
4634                 }
4635                 else if (g_fout->remoteVersion >= 70300)
4636                 {
4637                         /*
4638                          * We ignore triggers that are tied to a foreign-key constraint,
4639                          * but in these versions we have to grovel through pg_constraint
4640                          * to find out
4641                          */
4642                         appendPQExpBuffer(query,
4643                                                           "SELECT tgname, "
4644                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
4645                                                           "tgtype, tgnargs, tgargs, tgenabled, "
4646                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
4647                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
4648                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
4649                                                           "FROM pg_catalog.pg_trigger t "
4650                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
4651                                                           "AND (NOT tgisconstraint "
4652                                                           " OR NOT EXISTS"
4653                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
4654                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
4655                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
4656                                                           tbinfo->dobj.catId.oid);
4657                 }
4658                 else if (g_fout->remoteVersion >= 70100)
4659                 {
4660                         appendPQExpBuffer(query,
4661                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
4662                                                           "tgtype, tgnargs, tgargs, tgenabled, "
4663                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
4664                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
4665                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
4666                                                           "             AS tgconstrrelname "
4667                                                           "FROM pg_trigger "
4668                                                           "WHERE tgrelid = '%u'::oid",
4669                                                           tbinfo->dobj.catId.oid);
4670                 }
4671                 else
4672                 {
4673                         appendPQExpBuffer(query,
4674                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
4675                                                           "tgtype, tgnargs, tgargs, tgenabled, "
4676                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
4677                                                           "tgconstrrelid, tginitdeferred, "
4678                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
4679                                                           "oid, "
4680                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
4681                                                           "             AS tgconstrrelname "
4682                                                           "FROM pg_trigger "
4683                                                           "WHERE tgrelid = '%u'::oid",
4684                                                           tbinfo->dobj.catId.oid);
4685                 }
4686                 res = PQexec(g_conn, query->data);
4687                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4688
4689                 ntups = PQntuples(res);
4690
4691                 i_tableoid = PQfnumber(res, "tableoid");
4692                 i_oid = PQfnumber(res, "oid");
4693                 i_tgname = PQfnumber(res, "tgname");
4694                 i_tgfname = PQfnumber(res, "tgfname");
4695                 i_tgtype = PQfnumber(res, "tgtype");
4696                 i_tgnargs = PQfnumber(res, "tgnargs");
4697                 i_tgargs = PQfnumber(res, "tgargs");
4698                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
4699                 i_tgconstrname = PQfnumber(res, "tgconstrname");
4700                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
4701                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
4702                 i_tgenabled = PQfnumber(res, "tgenabled");
4703                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
4704                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
4705                 i_tgdef = PQfnumber(res, "tgdef");
4706
4707                 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
4708
4709                 for (j = 0; j < ntups; j++)
4710                 {
4711                         tginfo[j].dobj.objType = DO_TRIGGER;
4712                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4713                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4714                         AssignDumpId(&tginfo[j].dobj);
4715                         tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
4716                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
4717                         tginfo[j].tgtable = tbinfo;
4718                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
4719                         if (i_tgdef >= 0)
4720                         {
4721                                 tginfo[j].tgdef = strdup(PQgetvalue(res, j, i_tgdef));
4722
4723                                 /* remaining fields are not valid if we have tgdef */
4724                                 tginfo[j].tgfname = NULL;
4725                                 tginfo[j].tgtype = 0;
4726                                 tginfo[j].tgnargs = 0;
4727                                 tginfo[j].tgargs = NULL;
4728                                 tginfo[j].tgisconstraint = false;
4729                                 tginfo[j].tgdeferrable = false;
4730                                 tginfo[j].tginitdeferred = false;
4731                                 tginfo[j].tgconstrname = NULL;
4732                                 tginfo[j].tgconstrrelid = InvalidOid;
4733                                 tginfo[j].tgconstrrelname = NULL;
4734                         }
4735                         else
4736                         {
4737                                 tginfo[j].tgdef = NULL;
4738
4739                                 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
4740                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
4741                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
4742                                 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
4743                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
4744                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
4745                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
4746
4747                                 if (tginfo[j].tgisconstraint)
4748                                 {
4749                                         tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
4750                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
4751                                         if (OidIsValid(tginfo[j].tgconstrrelid))
4752                                         {
4753                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
4754                                                 {
4755                                                         write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
4756                                                                           tginfo[j].dobj.name, tbinfo->dobj.name,
4757                                                                           tginfo[j].tgconstrrelid);
4758                                                         exit_nicely();
4759                                                 }
4760                                                 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
4761                                         }
4762                                         else
4763                                                 tginfo[j].tgconstrrelname = NULL;
4764                                 }
4765                                 else
4766                                 {
4767                                         tginfo[j].tgconstrname = NULL;
4768                                         tginfo[j].tgconstrrelid = InvalidOid;
4769                                         tginfo[j].tgconstrrelname = NULL;
4770                                 }
4771                         }
4772                 }
4773
4774                 PQclear(res);
4775         }
4776
4777         destroyPQExpBuffer(query);
4778 }
4779
4780 /*
4781  * getProcLangs
4782  *        get basic information about every procedural language in the system
4783  *
4784  * numProcLangs is set to the number of langs read in
4785  *
4786  * NB: this must run after getFuncs() because we assume we can do
4787  * findFuncByOid().
4788  */
4789 ProcLangInfo *
4790 getProcLangs(int *numProcLangs)
4791 {
4792         PGresult   *res;
4793         int                     ntups;
4794         int                     i;
4795         PQExpBuffer query = createPQExpBuffer();
4796         ProcLangInfo *planginfo;
4797         int                     i_tableoid;
4798         int                     i_oid;
4799         int                     i_lanname;
4800         int                     i_lanpltrusted;
4801         int                     i_lanplcallfoid;
4802         int                     i_laninline;
4803         int                     i_lanvalidator;
4804         int                     i_lanacl;
4805         int                     i_lanowner;
4806
4807         /* Make sure we are in proper schema */
4808         selectSourceSchema("pg_catalog");
4809
4810         if (g_fout->remoteVersion >= 90000)
4811         {
4812                 /* pg_language has a laninline column */
4813                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4814                                                   "lanname, lanpltrusted, lanplcallfoid, "
4815                                                   "laninline, lanvalidator,  lanacl, "
4816                                                   "(%s lanowner) AS lanowner "
4817                                                   "FROM pg_language "
4818                                                   "WHERE lanispl "
4819                                                   "ORDER BY oid",
4820                                                   username_subquery);
4821         }
4822         else if (g_fout->remoteVersion >= 80300)
4823         {
4824                 /* pg_language has a lanowner column */
4825                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4826                                                   "lanname, lanpltrusted, lanplcallfoid, "
4827                                                   "lanvalidator,  lanacl, "
4828                                                   "(%s lanowner) AS lanowner "
4829                                                   "FROM pg_language "
4830                                                   "WHERE lanispl "
4831                                                   "ORDER BY oid",
4832                                                   username_subquery);
4833         }
4834         else if (g_fout->remoteVersion >= 80100)
4835         {
4836                 /* Languages are owned by the bootstrap superuser, OID 10 */
4837                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
4838                                                   "(%s '10') AS lanowner "
4839                                                   "FROM pg_language "
4840                                                   "WHERE lanispl "
4841                                                   "ORDER BY oid",
4842                                                   username_subquery);
4843         }
4844         else if (g_fout->remoteVersion >= 70400)
4845         {
4846                 /* Languages are owned by the bootstrap superuser, sysid 1 */
4847                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
4848                                                   "(%s '1') AS lanowner "
4849                                                   "FROM pg_language "
4850                                                   "WHERE lanispl "
4851                                                   "ORDER BY oid",
4852                                                   username_subquery);
4853         }
4854         else if (g_fout->remoteVersion >= 70100)
4855         {
4856                 /* No clear notion of an owner at all before 7.4 ... */
4857                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
4858                                                   "WHERE lanispl "
4859                                                   "ORDER BY oid");
4860         }
4861         else
4862         {
4863                 appendPQExpBuffer(query, "SELECT "
4864                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
4865                                                   "oid, * FROM pg_language "
4866                                                   "WHERE lanispl "
4867                                                   "ORDER BY oid");
4868         }
4869
4870         res = PQexec(g_conn, query->data);
4871         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4872
4873         ntups = PQntuples(res);
4874
4875         *numProcLangs = ntups;
4876
4877         planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
4878
4879         i_tableoid = PQfnumber(res, "tableoid");
4880         i_oid = PQfnumber(res, "oid");
4881         i_lanname = PQfnumber(res, "lanname");
4882         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
4883         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
4884         /* these may fail and return -1: */
4885         i_laninline = PQfnumber(res, "laninline");
4886         i_lanvalidator = PQfnumber(res, "lanvalidator");
4887         i_lanacl = PQfnumber(res, "lanacl");
4888         i_lanowner = PQfnumber(res, "lanowner");
4889
4890         for (i = 0; i < ntups; i++)
4891         {
4892                 planginfo[i].dobj.objType = DO_PROCLANG;
4893                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4894                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4895                 AssignDumpId(&planginfo[i].dobj);
4896
4897                 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
4898                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
4899                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
4900                 if (i_laninline >= 0)
4901                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
4902                 else
4903                         planginfo[i].laninline = InvalidOid;
4904                 if (i_lanvalidator >= 0)
4905                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
4906                 else
4907                         planginfo[i].lanvalidator = InvalidOid;
4908                 if (i_lanacl >= 0)
4909                         planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
4910                 else
4911                         planginfo[i].lanacl = strdup("{=U}");
4912                 if (i_lanowner >= 0)
4913                         planginfo[i].lanowner = strdup(PQgetvalue(res, i, i_lanowner));
4914                 else
4915                         planginfo[i].lanowner = strdup("");
4916
4917                 if (g_fout->remoteVersion < 70300)
4918                 {
4919                         /*
4920                          * We need to make a dependency to ensure the function will be
4921                          * dumped first.  (In 7.3 and later the regular dependency
4922                          * mechanism will handle this for us.)
4923                          */
4924                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
4925
4926                         if (funcInfo)
4927                                 addObjectDependency(&planginfo[i].dobj,
4928                                                                         funcInfo->dobj.dumpId);
4929                 }
4930         }
4931
4932         PQclear(res);
4933
4934         destroyPQExpBuffer(query);
4935
4936         return planginfo;
4937 }
4938
4939 /*
4940  * getCasts
4941  *        get basic information about every cast in the system
4942  *
4943  * numCasts is set to the number of casts read in
4944  */
4945 CastInfo *
4946 getCasts(int *numCasts)
4947 {
4948         PGresult   *res;
4949         int                     ntups;
4950         int                     i;
4951         PQExpBuffer query = createPQExpBuffer();
4952         CastInfo   *castinfo;
4953         int                     i_tableoid;
4954         int                     i_oid;
4955         int                     i_castsource;
4956         int                     i_casttarget;
4957         int                     i_castfunc;
4958         int                     i_castcontext;
4959         int                     i_castmethod;
4960
4961         /* Make sure we are in proper schema */
4962         selectSourceSchema("pg_catalog");
4963
4964         if (g_fout->remoteVersion >= 80400)
4965         {
4966                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4967                                                   "castsource, casttarget, castfunc, castcontext, "
4968                                                   "castmethod "
4969                                                   "FROM pg_cast ORDER BY 3,4");
4970         }
4971         else if (g_fout->remoteVersion >= 70300)
4972         {
4973                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4974                                                   "castsource, casttarget, castfunc, castcontext, "
4975                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
4976                                                   "FROM pg_cast ORDER BY 3,4");
4977         }
4978         else
4979         {
4980                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
4981                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
4982                                                   "p.oid AS castfunc, 'e' AS castcontext, "
4983                                                   "'f' AS castmethod "
4984                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
4985                                                   "WHERE p.pronargs = 1 AND "
4986                                                   "p.proargtypes[0] = t1.oid AND "
4987                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
4988                                                   "ORDER BY 3,4");
4989         }
4990
4991         res = PQexec(g_conn, query->data);
4992         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4993
4994         ntups = PQntuples(res);
4995
4996         *numCasts = ntups;
4997
4998         castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
4999
5000         i_tableoid = PQfnumber(res, "tableoid");
5001         i_oid = PQfnumber(res, "oid");
5002         i_castsource = PQfnumber(res, "castsource");
5003         i_casttarget = PQfnumber(res, "casttarget");
5004         i_castfunc = PQfnumber(res, "castfunc");
5005         i_castcontext = PQfnumber(res, "castcontext");
5006         i_castmethod = PQfnumber(res, "castmethod");
5007
5008         for (i = 0; i < ntups; i++)
5009         {
5010                 PQExpBufferData namebuf;
5011                 TypeInfo   *sTypeInfo;
5012                 TypeInfo   *tTypeInfo;
5013
5014                 castinfo[i].dobj.objType = DO_CAST;
5015                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5016                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5017                 AssignDumpId(&castinfo[i].dobj);
5018                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5019                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5020                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5021                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5022                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5023
5024                 /*
5025                  * Try to name cast as concatenation of typnames.  This is only used
5026                  * for purposes of sorting.  If we fail to find either type, the name
5027                  * will be an empty string.
5028                  */
5029                 initPQExpBuffer(&namebuf);
5030                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5031                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5032                 if (sTypeInfo && tTypeInfo)
5033                         appendPQExpBuffer(&namebuf, "%s %s",
5034                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5035                 castinfo[i].dobj.name = namebuf.data;
5036
5037                 if (OidIsValid(castinfo[i].castfunc))
5038                 {
5039                         /*
5040                          * We need to make a dependency to ensure the function will be
5041                          * dumped first.  (In 7.3 and later the regular dependency
5042                          * mechanism will handle this for us.)
5043                          */
5044                         FuncInfo   *funcInfo;
5045
5046                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5047                         if (funcInfo)
5048                                 addObjectDependency(&castinfo[i].dobj,
5049                                                                         funcInfo->dobj.dumpId);
5050                 }
5051         }
5052
5053         PQclear(res);
5054
5055         destroyPQExpBuffer(query);
5056
5057         return castinfo;
5058 }
5059
5060 /*
5061  * getTableAttrs -
5062  *        for each interesting table, read info about its attributes
5063  *        (names, types, default values, CHECK constraints, etc)
5064  *
5065  * This is implemented in a very inefficient way right now, looping
5066  * through the tblinfo and doing a join per table to find the attrs and their
5067  * types.  However, because we want type names and so forth to be named
5068  * relative to the schema of each table, we couldn't do it in just one
5069  * query.  (Maybe one query per schema?)
5070  *
5071  *      modifies tblinfo
5072  */
5073 void
5074 getTableAttrs(TableInfo *tblinfo, int numTables)
5075 {
5076         int                     i,
5077                                 j;
5078         PQExpBuffer q = createPQExpBuffer();
5079         int                     i_attnum;
5080         int                     i_attname;
5081         int                     i_atttypname;
5082         int                     i_atttypmod;
5083         int                     i_attstattarget;
5084         int                     i_attstorage;
5085         int                     i_typstorage;
5086         int                     i_attnotnull;
5087         int                     i_atthasdef;
5088         int                     i_attisdropped;
5089         int                     i_attlen;
5090         int                     i_attalign;
5091         int                     i_attislocal;
5092         int                     i_attoptions;
5093         PGresult   *res;
5094         int                     ntups;
5095         bool            hasdefaults;
5096
5097         for (i = 0; i < numTables; i++)
5098         {
5099                 TableInfo  *tbinfo = &tblinfo[i];
5100
5101                 /* Don't bother to collect info for sequences */
5102                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5103                         continue;
5104
5105                 /* Don't bother with uninteresting tables, either */
5106                 if (!tbinfo->interesting)
5107                         continue;
5108
5109                 /*
5110                  * Make sure we are in proper schema for this table; this allows
5111                  * correct retrieval of formatted type names and default exprs
5112                  */
5113                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
5114
5115                 /* find all the user attributes and their types */
5116
5117                 /*
5118                  * we must read the attribute names in attribute number order! because
5119                  * we will use the attnum to index into the attnames array later.  We
5120                  * actually ask to order by "attrelid, attnum" because (at least up to
5121                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5122                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5123                  */
5124                 if (g_verbose)
5125                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5126                                           tbinfo->dobj.name);
5127
5128                 resetPQExpBuffer(q);
5129
5130                 if (g_fout->remoteVersion >= 90000)
5131                 {
5132                         /* attoptions is new in 9.0 */
5133                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5134                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5135                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5136                                                           "a.attlen, a.attalign, a.attislocal, "
5137                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5138                                                    "array_to_string(attoptions, ', ') AS attoptions "
5139                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5140                                                           "ON a.atttypid = t.oid "
5141                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5142                                                           "AND a.attnum > 0::pg_catalog.int2 "
5143                                                           "ORDER BY a.attrelid, a.attnum",
5144                                                           tbinfo->dobj.catId.oid);
5145                 }
5146                 else if (g_fout->remoteVersion >= 70300)
5147                 {
5148                         /* need left join here to not fail on dropped columns ... */
5149                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5150                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5151                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5152                                                           "a.attlen, a.attalign, a.attislocal, "
5153                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5154                                                           "'' AS attoptions "
5155                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5156                                                           "ON a.atttypid = t.oid "
5157                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5158                                                           "AND a.attnum > 0::pg_catalog.int2 "
5159                                                           "ORDER BY a.attrelid, a.attnum",
5160                                                           tbinfo->dobj.catId.oid);
5161                 }
5162                 else if (g_fout->remoteVersion >= 70100)
5163                 {
5164                         /*
5165                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5166                          * we don't dump it because we can't tell whether it's been
5167                          * explicitly set or was just a default.
5168                          */
5169                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5170                                                           "-1 AS attstattarget, a.attstorage, "
5171                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5172                                                           "false AS attisdropped, a.attlen, "
5173                                                           "a.attalign, false AS attislocal, "
5174                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5175                                                           "'' AS attoptions "
5176                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5177                                                           "ON a.atttypid = t.oid "
5178                                                           "WHERE a.attrelid = '%u'::oid "
5179                                                           "AND a.attnum > 0::int2 "
5180                                                           "ORDER BY a.attrelid, a.attnum",
5181                                                           tbinfo->dobj.catId.oid);
5182                 }
5183                 else
5184                 {
5185                         /* format_type not available before 7.1 */
5186                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5187                                                           "-1 AS attstattarget, "
5188                                                           "attstorage, attstorage AS typstorage, "
5189                                                           "attnotnull, atthasdef, false AS attisdropped, "
5190                                                           "attlen, attalign, "
5191                                                           "false AS attislocal, "
5192                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5193                                                           "'' AS attoptions "
5194                                                           "FROM pg_attribute a "
5195                                                           "WHERE attrelid = '%u'::oid "
5196                                                           "AND attnum > 0::int2 "
5197                                                           "ORDER BY attrelid, attnum",
5198                                                           tbinfo->dobj.catId.oid);
5199                 }
5200
5201                 res = PQexec(g_conn, q->data);
5202                 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5203
5204                 ntups = PQntuples(res);
5205
5206                 i_attnum = PQfnumber(res, "attnum");
5207                 i_attname = PQfnumber(res, "attname");
5208                 i_atttypname = PQfnumber(res, "atttypname");
5209                 i_atttypmod = PQfnumber(res, "atttypmod");
5210                 i_attstattarget = PQfnumber(res, "attstattarget");
5211                 i_attstorage = PQfnumber(res, "attstorage");
5212                 i_typstorage = PQfnumber(res, "typstorage");
5213                 i_attnotnull = PQfnumber(res, "attnotnull");
5214                 i_atthasdef = PQfnumber(res, "atthasdef");
5215                 i_attisdropped = PQfnumber(res, "attisdropped");
5216                 i_attlen = PQfnumber(res, "attlen");
5217                 i_attalign = PQfnumber(res, "attalign");
5218                 i_attislocal = PQfnumber(res, "attislocal");
5219                 i_attoptions = PQfnumber(res, "attoptions");
5220
5221                 tbinfo->numatts = ntups;
5222                 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
5223                 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
5224                 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
5225                 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
5226                 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
5227                 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
5228                 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
5229                 tbinfo->attlen = (int *) malloc(ntups * sizeof(int));
5230                 tbinfo->attalign = (char *) malloc(ntups * sizeof(char));
5231                 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
5232                 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
5233                 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
5234                 tbinfo->attoptions = (char **) malloc(ntups * sizeof(char *));
5235                 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
5236                 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
5237                 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
5238                 hasdefaults = false;
5239
5240                 for (j = 0; j < ntups; j++)
5241                 {
5242                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5243                         {
5244                                 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5245                                                   tbinfo->dobj.name);
5246                                 exit_nicely();
5247                         }
5248                         tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
5249                         tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
5250                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5251                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5252                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5253                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5254                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5255                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5256                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5257                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5258                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5259                         tbinfo->attoptions[j] = strdup(PQgetvalue(res, j, i_attoptions));
5260                         tbinfo->attrdefs[j] = NULL; /* fix below */
5261                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5262                                 hasdefaults = true;
5263                         /* these flags will be set in flagInhAttrs() */
5264                         tbinfo->inhAttrs[j] = false;
5265                         tbinfo->inhAttrDef[j] = false;
5266                         tbinfo->inhNotNull[j] = false;
5267                 }
5268
5269                 PQclear(res);
5270
5271                 /*
5272                  * Get info about column defaults
5273                  */
5274                 if (hasdefaults)
5275                 {
5276                         AttrDefInfo *attrdefs;
5277                         int                     numDefaults;
5278
5279                         if (g_verbose)
5280                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5281                                                   tbinfo->dobj.name);
5282
5283                         resetPQExpBuffer(q);
5284                         if (g_fout->remoteVersion >= 70300)
5285                         {
5286                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5287                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5288                                                                   "FROM pg_catalog.pg_attrdef "
5289                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5290                                                                   tbinfo->dobj.catId.oid);
5291                         }
5292                         else if (g_fout->remoteVersion >= 70200)
5293                         {
5294                                 /* 7.2 did not have OIDs in pg_attrdef */
5295                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5296                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5297                                                                   "FROM pg_attrdef "
5298                                                                   "WHERE adrelid = '%u'::oid",
5299                                                                   tbinfo->dobj.catId.oid);
5300                         }
5301                         else if (g_fout->remoteVersion >= 70100)
5302                         {
5303                                 /* no pg_get_expr, so must rely on adsrc */
5304                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5305                                                                   "FROM pg_attrdef "
5306                                                                   "WHERE adrelid = '%u'::oid",
5307                                                                   tbinfo->dobj.catId.oid);
5308                         }
5309                         else
5310                         {
5311                                 /* no pg_get_expr, no tableoid either */
5312                                 appendPQExpBuffer(q, "SELECT "
5313                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5314                                                                   "oid, adnum, adsrc "
5315                                                                   "FROM pg_attrdef "
5316                                                                   "WHERE adrelid = '%u'::oid",
5317                                                                   tbinfo->dobj.catId.oid);
5318                         }
5319                         res = PQexec(g_conn, q->data);
5320                         check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5321
5322                         numDefaults = PQntuples(res);
5323                         attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
5324
5325                         for (j = 0; j < numDefaults; j++)
5326                         {
5327                                 int                     adnum;
5328
5329                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
5330                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5331                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5332                                 AssignDumpId(&attrdefs[j].dobj);
5333                                 attrdefs[j].adtable = tbinfo;
5334                                 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
5335                                 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
5336
5337                                 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
5338                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5339
5340                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5341
5342                                 /*
5343                                  * Defaults on a VIEW must always be dumped as separate ALTER
5344                                  * TABLE commands.      Defaults on regular tables are dumped as
5345                                  * part of the CREATE TABLE if possible.  To check if it's
5346                                  * safe, we mark the default as needing to appear before the
5347                                  * CREATE.
5348                                  */
5349                                 if (tbinfo->relkind == RELKIND_VIEW)
5350                                 {
5351                                         attrdefs[j].separate = true;
5352                                         /* needed in case pre-7.3 DB: */
5353                                         addObjectDependency(&attrdefs[j].dobj,
5354                                                                                 tbinfo->dobj.dumpId);
5355                                 }
5356                                 else
5357                                 {
5358                                         attrdefs[j].separate = false;
5359                                         addObjectDependency(&tbinfo->dobj,
5360                                                                                 attrdefs[j].dobj.dumpId);
5361                                 }
5362
5363                                 if (adnum <= 0 || adnum > ntups)
5364                                 {
5365                                         write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
5366                                                           adnum, tbinfo->dobj.name);
5367                                         exit_nicely();
5368                                 }
5369                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5370                         }
5371                         PQclear(res);
5372                 }
5373
5374                 /*
5375                  * Get info about table CHECK constraints
5376                  */
5377                 if (tbinfo->ncheck > 0)
5378                 {
5379                         ConstraintInfo *constrs;
5380                         int                     numConstrs;
5381
5382                         if (g_verbose)
5383                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5384                                                   tbinfo->dobj.name);
5385
5386                         resetPQExpBuffer(q);
5387                         if (g_fout->remoteVersion >= 80400)
5388                         {
5389                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5390                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5391                                                                   "conislocal "
5392                                                                   "FROM pg_catalog.pg_constraint "
5393                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5394                                                                   "   AND contype = 'c' "
5395                                                                   "ORDER BY conname",
5396                                                                   tbinfo->dobj.catId.oid);
5397                         }
5398                         else if (g_fout->remoteVersion >= 70400)
5399                         {
5400                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5401                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5402                                                                   "true AS conislocal "
5403                                                                   "FROM pg_catalog.pg_constraint "
5404                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5405                                                                   "   AND contype = 'c' "
5406                                                                   "ORDER BY conname",
5407                                                                   tbinfo->dobj.catId.oid);
5408                         }
5409                         else if (g_fout->remoteVersion >= 70300)
5410                         {
5411                                 /* no pg_get_constraintdef, must use consrc */
5412                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5413                                                                   "'CHECK (' || consrc || ')' AS consrc, "
5414                                                                   "true AS conislocal "
5415                                                                   "FROM pg_catalog.pg_constraint "
5416                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5417                                                                   "   AND contype = 'c' "
5418                                                                   "ORDER BY conname",
5419                                                                   tbinfo->dobj.catId.oid);
5420                         }
5421                         else if (g_fout->remoteVersion >= 70200)
5422                         {
5423                                 /* 7.2 did not have OIDs in pg_relcheck */
5424                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
5425                                                                   "rcname AS conname, "
5426                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
5427                                                                   "true AS conislocal "
5428                                                                   "FROM pg_relcheck "
5429                                                                   "WHERE rcrelid = '%u'::oid "
5430                                                                   "ORDER BY rcname",
5431                                                                   tbinfo->dobj.catId.oid);
5432                         }
5433                         else if (g_fout->remoteVersion >= 70100)
5434                         {
5435                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
5436                                                                   "rcname AS conname, "
5437                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
5438                                                                   "true AS conislocal "
5439                                                                   "FROM pg_relcheck "
5440                                                                   "WHERE rcrelid = '%u'::oid "
5441                                                                   "ORDER BY rcname",
5442                                                                   tbinfo->dobj.catId.oid);
5443                         }
5444                         else
5445                         {
5446                                 /* no tableoid in 7.0 */
5447                                 appendPQExpBuffer(q, "SELECT "
5448                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
5449                                                                   "oid, rcname AS conname, "
5450                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
5451                                                                   "true AS conislocal "
5452                                                                   "FROM pg_relcheck "
5453                                                                   "WHERE rcrelid = '%u'::oid "
5454                                                                   "ORDER BY rcname",
5455                                                                   tbinfo->dobj.catId.oid);
5456                         }
5457                         res = PQexec(g_conn, q->data);
5458                         check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5459
5460                         numConstrs = PQntuples(res);
5461                         if (numConstrs != tbinfo->ncheck)
5462                         {
5463                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
5464                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
5465                                                                                  tbinfo->ncheck),
5466                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
5467                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
5468                                 exit_nicely();
5469                         }
5470
5471                         constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
5472                         tbinfo->checkexprs = constrs;
5473
5474                         for (j = 0; j < numConstrs; j++)
5475                         {
5476                                 constrs[j].dobj.objType = DO_CONSTRAINT;
5477                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5478                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5479                                 AssignDumpId(&constrs[j].dobj);
5480                                 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
5481                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
5482                                 constrs[j].contable = tbinfo;
5483                                 constrs[j].condomain = NULL;
5484                                 constrs[j].contype = 'c';
5485                                 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
5486                                 constrs[j].confrelid = InvalidOid;
5487                                 constrs[j].conindex = 0;
5488                                 constrs[j].condeferrable = false;
5489                                 constrs[j].condeferred = false;
5490                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
5491                                 constrs[j].separate = false;
5492
5493                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
5494
5495                                 /*
5496                                  * Mark the constraint as needing to appear before the table
5497                                  * --- this is so that any other dependencies of the
5498                                  * constraint will be emitted before we try to create the
5499                                  * table.
5500                                  */
5501                                 addObjectDependency(&tbinfo->dobj,
5502                                                                         constrs[j].dobj.dumpId);
5503
5504                                 /*
5505                                  * If the constraint is inherited, this will be detected later
5506                                  * (in pre-8.4 databases).      We also detect later if the
5507                                  * constraint must be split out from the table definition.
5508                                  */
5509                         }
5510                         PQclear(res);
5511                 }
5512         }
5513
5514         destroyPQExpBuffer(q);
5515 }
5516
5517
5518 /*
5519  * getTSParsers:
5520  *        read all text search parsers in the system catalogs and return them
5521  *        in the TSParserInfo* structure
5522  *
5523  *      numTSParsers is set to the number of parsers read in
5524  */
5525 TSParserInfo *
5526 getTSParsers(int *numTSParsers)
5527 {
5528         PGresult   *res;
5529         int                     ntups;
5530         int                     i;
5531         PQExpBuffer query = createPQExpBuffer();
5532         TSParserInfo *prsinfo;
5533         int                     i_tableoid;
5534         int                     i_oid;
5535         int                     i_prsname;
5536         int                     i_prsnamespace;
5537         int                     i_prsstart;
5538         int                     i_prstoken;
5539         int                     i_prsend;
5540         int                     i_prsheadline;
5541         int                     i_prslextype;
5542
5543         /* Before 8.3, there is no built-in text search support */
5544         if (g_fout->remoteVersion < 80300)
5545         {
5546                 *numTSParsers = 0;
5547                 return NULL;
5548         }
5549
5550         /*
5551          * find all text search objects, including builtin ones; we filter out
5552          * system-defined objects at dump-out time.
5553          */
5554
5555         /* Make sure we are in proper schema */
5556         selectSourceSchema("pg_catalog");
5557
5558         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
5559                                           "prsstart::oid, prstoken::oid, "
5560                                           "prsend::oid, prsheadline::oid, prslextype::oid "
5561                                           "FROM pg_ts_parser");
5562
5563         res = PQexec(g_conn, query->data);
5564         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5565
5566         ntups = PQntuples(res);
5567         *numTSParsers = ntups;
5568
5569         prsinfo = (TSParserInfo *) malloc(ntups * sizeof(TSParserInfo));
5570
5571         i_tableoid = PQfnumber(res, "tableoid");
5572         i_oid = PQfnumber(res, "oid");
5573         i_prsname = PQfnumber(res, "prsname");
5574         i_prsnamespace = PQfnumber(res, "prsnamespace");
5575         i_prsstart = PQfnumber(res, "prsstart");
5576         i_prstoken = PQfnumber(res, "prstoken");
5577         i_prsend = PQfnumber(res, "prsend");
5578         i_prsheadline = PQfnumber(res, "prsheadline");
5579         i_prslextype = PQfnumber(res, "prslextype");
5580
5581         for (i = 0; i < ntups; i++)
5582         {
5583                 prsinfo[i].dobj.objType = DO_TSPARSER;
5584                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5585                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5586                 AssignDumpId(&prsinfo[i].dobj);
5587                 prsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_prsname));
5588                 prsinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_prsnamespace)),
5589                                                                                                   prsinfo[i].dobj.catId.oid);
5590                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
5591                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
5592                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
5593                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
5594                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
5595
5596                 /* Decide whether we want to dump it */
5597                 selectDumpableObject(&(prsinfo[i].dobj));
5598         }
5599
5600         PQclear(res);
5601
5602         destroyPQExpBuffer(query);
5603
5604         return prsinfo;
5605 }
5606
5607 /*
5608  * getTSDictionaries:
5609  *        read all text search dictionaries in the system catalogs and return them
5610  *        in the TSDictInfo* structure
5611  *
5612  *      numTSDicts is set to the number of dictionaries read in
5613  */
5614 TSDictInfo *
5615 getTSDictionaries(int *numTSDicts)
5616 {
5617         PGresult   *res;
5618         int                     ntups;
5619         int                     i;
5620         PQExpBuffer query = createPQExpBuffer();
5621         TSDictInfo *dictinfo;
5622         int                     i_tableoid;
5623         int                     i_oid;
5624         int                     i_dictname;
5625         int                     i_dictnamespace;
5626         int                     i_rolname;
5627         int                     i_dicttemplate;
5628         int                     i_dictinitoption;
5629
5630         /* Before 8.3, there is no built-in text search support */
5631         if (g_fout->remoteVersion < 80300)
5632         {
5633                 *numTSDicts = 0;
5634                 return NULL;
5635         }
5636
5637         /* Make sure we are in proper schema */
5638         selectSourceSchema("pg_catalog");
5639
5640         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
5641                                           "dictnamespace, (%s dictowner) AS rolname, "
5642                                           "dicttemplate, dictinitoption "
5643                                           "FROM pg_ts_dict",
5644                                           username_subquery);
5645
5646         res = PQexec(g_conn, query->data);
5647         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5648
5649         ntups = PQntuples(res);
5650         *numTSDicts = ntups;
5651
5652         dictinfo = (TSDictInfo *) malloc(ntups * sizeof(TSDictInfo));
5653
5654         i_tableoid = PQfnumber(res, "tableoid");
5655         i_oid = PQfnumber(res, "oid");
5656         i_dictname = PQfnumber(res, "dictname");
5657         i_dictnamespace = PQfnumber(res, "dictnamespace");
5658         i_rolname = PQfnumber(res, "rolname");
5659         i_dictinitoption = PQfnumber(res, "dictinitoption");
5660         i_dicttemplate = PQfnumber(res, "dicttemplate");
5661
5662         for (i = 0; i < ntups; i++)
5663         {
5664                 dictinfo[i].dobj.objType = DO_TSDICT;
5665                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5666                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5667                 AssignDumpId(&dictinfo[i].dobj);
5668                 dictinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_dictname));
5669                 dictinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_dictnamespace)),
5670                                                                                                  dictinfo[i].dobj.catId.oid);
5671                 dictinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5672                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
5673                 if (PQgetisnull(res, i, i_dictinitoption))
5674                         dictinfo[i].dictinitoption = NULL;
5675                 else
5676                         dictinfo[i].dictinitoption = strdup(PQgetvalue(res, i, i_dictinitoption));
5677
5678                 /* Decide whether we want to dump it */
5679                 selectDumpableObject(&(dictinfo[i].dobj));
5680         }
5681
5682         PQclear(res);
5683
5684         destroyPQExpBuffer(query);
5685
5686         return dictinfo;
5687 }
5688
5689 /*
5690  * getTSTemplates:
5691  *        read all text search templates in the system catalogs and return them
5692  *        in the TSTemplateInfo* structure
5693  *
5694  *      numTSTemplates is set to the number of templates read in
5695  */
5696 TSTemplateInfo *
5697 getTSTemplates(int *numTSTemplates)
5698 {
5699         PGresult   *res;
5700         int                     ntups;
5701         int                     i;
5702         PQExpBuffer query = createPQExpBuffer();
5703         TSTemplateInfo *tmplinfo;
5704         int                     i_tableoid;
5705         int                     i_oid;
5706         int                     i_tmplname;
5707         int                     i_tmplnamespace;
5708         int                     i_tmplinit;
5709         int                     i_tmpllexize;
5710
5711         /* Before 8.3, there is no built-in text search support */
5712         if (g_fout->remoteVersion < 80300)
5713         {
5714                 *numTSTemplates = 0;
5715                 return NULL;
5716         }
5717
5718         /* Make sure we are in proper schema */
5719         selectSourceSchema("pg_catalog");
5720
5721         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
5722                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
5723                                           "FROM pg_ts_template");
5724
5725         res = PQexec(g_conn, query->data);
5726         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5727
5728         ntups = PQntuples(res);
5729         *numTSTemplates = ntups;
5730
5731         tmplinfo = (TSTemplateInfo *) malloc(ntups * sizeof(TSTemplateInfo));
5732
5733         i_tableoid = PQfnumber(res, "tableoid");
5734         i_oid = PQfnumber(res, "oid");
5735         i_tmplname = PQfnumber(res, "tmplname");
5736         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
5737         i_tmplinit = PQfnumber(res, "tmplinit");
5738         i_tmpllexize = PQfnumber(res, "tmpllexize");
5739
5740         for (i = 0; i < ntups; i++)
5741         {
5742                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
5743                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5744                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5745                 AssignDumpId(&tmplinfo[i].dobj);
5746                 tmplinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_tmplname));
5747                 tmplinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_tmplnamespace)),
5748                                                                                                  tmplinfo[i].dobj.catId.oid);
5749                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
5750                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
5751
5752                 /* Decide whether we want to dump it */
5753                 selectDumpableObject(&(tmplinfo[i].dobj));
5754         }
5755
5756         PQclear(res);
5757
5758         destroyPQExpBuffer(query);
5759
5760         return tmplinfo;
5761 }
5762
5763 /*
5764  * getTSConfigurations:
5765  *        read all text search configurations in the system catalogs and return
5766  *        them in the TSConfigInfo* structure
5767  *
5768  *      numTSConfigs is set to the number of configurations read in
5769  */
5770 TSConfigInfo *
5771 getTSConfigurations(int *numTSConfigs)
5772 {
5773         PGresult   *res;
5774         int                     ntups;
5775         int                     i;
5776         PQExpBuffer query = createPQExpBuffer();
5777         TSConfigInfo *cfginfo;
5778         int                     i_tableoid;
5779         int                     i_oid;
5780         int                     i_cfgname;
5781         int                     i_cfgnamespace;
5782         int                     i_rolname;
5783         int                     i_cfgparser;
5784
5785         /* Before 8.3, there is no built-in text search support */
5786         if (g_fout->remoteVersion < 80300)
5787         {
5788                 *numTSConfigs = 0;
5789                 return NULL;
5790         }
5791
5792         /* Make sure we are in proper schema */
5793         selectSourceSchema("pg_catalog");
5794
5795         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
5796                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
5797                                           "FROM pg_ts_config",
5798                                           username_subquery);
5799
5800         res = PQexec(g_conn, query->data);
5801         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5802
5803         ntups = PQntuples(res);
5804         *numTSConfigs = ntups;
5805
5806         cfginfo = (TSConfigInfo *) malloc(ntups * sizeof(TSConfigInfo));
5807
5808         i_tableoid = PQfnumber(res, "tableoid");
5809         i_oid = PQfnumber(res, "oid");
5810         i_cfgname = PQfnumber(res, "cfgname");
5811         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
5812         i_rolname = PQfnumber(res, "rolname");
5813         i_cfgparser = PQfnumber(res, "cfgparser");
5814
5815         for (i = 0; i < ntups; i++)
5816         {
5817                 cfginfo[i].dobj.objType = DO_TSCONFIG;
5818                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5819                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5820                 AssignDumpId(&cfginfo[i].dobj);
5821                 cfginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_cfgname));
5822                 cfginfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_cfgnamespace)),
5823                                                                                                   cfginfo[i].dobj.catId.oid);
5824                 cfginfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5825                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
5826
5827                 /* Decide whether we want to dump it */
5828                 selectDumpableObject(&(cfginfo[i].dobj));
5829         }
5830
5831         PQclear(res);
5832
5833         destroyPQExpBuffer(query);
5834
5835         return cfginfo;
5836 }
5837
5838 /*
5839  * getForeignDataWrappers:
5840  *        read all foreign-data wrappers in the system catalogs and return
5841  *        them in the FdwInfo* structure
5842  *
5843  *      numForeignDataWrappers is set to the number of fdws read in
5844  */
5845 FdwInfo *
5846 getForeignDataWrappers(int *numForeignDataWrappers)
5847 {
5848         PGresult   *res;
5849         int                     ntups;
5850         int                     i;
5851         PQExpBuffer query = createPQExpBuffer();
5852         FdwInfo    *fdwinfo;
5853         int                     i_oid;
5854         int                     i_fdwname;
5855         int                     i_rolname;
5856         int                     i_fdwvalidator;
5857         int                     i_fdwacl;
5858         int                     i_fdwoptions;
5859
5860         /* Before 8.4, there are no foreign-data wrappers */
5861         if (g_fout->remoteVersion < 80400)
5862         {
5863                 *numForeignDataWrappers = 0;
5864                 return NULL;
5865         }
5866
5867         /* Make sure we are in proper schema */
5868         selectSourceSchema("pg_catalog");
5869
5870         appendPQExpBuffer(query, "SELECT oid, fdwname, "
5871                 "(%s fdwowner) AS rolname, fdwvalidator::pg_catalog.regproc, fdwacl,"
5872                                           "array_to_string(ARRAY("
5873                  "              SELECT option_name || ' ' || quote_literal(option_value) "
5874            "            FROM pg_options_to_table(fdwoptions)), ', ') AS fdwoptions "
5875                                           "FROM pg_foreign_data_wrapper",
5876                                           username_subquery);
5877
5878         res = PQexec(g_conn, query->data);
5879         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5880
5881         ntups = PQntuples(res);
5882         *numForeignDataWrappers = ntups;
5883
5884         fdwinfo = (FdwInfo *) malloc(ntups * sizeof(FdwInfo));
5885
5886         i_oid = PQfnumber(res, "oid");
5887         i_fdwname = PQfnumber(res, "fdwname");
5888         i_rolname = PQfnumber(res, "rolname");
5889         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
5890         i_fdwacl = PQfnumber(res, "fdwacl");
5891         i_fdwoptions = PQfnumber(res, "fdwoptions");
5892
5893         for (i = 0; i < ntups; i++)
5894         {
5895                 fdwinfo[i].dobj.objType = DO_FDW;
5896                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5897                 AssignDumpId(&fdwinfo[i].dobj);
5898                 fdwinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_fdwname));
5899                 fdwinfo[i].dobj.namespace = NULL;
5900                 fdwinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5901                 fdwinfo[i].fdwvalidator = strdup(PQgetvalue(res, i, i_fdwvalidator));
5902                 fdwinfo[i].fdwoptions = strdup(PQgetvalue(res, i, i_fdwoptions));
5903                 fdwinfo[i].fdwacl = strdup(PQgetvalue(res, i, i_fdwacl));
5904
5905
5906                 /* Decide whether we want to dump it */
5907                 selectDumpableObject(&(fdwinfo[i].dobj));
5908         }
5909
5910         PQclear(res);
5911
5912         destroyPQExpBuffer(query);
5913
5914         return fdwinfo;
5915 }
5916
5917 /*
5918  * getForeignServers:
5919  *        read all foreign servers in the system catalogs and return
5920  *        them in the ForeignServerInfo * structure
5921  *
5922  *      numForeignServers is set to the number of servers read in
5923  */
5924 ForeignServerInfo *
5925 getForeignServers(int *numForeignServers)
5926 {
5927         PGresult   *res;
5928         int                     ntups;
5929         int                     i;
5930         PQExpBuffer query = createPQExpBuffer();
5931         ForeignServerInfo *srvinfo;
5932         int                     i_oid;
5933         int                     i_srvname;
5934         int                     i_rolname;
5935         int                     i_srvfdw;
5936         int                     i_srvtype;
5937         int                     i_srvversion;
5938         int                     i_srvacl;
5939         int                     i_srvoptions;
5940
5941         /* Before 8.4, there are no foreign servers */
5942         if (g_fout->remoteVersion < 80400)
5943         {
5944                 *numForeignServers = 0;
5945                 return NULL;
5946         }
5947
5948         /* Make sure we are in proper schema */
5949         selectSourceSchema("pg_catalog");
5950
5951         appendPQExpBuffer(query, "SELECT oid, srvname, "
5952                                           "(%s srvowner) AS rolname, "
5953                                           "srvfdw, srvtype, srvversion, srvacl,"
5954                                           "array_to_string(ARRAY("
5955                  "              SELECT option_name || ' ' || quote_literal(option_value) "
5956            "            FROM pg_options_to_table(srvoptions)), ', ') AS srvoptions "
5957                                           "FROM pg_foreign_server",
5958                                           username_subquery);
5959
5960         res = PQexec(g_conn, query->data);
5961         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5962
5963         ntups = PQntuples(res);
5964         *numForeignServers = ntups;
5965
5966         srvinfo = (ForeignServerInfo *) malloc(ntups * sizeof(ForeignServerInfo));
5967
5968         i_oid = PQfnumber(res, "oid");
5969         i_srvname = PQfnumber(res, "srvname");
5970         i_rolname = PQfnumber(res, "rolname");
5971         i_srvfdw = PQfnumber(res, "srvfdw");
5972         i_srvtype = PQfnumber(res, "srvtype");
5973         i_srvversion = PQfnumber(res, "srvversion");
5974         i_srvacl = PQfnumber(res, "srvacl");
5975         i_srvoptions = PQfnumber(res, "srvoptions");
5976
5977         for (i = 0; i < ntups; i++)
5978         {
5979                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
5980                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5981                 AssignDumpId(&srvinfo[i].dobj);
5982                 srvinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_srvname));
5983                 srvinfo[i].dobj.namespace = NULL;
5984                 srvinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5985                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
5986                 srvinfo[i].srvtype = strdup(PQgetvalue(res, i, i_srvtype));
5987                 srvinfo[i].srvversion = strdup(PQgetvalue(res, i, i_srvversion));
5988                 srvinfo[i].srvoptions = strdup(PQgetvalue(res, i, i_srvoptions));
5989                 srvinfo[i].srvacl = strdup(PQgetvalue(res, i, i_srvacl));
5990
5991                 /* Decide whether we want to dump it */
5992                 selectDumpableObject(&(srvinfo[i].dobj));
5993         }
5994
5995         PQclear(res);
5996
5997         destroyPQExpBuffer(query);
5998
5999         return srvinfo;
6000 }
6001
6002 /*
6003  * getDefaultACLs:
6004  *        read all default ACL information in the system catalogs and return
6005  *        them in the DefaultACLInfo structure
6006  *
6007  *      numDefaultACLs is set to the number of ACLs read in
6008  */
6009 DefaultACLInfo *
6010 getDefaultACLs(int *numDefaultACLs)
6011 {
6012         DefaultACLInfo *daclinfo;
6013         PQExpBuffer query;
6014         PGresult   *res;
6015         int                     i_oid;
6016         int                     i_tableoid;
6017         int                     i_defaclrole;
6018         int                     i_defaclnamespace;
6019         int                     i_defaclobjtype;
6020         int                     i_defaclacl;
6021         int                     i,
6022                                 ntups;
6023
6024         if (g_fout->remoteVersion < 90000)
6025         {
6026                 *numDefaultACLs = 0;
6027                 return NULL;
6028         }
6029
6030         query = createPQExpBuffer();
6031
6032         /* Make sure we are in proper schema */
6033         selectSourceSchema("pg_catalog");
6034
6035         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6036                                           "(%s defaclrole) AS defaclrole, "
6037                                           "defaclnamespace, "
6038                                           "defaclobjtype, "
6039                                           "defaclacl "
6040                                           "FROM pg_default_acl",
6041                                           username_subquery);
6042
6043         res = PQexec(g_conn, query->data);
6044         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6045
6046         ntups = PQntuples(res);
6047         *numDefaultACLs = ntups;
6048
6049         daclinfo = (DefaultACLInfo *) malloc(ntups * sizeof(DefaultACLInfo));
6050
6051         i_oid = PQfnumber(res, "oid");
6052         i_tableoid = PQfnumber(res, "tableoid");
6053         i_defaclrole = PQfnumber(res, "defaclrole");
6054         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6055         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6056         i_defaclacl = PQfnumber(res, "defaclacl");
6057
6058         for (i = 0; i < ntups; i++)
6059         {
6060                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6061
6062                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6063                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6064                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6065                 AssignDumpId(&daclinfo[i].dobj);
6066                 /* cheesy ... is it worth coming up with a better object name? */
6067                 daclinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_defaclobjtype));
6068
6069                 if (nspid != InvalidOid)
6070                         daclinfo[i].dobj.namespace = findNamespace(nspid,
6071                                                                                                  daclinfo[i].dobj.catId.oid);
6072                 else
6073                         daclinfo[i].dobj.namespace = NULL;
6074
6075                 daclinfo[i].defaclrole = strdup(PQgetvalue(res, i, i_defaclrole));
6076                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6077                 daclinfo[i].defaclacl = strdup(PQgetvalue(res, i, i_defaclacl));
6078
6079                 /* Decide whether we want to dump it */
6080                 selectDumpableDefaultACL(&(daclinfo[i]));
6081         }
6082
6083         PQclear(res);
6084
6085         destroyPQExpBuffer(query);
6086
6087         return daclinfo;
6088 }
6089
6090 /*
6091  * dumpComment --
6092  *
6093  * This routine is used to dump any comments associated with the
6094  * object handed to this routine. The routine takes a constant character
6095  * string for the target part of the comment-creation command, plus
6096  * the namespace and owner of the object (for labeling the ArchiveEntry),
6097  * plus catalog ID and subid which are the lookup key for pg_description,
6098  * plus the dump ID for the object (for setting a dependency).
6099  * If a matching pg_description entry is found, it is dumped.
6100  *
6101  * Note: although this routine takes a dumpId for dependency purposes,
6102  * that purpose is just to mark the dependency in the emitted dump file
6103  * for possible future use by pg_restore.  We do NOT use it for determining
6104  * ordering of the comment in the dump file, because this routine is called
6105  * after dependency sorting occurs.  This routine should be called just after
6106  * calling ArchiveEntry() for the specified object.
6107  */
6108 static void
6109 dumpComment(Archive *fout, const char *target,
6110                         const char *namespace, const char *owner,
6111                         CatalogId catalogId, int subid, DumpId dumpId)
6112 {
6113         CommentItem *comments;
6114         int                     ncomments;
6115
6116         /* Comments are schema not data ... except blob comments are data */
6117         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6118         {
6119                 if (dataOnly)
6120                         return;
6121         }
6122         else
6123         {
6124                 if (schemaOnly)
6125                         return;
6126         }
6127
6128         /* Search for comments associated with catalogId, using table */
6129         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6130                                                          &comments);
6131
6132         /* Is there one matching the subid? */
6133         while (ncomments > 0)
6134         {
6135                 if (comments->objsubid == subid)
6136                         break;
6137                 comments++;
6138                 ncomments--;
6139         }
6140
6141         /* If a comment exists, build COMMENT ON statement */
6142         if (ncomments > 0)
6143         {
6144                 PQExpBuffer query = createPQExpBuffer();
6145
6146                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6147                 appendStringLiteralAH(query, comments->descr, fout);
6148                 appendPQExpBuffer(query, ";\n");
6149
6150                 /*
6151                  * We mark comments as SECTION_NONE because they really belong in the
6152                  * same section as their parent, whether that is pre-data or
6153                  * post-data.
6154                  */
6155                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6156                                          target, namespace, NULL, owner,
6157                                          false, "COMMENT", SECTION_NONE,
6158                                          query->data, "", NULL,
6159                                          &(dumpId), 1,
6160                                          NULL, NULL);
6161
6162                 destroyPQExpBuffer(query);
6163         }
6164 }
6165
6166 /*
6167  * dumpTableComment --
6168  *
6169  * As above, but dump comments for both the specified table (or view)
6170  * and its columns.
6171  */
6172 static void
6173 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6174                                  const char *reltypename)
6175 {
6176         CommentItem *comments;
6177         int                     ncomments;
6178         PQExpBuffer query;
6179         PQExpBuffer target;
6180
6181         /* Comments are SCHEMA not data */
6182         if (dataOnly)
6183                 return;
6184
6185         /* Search for comments associated with relation, using table */
6186         ncomments = findComments(fout,
6187                                                          tbinfo->dobj.catId.tableoid,
6188                                                          tbinfo->dobj.catId.oid,
6189                                                          &comments);
6190
6191         /* If comments exist, build COMMENT ON statements */
6192         if (ncomments <= 0)
6193                 return;
6194
6195         query = createPQExpBuffer();
6196         target = createPQExpBuffer();
6197
6198         while (ncomments > 0)
6199         {
6200                 const char *descr = comments->descr;
6201                 int                     objsubid = comments->objsubid;
6202
6203                 if (objsubid == 0)
6204                 {
6205                         resetPQExpBuffer(target);
6206                         appendPQExpBuffer(target, "%s %s", reltypename,
6207                                                           fmtId(tbinfo->dobj.name));
6208
6209                         resetPQExpBuffer(query);
6210                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6211                         appendStringLiteralAH(query, descr, fout);
6212                         appendPQExpBuffer(query, ";\n");
6213
6214                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6215                                                  target->data,
6216                                                  tbinfo->dobj.namespace->dobj.name,
6217                                                  NULL, tbinfo->rolname,
6218                                                  false, "COMMENT", SECTION_NONE,
6219                                                  query->data, "", NULL,
6220                                                  &(tbinfo->dobj.dumpId), 1,
6221                                                  NULL, NULL);
6222                 }
6223                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6224                 {
6225                         resetPQExpBuffer(target);
6226                         appendPQExpBuffer(target, "COLUMN %s.",
6227                                                           fmtId(tbinfo->dobj.name));
6228                         appendPQExpBuffer(target, "%s",
6229                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6230
6231                         resetPQExpBuffer(query);
6232                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6233                         appendStringLiteralAH(query, descr, fout);
6234                         appendPQExpBuffer(query, ";\n");
6235
6236                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6237                                                  target->data,
6238                                                  tbinfo->dobj.namespace->dobj.name,
6239                                                  NULL, tbinfo->rolname,
6240                                                  false, "COMMENT", SECTION_NONE,
6241                                                  query->data, "", NULL,
6242                                                  &(tbinfo->dobj.dumpId), 1,
6243                                                  NULL, NULL);
6244                 }
6245
6246                 comments++;
6247                 ncomments--;
6248         }
6249
6250         destroyPQExpBuffer(query);
6251         destroyPQExpBuffer(target);
6252 }
6253
6254 /*
6255  * findComments --
6256  *
6257  * Find the comment(s), if any, associated with the given object.  All the
6258  * objsubid values associated with the given classoid/objoid are found with
6259  * one search.
6260  */
6261 static int
6262 findComments(Archive *fout, Oid classoid, Oid objoid,
6263                          CommentItem **items)
6264 {
6265         /* static storage for table of comments */
6266         static CommentItem *comments = NULL;
6267         static int      ncomments = -1;
6268
6269         CommentItem *middle = NULL;
6270         CommentItem *low;
6271         CommentItem *high;
6272         int                     nmatch;
6273
6274         /* Get comments if we didn't already */
6275         if (ncomments < 0)
6276                 ncomments = collectComments(fout, &comments);
6277
6278         /*
6279          * Pre-7.2, pg_description does not contain classoid, so collectComments
6280          * just stores a zero.  If there's a collision on object OID, well, you
6281          * get duplicate comments.
6282          */
6283         if (fout->remoteVersion < 70200)
6284                 classoid = 0;
6285
6286         /*
6287          * Do binary search to find some item matching the object.
6288          */
6289         low = &comments[0];
6290         high = &comments[ncomments - 1];
6291         while (low <= high)
6292         {
6293                 middle = low + (high - low) / 2;
6294
6295                 if (classoid < middle->classoid)
6296                         high = middle - 1;
6297                 else if (classoid > middle->classoid)
6298                         low = middle + 1;
6299                 else if (objoid < middle->objoid)
6300                         high = middle - 1;
6301                 else if (objoid > middle->objoid)
6302                         low = middle + 1;
6303                 else
6304                         break;                          /* found a match */
6305         }
6306
6307         if (low > high)                         /* no matches */
6308         {
6309                 *items = NULL;
6310                 return 0;
6311         }
6312
6313         /*
6314          * Now determine how many items match the object.  The search loop
6315          * invariant still holds: only items between low and high inclusive could
6316          * match.
6317          */
6318         nmatch = 1;
6319         while (middle > low)
6320         {
6321                 if (classoid != middle[-1].classoid ||
6322                         objoid != middle[-1].objoid)
6323                         break;
6324                 middle--;
6325                 nmatch++;
6326         }
6327
6328         *items = middle;
6329
6330         middle += nmatch;
6331         while (middle <= high)
6332         {
6333                 if (classoid != middle->classoid ||
6334                         objoid != middle->objoid)
6335                         break;
6336                 middle++;
6337                 nmatch++;
6338         }
6339
6340         return nmatch;
6341 }
6342
6343 /*
6344  * collectComments --
6345  *
6346  * Construct a table of all comments available for database objects.
6347  * We used to do per-object queries for the comments, but it's much faster
6348  * to pull them all over at once, and on most databases the memory cost
6349  * isn't high.
6350  *
6351  * The table is sorted by classoid/objid/objsubid for speed in lookup.
6352  */
6353 static int
6354 collectComments(Archive *fout, CommentItem **items)
6355 {
6356         PGresult   *res;
6357         PQExpBuffer query;
6358         int                     i_description;
6359         int                     i_classoid;
6360         int                     i_objoid;
6361         int                     i_objsubid;
6362         int                     ntups;
6363         int                     i;
6364         CommentItem *comments;
6365
6366         /*
6367          * Note we do NOT change source schema here; preserve the caller's
6368          * setting, instead.
6369          */
6370
6371         query = createPQExpBuffer();
6372
6373         if (fout->remoteVersion >= 70300)
6374         {
6375                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
6376                                                   "FROM pg_catalog.pg_description "
6377                                                   "ORDER BY classoid, objoid, objsubid");
6378         }
6379         else if (fout->remoteVersion >= 70200)
6380         {
6381                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
6382                                                   "FROM pg_description "
6383                                                   "ORDER BY classoid, objoid, objsubid");
6384         }
6385         else
6386         {
6387                 /* Note: this will fail to find attribute comments in pre-7.2... */
6388                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
6389                                                   "FROM pg_description "
6390                                                   "ORDER BY objoid");
6391         }
6392
6393         res = PQexec(g_conn, query->data);
6394         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6395
6396         /* Construct lookup table containing OIDs in numeric form */
6397
6398         i_description = PQfnumber(res, "description");
6399         i_classoid = PQfnumber(res, "classoid");
6400         i_objoid = PQfnumber(res, "objoid");
6401         i_objsubid = PQfnumber(res, "objsubid");
6402
6403         ntups = PQntuples(res);
6404
6405         comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
6406
6407         for (i = 0; i < ntups; i++)
6408         {
6409                 comments[i].descr = PQgetvalue(res, i, i_description);
6410                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
6411                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
6412                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
6413         }
6414
6415         /* Do NOT free the PGresult since we are keeping pointers into it */
6416         destroyPQExpBuffer(query);
6417
6418         *items = comments;
6419         return ntups;
6420 }
6421
6422 /*
6423  * dumpDumpableObject
6424  *
6425  * This routine and its subsidiaries are responsible for creating
6426  * ArchiveEntries (TOC objects) for each object to be dumped.
6427  */
6428 static void
6429 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
6430 {
6431         switch (dobj->objType)
6432         {
6433                 case DO_NAMESPACE:
6434                         dumpNamespace(fout, (NamespaceInfo *) dobj);
6435                         break;
6436                 case DO_TYPE:
6437                         dumpType(fout, (TypeInfo *) dobj);
6438                         break;
6439                 case DO_SHELL_TYPE:
6440                         dumpShellType(fout, (ShellTypeInfo *) dobj);
6441                         break;
6442                 case DO_FUNC:
6443                         dumpFunc(fout, (FuncInfo *) dobj);
6444                         break;
6445                 case DO_AGG:
6446                         dumpAgg(fout, (AggInfo *) dobj);
6447                         break;
6448                 case DO_OPERATOR:
6449                         dumpOpr(fout, (OprInfo *) dobj);
6450                         break;
6451                 case DO_OPCLASS:
6452                         dumpOpclass(fout, (OpclassInfo *) dobj);
6453                         break;
6454                 case DO_OPFAMILY:
6455                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
6456                         break;
6457                 case DO_CONVERSION:
6458                         dumpConversion(fout, (ConvInfo *) dobj);
6459                         break;
6460                 case DO_TABLE:
6461                         dumpTable(fout, (TableInfo *) dobj);
6462                         break;
6463                 case DO_ATTRDEF:
6464                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
6465                         break;
6466                 case DO_INDEX:
6467                         dumpIndex(fout, (IndxInfo *) dobj);
6468                         break;
6469                 case DO_RULE:
6470                         dumpRule(fout, (RuleInfo *) dobj);
6471                         break;
6472                 case DO_TRIGGER:
6473                         dumpTrigger(fout, (TriggerInfo *) dobj);
6474                         break;
6475                 case DO_CONSTRAINT:
6476                         dumpConstraint(fout, (ConstraintInfo *) dobj);
6477                         break;
6478                 case DO_FK_CONSTRAINT:
6479                         dumpConstraint(fout, (ConstraintInfo *) dobj);
6480                         break;
6481                 case DO_PROCLANG:
6482                         dumpProcLang(fout, (ProcLangInfo *) dobj);
6483                         break;
6484                 case DO_CAST:
6485                         dumpCast(fout, (CastInfo *) dobj);
6486                         break;
6487                 case DO_TABLE_DATA:
6488                         dumpTableData(fout, (TableDataInfo *) dobj);
6489                         break;
6490                 case DO_DUMMY_TYPE:
6491                         /* table rowtypes and array types are never dumped separately */
6492                         break;
6493                 case DO_TSPARSER:
6494                         dumpTSParser(fout, (TSParserInfo *) dobj);
6495                         break;
6496                 case DO_TSDICT:
6497                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
6498                         break;
6499                 case DO_TSTEMPLATE:
6500                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
6501                         break;
6502                 case DO_TSCONFIG:
6503                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
6504                         break;
6505                 case DO_FDW:
6506                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
6507                         break;
6508                 case DO_FOREIGN_SERVER:
6509                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
6510                         break;
6511                 case DO_DEFAULT_ACL:
6512                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
6513                         break;
6514                 case DO_BLOB:
6515                         dumpBlob(fout, (BlobInfo *) dobj);
6516                         break;
6517                 case DO_BLOB_DATA:
6518                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
6519                                                  dobj->name, NULL, NULL, "",
6520                                                  false, "BLOBS", SECTION_DATA,
6521                                                  "", "", NULL,
6522                                                  dobj->dependencies, dobj->nDeps,
6523                                                  dumpBlobs, NULL);
6524                         break;
6525         }
6526 }
6527
6528 /*
6529  * dumpNamespace
6530  *        writes out to fout the queries to recreate a user-defined namespace
6531  */
6532 static void
6533 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
6534 {
6535         PQExpBuffer q;
6536         PQExpBuffer delq;
6537         char       *qnspname;
6538
6539         /* Skip if not to be dumped */
6540         if (!nspinfo->dobj.dump || dataOnly)
6541                 return;
6542
6543         /* don't dump dummy namespace from pre-7.3 source */
6544         if (strlen(nspinfo->dobj.name) == 0)
6545                 return;
6546
6547         q = createPQExpBuffer();
6548         delq = createPQExpBuffer();
6549
6550         qnspname = strdup(fmtId(nspinfo->dobj.name));
6551
6552         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
6553
6554         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
6555
6556         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
6557                                  nspinfo->dobj.name,
6558                                  NULL, NULL,
6559                                  nspinfo->rolname,
6560                                  false, "SCHEMA", SECTION_PRE_DATA,
6561                                  q->data, delq->data, NULL,
6562                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
6563                                  NULL, NULL);
6564
6565         /* Dump Schema Comments */
6566         resetPQExpBuffer(q);
6567         appendPQExpBuffer(q, "SCHEMA %s", qnspname);
6568         dumpComment(fout, q->data,
6569                                 NULL, nspinfo->rolname,
6570                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
6571
6572         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
6573                         qnspname, NULL, nspinfo->dobj.name, NULL,
6574                         nspinfo->rolname, nspinfo->nspacl);
6575
6576         free(qnspname);
6577
6578         destroyPQExpBuffer(q);
6579         destroyPQExpBuffer(delq);
6580 }
6581
6582 /*
6583  * dumpType
6584  *        writes out to fout the queries to recreate a user-defined type
6585  */
6586 static void
6587 dumpType(Archive *fout, TypeInfo *tyinfo)
6588 {
6589         /* Skip if not to be dumped */
6590         if (!tyinfo->dobj.dump || dataOnly)
6591                 return;
6592
6593         /* Dump out in proper style */
6594         if (tyinfo->typtype == TYPTYPE_BASE)
6595                 dumpBaseType(fout, tyinfo);
6596         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
6597                 dumpDomain(fout, tyinfo);
6598         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
6599                 dumpCompositeType(fout, tyinfo);
6600         else if (tyinfo->typtype == TYPTYPE_ENUM)
6601                 dumpEnumType(fout, tyinfo);
6602 }
6603
6604 /*
6605  * dumpEnumType
6606  *        writes out to fout the queries to recreate a user-defined enum type
6607  */
6608 static void
6609 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
6610 {
6611         PQExpBuffer q = createPQExpBuffer();
6612         PQExpBuffer delq = createPQExpBuffer();
6613         PQExpBuffer query = createPQExpBuffer();
6614         PGresult   *res;
6615         int                     num,
6616                                 i;
6617         Oid                     enum_oid;
6618         char       *label;
6619
6620         /* Set proper schema search path so regproc references list correctly */
6621         selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
6622
6623         appendPQExpBuffer(query, "SELECT oid, enumlabel "
6624                                           "FROM pg_catalog.pg_enum "
6625                                           "WHERE enumtypid = '%u'"
6626                                           "ORDER BY oid",
6627                                           tyinfo->dobj.catId.oid);
6628
6629         res = PQexec(g_conn, query->data);
6630         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6631
6632         num = PQntuples(res);
6633
6634         /*
6635          * DROP must be fully qualified in case same name appears in pg_catalog.
6636          * CASCADE shouldn't be required here as for normal types since the I/O
6637          * functions are generic and do not get dropped.
6638          */
6639         appendPQExpBuffer(delq, "DROP TYPE %s.",
6640                                           fmtId(tyinfo->dobj.namespace->dobj.name));
6641         appendPQExpBuffer(delq, "%s;\n",
6642                                           fmtId(tyinfo->dobj.name));
6643
6644         if (binary_upgrade)
6645                 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
6646
6647         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
6648                                           fmtId(tyinfo->dobj.name));
6649
6650         if (!binary_upgrade)
6651         {
6652                 /* Labels with server-assigned oids */
6653                 for (i = 0; i < num; i++)
6654                 {
6655                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
6656                         if (i > 0)
6657                                 appendPQExpBuffer(q, ",");
6658                         appendPQExpBuffer(q, "\n    ");
6659                         appendStringLiteralAH(q, label, fout);
6660                 }
6661         }
6662
6663         appendPQExpBuffer(q, "\n);\n");
6664
6665         if (binary_upgrade)
6666         {
6667                 /* Labels with dump-assigned (preserved) oids */
6668                 for (i = 0; i < num; i++)
6669                 {
6670                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
6671                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
6672
6673                         if (i == 0)
6674                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
6675                         appendPQExpBuffer(q,
6676                          "SELECT binary_upgrade.add_pg_enum_label('%u'::pg_catalog.oid, "
6677                                                           "'%u'::pg_catalog.oid, ",
6678                                                           enum_oid, tyinfo->dobj.catId.oid);
6679                         appendStringLiteralAH(q, label, fout);
6680                         appendPQExpBuffer(q, ");\n");
6681                 }
6682                 appendPQExpBuffer(q, "\n");
6683         }
6684
6685         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
6686                                  tyinfo->dobj.name,
6687                                  tyinfo->dobj.namespace->dobj.name,
6688                                  NULL,
6689                                  tyinfo->rolname, false,
6690                                  "TYPE", SECTION_PRE_DATA,
6691                                  q->data, delq->data, NULL,
6692                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
6693                                  NULL, NULL);
6694
6695         /* Dump Type Comments */
6696         resetPQExpBuffer(q);
6697
6698         appendPQExpBuffer(q, "TYPE %s", fmtId(tyinfo->dobj.name));
6699         dumpComment(fout, q->data,
6700                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
6701                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
6702
6703         PQclear(res);
6704         destroyPQExpBuffer(q);
6705         destroyPQExpBuffer(delq);
6706         destroyPQExpBuffer(query);
6707 }
6708
6709 /*
6710  * dumpBaseType
6711  *        writes out to fout the queries to recreate a user-defined base type
6712  */
6713 static void
6714 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
6715 {
6716         PQExpBuffer q = createPQExpBuffer();
6717         PQExpBuffer delq = createPQExpBuffer();
6718         PQExpBuffer query = createPQExpBuffer();
6719         PGresult   *res;
6720         int                     ntups;
6721         char       *typlen;
6722         char       *typinput;
6723         char       *typoutput;
6724         char       *typreceive;
6725         char       *typsend;
6726         char       *typmodin;
6727         char       *typmodout;
6728         char       *typanalyze;
6729         Oid                     typinputoid;
6730         Oid                     typoutputoid;
6731         Oid                     typreceiveoid;
6732         Oid                     typsendoid;
6733         Oid                     typmodinoid;
6734         Oid                     typmodoutoid;
6735         Oid                     typanalyzeoid;
6736         char       *typcategory;
6737         char       *typispreferred;
6738         char       *typdelim;
6739         char       *typbyval;
6740         char       *typalign;
6741         char       *typstorage;
6742         char       *typdefault;
6743         bool            typdefault_is_literal = false;
6744
6745         /* Set proper schema search path so regproc references list correctly */
6746         selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
6747
6748         /* Fetch type-specific details */
6749         if (fout->remoteVersion >= 80400)
6750         {
6751                 appendPQExpBuffer(query, "SELECT typlen, "
6752                                                   "typinput, typoutput, typreceive, typsend, "
6753                                                   "typmodin, typmodout, typanalyze, "
6754                                                   "typinput::pg_catalog.oid AS typinputoid, "
6755                                                   "typoutput::pg_catalog.oid AS typoutputoid, "
6756                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
6757                                                   "typsend::pg_catalog.oid AS typsendoid, "
6758                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
6759                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
6760                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
6761                                                   "typcategory, typispreferred, "
6762                                                   "typdelim, typbyval, typalign, typstorage, "
6763                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
6764                                                   "FROM pg_catalog.pg_type "
6765                                                   "WHERE oid = '%u'::pg_catalog.oid",
6766                                                   tyinfo->dobj.catId.oid);
6767         }
6768         else if (fout->remoteVersion >= 80300)
6769         {
6770                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
6771                 appendPQExpBuffer(query, "SELECT typlen, "
6772                                                   "typinput, typoutput, typreceive, typsend, "
6773                                                   "typmodin, typmodout, typanalyze, "
6774                                                   "typinput::pg_catalog.oid AS typinputoid, "
6775                                                   "typoutput::pg_catalog.oid AS typoutputoid, "
6776                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
6777                                                   "typsend::pg_catalog.oid AS typsendoid, "
6778                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
6779                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
6780                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
6781                                                   "'U' AS typcategory, false AS typispreferred, "
6782                                                   "typdelim, typbyval, typalign, typstorage, "
6783                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6784                                                   "FROM pg_catalog.pg_type "
6785                                                   "WHERE oid = '%u'::pg_catalog.oid",
6786                                                   tyinfo->dobj.catId.oid);
6787         }
6788         else if (fout->remoteVersion >= 80000)
6789         {
6790                 appendPQExpBuffer(query, "SELECT typlen, "
6791                                                   "typinput, typoutput, typreceive, typsend, "
6792                                                   "'-' AS typmodin, '-' AS typmodout, "
6793                                                   "typanalyze, "
6794                                                   "typinput::pg_catalog.oid AS typinputoid, "
6795                                                   "typoutput::pg_catalog.oid AS typoutputoid, "
6796                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
6797                                                   "typsend::pg_catalog.oid AS typsendoid, "
6798                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
6799                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
6800                                                   "'U' AS typcategory, false AS typispreferred, "
6801                                                   "typdelim, typbyval, typalign, typstorage, "
6802                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6803                                                   "FROM pg_catalog.pg_type "
6804                                                   "WHERE oid = '%u'::pg_catalog.oid",
6805                                                   tyinfo->dobj.catId.oid);
6806         }
6807         else if (fout->remoteVersion >= 70400)
6808         {
6809                 appendPQExpBuffer(query, "SELECT typlen, "
6810                                                   "typinput, typoutput, typreceive, typsend, "
6811                                                   "'-' AS typmodin, '-' AS typmodout, "
6812                                                   "'-' AS typanalyze, "
6813                                                   "typinput::pg_catalog.oid AS typinputoid, "
6814                                                   "typoutput::pg_catalog.oid AS typoutputoid, "
6815                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
6816                                                   "typsend::pg_catalog.oid AS typsendoid, "
6817                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
6818                                                   "0 AS typanalyzeoid, "
6819                                                   "'U' AS typcategory, false AS typispreferred, "
6820                                                   "typdelim, typbyval, typalign, typstorage, "
6821                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6822                                                   "FROM pg_catalog.pg_type "
6823                                                   "WHERE oid = '%u'::pg_catalog.oid",
6824                                                   tyinfo->dobj.catId.oid);
6825         }
6826         else if (fout->remoteVersion >= 70300)
6827         {
6828                 appendPQExpBuffer(query, "SELECT typlen, "
6829                                                   "typinput, typoutput, "
6830                                                   "'-' AS typreceive, '-' AS typsend, "
6831                                                   "'-' AS typmodin, '-' AS typmodout, "
6832                                                   "'-' AS typanalyze, "
6833                                                   "typinput::pg_catalog.oid AS typinputoid, "
6834                                                   "typoutput::pg_catalog.oid AS typoutputoid, "
6835                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
6836                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
6837                                                   "0 AS typanalyzeoid, "
6838                                                   "'U' AS typcategory, false AS typispreferred, "
6839                                                   "typdelim, typbyval, typalign, typstorage, "
6840                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6841                                                   "FROM pg_catalog.pg_type "
6842                                                   "WHERE oid = '%u'::pg_catalog.oid",
6843                                                   tyinfo->dobj.catId.oid);
6844         }
6845         else if (fout->remoteVersion >= 70200)
6846         {
6847                 /*
6848                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
6849                  * ignore them because they are not right.
6850                  */
6851                 appendPQExpBuffer(query, "SELECT typlen, "
6852                                                   "typinput, typoutput, "
6853                                                   "'-' AS typreceive, '-' AS typsend, "
6854                                                   "'-' AS typmodin, '-' AS typmodout, "
6855                                                   "'-' AS typanalyze, "
6856                                                   "typinput::oid AS typinputoid, "
6857                                                   "typoutput::oid AS typoutputoid, "
6858                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
6859                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
6860                                                   "0 AS typanalyzeoid, "
6861                                                   "'U' AS typcategory, false AS typispreferred, "
6862                                                   "typdelim, typbyval, typalign, typstorage, "
6863                                                   "NULL AS typdefaultbin, typdefault "
6864                                                   "FROM pg_type "
6865                                                   "WHERE oid = '%u'::oid",
6866                                                   tyinfo->dobj.catId.oid);
6867         }
6868         else if (fout->remoteVersion >= 70100)
6869         {
6870                 /*
6871                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
6872                  * representation.
6873                  */
6874                 appendPQExpBuffer(query, "SELECT typlen, "
6875                                                   "typinput, typoutput, "
6876                                                   "'-' AS typreceive, '-' AS typsend, "
6877                                                   "'-' AS typmodin, '-' AS typmodout, "
6878                                                   "'-' AS typanalyze, "
6879                                                   "typinput::oid AS typinputoid, "
6880                                                   "typoutput::oid AS typoutputoid, "
6881                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
6882                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
6883                                                   "0 AS typanalyzeoid, "
6884                                                   "'U' AS typcategory, false AS typispreferred, "
6885                                                   "typdelim, typbyval, typalign, typstorage, "
6886                                                   "NULL AS typdefaultbin, NULL AS typdefault "
6887                                                   "FROM pg_type "
6888                                                   "WHERE oid = '%u'::oid",
6889                                                   tyinfo->dobj.catId.oid);
6890         }
6891         else
6892         {
6893                 appendPQExpBuffer(query, "SELECT typlen, "
6894                                                   "typinput, typoutput, "
6895                                                   "'-' AS typreceive, '-' AS typsend, "
6896                                                   "'-' AS typmodin, '-' AS typmodout, "
6897                                                   "'-' AS typanalyze, "
6898                                                   "typinput::oid AS typinputoid, "
6899                                                   "typoutput::oid AS typoutputoid, "
6900                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
6901                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
6902                                                   "0 AS typanalyzeoid, "
6903                                                   "'U' AS typcategory, false AS typispreferred, "
6904                                                   "typdelim, typbyval, typalign, "
6905                                                   "'p'::char AS typstorage, "
6906                                                   "NULL AS typdefaultbin, NULL AS typdefault "
6907                                                   "FROM pg_type "
6908                                                   "WHERE oid = '%u'::oid",
6909                                                   tyinfo->dobj.catId.oid);
6910         }
6911
6912         res = PQexec(g_conn, query->data);
6913         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6914
6915         /* Expecting a single result only */
6916         ntups = PQntuples(res);
6917         if (ntups != 1)
6918         {
6919                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
6920                                                            "query returned %d rows instead of one: %s\n",
6921                                                                  ntups),
6922                                   ntups, query->data);
6923                 exit_nicely();
6924         }
6925
6926         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
6927         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
6928         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
6929         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
6930         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
6931         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
6932         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
6933         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
6934         typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
6935         typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
6936         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
6937         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
6938         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
6939         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
6940         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
6941         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
6942         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
6943         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
6944         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
6945         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
6946         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
6947         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
6948                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
6949         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
6950         {
6951                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
6952                 typdefault_is_literal = true;   /* it needs quotes */
6953         }
6954         else
6955                 typdefault = NULL;
6956
6957         /*
6958          * DROP must be fully qualified in case same name appears in pg_catalog.
6959          * The reason we include CASCADE is that the circular dependency between
6960          * the type and its I/O functions makes it impossible to drop the type any
6961          * other way.
6962          */
6963         appendPQExpBuffer(delq, "DROP TYPE %s.",
6964                                           fmtId(tyinfo->dobj.namespace->dobj.name));
6965         appendPQExpBuffer(delq, "%s CASCADE;\n",
6966                                           fmtId(tyinfo->dobj.name));
6967
6968         /* We might already have a shell type, but setting pg_type_oid is harmless */
6969         if (binary_upgrade)
6970                 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
6971
6972         appendPQExpBuffer(q,
6973                                           "CREATE TYPE %s (\n"
6974                                           "    INTERNALLENGTH = %s",
6975                                           fmtId(tyinfo->dobj.name),
6976                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
6977
6978         if (fout->remoteVersion >= 70300)
6979         {
6980                 /* regproc result is correctly quoted as of 7.3 */
6981                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
6982                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
6983                 if (OidIsValid(typreceiveoid))
6984                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
6985                 if (OidIsValid(typsendoid))
6986                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
6987                 if (OidIsValid(typmodinoid))
6988                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
6989                 if (OidIsValid(typmodoutoid))
6990                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
6991                 if (OidIsValid(typanalyzeoid))
6992                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
6993         }
6994         else
6995         {
6996                 /* regproc delivers an unquoted name before 7.3 */
6997                 /* cannot combine these because fmtId uses static result area */
6998                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
6999                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7000                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7001         }
7002
7003         if (typdefault != NULL)
7004         {
7005                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7006                 if (typdefault_is_literal)
7007                         appendStringLiteralAH(q, typdefault, fout);
7008                 else
7009                         appendPQExpBufferStr(q, typdefault);
7010         }
7011
7012         if (OidIsValid(tyinfo->typelem))
7013         {
7014                 char       *elemType;
7015
7016                 /* reselect schema in case changed by function dump */
7017                 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7018                 elemType = getFormattedTypeName(tyinfo->typelem, zeroAsOpaque);
7019                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
7020                 free(elemType);
7021         }
7022
7023         if (strcmp(typcategory, "U") != 0)
7024         {
7025                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
7026                 appendStringLiteralAH(q, typcategory, fout);
7027         }
7028
7029         if (strcmp(typispreferred, "t") == 0)
7030                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
7031
7032         if (typdelim && strcmp(typdelim, ",") != 0)
7033         {
7034                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
7035                 appendStringLiteralAH(q, typdelim, fout);
7036         }
7037
7038         if (strcmp(typalign, "c") == 0)
7039                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
7040         else if (strcmp(typalign, "s") == 0)
7041                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
7042         else if (strcmp(typalign, "i") == 0)
7043                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
7044         else if (strcmp(typalign, "d") == 0)
7045                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
7046
7047         if (strcmp(typstorage, "p") == 0)
7048                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
7049         else if (strcmp(typstorage, "e") == 0)
7050                 appendPQExpBuffer(q, ",\n    STORAGE = external");
7051         else if (strcmp(typstorage, "x") == 0)
7052                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
7053         else if (strcmp(typstorage, "m") == 0)
7054                 appendPQExpBuffer(q, ",\n    STORAGE = main");
7055
7056         if (strcmp(typbyval, "t") == 0)
7057                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
7058
7059         appendPQExpBuffer(q, "\n);\n");
7060
7061         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7062                                  tyinfo->dobj.name,
7063                                  tyinfo->dobj.namespace->dobj.name,
7064                                  NULL,
7065                                  tyinfo->rolname, false,
7066                                  "TYPE", SECTION_PRE_DATA,
7067                                  q->data, delq->data, NULL,
7068                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7069                                  NULL, NULL);
7070
7071         /* Dump Type Comments */
7072         resetPQExpBuffer(q);
7073
7074         appendPQExpBuffer(q, "TYPE %s", fmtId(tyinfo->dobj.name));
7075         dumpComment(fout, q->data,
7076                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7077                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7078
7079         PQclear(res);
7080         destroyPQExpBuffer(q);
7081         destroyPQExpBuffer(delq);
7082         destroyPQExpBuffer(query);
7083 }
7084
7085 /*
7086  * dumpDomain
7087  *        writes out to fout the queries to recreate a user-defined domain
7088  */
7089 static void
7090 dumpDomain(Archive *fout, TypeInfo *tyinfo)
7091 {
7092         PQExpBuffer q = createPQExpBuffer();
7093         PQExpBuffer delq = createPQExpBuffer();
7094         PQExpBuffer query = createPQExpBuffer();
7095         PGresult   *res;
7096         int                     ntups;
7097         int                     i;
7098         char       *typnotnull;
7099         char       *typdefn;
7100         char       *typdefault;
7101         bool            typdefault_is_literal = false;
7102
7103         /* Set proper schema search path so type references list correctly */
7104         selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7105
7106         /* Fetch domain specific details */
7107         /* We assume here that remoteVersion must be at least 70300 */
7108         appendPQExpBuffer(query, "SELECT typnotnull, "
7109                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
7110                                           "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7111                                           "FROM pg_catalog.pg_type "
7112                                           "WHERE oid = '%u'::pg_catalog.oid",
7113                                           tyinfo->dobj.catId.oid);
7114
7115         res = PQexec(g_conn, query->data);
7116         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7117
7118         /* Expecting a single result only */
7119         ntups = PQntuples(res);
7120         if (ntups != 1)
7121         {
7122                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7123                                                            "query returned %d rows instead of one: %s\n",
7124                                                                  ntups),
7125                                   ntups, query->data);
7126                 exit_nicely();
7127         }
7128
7129         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
7130         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
7131         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7132                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7133         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7134         {
7135                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7136                 typdefault_is_literal = true;   /* it needs quotes */
7137         }
7138         else
7139                 typdefault = NULL;
7140
7141         if (binary_upgrade)
7142                 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7143
7144         appendPQExpBuffer(q,
7145                                           "CREATE DOMAIN %s AS %s",
7146                                           fmtId(tyinfo->dobj.name),
7147                                           typdefn);
7148
7149         if (typnotnull[0] == 't')
7150                 appendPQExpBuffer(q, " NOT NULL");
7151
7152         if (typdefault != NULL)
7153         {
7154                 appendPQExpBuffer(q, " DEFAULT ");
7155                 if (typdefault_is_literal)
7156                         appendStringLiteralAH(q, typdefault, fout);
7157                 else
7158                         appendPQExpBufferStr(q, typdefault);
7159         }
7160
7161         PQclear(res);
7162
7163         /*
7164          * Add any CHECK constraints for the domain
7165          */
7166         for (i = 0; i < tyinfo->nDomChecks; i++)
7167         {
7168                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
7169
7170                 if (!domcheck->separate)
7171                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
7172                                                           fmtId(domcheck->dobj.name), domcheck->condef);
7173         }
7174
7175         appendPQExpBuffer(q, ";\n");
7176
7177         /*
7178          * DROP must be fully qualified in case same name appears in pg_catalog
7179          */
7180         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
7181                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7182         appendPQExpBuffer(delq, "%s;\n",
7183                                           fmtId(tyinfo->dobj.name));
7184
7185         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7186                                  tyinfo->dobj.name,
7187                                  tyinfo->dobj.namespace->dobj.name,
7188                                  NULL,
7189                                  tyinfo->rolname, false,
7190                                  "DOMAIN", SECTION_PRE_DATA,
7191                                  q->data, delq->data, NULL,
7192                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7193                                  NULL, NULL);
7194
7195         /* Dump Domain Comments */
7196         resetPQExpBuffer(q);
7197
7198         appendPQExpBuffer(q, "DOMAIN %s", fmtId(tyinfo->dobj.name));
7199         dumpComment(fout, q->data,
7200                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7201                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7202
7203         destroyPQExpBuffer(q);
7204         destroyPQExpBuffer(delq);
7205         destroyPQExpBuffer(query);
7206 }
7207
7208 /*
7209  * dumpCompositeType
7210  *        writes out to fout the queries to recreate a user-defined stand-alone
7211  *        composite type
7212  */
7213 static void
7214 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
7215 {
7216         PQExpBuffer q = createPQExpBuffer();
7217         PQExpBuffer delq = createPQExpBuffer();
7218         PQExpBuffer query = createPQExpBuffer();
7219         PGresult   *res;
7220         int                     ntups;
7221         int                     i_attname;
7222         int                     i_atttypdefn;
7223         int                     i_typrelid;
7224         int                     i;
7225
7226         /* Set proper schema search path so type references list correctly */
7227         selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7228
7229         /* Fetch type specific details */
7230         /* We assume here that remoteVersion must be at least 70300 */
7231
7232         appendPQExpBuffer(query, "SELECT a.attname, "
7233                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
7234                                           "typrelid "
7235                                           "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
7236                                           "WHERE t.oid = '%u'::pg_catalog.oid "
7237                                           "AND a.attrelid = t.typrelid "
7238                                           "AND NOT a.attisdropped "
7239                                           "ORDER BY a.attnum ",
7240                                           tyinfo->dobj.catId.oid);
7241
7242         res = PQexec(g_conn, query->data);
7243         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7244
7245         /* Expecting at least a single result */
7246         ntups = PQntuples(res);
7247         if (ntups < 1)
7248         {
7249                 write_msg(NULL, "query returned no rows: %s\n", query->data);
7250                 exit_nicely();
7251         }
7252
7253         i_attname = PQfnumber(res, "attname");
7254         i_atttypdefn = PQfnumber(res, "atttypdefn");
7255         i_typrelid = PQfnumber(res, "typrelid");
7256
7257         if (binary_upgrade)
7258         {
7259                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
7260
7261                 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7262                 binary_upgrade_set_relfilenodes(q, typrelid, false);
7263         }
7264
7265         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
7266                                           fmtId(tyinfo->dobj.name));
7267
7268         for (i = 0; i < ntups; i++)
7269         {
7270                 char       *attname;
7271                 char       *atttypdefn;
7272
7273                 attname = PQgetvalue(res, i, i_attname);
7274                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
7275
7276                 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
7277                 if (i < ntups - 1)
7278                         appendPQExpBuffer(q, ",");
7279         }
7280         appendPQExpBuffer(q, "\n);\n");
7281
7282         /*
7283          * DROP must be fully qualified in case same name appears in pg_catalog
7284          */
7285         appendPQExpBuffer(delq, "DROP TYPE %s.",
7286                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7287         appendPQExpBuffer(delq, "%s;\n",
7288                                           fmtId(tyinfo->dobj.name));
7289
7290         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7291                                  tyinfo->dobj.name,
7292                                  tyinfo->dobj.namespace->dobj.name,
7293                                  NULL,
7294                                  tyinfo->rolname, false,
7295                                  "TYPE", SECTION_PRE_DATA,
7296                                  q->data, delq->data, NULL,
7297                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7298                                  NULL, NULL);
7299
7300
7301         /* Dump Type Comments */
7302         resetPQExpBuffer(q);
7303
7304         appendPQExpBuffer(q, "TYPE %s", fmtId(tyinfo->dobj.name));
7305         dumpComment(fout, q->data,
7306                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7307                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7308
7309         PQclear(res);
7310         destroyPQExpBuffer(q);
7311         destroyPQExpBuffer(delq);
7312         destroyPQExpBuffer(query);
7313
7314         /* Dump any per-column comments */
7315         dumpCompositeTypeColComments(fout, tyinfo);
7316 }
7317
7318 /*
7319  * dumpCompositeTypeColComments
7320  *        writes out to fout the queries to recreate comments on the columns of
7321  *        a user-defined stand-alone composite type
7322  */
7323 static void
7324 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
7325 {
7326         CommentItem *comments;
7327         int                     ncomments;
7328         PGresult   *res;
7329         PQExpBuffer query;
7330         PQExpBuffer target;
7331         Oid                     pgClassOid;
7332         int                     i;
7333         int                     ntups;
7334         int                     i_attname;
7335         int                     i_attnum;
7336
7337         query = createPQExpBuffer();
7338
7339         /* We assume here that remoteVersion must be at least 70300 */
7340         appendPQExpBuffer(query,
7341                                           "SELECT c.tableoid, a.attname, a.attnum "
7342                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
7343                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
7344                                           "  AND NOT a.attisdropped "
7345                                           "ORDER BY a.attnum ",
7346                                           tyinfo->typrelid);
7347
7348         /* Fetch column attnames */
7349         res = PQexec(g_conn, query->data);
7350         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7351
7352         /* Expecting at least a single result */
7353         ntups = PQntuples(res);
7354         if (ntups < 1)
7355         {
7356                 write_msg(NULL, "query returned no rows: %s\n", query->data);
7357                 exit_nicely();
7358         }
7359
7360         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
7361
7362         /* Search for comments associated with type's pg_class OID */
7363         ncomments = findComments(fout,
7364                                                          pgClassOid,
7365                                                          tyinfo->typrelid,
7366                                                          &comments);
7367
7368         /* If no comments exist, we're done */
7369         if (ncomments <= 0)
7370         {
7371                 PQclear(res);
7372                 destroyPQExpBuffer(query);
7373                 return;
7374         }
7375
7376         /* Build COMMENT ON statements */
7377         target = createPQExpBuffer();
7378
7379         i_attnum = PQfnumber(res, "attnum");
7380         i_attname = PQfnumber(res, "attname");
7381         while (ncomments > 0)
7382         {
7383                 const char *attname;
7384
7385                 attname = NULL;
7386                 for (i = 0; i < ntups; i++)
7387                 {
7388                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
7389                         {
7390                                 attname = PQgetvalue(res, i, i_attname);
7391                                 break;
7392                         }
7393                 }
7394                 if (attname)                    /* just in case we don't find it */
7395                 {
7396                         const char *descr = comments->descr;
7397
7398                         resetPQExpBuffer(target);
7399                         appendPQExpBuffer(target, "COLUMN %s.",
7400                                                           fmtId(tyinfo->dobj.name));
7401                         appendPQExpBuffer(target, "%s",
7402                                                           fmtId(attname));
7403
7404                         resetPQExpBuffer(query);
7405                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7406                         appendStringLiteralAH(query, descr, fout);
7407                         appendPQExpBuffer(query, ";\n");
7408
7409                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7410                                                  target->data,
7411                                                  tyinfo->dobj.namespace->dobj.name,
7412                                                  NULL, tyinfo->rolname,
7413                                                  false, "COMMENT", SECTION_NONE,
7414                                                  query->data, "", NULL,
7415                                                  &(tyinfo->dobj.dumpId), 1,
7416                                                  NULL, NULL);
7417                 }
7418
7419                 comments++;
7420                 ncomments--;
7421         }
7422
7423         PQclear(res);
7424         destroyPQExpBuffer(query);
7425         destroyPQExpBuffer(target);
7426 }
7427
7428 /*
7429  * dumpShellType
7430  *        writes out to fout the queries to create a shell type
7431  *
7432  * We dump a shell definition in advance of the I/O functions for the type.
7433  */
7434 static void
7435 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
7436 {
7437         PQExpBuffer q;
7438
7439         /* Skip if not to be dumped */
7440         if (!stinfo->dobj.dump || dataOnly)
7441                 return;
7442
7443         q = createPQExpBuffer();
7444
7445         /*
7446          * Note the lack of a DROP command for the shell type; any required DROP
7447          * is driven off the base type entry, instead.  This interacts with
7448          * _printTocEntry()'s use of the presence of a DROP command to decide
7449          * whether an entry needs an ALTER OWNER command.  We don't want to alter
7450          * the shell type's owner immediately on creation; that should happen only
7451          * after it's filled in, otherwise the backend complains.
7452          */
7453
7454         if (binary_upgrade)
7455                 binary_upgrade_set_type_oids_by_type_oid(q,
7456                                                                                    stinfo->baseType->dobj.catId.oid);
7457
7458         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
7459                                           fmtId(stinfo->dobj.name));
7460
7461         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
7462                                  stinfo->dobj.name,
7463                                  stinfo->dobj.namespace->dobj.name,
7464                                  NULL,
7465                                  stinfo->baseType->rolname, false,
7466                                  "SHELL TYPE", SECTION_PRE_DATA,
7467                                  q->data, "", NULL,
7468                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
7469                                  NULL, NULL);
7470
7471         destroyPQExpBuffer(q);
7472 }
7473
7474 /*
7475  * Determine whether we want to dump definitions for procedural languages.
7476  * Since the languages themselves don't have schemas, we can't rely on
7477  * the normal schema-based selection mechanism.  We choose to dump them
7478  * whenever neither --schema nor --table was given.  (Before 8.1, we used
7479  * the dump flag of the PL's call handler function, but in 8.1 this will
7480  * probably always be false since call handlers are created in pg_catalog.)
7481  *
7482  * For some backwards compatibility with the older behavior, we forcibly
7483  * dump a PL if its handler function (and validator if any) are in a
7484  * dumpable namespace.  That case is not checked here.
7485  */
7486 static bool
7487 shouldDumpProcLangs(void)
7488 {
7489         if (!include_everything)
7490                 return false;
7491         /* And they're schema not data */
7492         if (dataOnly)
7493                 return false;
7494         return true;
7495 }
7496
7497 /*
7498  * dumpProcLang
7499  *                writes out to fout the queries to recreate a user-defined
7500  *                procedural language
7501  */
7502 static void
7503 dumpProcLang(Archive *fout, ProcLangInfo *plang)
7504 {
7505         PQExpBuffer defqry;
7506         PQExpBuffer delqry;
7507         bool            useParams;
7508         char       *qlanname;
7509         char       *lanschema;
7510         FuncInfo   *funcInfo;
7511         FuncInfo   *inlineInfo = NULL;
7512         FuncInfo   *validatorInfo = NULL;
7513
7514         if (dataOnly)
7515                 return;
7516
7517         /*
7518          * Try to find the support function(s).  It is not an error if we don't
7519          * find them --- if the functions are in the pg_catalog schema, as is
7520          * standard in 8.1 and up, then we won't have loaded them. (In this case
7521          * we will emit a parameterless CREATE LANGUAGE command, which will
7522          * require PL template knowledge in the backend to reload.)
7523          */
7524
7525         funcInfo = findFuncByOid(plang->lanplcallfoid);
7526         if (funcInfo != NULL && !funcInfo->dobj.dump)
7527                 funcInfo = NULL;                /* treat not-dumped same as not-found */
7528
7529         if (OidIsValid(plang->laninline))
7530         {
7531                 inlineInfo = findFuncByOid(plang->laninline);
7532                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
7533                         inlineInfo = NULL;
7534         }
7535
7536         if (OidIsValid(plang->lanvalidator))
7537         {
7538                 validatorInfo = findFuncByOid(plang->lanvalidator);
7539                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
7540                         validatorInfo = NULL;
7541         }
7542
7543         /*
7544          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
7545          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
7546          * dump it.
7547          */
7548         useParams = (funcInfo != NULL &&
7549                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
7550                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
7551
7552         if (!useParams && !shouldDumpProcLangs())
7553                 return;
7554
7555         defqry = createPQExpBuffer();
7556         delqry = createPQExpBuffer();
7557
7558         qlanname = strdup(fmtId(plang->dobj.name));
7559
7560         /*
7561          * If dumping a HANDLER clause, treat the language as being in the handler
7562          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
7563          * it doesn't really have a schema.
7564          */
7565         if (useParams)
7566                 lanschema = funcInfo->dobj.namespace->dobj.name;
7567         else
7568                 lanschema = NULL;
7569
7570         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
7571                                           qlanname);
7572
7573         if (useParams)
7574         {
7575                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
7576                                                   plang->lanpltrusted ? "TRUSTED " : "",
7577                                                   qlanname);
7578                 appendPQExpBuffer(defqry, " HANDLER %s",
7579                                                   fmtId(funcInfo->dobj.name));
7580                 if (OidIsValid(plang->laninline))
7581                 {
7582                         appendPQExpBuffer(defqry, " INLINE ");
7583                         /* Cope with possibility that inline is in different schema */
7584                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
7585                                 appendPQExpBuffer(defqry, "%s.",
7586                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
7587                         appendPQExpBuffer(defqry, "%s",
7588                                                           fmtId(inlineInfo->dobj.name));
7589                 }
7590                 if (OidIsValid(plang->lanvalidator))
7591                 {
7592                         appendPQExpBuffer(defqry, " VALIDATOR ");
7593                         /* Cope with possibility that validator is in different schema */
7594                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
7595                                 appendPQExpBuffer(defqry, "%s.",
7596                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
7597                         appendPQExpBuffer(defqry, "%s",
7598                                                           fmtId(validatorInfo->dobj.name));
7599                 }
7600         }
7601         else
7602         {
7603                 /*
7604                  * If not dumping parameters, then use CREATE OR REPLACE so that the
7605                  * command will not fail if the language is preinstalled in the target
7606                  * database.  We restrict the use of REPLACE to this case so as to
7607                  * eliminate the risk of replacing a language with incompatible
7608                  * parameter settings: this command will only succeed at all if there
7609                  * is a pg_pltemplate entry, and if there is one, the existing entry
7610                  * must match it too.
7611                  */
7612                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
7613                                                   qlanname);
7614         }
7615         appendPQExpBuffer(defqry, ";\n");
7616
7617         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
7618                                  plang->dobj.name,
7619                                  lanschema, NULL, plang->lanowner,
7620                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
7621                                  defqry->data, delqry->data, NULL,
7622                                  plang->dobj.dependencies, plang->dobj.nDeps,
7623                                  NULL, NULL);
7624
7625         /* Dump Proc Lang Comments */
7626         resetPQExpBuffer(defqry);
7627         appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
7628         dumpComment(fout, defqry->data,
7629                                 NULL, "",
7630                                 plang->dobj.catId, 0, plang->dobj.dumpId);
7631
7632         if (plang->lanpltrusted)
7633                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
7634                                 qlanname, NULL, plang->dobj.name,
7635                                 lanschema,
7636                                 plang->lanowner, plang->lanacl);
7637
7638         free(qlanname);
7639
7640         destroyPQExpBuffer(defqry);
7641         destroyPQExpBuffer(delqry);
7642 }
7643
7644 /*
7645  * format_function_arguments: generate function name and argument list
7646  *
7647  * This is used when we can rely on pg_get_function_arguments to format
7648  * the argument list.
7649  */
7650 static char *
7651 format_function_arguments(FuncInfo *finfo, char *funcargs)
7652 {
7653         PQExpBufferData fn;
7654
7655         initPQExpBuffer(&fn);
7656         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
7657         return fn.data;
7658 }
7659
7660 /*
7661  * format_function_arguments_old: generate function name and argument list
7662  *
7663  * The argument type names are qualified if needed.  The function name
7664  * is never qualified.
7665  *
7666  * This is used only with pre-8.4 servers, so we aren't expecting to see
7667  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
7668  *
7669  * Any or all of allargtypes, argmodes, argnames may be NULL.
7670  */
7671 static char *
7672 format_function_arguments_old(FuncInfo *finfo, int nallargs,
7673                                                           char **allargtypes,
7674                                                           char **argmodes,
7675                                                           char **argnames)
7676 {
7677         PQExpBufferData fn;
7678         int                     j;
7679
7680         initPQExpBuffer(&fn);
7681         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
7682         for (j = 0; j < nallargs; j++)
7683         {
7684                 Oid                     typid;
7685                 char       *typname;
7686                 const char *argmode;
7687                 const char *argname;
7688
7689                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
7690                 typname = getFormattedTypeName(typid, zeroAsOpaque);
7691
7692                 if (argmodes)
7693                 {
7694                         switch (argmodes[j][0])
7695                         {
7696                                 case PROARGMODE_IN:
7697                                         argmode = "";
7698                                         break;
7699                                 case PROARGMODE_OUT:
7700                                         argmode = "OUT ";
7701                                         break;
7702                                 case PROARGMODE_INOUT:
7703                                         argmode = "INOUT ";
7704                                         break;
7705                                 default:
7706                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
7707                                         argmode = "";
7708                                         break;
7709                         }
7710                 }
7711                 else
7712                         argmode = "";
7713
7714                 argname = argnames ? argnames[j] : (char *) NULL;
7715                 if (argname && argname[0] == '\0')
7716                         argname = NULL;
7717
7718                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
7719                                                   (j > 0) ? ", " : "",
7720                                                   argmode,
7721                                                   argname ? fmtId(argname) : "",
7722                                                   argname ? " " : "",
7723                                                   typname);
7724                 free(typname);
7725         }
7726         appendPQExpBuffer(&fn, ")");
7727         return fn.data;
7728 }
7729
7730 /*
7731  * format_function_signature: generate function name and argument list
7732  *
7733  * This is like format_function_arguments_old except that only a minimal
7734  * list of input argument types is generated; this is sufficient to
7735  * reference the function, but not to define it.
7736  *
7737  * If honor_quotes is false then the function name is never quoted.
7738  * This is appropriate for use in TOC tags, but not in SQL commands.
7739  */
7740 static char *
7741 format_function_signature(FuncInfo *finfo, bool honor_quotes)
7742 {
7743         PQExpBufferData fn;
7744         int                     j;
7745
7746         initPQExpBuffer(&fn);
7747         if (honor_quotes)
7748                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
7749         else
7750                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
7751         for (j = 0; j < finfo->nargs; j++)
7752         {
7753                 char       *typname;
7754
7755                 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
7756
7757                 appendPQExpBuffer(&fn, "%s%s",
7758                                                   (j > 0) ? ", " : "",
7759                                                   typname);
7760                 free(typname);
7761         }
7762         appendPQExpBuffer(&fn, ")");
7763         return fn.data;
7764 }
7765
7766
7767 /*
7768  * dumpFunc:
7769  *        dump out one function
7770  */
7771 static void
7772 dumpFunc(Archive *fout, FuncInfo *finfo)
7773 {
7774         PQExpBuffer query;
7775         PQExpBuffer q;
7776         PQExpBuffer delqry;
7777         PQExpBuffer asPart;
7778         PGresult   *res;
7779         char       *funcsig;            /* identity signature */
7780         char       *funcfullsig;        /* full signature */
7781         char       *funcsig_tag;
7782         int                     ntups;
7783         char       *proretset;
7784         char       *prosrc;
7785         char       *probin;
7786         char       *funcargs;
7787         char       *funciargs;
7788         char       *funcresult;
7789         char       *proallargtypes;
7790         char       *proargmodes;
7791         char       *proargnames;
7792         char       *proiswindow;
7793         char       *provolatile;
7794         char       *proisstrict;
7795         char       *prosecdef;
7796         char       *proconfig;
7797         char       *procost;
7798         char       *prorows;
7799         char       *lanname;
7800         char       *rettypename;
7801         int                     nallargs;
7802         char      **allargtypes = NULL;
7803         char      **argmodes = NULL;
7804         char      **argnames = NULL;
7805         char      **configitems = NULL;
7806         int                     nconfigitems = 0;
7807         int                     i;
7808
7809         /* Skip if not to be dumped */
7810         if (!finfo->dobj.dump || dataOnly)
7811                 return;
7812
7813         query = createPQExpBuffer();
7814         q = createPQExpBuffer();
7815         delqry = createPQExpBuffer();
7816         asPart = createPQExpBuffer();
7817
7818         /* Set proper schema search path so type references list correctly */
7819         selectSourceSchema(finfo->dobj.namespace->dobj.name);
7820
7821         /* Fetch function-specific details */
7822         if (g_fout->remoteVersion >= 80400)
7823         {
7824                 /*
7825                  * In 8.4 and up we rely on pg_get_function_arguments and
7826                  * pg_get_function_result instead of examining proallargtypes etc.
7827                  */
7828                 appendPQExpBuffer(query,
7829                                                   "SELECT proretset, prosrc, probin, "
7830                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
7831                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
7832                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
7833                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
7834                                                   "proconfig, procost, prorows, "
7835                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7836                                                   "FROM pg_catalog.pg_proc "
7837                                                   "WHERE oid = '%u'::pg_catalog.oid",
7838                                                   finfo->dobj.catId.oid);
7839         }
7840         else if (g_fout->remoteVersion >= 80300)
7841         {
7842                 appendPQExpBuffer(query,
7843                                                   "SELECT proretset, prosrc, probin, "
7844                                                   "proallargtypes, proargmodes, proargnames, "
7845                                                   "false AS proiswindow, "
7846                                                   "provolatile, proisstrict, prosecdef, "
7847                                                   "proconfig, procost, prorows, "
7848                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7849                                                   "FROM pg_catalog.pg_proc "
7850                                                   "WHERE oid = '%u'::pg_catalog.oid",
7851                                                   finfo->dobj.catId.oid);
7852         }
7853         else if (g_fout->remoteVersion >= 80100)
7854         {
7855                 appendPQExpBuffer(query,
7856                                                   "SELECT proretset, prosrc, probin, "
7857                                                   "proallargtypes, proargmodes, proargnames, "
7858                                                   "false AS proiswindow, "
7859                                                   "provolatile, proisstrict, prosecdef, "
7860                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
7861                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7862                                                   "FROM pg_catalog.pg_proc "
7863                                                   "WHERE oid = '%u'::pg_catalog.oid",
7864                                                   finfo->dobj.catId.oid);
7865         }
7866         else if (g_fout->remoteVersion >= 80000)
7867         {
7868                 appendPQExpBuffer(query,
7869                                                   "SELECT proretset, prosrc, probin, "
7870                                                   "null AS proallargtypes, "
7871                                                   "null AS proargmodes, "
7872                                                   "proargnames, "
7873                                                   "false AS proiswindow, "
7874                                                   "provolatile, proisstrict, prosecdef, "
7875                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
7876                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7877                                                   "FROM pg_catalog.pg_proc "
7878                                                   "WHERE oid = '%u'::pg_catalog.oid",
7879                                                   finfo->dobj.catId.oid);
7880         }
7881         else if (g_fout->remoteVersion >= 70300)
7882         {
7883                 appendPQExpBuffer(query,
7884                                                   "SELECT proretset, prosrc, probin, "
7885                                                   "null AS proallargtypes, "
7886                                                   "null AS proargmodes, "
7887                                                   "null AS proargnames, "
7888                                                   "false AS proiswindow, "
7889                                                   "provolatile, proisstrict, prosecdef, "
7890                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
7891                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7892                                                   "FROM pg_catalog.pg_proc "
7893                                                   "WHERE oid = '%u'::pg_catalog.oid",
7894                                                   finfo->dobj.catId.oid);
7895         }
7896         else if (g_fout->remoteVersion >= 70100)
7897         {
7898                 appendPQExpBuffer(query,
7899                                                   "SELECT proretset, prosrc, probin, "
7900                                                   "null AS proallargtypes, "
7901                                                   "null AS proargmodes, "
7902                                                   "null AS proargnames, "
7903                                                   "false AS proiswindow, "
7904                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
7905                                                   "proisstrict, "
7906                                                   "false AS prosecdef, "
7907                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
7908                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
7909                                                   "FROM pg_proc "
7910                                                   "WHERE oid = '%u'::oid",
7911                                                   finfo->dobj.catId.oid);
7912         }
7913         else
7914         {
7915                 appendPQExpBuffer(query,
7916                                                   "SELECT proretset, prosrc, probin, "
7917                                                   "null AS proallargtypes, "
7918                                                   "null AS proargmodes, "
7919                                                   "null AS proargnames, "
7920                                                   "false AS proiswindow, "
7921                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
7922                                                   "false AS proisstrict, "
7923                                                   "false AS prosecdef, "
7924                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
7925                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
7926                                                   "FROM pg_proc "
7927                                                   "WHERE oid = '%u'::oid",
7928                                                   finfo->dobj.catId.oid);
7929         }
7930
7931         res = PQexec(g_conn, query->data);
7932         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7933
7934         /* Expecting a single result only */
7935         ntups = PQntuples(res);
7936         if (ntups != 1)
7937         {
7938                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7939                                                            "query returned %d rows instead of one: %s\n",
7940                                                                  ntups),
7941                                   ntups, query->data);
7942                 exit_nicely();
7943         }
7944
7945         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
7946         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
7947         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
7948         if (g_fout->remoteVersion >= 80400)
7949         {
7950                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
7951                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
7952                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
7953                 proallargtypes = proargmodes = proargnames = NULL;
7954         }
7955         else
7956         {
7957                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
7958                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
7959                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
7960                 funcargs = funciargs = funcresult = NULL;
7961         }
7962         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
7963         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
7964         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
7965         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
7966         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
7967         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
7968         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
7969         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
7970
7971         /*
7972          * See backend/commands/functioncmds.c for details of how the 'AS' clause
7973          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
7974          * versions would set it to "-".  There are no known cases in which prosrc
7975          * is unused, so the tests below for "-" are probably useless.
7976          */
7977         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
7978         {
7979                 appendPQExpBuffer(asPart, "AS ");
7980                 appendStringLiteralAH(asPart, probin, fout);
7981                 if (strcmp(prosrc, "-") != 0)
7982                 {
7983                         appendPQExpBuffer(asPart, ", ");
7984
7985                         /*
7986                          * where we have bin, use dollar quoting if allowed and src
7987                          * contains quote or backslash; else use regular quoting.
7988                          */
7989                         if (disable_dollar_quoting ||
7990                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
7991                                 appendStringLiteralAH(asPart, prosrc, fout);
7992                         else
7993                                 appendStringLiteralDQ(asPart, prosrc, NULL);
7994                 }
7995         }
7996         else
7997         {
7998                 if (strcmp(prosrc, "-") != 0)
7999                 {
8000                         appendPQExpBuffer(asPart, "AS ");
8001                         /* with no bin, dollar quote src unconditionally if allowed */
8002                         if (disable_dollar_quoting)
8003                                 appendStringLiteralAH(asPart, prosrc, fout);
8004                         else
8005                                 appendStringLiteralDQ(asPart, prosrc, NULL);
8006                 }
8007         }
8008
8009         nallargs = finfo->nargs;        /* unless we learn different from allargs */
8010
8011         if (proallargtypes && *proallargtypes)
8012         {
8013                 int                     nitems = 0;
8014
8015                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
8016                         nitems < finfo->nargs)
8017                 {
8018                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
8019                         if (allargtypes)
8020                                 free(allargtypes);
8021                         allargtypes = NULL;
8022                 }
8023                 else
8024                         nallargs = nitems;
8025         }
8026
8027         if (proargmodes && *proargmodes)
8028         {
8029                 int                     nitems = 0;
8030
8031                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
8032                         nitems != nallargs)
8033                 {
8034                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
8035                         if (argmodes)
8036                                 free(argmodes);
8037                         argmodes = NULL;
8038                 }
8039         }
8040
8041         if (proargnames && *proargnames)
8042         {
8043                 int                     nitems = 0;
8044
8045                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
8046                         nitems != nallargs)
8047                 {
8048                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
8049                         if (argnames)
8050                                 free(argnames);
8051                         argnames = NULL;
8052                 }
8053         }
8054
8055         if (proconfig && *proconfig)
8056         {
8057                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
8058                 {
8059                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
8060                         if (configitems)
8061                                 free(configitems);
8062                         configitems = NULL;
8063                         nconfigitems = 0;
8064                 }
8065         }
8066
8067         if (funcargs)
8068         {
8069                 /* 8.4 or later; we rely on server-side code for most of the work */
8070                 funcfullsig = format_function_arguments(finfo, funcargs);
8071                 funcsig = format_function_arguments(finfo, funciargs);
8072         }
8073         else
8074         {
8075                 /* pre-8.4, do it ourselves */
8076                 funcsig = format_function_arguments_old(finfo, nallargs, allargtypes,
8077                                                                                                 argmodes, argnames);
8078                 funcfullsig = funcsig;
8079         }
8080
8081         funcsig_tag = format_function_signature(finfo, false);
8082
8083         /*
8084          * DROP must be fully qualified in case same name appears in pg_catalog
8085          */
8086         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
8087                                           fmtId(finfo->dobj.namespace->dobj.name),
8088                                           funcsig);
8089
8090         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
8091         if (funcresult)
8092                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
8093         else
8094         {
8095                 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
8096                 appendPQExpBuffer(q, "RETURNS %s%s",
8097                                                   (proretset[0] == 't') ? "SETOF " : "",
8098                                                   rettypename);
8099                 free(rettypename);
8100         }
8101
8102         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
8103
8104         if (proiswindow[0] == 't')
8105                 appendPQExpBuffer(q, " WINDOW");
8106
8107         if (provolatile[0] != PROVOLATILE_VOLATILE)
8108         {
8109                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
8110                         appendPQExpBuffer(q, " IMMUTABLE");
8111                 else if (provolatile[0] == PROVOLATILE_STABLE)
8112                         appendPQExpBuffer(q, " STABLE");
8113                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
8114                 {
8115                         write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
8116                                           finfo->dobj.name);
8117                         exit_nicely();
8118                 }
8119         }
8120
8121         if (proisstrict[0] == 't')
8122                 appendPQExpBuffer(q, " STRICT");
8123
8124         if (prosecdef[0] == 't')
8125                 appendPQExpBuffer(q, " SECURITY DEFINER");
8126
8127         /*
8128          * COST and ROWS are emitted only if present and not default, so as not to
8129          * break backwards-compatibility of the dump without need.      Keep this code
8130          * in sync with the defaults in functioncmds.c.
8131          */
8132         if (strcmp(procost, "0") != 0)
8133         {
8134                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
8135                 {
8136                         /* default cost is 1 */
8137                         if (strcmp(procost, "1") != 0)
8138                                 appendPQExpBuffer(q, " COST %s", procost);
8139                 }
8140                 else
8141                 {
8142                         /* default cost is 100 */
8143                         if (strcmp(procost, "100") != 0)
8144                                 appendPQExpBuffer(q, " COST %s", procost);
8145                 }
8146         }
8147         if (proretset[0] == 't' &&
8148                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
8149                 appendPQExpBuffer(q, " ROWS %s", prorows);
8150
8151         for (i = 0; i < nconfigitems; i++)
8152         {
8153                 /* we feel free to scribble on configitems[] here */
8154                 char       *configitem = configitems[i];
8155                 char       *pos;
8156
8157                 pos = strchr(configitem, '=');
8158                 if (pos == NULL)
8159                         continue;
8160                 *pos++ = '\0';
8161                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
8162
8163                 /*
8164                  * Some GUC variable names are 'LIST' type and hence must not be
8165                  * quoted.
8166                  */
8167                 if (pg_strcasecmp(configitem, "DateStyle") == 0
8168                         || pg_strcasecmp(configitem, "search_path") == 0)
8169                         appendPQExpBuffer(q, "%s", pos);
8170                 else
8171                         appendStringLiteralAH(q, pos, fout);
8172         }
8173
8174         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
8175
8176         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
8177                                  funcsig_tag,
8178                                  finfo->dobj.namespace->dobj.name,
8179                                  NULL,
8180                                  finfo->rolname, false,
8181                                  "FUNCTION", SECTION_PRE_DATA,
8182                                  q->data, delqry->data, NULL,
8183                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
8184                                  NULL, NULL);
8185
8186         /* Dump Function Comments */
8187         resetPQExpBuffer(q);
8188         appendPQExpBuffer(q, "FUNCTION %s", funcsig);
8189         dumpComment(fout, q->data,
8190                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
8191                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
8192
8193         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
8194                         funcsig, NULL, funcsig_tag,
8195                         finfo->dobj.namespace->dobj.name,
8196                         finfo->rolname, finfo->proacl);
8197
8198         PQclear(res);
8199
8200         destroyPQExpBuffer(query);
8201         destroyPQExpBuffer(q);
8202         destroyPQExpBuffer(delqry);
8203         destroyPQExpBuffer(asPart);
8204         free(funcsig);
8205         free(funcsig_tag);
8206         if (allargtypes)
8207                 free(allargtypes);
8208         if (argmodes)
8209                 free(argmodes);
8210         if (argnames)
8211                 free(argnames);
8212         if (configitems)
8213                 free(configitems);
8214 }
8215
8216
8217 /*
8218  * Dump a user-defined cast
8219  */
8220 static void
8221 dumpCast(Archive *fout, CastInfo *cast)
8222 {
8223         PQExpBuffer defqry;
8224         PQExpBuffer delqry;
8225         PQExpBuffer castsig;
8226         FuncInfo   *funcInfo = NULL;
8227         TypeInfo   *sourceInfo;
8228         TypeInfo   *targetInfo;
8229
8230         if (dataOnly)
8231                 return;
8232
8233         if (OidIsValid(cast->castfunc))
8234         {
8235                 funcInfo = findFuncByOid(cast->castfunc);
8236                 if (funcInfo == NULL)
8237                         return;
8238         }
8239
8240         /*
8241          * As per discussion we dump casts if one or more of the underlying
8242          * objects (the conversion function and the two data types) are not
8243          * builtin AND if all of the non-builtin objects are included in the dump.
8244          * Builtin meaning, the namespace name does not start with "pg_".
8245          */
8246         sourceInfo = findTypeByOid(cast->castsource);
8247         targetInfo = findTypeByOid(cast->casttarget);
8248
8249         if (sourceInfo == NULL || targetInfo == NULL)
8250                 return;
8251
8252         /*
8253          * Skip this cast if all objects are from pg_
8254          */
8255         if ((funcInfo == NULL ||
8256                  strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
8257                 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
8258                 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
8259                 return;
8260
8261         /*
8262          * Skip cast if function isn't from pg_ and is not to be dumped.
8263          */
8264         if (funcInfo &&
8265                 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
8266                 !funcInfo->dobj.dump)
8267                 return;
8268
8269         /*
8270          * Same for the source type
8271          */
8272         if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
8273                 !sourceInfo->dobj.dump)
8274                 return;
8275
8276         /*
8277          * and the target type.
8278          */
8279         if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
8280                 !targetInfo->dobj.dump)
8281                 return;
8282
8283         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
8284         selectSourceSchema("pg_catalog");
8285
8286         defqry = createPQExpBuffer();
8287         delqry = createPQExpBuffer();
8288         castsig = createPQExpBuffer();
8289
8290         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
8291                                           getFormattedTypeName(cast->castsource, zeroAsNone),
8292                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
8293
8294         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
8295                                           getFormattedTypeName(cast->castsource, zeroAsNone),
8296                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
8297
8298         switch (cast->castmethod)
8299         {
8300                 case COERCION_METHOD_BINARY:
8301                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
8302                         break;
8303                 case COERCION_METHOD_INOUT:
8304                         appendPQExpBuffer(defqry, "WITH INOUT");
8305                         break;
8306                 case COERCION_METHOD_FUNCTION:
8307
8308                         /*
8309                          * Always qualify the function name, in case it is not in
8310                          * pg_catalog schema (format_function_signature won't qualify it).
8311                          */
8312                         appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
8313                                                           fmtId(funcInfo->dobj.namespace->dobj.name));
8314                         appendPQExpBuffer(defqry, "%s",
8315                                                           format_function_signature(funcInfo, true));
8316                         break;
8317                 default:
8318                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
8319         }
8320
8321         if (cast->castcontext == 'a')
8322                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
8323         else if (cast->castcontext == 'i')
8324                 appendPQExpBuffer(defqry, " AS IMPLICIT");
8325         appendPQExpBuffer(defqry, ";\n");
8326
8327         appendPQExpBuffer(castsig, "CAST (%s AS %s)",
8328                                           getFormattedTypeName(cast->castsource, zeroAsNone),
8329                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
8330
8331         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
8332                                  castsig->data,
8333                                  "pg_catalog", NULL, "",
8334                                  false, "CAST", SECTION_PRE_DATA,
8335                                  defqry->data, delqry->data, NULL,
8336                                  cast->dobj.dependencies, cast->dobj.nDeps,
8337                                  NULL, NULL);
8338
8339         /* Dump Cast Comments */
8340         resetPQExpBuffer(defqry);
8341         appendPQExpBuffer(defqry, "CAST (%s AS %s)",
8342                                           getFormattedTypeName(cast->castsource, zeroAsNone),
8343                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
8344         dumpComment(fout, defqry->data,
8345                                 NULL, "",
8346                                 cast->dobj.catId, 0, cast->dobj.dumpId);
8347
8348         destroyPQExpBuffer(defqry);
8349         destroyPQExpBuffer(delqry);
8350         destroyPQExpBuffer(castsig);
8351 }
8352
8353 /*
8354  * dumpOpr
8355  *        write out a single operator definition
8356  */
8357 static void
8358 dumpOpr(Archive *fout, OprInfo *oprinfo)
8359 {
8360         PQExpBuffer query;
8361         PQExpBuffer q;
8362         PQExpBuffer delq;
8363         PQExpBuffer oprid;
8364         PQExpBuffer details;
8365         const char *name;
8366         PGresult   *res;
8367         int                     ntups;
8368         int                     i_oprkind;
8369         int                     i_oprcode;
8370         int                     i_oprleft;
8371         int                     i_oprright;
8372         int                     i_oprcom;
8373         int                     i_oprnegate;
8374         int                     i_oprrest;
8375         int                     i_oprjoin;
8376         int                     i_oprcanmerge;
8377         int                     i_oprcanhash;
8378         char       *oprkind;
8379         char       *oprcode;
8380         char       *oprleft;
8381         char       *oprright;
8382         char       *oprcom;
8383         char       *oprnegate;
8384         char       *oprrest;
8385         char       *oprjoin;
8386         char       *oprcanmerge;
8387         char       *oprcanhash;
8388
8389         /* Skip if not to be dumped */
8390         if (!oprinfo->dobj.dump || dataOnly)
8391                 return;
8392
8393         /*
8394          * some operators are invalid because they were the result of user
8395          * defining operators before commutators exist
8396          */
8397         if (!OidIsValid(oprinfo->oprcode))
8398                 return;
8399
8400         query = createPQExpBuffer();
8401         q = createPQExpBuffer();
8402         delq = createPQExpBuffer();
8403         oprid = createPQExpBuffer();
8404         details = createPQExpBuffer();
8405
8406         /* Make sure we are in proper schema so regoperator works correctly */
8407         selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
8408
8409         if (g_fout->remoteVersion >= 80300)
8410         {
8411                 appendPQExpBuffer(query, "SELECT oprkind, "
8412                                                   "oprcode::pg_catalog.regprocedure, "
8413                                                   "oprleft::pg_catalog.regtype, "
8414                                                   "oprright::pg_catalog.regtype, "
8415                                                   "oprcom::pg_catalog.regoperator, "
8416                                                   "oprnegate::pg_catalog.regoperator, "
8417                                                   "oprrest::pg_catalog.regprocedure, "
8418                                                   "oprjoin::pg_catalog.regprocedure, "
8419                                                   "oprcanmerge, oprcanhash "
8420                                                   "FROM pg_catalog.pg_operator "
8421                                                   "WHERE oid = '%u'::pg_catalog.oid",
8422                                                   oprinfo->dobj.catId.oid);
8423         }
8424         else if (g_fout->remoteVersion >= 70300)
8425         {
8426                 appendPQExpBuffer(query, "SELECT oprkind, "
8427                                                   "oprcode::pg_catalog.regprocedure, "
8428                                                   "oprleft::pg_catalog.regtype, "
8429                                                   "oprright::pg_catalog.regtype, "
8430                                                   "oprcom::pg_catalog.regoperator, "
8431                                                   "oprnegate::pg_catalog.regoperator, "
8432                                                   "oprrest::pg_catalog.regprocedure, "
8433                                                   "oprjoin::pg_catalog.regprocedure, "
8434                                                   "(oprlsortop != 0) AS oprcanmerge, "
8435                                                   "oprcanhash "
8436                                                   "FROM pg_catalog.pg_operator "
8437                                                   "WHERE oid = '%u'::pg_catalog.oid",
8438                                                   oprinfo->dobj.catId.oid);
8439         }
8440         else if (g_fout->remoteVersion >= 70100)
8441         {
8442                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
8443                                                   "CASE WHEN oprleft = 0 THEN '-' "
8444                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
8445                                                   "CASE WHEN oprright = 0 THEN '-' "
8446                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
8447                                                   "oprcom, oprnegate, oprrest, oprjoin, "
8448                                                   "(oprlsortop != 0) AS oprcanmerge, "
8449                                                   "oprcanhash "
8450                                                   "FROM pg_operator "
8451                                                   "WHERE oid = '%u'::oid",
8452                                                   oprinfo->dobj.catId.oid);
8453         }
8454         else
8455         {
8456                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
8457                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
8458                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
8459                                                   "CASE WHEN oprright = 0 THEN '-'::name "
8460                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
8461                                                   "oprcom, oprnegate, oprrest, oprjoin, "
8462                                                   "(oprlsortop != 0) AS oprcanmerge, "
8463                                                   "oprcanhash "
8464                                                   "FROM pg_operator "
8465                                                   "WHERE oid = '%u'::oid",
8466                                                   oprinfo->dobj.catId.oid);
8467         }
8468
8469         res = PQexec(g_conn, query->data);
8470         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8471
8472         /* Expecting a single result only */
8473         ntups = PQntuples(res);
8474         if (ntups != 1)
8475         {
8476                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8477                                                            "query returned %d rows instead of one: %s\n",
8478                                                                  ntups),
8479                                   ntups, query->data);
8480                 exit_nicely();
8481         }
8482
8483         i_oprkind = PQfnumber(res, "oprkind");
8484         i_oprcode = PQfnumber(res, "oprcode");
8485         i_oprleft = PQfnumber(res, "oprleft");
8486         i_oprright = PQfnumber(res, "oprright");
8487         i_oprcom = PQfnumber(res, "oprcom");
8488         i_oprnegate = PQfnumber(res, "oprnegate");
8489         i_oprrest = PQfnumber(res, "oprrest");
8490         i_oprjoin = PQfnumber(res, "oprjoin");
8491         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
8492         i_oprcanhash = PQfnumber(res, "oprcanhash");
8493
8494         oprkind = PQgetvalue(res, 0, i_oprkind);
8495         oprcode = PQgetvalue(res, 0, i_oprcode);
8496         oprleft = PQgetvalue(res, 0, i_oprleft);
8497         oprright = PQgetvalue(res, 0, i_oprright);
8498         oprcom = PQgetvalue(res, 0, i_oprcom);
8499         oprnegate = PQgetvalue(res, 0, i_oprnegate);
8500         oprrest = PQgetvalue(res, 0, i_oprrest);
8501         oprjoin = PQgetvalue(res, 0, i_oprjoin);
8502         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
8503         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
8504
8505         appendPQExpBuffer(details, "    PROCEDURE = %s",
8506                                           convertRegProcReference(oprcode));
8507
8508         appendPQExpBuffer(oprid, "%s (",
8509                                           oprinfo->dobj.name);
8510
8511         /*
8512          * right unary means there's a left arg and left unary means there's a
8513          * right arg
8514          */
8515         if (strcmp(oprkind, "r") == 0 ||
8516                 strcmp(oprkind, "b") == 0)
8517         {
8518                 if (g_fout->remoteVersion >= 70100)
8519                         name = oprleft;
8520                 else
8521                         name = fmtId(oprleft);
8522                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
8523                 appendPQExpBuffer(oprid, "%s", name);
8524         }
8525         else
8526                 appendPQExpBuffer(oprid, "NONE");
8527
8528         if (strcmp(oprkind, "l") == 0 ||
8529                 strcmp(oprkind, "b") == 0)
8530         {
8531                 if (g_fout->remoteVersion >= 70100)
8532                         name = oprright;
8533                 else
8534                         name = fmtId(oprright);
8535                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
8536                 appendPQExpBuffer(oprid, ", %s)", name);
8537         }
8538         else
8539                 appendPQExpBuffer(oprid, ", NONE)");
8540
8541         name = convertOperatorReference(oprcom);
8542         if (name)
8543                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
8544
8545         name = convertOperatorReference(oprnegate);
8546         if (name)
8547                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
8548
8549         if (strcmp(oprcanmerge, "t") == 0)
8550                 appendPQExpBuffer(details, ",\n    MERGES");
8551
8552         if (strcmp(oprcanhash, "t") == 0)
8553                 appendPQExpBuffer(details, ",\n    HASHES");
8554
8555         name = convertRegProcReference(oprrest);
8556         if (name)
8557                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
8558
8559         name = convertRegProcReference(oprjoin);
8560         if (name)
8561                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
8562
8563         /*
8564          * DROP must be fully qualified in case same name appears in pg_catalog
8565          */
8566         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
8567                                           fmtId(oprinfo->dobj.namespace->dobj.name),
8568                                           oprid->data);
8569
8570         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
8571                                           oprinfo->dobj.name, details->data);
8572
8573         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
8574                                  oprinfo->dobj.name,
8575                                  oprinfo->dobj.namespace->dobj.name,
8576                                  NULL,
8577                                  oprinfo->rolname,
8578                                  false, "OPERATOR", SECTION_PRE_DATA,
8579                                  q->data, delq->data, NULL,
8580                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
8581                                  NULL, NULL);
8582
8583         /* Dump Operator Comments */
8584         resetPQExpBuffer(q);
8585         appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
8586         dumpComment(fout, q->data,
8587                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
8588                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
8589
8590         PQclear(res);
8591
8592         destroyPQExpBuffer(query);
8593         destroyPQExpBuffer(q);
8594         destroyPQExpBuffer(delq);
8595         destroyPQExpBuffer(oprid);
8596         destroyPQExpBuffer(details);
8597 }
8598
8599 /*
8600  * Convert a function reference obtained from pg_operator
8601  *
8602  * Returns what to print, or NULL if function references is InvalidOid
8603  *
8604  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
8605  * argument-types part.  In prior versions, the input is a REGPROC display.
8606  */
8607 static const char *
8608 convertRegProcReference(const char *proc)
8609 {
8610         /* In all cases "-" means a null reference */
8611         if (strcmp(proc, "-") == 0)
8612                 return NULL;
8613
8614         if (g_fout->remoteVersion >= 70300)
8615         {
8616                 char       *name;
8617                 char       *paren;
8618                 bool            inquote;
8619
8620                 name = strdup(proc);
8621                 /* find non-double-quoted left paren */
8622                 inquote = false;
8623                 for (paren = name; *paren; paren++)
8624                 {
8625                         if (*paren == '(' && !inquote)
8626                         {
8627                                 *paren = '\0';
8628                                 break;
8629                         }
8630                         if (*paren == '"')
8631                                 inquote = !inquote;
8632                 }
8633                 return name;
8634         }
8635
8636         /* REGPROC before 7.3 does not quote its result */
8637         return fmtId(proc);
8638 }
8639
8640 /*
8641  * Convert an operator cross-reference obtained from pg_operator
8642  *
8643  * Returns what to print, or NULL to print nothing
8644  *
8645  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
8646  * argument-types part, and add OPERATOR() decoration if the name is
8647  * schema-qualified.  In older versions, the input is just a numeric OID,
8648  * which we search our operator list for.
8649  */
8650 static const char *
8651 convertOperatorReference(const char *opr)
8652 {
8653         OprInfo    *oprInfo;
8654
8655         /* In all cases "0" means a null reference */
8656         if (strcmp(opr, "0") == 0)
8657                 return NULL;
8658
8659         if (g_fout->remoteVersion >= 70300)
8660         {
8661                 char       *name;
8662                 char       *oname;
8663                 char       *ptr;
8664                 bool            inquote;
8665                 bool            sawdot;
8666
8667                 name = strdup(opr);
8668                 /* find non-double-quoted left paren, and check for non-quoted dot */
8669                 inquote = false;
8670                 sawdot = false;
8671                 for (ptr = name; *ptr; ptr++)
8672                 {
8673                         if (*ptr == '"')
8674                                 inquote = !inquote;
8675                         else if (*ptr == '.' && !inquote)
8676                                 sawdot = true;
8677                         else if (*ptr == '(' && !inquote)
8678                         {
8679                                 *ptr = '\0';
8680                                 break;
8681                         }
8682                 }
8683                 /* If not schema-qualified, don't need to add OPERATOR() */
8684                 if (!sawdot)
8685                         return name;
8686                 oname = malloc(strlen(name) + 11);
8687                 sprintf(oname, "OPERATOR(%s)", name);
8688                 free(name);
8689                 return oname;
8690         }
8691
8692         oprInfo = findOprByOid(atooid(opr));
8693         if (oprInfo == NULL)
8694         {
8695                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
8696                                   opr);
8697                 return NULL;
8698         }
8699         return oprInfo->dobj.name;
8700 }
8701
8702 /*
8703  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
8704  *
8705  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
8706  * argument lists of these functions are predetermined.  Note that the
8707  * caller should ensure we are in the proper schema, because the results
8708  * are search path dependent!
8709  */
8710 static const char *
8711 convertTSFunction(Oid funcOid)
8712 {
8713         char       *result;
8714         char            query[128];
8715         PGresult   *res;
8716         int                     ntups;
8717
8718         snprintf(query, sizeof(query),
8719                          "SELECT '%u'::pg_catalog.regproc", funcOid);
8720         res = PQexec(g_conn, query);
8721         check_sql_result(res, g_conn, query, PGRES_TUPLES_OK);
8722
8723         ntups = PQntuples(res);
8724         if (ntups != 1)
8725         {
8726                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8727                                                            "query returned %d rows instead of one: %s\n",
8728                                                                  ntups),
8729                                   ntups, query);
8730                 exit_nicely();
8731         }
8732
8733         result = strdup(PQgetvalue(res, 0, 0));
8734
8735         PQclear(res);
8736
8737         return result;
8738 }
8739
8740
8741 /*
8742  * dumpOpclass
8743  *        write out a single operator class definition
8744  */
8745 static void
8746 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
8747 {
8748         PQExpBuffer query;
8749         PQExpBuffer q;
8750         PQExpBuffer delq;
8751         PGresult   *res;
8752         int                     ntups;
8753         int                     i_opcintype;
8754         int                     i_opckeytype;
8755         int                     i_opcdefault;
8756         int                     i_opcfamily;
8757         int                     i_opcfamilynsp;
8758         int                     i_amname;
8759         int                     i_amopstrategy;
8760         int                     i_amopreqcheck;
8761         int                     i_amopopr;
8762         int                     i_amprocnum;
8763         int                     i_amproc;
8764         char       *opcintype;
8765         char       *opckeytype;
8766         char       *opcdefault;
8767         char       *opcfamily;
8768         char       *opcfamilynsp;
8769         char       *amname;
8770         char       *amopstrategy;
8771         char       *amopreqcheck;
8772         char       *amopopr;
8773         char       *amprocnum;
8774         char       *amproc;
8775         bool            needComma;
8776         int                     i;
8777
8778         /* Skip if not to be dumped */
8779         if (!opcinfo->dobj.dump || dataOnly)
8780                 return;
8781
8782         /*
8783          * XXX currently we do not implement dumping of operator classes from
8784          * pre-7.3 databases.  This could be done but it seems not worth the
8785          * trouble.
8786          */
8787         if (g_fout->remoteVersion < 70300)
8788                 return;
8789
8790         query = createPQExpBuffer();
8791         q = createPQExpBuffer();
8792         delq = createPQExpBuffer();
8793
8794         /* Make sure we are in proper schema so regoperator works correctly */
8795         selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
8796
8797         /* Get additional fields from the pg_opclass row */
8798         if (g_fout->remoteVersion >= 80300)
8799         {
8800                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
8801                                                   "opckeytype::pg_catalog.regtype, "
8802                                                   "opcdefault, "
8803                                                   "opfname AS opcfamily, "
8804                                                   "nspname AS opcfamilynsp, "
8805                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
8806                                                   "FROM pg_catalog.pg_opclass c "
8807                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
8808                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
8809                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
8810                                                   opcinfo->dobj.catId.oid);
8811         }
8812         else
8813         {
8814                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
8815                                                   "opckeytype::pg_catalog.regtype, "
8816                                                   "opcdefault, "
8817                                                   "NULL AS opcfamily, "
8818                                                   "NULL AS opcfamilynsp, "
8819                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
8820                                                   "FROM pg_catalog.pg_opclass "
8821                                                   "WHERE oid = '%u'::pg_catalog.oid",
8822                                                   opcinfo->dobj.catId.oid);
8823         }
8824
8825         res = PQexec(g_conn, query->data);
8826         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8827
8828         /* Expecting a single result only */
8829         ntups = PQntuples(res);
8830         if (ntups != 1)
8831         {
8832                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8833                                                            "query returned %d rows instead of one: %s\n",
8834                                                                  ntups),
8835                                   ntups, query->data);
8836                 exit_nicely();
8837         }
8838
8839         i_opcintype = PQfnumber(res, "opcintype");
8840         i_opckeytype = PQfnumber(res, "opckeytype");
8841         i_opcdefault = PQfnumber(res, "opcdefault");
8842         i_opcfamily = PQfnumber(res, "opcfamily");
8843         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
8844         i_amname = PQfnumber(res, "amname");
8845
8846         opcintype = PQgetvalue(res, 0, i_opcintype);
8847         opckeytype = PQgetvalue(res, 0, i_opckeytype);
8848         opcdefault = PQgetvalue(res, 0, i_opcdefault);
8849         opcfamily = PQgetvalue(res, 0, i_opcfamily);
8850         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
8851         /* amname will still be needed after we PQclear res */
8852         amname = strdup(PQgetvalue(res, 0, i_amname));
8853
8854         /*
8855          * DROP must be fully qualified in case same name appears in pg_catalog
8856          */
8857         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
8858                                           fmtId(opcinfo->dobj.namespace->dobj.name));
8859         appendPQExpBuffer(delq, ".%s",
8860                                           fmtId(opcinfo->dobj.name));
8861         appendPQExpBuffer(delq, " USING %s;\n",
8862                                           fmtId(amname));
8863
8864         /* Build the fixed portion of the CREATE command */
8865         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
8866                                           fmtId(opcinfo->dobj.name));
8867         if (strcmp(opcdefault, "t") == 0)
8868                 appendPQExpBuffer(q, "DEFAULT ");
8869         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
8870                                           opcintype,
8871                                           fmtId(amname));
8872         if (strlen(opcfamily) > 0 &&
8873                 (strcmp(opcfamily, opcinfo->dobj.name) != 0 ||
8874                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
8875         {
8876                 appendPQExpBuffer(q, " FAMILY ");
8877                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
8878                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
8879                 appendPQExpBuffer(q, "%s", fmtId(opcfamily));
8880         }
8881         appendPQExpBuffer(q, " AS\n    ");
8882
8883         needComma = false;
8884
8885         if (strcmp(opckeytype, "-") != 0)
8886         {
8887                 appendPQExpBuffer(q, "STORAGE %s",
8888                                                   opckeytype);
8889                 needComma = true;
8890         }
8891
8892         PQclear(res);
8893
8894         /*
8895          * Now fetch and print the OPERATOR entries (pg_amop rows).
8896          */
8897         resetPQExpBuffer(query);
8898
8899         if (g_fout->remoteVersion >= 80400)
8900         {
8901                 /*
8902                  * Print only those opfamily members that are tied to the opclass by
8903                  * pg_depend entries.
8904                  *
8905                  * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping
8906                  * an older server's opclass in which it is used.  This is to avoid
8907                  * hard-to-detect breakage if a newer pg_dump is used to dump from an
8908                  * older server and then reload into that old version.  This can go
8909                  * away once 8.3 is so old as to not be of interest to anyone.
8910                  */
8911                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
8912                                                   "amopopr::pg_catalog.regoperator "
8913                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
8914                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
8915                                                   "AND refobjid = '%u'::pg_catalog.oid "
8916                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
8917                                                   "AND objid = ao.oid "
8918                                                   "ORDER BY amopstrategy",
8919                                                   opcinfo->dobj.catId.oid);
8920         }
8921         else if (g_fout->remoteVersion >= 80300)
8922         {
8923                 /*
8924                  * Print only those opfamily members that are tied to the opclass by
8925                  * pg_depend entries.
8926                  */
8927                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
8928                                                   "amopopr::pg_catalog.regoperator "
8929                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
8930                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
8931                                                   "AND refobjid = '%u'::pg_catalog.oid "
8932                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
8933                                                   "AND objid = ao.oid "
8934                                                   "ORDER BY amopstrategy",
8935                                                   opcinfo->dobj.catId.oid);
8936         }
8937         else
8938         {
8939                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
8940                                                   "amopopr::pg_catalog.regoperator "
8941                                                   "FROM pg_catalog.pg_amop "
8942                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
8943                                                   "ORDER BY amopstrategy",
8944                                                   opcinfo->dobj.catId.oid);
8945         }
8946
8947         res = PQexec(g_conn, query->data);
8948         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8949
8950         ntups = PQntuples(res);
8951
8952         i_amopstrategy = PQfnumber(res, "amopstrategy");
8953         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
8954         i_amopopr = PQfnumber(res, "amopopr");
8955
8956         for (i = 0; i < ntups; i++)
8957         {
8958                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
8959                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
8960                 amopopr = PQgetvalue(res, i, i_amopopr);
8961
8962                 if (needComma)
8963                         appendPQExpBuffer(q, " ,\n    ");
8964
8965                 appendPQExpBuffer(q, "OPERATOR %s %s",
8966                                                   amopstrategy, amopopr);
8967                 if (strcmp(amopreqcheck, "t") == 0)
8968                         appendPQExpBuffer(q, " RECHECK");
8969
8970                 needComma = true;
8971         }
8972
8973         PQclear(res);
8974
8975         /*
8976          * Now fetch and print the FUNCTION entries (pg_amproc rows).
8977          */
8978         resetPQExpBuffer(query);
8979
8980         if (g_fout->remoteVersion >= 80300)
8981         {
8982                 /*
8983                  * Print only those opfamily members that are tied to the opclass by
8984                  * pg_depend entries.
8985                  */
8986                 appendPQExpBuffer(query, "SELECT amprocnum, "
8987                                                   "amproc::pg_catalog.regprocedure "
8988                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
8989                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
8990                                                   "AND refobjid = '%u'::pg_catalog.oid "
8991                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
8992                                                   "AND objid = ap.oid "
8993                                                   "ORDER BY amprocnum",
8994                                                   opcinfo->dobj.catId.oid);
8995         }
8996         else
8997         {
8998                 appendPQExpBuffer(query, "SELECT amprocnum, "
8999                                                   "amproc::pg_catalog.regprocedure "
9000                                                   "FROM pg_catalog.pg_amproc "
9001                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
9002                                                   "ORDER BY amprocnum",
9003                                                   opcinfo->dobj.catId.oid);
9004         }
9005
9006         res = PQexec(g_conn, query->data);
9007         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9008
9009         ntups = PQntuples(res);
9010
9011         i_amprocnum = PQfnumber(res, "amprocnum");
9012         i_amproc = PQfnumber(res, "amproc");
9013
9014         for (i = 0; i < ntups; i++)
9015         {
9016                 amprocnum = PQgetvalue(res, i, i_amprocnum);
9017                 amproc = PQgetvalue(res, i, i_amproc);
9018
9019                 if (needComma)
9020                         appendPQExpBuffer(q, " ,\n    ");
9021
9022                 appendPQExpBuffer(q, "FUNCTION %s %s",
9023                                                   amprocnum, amproc);
9024
9025                 needComma = true;
9026         }
9027
9028         PQclear(res);
9029
9030         appendPQExpBuffer(q, ";\n");
9031
9032         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
9033                                  opcinfo->dobj.name,
9034                                  opcinfo->dobj.namespace->dobj.name,
9035                                  NULL,
9036                                  opcinfo->rolname,
9037                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
9038                                  q->data, delq->data, NULL,
9039                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
9040                                  NULL, NULL);
9041
9042         /* Dump Operator Class Comments */
9043         resetPQExpBuffer(q);
9044         appendPQExpBuffer(q, "OPERATOR CLASS %s",
9045                                           fmtId(opcinfo->dobj.name));
9046         appendPQExpBuffer(q, " USING %s",
9047                                           fmtId(amname));
9048         dumpComment(fout, q->data,
9049                                 NULL, opcinfo->rolname,
9050                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
9051
9052         free(amname);
9053         destroyPQExpBuffer(query);
9054         destroyPQExpBuffer(q);
9055         destroyPQExpBuffer(delq);
9056 }
9057
9058 /*
9059  * dumpOpfamily
9060  *        write out a single operator family definition
9061  */
9062 static void
9063 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
9064 {
9065         PQExpBuffer query;
9066         PQExpBuffer q;
9067         PQExpBuffer delq;
9068         PGresult   *res;
9069         PGresult   *res_ops;
9070         PGresult   *res_procs;
9071         int                     ntups;
9072         int                     i_amname;
9073         int                     i_amopstrategy;
9074         int                     i_amopreqcheck;
9075         int                     i_amopopr;
9076         int                     i_amprocnum;
9077         int                     i_amproc;
9078         int                     i_amproclefttype;
9079         int                     i_amprocrighttype;
9080         char       *amname;
9081         char       *amopstrategy;
9082         char       *amopreqcheck;
9083         char       *amopopr;
9084         char       *amprocnum;
9085         char       *amproc;
9086         char       *amproclefttype;
9087         char       *amprocrighttype;
9088         bool            needComma;
9089         int                     i;
9090
9091         /* Skip if not to be dumped */
9092         if (!opfinfo->dobj.dump || dataOnly)
9093                 return;
9094
9095         /*
9096          * We want to dump the opfamily only if (1) it contains "loose" operators
9097          * or functions, or (2) it contains an opclass with a different name or
9098          * owner.  Otherwise it's sufficient to let it be created during creation
9099          * of the contained opclass, and not dumping it improves portability of
9100          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
9101          * that first.
9102          */
9103
9104         query = createPQExpBuffer();
9105         q = createPQExpBuffer();
9106         delq = createPQExpBuffer();
9107
9108         /* Make sure we are in proper schema so regoperator works correctly */
9109         selectSourceSchema(opfinfo->dobj.namespace->dobj.name);
9110
9111         /*
9112          * Fetch only those opfamily members that are tied directly to the
9113          * opfamily by pg_depend entries.
9114          */
9115         if (g_fout->remoteVersion >= 80400)
9116         {
9117                 /*
9118                  * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping
9119                  * an older server's opclass in which it is used.  This is to avoid
9120                  * hard-to-detect breakage if a newer pg_dump is used to dump from an
9121                  * older server and then reload into that old version.  This can go
9122                  * away once 8.3 is so old as to not be of interest to anyone.
9123                  */
9124                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
9125                                                   "amopopr::pg_catalog.regoperator "
9126                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
9127                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9128                                                   "AND refobjid = '%u'::pg_catalog.oid "
9129                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
9130                                                   "AND objid = ao.oid "
9131                                                   "ORDER BY amopstrategy",
9132                                                   opfinfo->dobj.catId.oid);
9133         }
9134         else
9135         {
9136                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
9137                                                   "amopopr::pg_catalog.regoperator "
9138                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
9139                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9140                                                   "AND refobjid = '%u'::pg_catalog.oid "
9141                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
9142                                                   "AND objid = ao.oid "
9143                                                   "ORDER BY amopstrategy",
9144                                                   opfinfo->dobj.catId.oid);
9145         }
9146
9147         res_ops = PQexec(g_conn, query->data);
9148         check_sql_result(res_ops, g_conn, query->data, PGRES_TUPLES_OK);
9149
9150         resetPQExpBuffer(query);
9151
9152         appendPQExpBuffer(query, "SELECT amprocnum, "
9153                                           "amproc::pg_catalog.regprocedure, "
9154                                           "amproclefttype::pg_catalog.regtype, "
9155                                           "amprocrighttype::pg_catalog.regtype "
9156                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
9157                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9158                                           "AND refobjid = '%u'::pg_catalog.oid "
9159                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
9160                                           "AND objid = ap.oid "
9161                                           "ORDER BY amprocnum",
9162                                           opfinfo->dobj.catId.oid);
9163
9164         res_procs = PQexec(g_conn, query->data);
9165         check_sql_result(res_procs, g_conn, query->data, PGRES_TUPLES_OK);
9166
9167         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
9168         {
9169                 /* No loose members, so check contained opclasses */
9170                 resetPQExpBuffer(query);
9171
9172                 appendPQExpBuffer(query, "SELECT 1 "
9173                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
9174                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
9175                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9176                                                   "AND refobjid = f.oid "
9177                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
9178                                                   "AND objid = c.oid "
9179                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
9180                                                   "LIMIT 1",
9181                                                   opfinfo->dobj.catId.oid);
9182
9183                 res = PQexec(g_conn, query->data);
9184                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9185
9186                 if (PQntuples(res) == 0)
9187                 {
9188                         /* no need to dump it, so bail out */
9189                         PQclear(res);
9190                         PQclear(res_ops);
9191                         PQclear(res_procs);
9192                         destroyPQExpBuffer(query);
9193                         destroyPQExpBuffer(q);
9194                         destroyPQExpBuffer(delq);
9195                         return;
9196                 }
9197
9198                 PQclear(res);
9199         }
9200
9201         /* Get additional fields from the pg_opfamily row */
9202         resetPQExpBuffer(query);
9203
9204         appendPQExpBuffer(query, "SELECT "
9205          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
9206                                           "FROM pg_catalog.pg_opfamily "
9207                                           "WHERE oid = '%u'::pg_catalog.oid",
9208                                           opfinfo->dobj.catId.oid);
9209
9210         res = PQexec(g_conn, query->data);
9211         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9212
9213         /* Expecting a single result only */
9214         ntups = PQntuples(res);
9215         if (ntups != 1)
9216         {
9217                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9218                                                            "query returned %d rows instead of one: %s\n",
9219                                                                  ntups),
9220                                   ntups, query->data);
9221                 exit_nicely();
9222         }
9223
9224         i_amname = PQfnumber(res, "amname");
9225
9226         /* amname will still be needed after we PQclear res */
9227         amname = strdup(PQgetvalue(res, 0, i_amname));
9228
9229         /*
9230          * DROP must be fully qualified in case same name appears in pg_catalog
9231          */
9232         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
9233                                           fmtId(opfinfo->dobj.namespace->dobj.name));
9234         appendPQExpBuffer(delq, ".%s",
9235                                           fmtId(opfinfo->dobj.name));
9236         appendPQExpBuffer(delq, " USING %s;\n",
9237                                           fmtId(amname));
9238
9239         /* Build the fixed portion of the CREATE command */
9240         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
9241                                           fmtId(opfinfo->dobj.name));
9242         appendPQExpBuffer(q, " USING %s;\n",
9243                                           fmtId(amname));
9244
9245         PQclear(res);
9246
9247         /* Do we need an ALTER to add loose members? */
9248         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
9249         {
9250                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
9251                                                   fmtId(opfinfo->dobj.name));
9252                 appendPQExpBuffer(q, " USING %s ADD\n    ",
9253                                                   fmtId(amname));
9254
9255                 needComma = false;
9256
9257                 /*
9258                  * Now fetch and print the OPERATOR entries (pg_amop rows).
9259                  */
9260                 ntups = PQntuples(res_ops);
9261
9262                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
9263                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
9264                 i_amopopr = PQfnumber(res_ops, "amopopr");
9265
9266                 for (i = 0; i < ntups; i++)
9267                 {
9268                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
9269                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
9270                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
9271
9272                         if (needComma)
9273                                 appendPQExpBuffer(q, " ,\n    ");
9274
9275                         appendPQExpBuffer(q, "OPERATOR %s %s",
9276                                                           amopstrategy, amopopr);
9277                         if (strcmp(amopreqcheck, "t") == 0)
9278                                 appendPQExpBuffer(q, " RECHECK");
9279
9280                         needComma = true;
9281                 }
9282
9283                 /*
9284                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
9285                  */
9286                 ntups = PQntuples(res_procs);
9287
9288                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
9289                 i_amproc = PQfnumber(res_procs, "amproc");
9290                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
9291                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
9292
9293                 for (i = 0; i < ntups; i++)
9294                 {
9295                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
9296                         amproc = PQgetvalue(res_procs, i, i_amproc);
9297                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
9298                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
9299
9300                         if (needComma)
9301                                 appendPQExpBuffer(q, " ,\n    ");
9302
9303                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
9304                                                           amprocnum, amproclefttype, amprocrighttype,
9305                                                           amproc);
9306
9307                         needComma = true;
9308                 }
9309
9310                 appendPQExpBuffer(q, ";\n");
9311         }
9312
9313         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
9314                                  opfinfo->dobj.name,
9315                                  opfinfo->dobj.namespace->dobj.name,
9316                                  NULL,
9317                                  opfinfo->rolname,
9318                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
9319                                  q->data, delq->data, NULL,
9320                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
9321                                  NULL, NULL);
9322
9323         /* Dump Operator Family Comments */
9324         resetPQExpBuffer(q);
9325         appendPQExpBuffer(q, "OPERATOR FAMILY %s",
9326                                           fmtId(opfinfo->dobj.name));
9327         appendPQExpBuffer(q, " USING %s",
9328                                           fmtId(amname));
9329         dumpComment(fout, q->data,
9330                                 NULL, opfinfo->rolname,
9331                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
9332
9333         free(amname);
9334         PQclear(res_ops);
9335         PQclear(res_procs);
9336         destroyPQExpBuffer(query);
9337         destroyPQExpBuffer(q);
9338         destroyPQExpBuffer(delq);
9339 }
9340
9341 /*
9342  * dumpConversion
9343  *        write out a single conversion definition
9344  */
9345 static void
9346 dumpConversion(Archive *fout, ConvInfo *convinfo)
9347 {
9348         PQExpBuffer query;
9349         PQExpBuffer q;
9350         PQExpBuffer delq;
9351         PQExpBuffer details;
9352         PGresult   *res;
9353         int                     ntups;
9354         int                     i_conname;
9355         int                     i_conforencoding;
9356         int                     i_contoencoding;
9357         int                     i_conproc;
9358         int                     i_condefault;
9359         const char *conname;
9360         const char *conforencoding;
9361         const char *contoencoding;
9362         const char *conproc;
9363         bool            condefault;
9364
9365         /* Skip if not to be dumped */
9366         if (!convinfo->dobj.dump || dataOnly)
9367                 return;
9368
9369         query = createPQExpBuffer();
9370         q = createPQExpBuffer();
9371         delq = createPQExpBuffer();
9372         details = createPQExpBuffer();
9373
9374         /* Make sure we are in proper schema */
9375         selectSourceSchema(convinfo->dobj.namespace->dobj.name);
9376
9377         /* Get conversion-specific details */
9378         appendPQExpBuffer(query, "SELECT conname, "
9379                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
9380                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
9381                                           "conproc, condefault "
9382                                           "FROM pg_catalog.pg_conversion c "
9383                                           "WHERE c.oid = '%u'::pg_catalog.oid",
9384                                           convinfo->dobj.catId.oid);
9385
9386         res = PQexec(g_conn, query->data);
9387         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9388
9389         /* Expecting a single result only */
9390         ntups = PQntuples(res);
9391         if (ntups != 1)
9392         {
9393                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9394                                                            "query returned %d rows instead of one: %s\n",
9395                                                                  ntups),
9396                                   ntups, query->data);
9397                 exit_nicely();
9398         }
9399
9400         i_conname = PQfnumber(res, "conname");
9401         i_conforencoding = PQfnumber(res, "conforencoding");
9402         i_contoencoding = PQfnumber(res, "contoencoding");
9403         i_conproc = PQfnumber(res, "conproc");
9404         i_condefault = PQfnumber(res, "condefault");
9405
9406         conname = PQgetvalue(res, 0, i_conname);
9407         conforencoding = PQgetvalue(res, 0, i_conforencoding);
9408         contoencoding = PQgetvalue(res, 0, i_contoencoding);
9409         conproc = PQgetvalue(res, 0, i_conproc);
9410         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
9411
9412         /*
9413          * DROP must be fully qualified in case same name appears in pg_catalog
9414          */
9415         appendPQExpBuffer(delq, "DROP CONVERSION %s",
9416                                           fmtId(convinfo->dobj.namespace->dobj.name));
9417         appendPQExpBuffer(delq, ".%s;\n",
9418                                           fmtId(convinfo->dobj.name));
9419
9420         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
9421                                           (condefault) ? "DEFAULT " : "",
9422                                           fmtId(convinfo->dobj.name));
9423         appendStringLiteralAH(q, conforencoding, fout);
9424         appendPQExpBuffer(q, " TO ");
9425         appendStringLiteralAH(q, contoencoding, fout);
9426         /* regproc is automatically quoted in 7.3 and above */
9427         appendPQExpBuffer(q, " FROM %s;\n", conproc);
9428
9429         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
9430                                  convinfo->dobj.name,
9431                                  convinfo->dobj.namespace->dobj.name,
9432                                  NULL,
9433                                  convinfo->rolname,
9434                                  false, "CONVERSION", SECTION_PRE_DATA,
9435                                  q->data, delq->data, NULL,
9436                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
9437                                  NULL, NULL);
9438
9439         /* Dump Conversion Comments */
9440         resetPQExpBuffer(q);
9441         appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
9442         dumpComment(fout, q->data,
9443                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
9444                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
9445
9446         PQclear(res);
9447
9448         destroyPQExpBuffer(query);
9449         destroyPQExpBuffer(q);
9450         destroyPQExpBuffer(delq);
9451         destroyPQExpBuffer(details);
9452 }
9453
9454 /*
9455  * format_aggregate_signature: generate aggregate name and argument list
9456  *
9457  * The argument type names are qualified if needed.  The aggregate name
9458  * is never qualified.
9459  */
9460 static char *
9461 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
9462 {
9463         PQExpBufferData buf;
9464         int                     j;
9465
9466         initPQExpBuffer(&buf);
9467         if (honor_quotes)
9468                 appendPQExpBuffer(&buf, "%s",
9469                                                   fmtId(agginfo->aggfn.dobj.name));
9470         else
9471                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
9472
9473         if (agginfo->aggfn.nargs == 0)
9474                 appendPQExpBuffer(&buf, "(*)");
9475         else
9476         {
9477                 appendPQExpBuffer(&buf, "(");
9478                 for (j = 0; j < agginfo->aggfn.nargs; j++)
9479                 {
9480                         char       *typname;
9481
9482                         typname = getFormattedTypeName(agginfo->aggfn.argtypes[j], zeroAsOpaque);
9483
9484                         appendPQExpBuffer(&buf, "%s%s",
9485                                                           (j > 0) ? ", " : "",
9486                                                           typname);
9487                         free(typname);
9488                 }
9489                 appendPQExpBuffer(&buf, ")");
9490         }
9491         return buf.data;
9492 }
9493
9494 /*
9495  * dumpAgg
9496  *        write out a single aggregate definition
9497  */
9498 static void
9499 dumpAgg(Archive *fout, AggInfo *agginfo)
9500 {
9501         PQExpBuffer query;
9502         PQExpBuffer q;
9503         PQExpBuffer delq;
9504         PQExpBuffer details;
9505         char       *aggsig;
9506         char       *aggsig_tag;
9507         PGresult   *res;
9508         int                     ntups;
9509         int                     i_aggtransfn;
9510         int                     i_aggfinalfn;
9511         int                     i_aggsortop;
9512         int                     i_aggtranstype;
9513         int                     i_agginitval;
9514         int                     i_convertok;
9515         const char *aggtransfn;
9516         const char *aggfinalfn;
9517         const char *aggsortop;
9518         const char *aggtranstype;
9519         const char *agginitval;
9520         bool            convertok;
9521
9522         /* Skip if not to be dumped */
9523         if (!agginfo->aggfn.dobj.dump || dataOnly)
9524                 return;
9525
9526         query = createPQExpBuffer();
9527         q = createPQExpBuffer();
9528         delq = createPQExpBuffer();
9529         details = createPQExpBuffer();
9530
9531         /* Make sure we are in proper schema */
9532         selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
9533
9534         /* Get aggregate-specific details */
9535         if (g_fout->remoteVersion >= 80100)
9536         {
9537                 appendPQExpBuffer(query, "SELECT aggtransfn, "
9538                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
9539                                                   "aggsortop::pg_catalog.regoperator, "
9540                                                   "agginitval, "
9541                                                   "'t'::boolean AS convertok "
9542                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
9543                                                   "WHERE a.aggfnoid = p.oid "
9544                                                   "AND p.oid = '%u'::pg_catalog.oid",
9545                                                   agginfo->aggfn.dobj.catId.oid);
9546         }
9547         else if (g_fout->remoteVersion >= 70300)
9548         {
9549                 appendPQExpBuffer(query, "SELECT aggtransfn, "
9550                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
9551                                                   "0 AS aggsortop, "
9552                                                   "agginitval, "
9553                                                   "'t'::boolean AS convertok "
9554                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
9555                                                   "WHERE a.aggfnoid = p.oid "
9556                                                   "AND p.oid = '%u'::pg_catalog.oid",
9557                                                   agginfo->aggfn.dobj.catId.oid);
9558         }
9559         else if (g_fout->remoteVersion >= 70100)
9560         {
9561                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
9562                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
9563                                                   "0 AS aggsortop, "
9564                                                   "agginitval, "
9565                                                   "'t'::boolean AS convertok "
9566                                                   "FROM pg_aggregate "
9567                                                   "WHERE oid = '%u'::oid",
9568                                                   agginfo->aggfn.dobj.catId.oid);
9569         }
9570         else
9571         {
9572                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
9573                                                   "aggfinalfn, "
9574                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
9575                                                   "0 AS aggsortop, "
9576                                                   "agginitval1 AS agginitval, "
9577                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
9578                                                   "FROM pg_aggregate "
9579                                                   "WHERE oid = '%u'::oid",
9580                                                   agginfo->aggfn.dobj.catId.oid);
9581         }
9582
9583         res = PQexec(g_conn, query->data);
9584         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9585
9586         /* Expecting a single result only */
9587         ntups = PQntuples(res);
9588         if (ntups != 1)
9589         {
9590                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9591                                                            "query returned %d rows instead of one: %s\n",
9592                                                                  ntups),
9593                                   ntups, query->data);
9594                 exit_nicely();
9595         }
9596
9597         i_aggtransfn = PQfnumber(res, "aggtransfn");
9598         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
9599         i_aggsortop = PQfnumber(res, "aggsortop");
9600         i_aggtranstype = PQfnumber(res, "aggtranstype");
9601         i_agginitval = PQfnumber(res, "agginitval");
9602         i_convertok = PQfnumber(res, "convertok");
9603
9604         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
9605         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
9606         aggsortop = PQgetvalue(res, 0, i_aggsortop);
9607         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
9608         agginitval = PQgetvalue(res, 0, i_agginitval);
9609         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
9610
9611         aggsig = format_aggregate_signature(agginfo, fout, true);
9612         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
9613
9614         if (!convertok)
9615         {
9616                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
9617                                   aggsig);
9618                 return;
9619         }
9620
9621         if (g_fout->remoteVersion >= 70300)
9622         {
9623                 /* If using 7.3's regproc or regtype, data is already quoted */
9624                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
9625                                                   aggtransfn,
9626                                                   aggtranstype);
9627         }
9628         else if (g_fout->remoteVersion >= 70100)
9629         {
9630                 /* format_type quotes, regproc does not */
9631                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
9632                                                   fmtId(aggtransfn),
9633                                                   aggtranstype);
9634         }
9635         else
9636         {
9637                 /* need quotes all around */
9638                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
9639                                                   fmtId(aggtransfn));
9640                 appendPQExpBuffer(details, "    STYPE = %s",
9641                                                   fmtId(aggtranstype));
9642         }
9643
9644         if (!PQgetisnull(res, 0, i_agginitval))
9645         {
9646                 appendPQExpBuffer(details, ",\n    INITCOND = ");
9647                 appendStringLiteralAH(details, agginitval, fout);
9648         }
9649
9650         if (strcmp(aggfinalfn, "-") != 0)
9651         {
9652                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
9653                                                   aggfinalfn);
9654         }
9655
9656         aggsortop = convertOperatorReference(aggsortop);
9657         if (aggsortop)
9658         {
9659                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
9660                                                   aggsortop);
9661         }
9662
9663         /*
9664          * DROP must be fully qualified in case same name appears in pg_catalog
9665          */
9666         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
9667                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
9668                                           aggsig);
9669
9670         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
9671                                           aggsig, details->data);
9672
9673         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
9674                                  aggsig_tag,
9675                                  agginfo->aggfn.dobj.namespace->dobj.name,
9676                                  NULL,
9677                                  agginfo->aggfn.rolname,
9678                                  false, "AGGREGATE", SECTION_PRE_DATA,
9679                                  q->data, delq->data, NULL,
9680                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
9681                                  NULL, NULL);
9682
9683         /* Dump Aggregate Comments */
9684         resetPQExpBuffer(q);
9685         appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
9686         dumpComment(fout, q->data,
9687                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
9688                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
9689
9690         /*
9691          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
9692          * command look like a function's GRANT; in particular this affects the
9693          * syntax for zero-argument aggregates.
9694          */
9695         free(aggsig);
9696         free(aggsig_tag);
9697
9698         aggsig = format_function_signature(&agginfo->aggfn, true);
9699         aggsig_tag = format_function_signature(&agginfo->aggfn, false);
9700
9701         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
9702                         "FUNCTION",
9703                         aggsig, NULL, aggsig_tag,
9704                         agginfo->aggfn.dobj.namespace->dobj.name,
9705                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
9706
9707         free(aggsig);
9708         free(aggsig_tag);
9709
9710         PQclear(res);
9711
9712         destroyPQExpBuffer(query);
9713         destroyPQExpBuffer(q);
9714         destroyPQExpBuffer(delq);
9715         destroyPQExpBuffer(details);
9716 }
9717
9718 /*
9719  * dumpTSParser
9720  *        write out a single text search parser
9721  */
9722 static void
9723 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
9724 {
9725         PQExpBuffer q;
9726         PQExpBuffer delq;
9727
9728         /* Skip if not to be dumped */
9729         if (!prsinfo->dobj.dump || dataOnly)
9730                 return;
9731
9732         q = createPQExpBuffer();
9733         delq = createPQExpBuffer();
9734
9735         /* Make sure we are in proper schema */
9736         selectSourceSchema(prsinfo->dobj.namespace->dobj.name);
9737
9738         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
9739                                           fmtId(prsinfo->dobj.name));
9740
9741         appendPQExpBuffer(q, "    START = %s,\n",
9742                                           convertTSFunction(prsinfo->prsstart));
9743         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
9744                                           convertTSFunction(prsinfo->prstoken));
9745         appendPQExpBuffer(q, "    END = %s,\n",
9746                                           convertTSFunction(prsinfo->prsend));
9747         if (prsinfo->prsheadline != InvalidOid)
9748                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
9749                                                   convertTSFunction(prsinfo->prsheadline));
9750         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
9751                                           convertTSFunction(prsinfo->prslextype));
9752
9753         /*
9754          * DROP must be fully qualified in case same name appears in pg_catalog
9755          */
9756         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
9757                                           fmtId(prsinfo->dobj.namespace->dobj.name));
9758         appendPQExpBuffer(delq, ".%s;\n",
9759                                           fmtId(prsinfo->dobj.name));
9760
9761         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
9762                                  prsinfo->dobj.name,
9763                                  prsinfo->dobj.namespace->dobj.name,
9764                                  NULL,
9765                                  "",
9766                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
9767                                  q->data, delq->data, NULL,
9768                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
9769                                  NULL, NULL);
9770
9771         /* Dump Parser Comments */
9772         resetPQExpBuffer(q);
9773         appendPQExpBuffer(q, "TEXT SEARCH PARSER %s",
9774                                           fmtId(prsinfo->dobj.name));
9775         dumpComment(fout, q->data,
9776                                 NULL, "",
9777                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
9778
9779         destroyPQExpBuffer(q);
9780         destroyPQExpBuffer(delq);
9781 }
9782
9783 /*
9784  * dumpTSDictionary
9785  *        write out a single text search dictionary
9786  */
9787 static void
9788 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
9789 {
9790         PQExpBuffer q;
9791         PQExpBuffer delq;
9792         PQExpBuffer query;
9793         PGresult   *res;
9794         int                     ntups;
9795         char       *nspname;
9796         char       *tmplname;
9797
9798         /* Skip if not to be dumped */
9799         if (!dictinfo->dobj.dump || dataOnly)
9800                 return;
9801
9802         q = createPQExpBuffer();
9803         delq = createPQExpBuffer();
9804         query = createPQExpBuffer();
9805
9806         /* Fetch name and namespace of the dictionary's template */
9807         selectSourceSchema("pg_catalog");
9808         appendPQExpBuffer(query, "SELECT nspname, tmplname "
9809                                           "FROM pg_ts_template p, pg_namespace n "
9810                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
9811                                           dictinfo->dicttemplate);
9812         res = PQexec(g_conn, query->data);
9813         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9814         ntups = PQntuples(res);
9815         if (ntups != 1)
9816         {
9817                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9818                                                            "query returned %d rows instead of one: %s\n",
9819                                                                  ntups),
9820                                   ntups, query->data);
9821                 exit_nicely();
9822         }
9823         nspname = PQgetvalue(res, 0, 0);
9824         tmplname = PQgetvalue(res, 0, 1);
9825
9826         /* Make sure we are in proper schema */
9827         selectSourceSchema(dictinfo->dobj.namespace->dobj.name);
9828
9829         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
9830                                           fmtId(dictinfo->dobj.name));
9831
9832         appendPQExpBuffer(q, "    TEMPLATE = ");
9833         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
9834                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
9835         appendPQExpBuffer(q, "%s", fmtId(tmplname));
9836
9837         PQclear(res);
9838
9839         /* the dictinitoption can be dumped straight into the command */
9840         if (dictinfo->dictinitoption)
9841                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
9842
9843         appendPQExpBuffer(q, " );\n");
9844
9845         /*
9846          * DROP must be fully qualified in case same name appears in pg_catalog
9847          */
9848         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
9849                                           fmtId(dictinfo->dobj.namespace->dobj.name));
9850         appendPQExpBuffer(delq, ".%s;\n",
9851                                           fmtId(dictinfo->dobj.name));
9852
9853         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
9854                                  dictinfo->dobj.name,
9855                                  dictinfo->dobj.namespace->dobj.name,
9856                                  NULL,
9857                                  dictinfo->rolname,
9858                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
9859                                  q->data, delq->data, NULL,
9860                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
9861                                  NULL, NULL);
9862
9863         /* Dump Dictionary Comments */
9864         resetPQExpBuffer(q);
9865         appendPQExpBuffer(q, "TEXT SEARCH DICTIONARY %s",
9866                                           fmtId(dictinfo->dobj.name));
9867         dumpComment(fout, q->data,
9868                                 NULL, dictinfo->rolname,
9869                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
9870
9871         destroyPQExpBuffer(q);
9872         destroyPQExpBuffer(delq);
9873         destroyPQExpBuffer(query);
9874 }
9875
9876 /*
9877  * dumpTSTemplate
9878  *        write out a single text search template
9879  */
9880 static void
9881 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
9882 {
9883         PQExpBuffer q;
9884         PQExpBuffer delq;
9885
9886         /* Skip if not to be dumped */
9887         if (!tmplinfo->dobj.dump || dataOnly)
9888                 return;
9889
9890         q = createPQExpBuffer();
9891         delq = createPQExpBuffer();
9892
9893         /* Make sure we are in proper schema */
9894         selectSourceSchema(tmplinfo->dobj.namespace->dobj.name);
9895
9896         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
9897                                           fmtId(tmplinfo->dobj.name));
9898
9899         if (tmplinfo->tmplinit != InvalidOid)
9900                 appendPQExpBuffer(q, "    INIT = %s,\n",
9901                                                   convertTSFunction(tmplinfo->tmplinit));
9902         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
9903                                           convertTSFunction(tmplinfo->tmpllexize));
9904
9905         /*
9906          * DROP must be fully qualified in case same name appears in pg_catalog
9907          */
9908         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
9909                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
9910         appendPQExpBuffer(delq, ".%s;\n",
9911                                           fmtId(tmplinfo->dobj.name));
9912
9913         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
9914                                  tmplinfo->dobj.name,
9915                                  tmplinfo->dobj.namespace->dobj.name,
9916                                  NULL,
9917                                  "",
9918                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
9919                                  q->data, delq->data, NULL,
9920                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
9921                                  NULL, NULL);
9922
9923         /* Dump Template Comments */
9924         resetPQExpBuffer(q);
9925         appendPQExpBuffer(q, "TEXT SEARCH TEMPLATE %s",
9926                                           fmtId(tmplinfo->dobj.name));
9927         dumpComment(fout, q->data,
9928                                 NULL, "",
9929                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
9930
9931         destroyPQExpBuffer(q);
9932         destroyPQExpBuffer(delq);
9933 }
9934
9935 /*
9936  * dumpTSConfig
9937  *        write out a single text search configuration
9938  */
9939 static void
9940 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
9941 {
9942         PQExpBuffer q;
9943         PQExpBuffer delq;
9944         PQExpBuffer query;
9945         PGresult   *res;
9946         char       *nspname;
9947         char       *prsname;
9948         int                     ntups,
9949                                 i;
9950         int                     i_tokenname;
9951         int                     i_dictname;
9952
9953         /* Skip if not to be dumped */
9954         if (!cfginfo->dobj.dump || dataOnly)
9955                 return;
9956
9957         q = createPQExpBuffer();
9958         delq = createPQExpBuffer();
9959         query = createPQExpBuffer();
9960
9961         /* Fetch name and namespace of the config's parser */
9962         selectSourceSchema("pg_catalog");
9963         appendPQExpBuffer(query, "SELECT nspname, prsname "
9964                                           "FROM pg_ts_parser p, pg_namespace n "
9965                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
9966                                           cfginfo->cfgparser);
9967         res = PQexec(g_conn, query->data);
9968         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9969         ntups = PQntuples(res);
9970         if (ntups != 1)
9971         {
9972                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9973                                                            "query returned %d rows instead of one: %s\n",
9974                                                                  ntups),
9975                                   ntups, query->data);
9976                 exit_nicely();
9977         }
9978         nspname = PQgetvalue(res, 0, 0);
9979         prsname = PQgetvalue(res, 0, 1);
9980
9981         /* Make sure we are in proper schema */
9982         selectSourceSchema(cfginfo->dobj.namespace->dobj.name);
9983
9984         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
9985                                           fmtId(cfginfo->dobj.name));
9986
9987         appendPQExpBuffer(q, "    PARSER = ");
9988         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
9989                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
9990         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
9991
9992         PQclear(res);
9993
9994         resetPQExpBuffer(query);
9995         appendPQExpBuffer(query,
9996                                           "SELECT \n"
9997                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
9998                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
9999                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
10000                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
10001                                           "WHERE m.mapcfg = '%u' \n"
10002                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
10003                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
10004
10005         res = PQexec(g_conn, query->data);
10006         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10007         ntups = PQntuples(res);
10008
10009         i_tokenname = PQfnumber(res, "tokenname");
10010         i_dictname = PQfnumber(res, "dictname");
10011
10012         for (i = 0; i < ntups; i++)
10013         {
10014                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
10015                 char       *dictname = PQgetvalue(res, i, i_dictname);
10016
10017                 if (i == 0 ||
10018                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
10019                 {
10020                         /* starting a new token type, so start a new command */
10021                         if (i > 0)
10022                                 appendPQExpBuffer(q, ";\n");
10023                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
10024                                                           fmtId(cfginfo->dobj.name));
10025                         /* tokenname needs quoting, dictname does NOT */
10026                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
10027                                                           fmtId(tokenname), dictname);
10028                 }
10029                 else
10030                         appendPQExpBuffer(q, ", %s", dictname);
10031         }
10032
10033         if (ntups > 0)
10034                 appendPQExpBuffer(q, ";\n");
10035
10036         PQclear(res);
10037
10038         /*
10039          * DROP must be fully qualified in case same name appears in pg_catalog
10040          */
10041         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
10042                                           fmtId(cfginfo->dobj.namespace->dobj.name));
10043         appendPQExpBuffer(delq, ".%s;\n",
10044                                           fmtId(cfginfo->dobj.name));
10045
10046         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
10047                                  cfginfo->dobj.name,
10048                                  cfginfo->dobj.namespace->dobj.name,
10049                                  NULL,
10050                                  cfginfo->rolname,
10051                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
10052                                  q->data, delq->data, NULL,
10053                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
10054                                  NULL, NULL);
10055
10056         /* Dump Configuration Comments */
10057         resetPQExpBuffer(q);
10058         appendPQExpBuffer(q, "TEXT SEARCH CONFIGURATION %s",
10059                                           fmtId(cfginfo->dobj.name));
10060         dumpComment(fout, q->data,
10061                                 NULL, cfginfo->rolname,
10062                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
10063
10064         destroyPQExpBuffer(q);
10065         destroyPQExpBuffer(delq);
10066         destroyPQExpBuffer(query);
10067 }
10068
10069 /*
10070  * dumpForeignDataWrapper
10071  *        write out a single foreign-data wrapper definition
10072  */
10073 static void
10074 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
10075 {
10076         PQExpBuffer q;
10077         PQExpBuffer delq;
10078         char       *namecopy;
10079
10080         /* Skip if not to be dumped */
10081         if (!fdwinfo->dobj.dump || dataOnly)
10082                 return;
10083
10084         q = createPQExpBuffer();
10085         delq = createPQExpBuffer();
10086
10087         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
10088                                           fmtId(fdwinfo->dobj.name));
10089
10090         if (fdwinfo->fdwvalidator && strcmp(fdwinfo->fdwvalidator, "-") != 0)
10091                 appendPQExpBuffer(q, " VALIDATOR %s",
10092                                                   fdwinfo->fdwvalidator);
10093
10094         if (fdwinfo->fdwoptions && strlen(fdwinfo->fdwoptions) > 0)
10095                 appendPQExpBuffer(q, " OPTIONS (%s)", fdwinfo->fdwoptions);
10096
10097         appendPQExpBuffer(q, ";\n");
10098
10099         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
10100                                           fmtId(fdwinfo->dobj.name));
10101
10102         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
10103                                  fdwinfo->dobj.name,
10104                                  NULL,
10105                                  NULL,
10106                                  fdwinfo->rolname,
10107                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
10108                                  q->data, delq->data, NULL,
10109                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
10110                                  NULL, NULL);
10111
10112         /* Handle the ACL */
10113         namecopy = strdup(fmtId(fdwinfo->dobj.name));
10114         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
10115                         "FOREIGN DATA WRAPPER",
10116                         namecopy, NULL, fdwinfo->dobj.name,
10117                         NULL, fdwinfo->rolname,
10118                         fdwinfo->fdwacl);
10119         free(namecopy);
10120
10121         destroyPQExpBuffer(q);
10122         destroyPQExpBuffer(delq);
10123 }
10124
10125 /*
10126  * dumpForeignServer
10127  *        write out a foreign server definition
10128  */
10129 static void
10130 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
10131 {
10132         PQExpBuffer q;
10133         PQExpBuffer delq;
10134         PQExpBuffer query;
10135         PGresult   *res;
10136         int                     ntups;
10137         char       *namecopy;
10138         char       *fdwname;
10139
10140         /* Skip if not to be dumped */
10141         if (!srvinfo->dobj.dump || dataOnly)
10142                 return;
10143
10144         q = createPQExpBuffer();
10145         delq = createPQExpBuffer();
10146         query = createPQExpBuffer();
10147
10148         /* look up the foreign-data wrapper */
10149         selectSourceSchema("pg_catalog");
10150         appendPQExpBuffer(query, "SELECT fdwname "
10151                                           "FROM pg_foreign_data_wrapper w "
10152                                           "WHERE w.oid = '%u'",
10153                                           srvinfo->srvfdw);
10154         res = PQexec(g_conn, query->data);
10155         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10156         ntups = PQntuples(res);
10157         if (ntups != 1)
10158         {
10159                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10160                                                            "query returned %d rows instead of one: %s\n",
10161                                                                  ntups),
10162                                   ntups, query->data);
10163                 exit_nicely();
10164         }
10165         fdwname = PQgetvalue(res, 0, 0);
10166
10167         appendPQExpBuffer(q, "CREATE SERVER %s", fmtId(srvinfo->dobj.name));
10168         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
10169         {
10170                 appendPQExpBuffer(q, " TYPE ");
10171                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
10172         }
10173         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
10174         {
10175                 appendPQExpBuffer(q, " VERSION ");
10176                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
10177         }
10178
10179         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
10180         appendPQExpBuffer(q, "%s", fmtId(fdwname));
10181
10182         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
10183                 appendPQExpBuffer(q, " OPTIONS (%s)", srvinfo->srvoptions);
10184
10185         appendPQExpBuffer(q, ";\n");
10186
10187         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
10188                                           fmtId(srvinfo->dobj.name));
10189
10190         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
10191                                  srvinfo->dobj.name,
10192                                  NULL,
10193                                  NULL,
10194                                  srvinfo->rolname,
10195                                  false, "SERVER", SECTION_PRE_DATA,
10196                                  q->data, delq->data, NULL,
10197                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
10198                                  NULL, NULL);
10199
10200         /* Handle the ACL */
10201         namecopy = strdup(fmtId(srvinfo->dobj.name));
10202         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
10203                         "FOREIGN SERVER",
10204                         namecopy, NULL, srvinfo->dobj.name,
10205                         NULL, srvinfo->rolname,
10206                         srvinfo->srvacl);
10207         free(namecopy);
10208
10209         /* Dump user mappings */
10210         dumpUserMappings(fout,
10211                                          srvinfo->dobj.name, NULL,
10212                                          srvinfo->rolname,
10213                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
10214
10215         destroyPQExpBuffer(q);
10216         destroyPQExpBuffer(delq);
10217 }
10218
10219 /*
10220  * dumpUserMappings
10221  *
10222  * This routine is used to dump any user mappings associated with the
10223  * server handed to this routine. Should be called after ArchiveEntry()
10224  * for the server.
10225  */
10226 static void
10227 dumpUserMappings(Archive *fout,
10228                                  const char *servername, const char *namespace,
10229                                  const char *owner,
10230                                  CatalogId catalogId, DumpId dumpId)
10231 {
10232         PQExpBuffer q;
10233         PQExpBuffer delq;
10234         PQExpBuffer query;
10235         PQExpBuffer tag;
10236         PGresult   *res;
10237         int                     ntups;
10238         int                     i_usename;
10239         int                     i_umoptions;
10240         int                     i;
10241
10242         q = createPQExpBuffer();
10243         tag = createPQExpBuffer();
10244         delq = createPQExpBuffer();
10245         query = createPQExpBuffer();
10246
10247         /*
10248          * We read from the publicly accessible view pg_user_mappings, so as not
10249          * to fail if run by a non-superuser.  Note that the view will show
10250          * umoptions as null if the user hasn't got privileges for the associated
10251          * server; this means that pg_dump will dump such a mapping, but with no
10252          * OPTIONS clause.  A possible alternative is to skip such mappings
10253          * altogether, but it's not clear that that's an improvement.
10254          */
10255         selectSourceSchema("pg_catalog");
10256
10257         appendPQExpBuffer(query,
10258                                           "SELECT usename, "
10259                                           "array_to_string(ARRAY(SELECT option_name || ' ' || quote_literal(option_value) FROM pg_options_to_table(umoptions)), ', ') AS umoptions\n"
10260                                           "FROM pg_user_mappings "
10261                                           "WHERE srvid = %u",
10262                                           catalogId.oid);
10263
10264         res = PQexec(g_conn, query->data);
10265         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10266
10267         ntups = PQntuples(res);
10268         i_usename = PQfnumber(res, "usename");
10269         i_umoptions = PQfnumber(res, "umoptions");
10270
10271         for (i = 0; i < ntups; i++)
10272         {
10273                 char       *usename;
10274                 char       *umoptions;
10275
10276                 usename = PQgetvalue(res, i, i_usename);
10277                 umoptions = PQgetvalue(res, i, i_umoptions);
10278
10279                 resetPQExpBuffer(q);
10280                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
10281                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
10282
10283                 if (umoptions && strlen(umoptions) > 0)
10284                         appendPQExpBuffer(q, " OPTIONS (%s)", umoptions);
10285
10286                 appendPQExpBuffer(q, ";\n");
10287
10288                 resetPQExpBuffer(delq);
10289                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
10290                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
10291
10292                 resetPQExpBuffer(tag);
10293                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
10294                                                   usename, servername);
10295
10296                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
10297                                          tag->data,
10298                                          namespace,
10299                                          NULL,
10300                                          owner, false,
10301                                          "USER MAPPING", SECTION_PRE_DATA,
10302                                          q->data, delq->data, NULL,
10303                                          &dumpId, 1,
10304                                          NULL, NULL);
10305         }
10306
10307         PQclear(res);
10308
10309         destroyPQExpBuffer(query);
10310         destroyPQExpBuffer(delq);
10311         destroyPQExpBuffer(q);
10312 }
10313
10314 /*
10315  * Write out default privileges information
10316  */
10317 static void
10318 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
10319 {
10320         PQExpBuffer q;
10321         PQExpBuffer tag;
10322         const char *type;
10323
10324         /* Skip if not to be dumped */
10325         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
10326                 return;
10327
10328         q = createPQExpBuffer();
10329         tag = createPQExpBuffer();
10330
10331         switch (daclinfo->defaclobjtype)
10332         {
10333                 case DEFACLOBJ_RELATION:
10334                         type = "TABLES";
10335                         break;
10336                 case DEFACLOBJ_SEQUENCE:
10337                         type = "SEQUENCES";
10338                         break;
10339                 case DEFACLOBJ_FUNCTION:
10340                         type = "FUNCTIONS";
10341                         break;
10342                 default:
10343                         /* shouldn't get here */
10344                         write_msg(NULL, "unknown object type (%d) in default privileges\n",
10345                                           (int) daclinfo->defaclobjtype);
10346                         exit_nicely();
10347                         type = "";                      /* keep compiler quiet */
10348         }
10349
10350         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
10351
10352         /* build the actual command(s) for this tuple */
10353         if (!buildDefaultACLCommands(type,
10354                                                                  daclinfo->dobj.namespace != NULL ?
10355                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
10356                                                                  daclinfo->defaclacl,
10357                                                                  daclinfo->defaclrole,
10358                                                                  fout->remoteVersion,
10359                                                                  q))
10360         {
10361                 write_msg(NULL, "could not parse default ACL list (%s)\n",
10362                                   daclinfo->defaclacl);
10363                 exit_nicely();
10364         }
10365
10366         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
10367                                  tag->data,
10368            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
10369                                  NULL,
10370                                  daclinfo->defaclrole,
10371                                  false, "DEFAULT ACL", SECTION_NONE,
10372                                  q->data, "", NULL,
10373                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
10374                                  NULL, NULL);
10375
10376         destroyPQExpBuffer(tag);
10377         destroyPQExpBuffer(q);
10378 }
10379
10380 /*----------
10381  * Write out grant/revoke information
10382  *
10383  * 'objCatId' is the catalog ID of the underlying object.
10384  * 'objDumpId' is the dump ID of the underlying object.
10385  * 'type' must be one of
10386  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
10387  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
10388  * 'name' is the formatted name of the object.  Must be quoted etc. already.
10389  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
10390  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
10391  * 'nspname' is the namespace the object is in (NULL if none).
10392  * 'owner' is the owner, NULL if there is no owner (for languages).
10393  * 'acls' is the string read out of the fooacl system catalog field;
10394  *              it will be parsed here.
10395  *----------
10396  */
10397 static void
10398 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
10399                 const char *type, const char *name, const char *subname,
10400                 const char *tag, const char *nspname, const char *owner,
10401                 const char *acls)
10402 {
10403         PQExpBuffer sql;
10404
10405         /* Do nothing if ACL dump is not enabled */
10406         if (aclsSkip)
10407                 return;
10408
10409         /* --data-only skips ACLs *except* BLOB ACLs */
10410         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
10411                 return;
10412
10413         sql = createPQExpBuffer();
10414
10415         if (!buildACLCommands(name, subname, type, acls, owner,
10416                                                   "", fout->remoteVersion, sql))
10417         {
10418                 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
10419                                   acls, name, type);
10420                 exit_nicely();
10421         }
10422
10423         if (sql->len > 0)
10424                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
10425                                          tag, nspname,
10426                                          NULL,
10427                                          owner ? owner : "",
10428                                          false, "ACL", SECTION_NONE,
10429                                          sql->data, "", NULL,
10430                                          &(objDumpId), 1,
10431                                          NULL, NULL);
10432
10433         destroyPQExpBuffer(sql);
10434 }
10435
10436 /*
10437  * dumpTable
10438  *        write out to fout the declarations (not data) of a user-defined table
10439  */
10440 static void
10441 dumpTable(Archive *fout, TableInfo *tbinfo)
10442 {
10443         if (tbinfo->dobj.dump)
10444         {
10445                 char       *namecopy;
10446
10447                 if (tbinfo->relkind == RELKIND_SEQUENCE)
10448                         dumpSequence(fout, tbinfo);
10449                 else if (!dataOnly)
10450                         dumpTableSchema(fout, tbinfo);
10451
10452                 /* Handle the ACL here */
10453                 namecopy = strdup(fmtId(tbinfo->dobj.name));
10454                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
10455                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE",
10456                                 namecopy, NULL, tbinfo->dobj.name,
10457                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
10458                                 tbinfo->relacl);
10459
10460                 /*
10461                  * Handle column ACLs, if any.  Note: we pull these with a separate
10462                  * query rather than trying to fetch them during getTableAttrs, so
10463                  * that we won't miss ACLs on system columns.
10464                  */
10465                 if (g_fout->remoteVersion >= 80400)
10466                 {
10467                         PQExpBuffer query = createPQExpBuffer();
10468                         PGresult   *res;
10469                         int                     i;
10470
10471                         appendPQExpBuffer(query,
10472                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
10473                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
10474                                                           "ORDER BY attnum",
10475                                                           tbinfo->dobj.catId.oid);
10476                         res = PQexec(g_conn, query->data);
10477                         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10478
10479                         for (i = 0; i < PQntuples(res); i++)
10480                         {
10481                                 char       *attname = PQgetvalue(res, i, 0);
10482                                 char       *attacl = PQgetvalue(res, i, 1);
10483                                 char       *attnamecopy;
10484                                 char       *acltag;
10485
10486                                 attnamecopy = strdup(fmtId(attname));
10487                                 acltag = malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
10488                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
10489                                 /* Column's GRANT type is always TABLE */
10490                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
10491                                                 namecopy, attnamecopy, acltag,
10492                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
10493                                                 attacl);
10494                                 free(attnamecopy);
10495                                 free(acltag);
10496                         }
10497                         PQclear(res);
10498                         destroyPQExpBuffer(query);
10499                 }
10500
10501                 free(namecopy);
10502         }
10503 }
10504
10505 /*
10506  * dumpTableSchema
10507  *        write the declaration (not data) of one user-defined table or view
10508  */
10509 static void
10510 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
10511 {
10512         PQExpBuffer query = createPQExpBuffer();
10513         PQExpBuffer q = createPQExpBuffer();
10514         PQExpBuffer delq = createPQExpBuffer();
10515         PGresult   *res;
10516         int                     numParents;
10517         TableInfo **parents;
10518         int                     actual_atts;    /* number of attrs in this CREATE statment */
10519         char       *reltypename;
10520         char       *storage;
10521         int                     j,
10522                                 k;
10523         bool            toast_set = false;
10524
10525         /* Make sure we are in proper schema */
10526         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
10527
10528         if (binary_upgrade)
10529                 toast_set = binary_upgrade_set_type_oids_by_rel_oid(q,
10530                                                                                                          tbinfo->dobj.catId.oid);
10531
10532         /* Is it a table or a view? */
10533         if (tbinfo->relkind == RELKIND_VIEW)
10534         {
10535                 char       *viewdef;
10536
10537                 reltypename = "VIEW";
10538
10539                 /* Fetch the view definition */
10540                 if (g_fout->remoteVersion >= 70300)
10541                 {
10542                         /* Beginning in 7.3, viewname is not unique; rely on OID */
10543                         appendPQExpBuffer(query,
10544                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
10545                                                           tbinfo->dobj.catId.oid);
10546                 }
10547                 else
10548                 {
10549                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
10550                                                           "FROM pg_views WHERE viewname = ");
10551                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
10552                         appendPQExpBuffer(query, ";");
10553                 }
10554
10555                 res = PQexec(g_conn, query->data);
10556                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10557
10558                 if (PQntuples(res) != 1)
10559                 {
10560                         if (PQntuples(res) < 1)
10561                                 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
10562                                                   tbinfo->dobj.name);
10563                         else
10564                                 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
10565                                                   tbinfo->dobj.name);
10566                         exit_nicely();
10567                 }
10568
10569                 viewdef = PQgetvalue(res, 0, 0);
10570
10571                 if (strlen(viewdef) == 0)
10572                 {
10573                         write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
10574                                           tbinfo->dobj.name);
10575                         exit_nicely();
10576                 }
10577
10578                 /*
10579                  * DROP must be fully qualified in case same name appears in
10580                  * pg_catalog
10581                  */
10582                 appendPQExpBuffer(delq, "DROP VIEW %s.",
10583                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
10584                 appendPQExpBuffer(delq, "%s;\n",
10585                                                   fmtId(tbinfo->dobj.name));
10586
10587                 if (binary_upgrade)
10588                         binary_upgrade_set_relfilenodes(q, tbinfo->dobj.catId.oid, false);
10589
10590                 appendPQExpBuffer(q, "CREATE VIEW %s AS\n    %s\n",
10591                                                   fmtId(tbinfo->dobj.name), viewdef);
10592
10593                 PQclear(res);
10594         }
10595         else
10596         {
10597                 reltypename = "TABLE";
10598                 numParents = tbinfo->numParents;
10599                 parents = tbinfo->parents;
10600
10601                 /*
10602                  * DROP must be fully qualified in case same name appears in
10603                  * pg_catalog
10604                  */
10605                 appendPQExpBuffer(delq, "DROP TABLE %s.",
10606                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
10607                 appendPQExpBuffer(delq, "%s;\n",
10608                                                   fmtId(tbinfo->dobj.name));
10609
10610                 if (binary_upgrade)
10611                         binary_upgrade_set_relfilenodes(q, tbinfo->dobj.catId.oid, false);
10612
10613                 appendPQExpBuffer(q, "CREATE TABLE %s",
10614                                                   fmtId(tbinfo->dobj.name));
10615                 if (tbinfo->reloftype)
10616                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
10617                 actual_atts = 0;
10618                 for (j = 0; j < tbinfo->numatts; j++)
10619                 {
10620                         /*
10621                          * Normally, dump if it's one of the table's own attrs, and not
10622                          * dropped.  But for binary upgrade, dump all the columns.
10623                          */
10624                         if ((!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j]) ||
10625                                 binary_upgrade)
10626                         {
10627                                 /*
10628                                  * Default value --- suppress if inherited (except in
10629                                  * binary-upgrade case, where we're not doing normal
10630                                  * inheritance) or if it's to be printed separately.
10631                                  */
10632                                 bool            has_default = (tbinfo->attrdefs[j] != NULL
10633                                                                 && (!tbinfo->inhAttrDef[j] || binary_upgrade)
10634                                                                                    && !tbinfo->attrdefs[j]->separate);
10635
10636                                 /*
10637                                  * Not Null constraint --- suppress if inherited, except in
10638                                  * binary-upgrade case.
10639                                  */
10640                                 bool            has_notnull = (tbinfo->notnull[j]
10641                                                           && (!tbinfo->inhNotNull[j] || binary_upgrade));
10642
10643                                 if (tbinfo->reloftype && !has_default && !has_notnull)
10644                                         continue;
10645
10646                                 /* Format properly if not first attr */
10647                                 if (actual_atts == 0)
10648                                         appendPQExpBuffer(q, " (");
10649                                 else
10650                                         appendPQExpBuffer(q, ",");
10651                                 appendPQExpBuffer(q, "\n    ");
10652                                 actual_atts++;
10653
10654                                 /* Attribute name */
10655                                 appendPQExpBuffer(q, "%s ",
10656                                                                   fmtId(tbinfo->attnames[j]));
10657
10658                                 if (tbinfo->attisdropped[j])
10659                                 {
10660                                         /*
10661                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
10662                                          * so we will not have gotten a valid type name; insert
10663                                          * INTEGER as a stopgap.  We'll clean things up later.
10664                                          */
10665                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
10666                                         /* Skip all the rest, too */
10667                                         continue;
10668                                 }
10669
10670                                 /* Attribute type */
10671                                 if (tbinfo->reloftype)
10672                                 {
10673                                         appendPQExpBuffer(q, "WITH OPTIONS");
10674                                 }
10675                                 else if (g_fout->remoteVersion >= 70100)
10676                                 {
10677                                         appendPQExpBuffer(q, "%s",
10678                                                                           tbinfo->atttypnames[j]);
10679                                 }
10680                                 else
10681                                 {
10682                                         /* If no format_type, fake it */
10683                                         appendPQExpBuffer(q, "%s",
10684                                                                           myFormatType(tbinfo->atttypnames[j],
10685                                                                                                    tbinfo->atttypmod[j]));
10686                                 }
10687
10688                                 if (has_default)
10689                                         appendPQExpBuffer(q, " DEFAULT %s",
10690                                                                           tbinfo->attrdefs[j]->adef_expr);
10691
10692                                 if (has_notnull)
10693                                         appendPQExpBuffer(q, " NOT NULL");
10694                         }
10695                 }
10696
10697                 /*
10698                  * Add non-inherited CHECK constraints, if any.
10699                  */
10700                 for (j = 0; j < tbinfo->ncheck; j++)
10701                 {
10702                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
10703
10704                         if (constr->separate || !constr->conislocal)
10705                                 continue;
10706
10707                         if (actual_atts == 0)
10708                                 appendPQExpBuffer(q, " (\n    ");
10709                         else
10710                                 appendPQExpBuffer(q, ",\n    ");
10711
10712                         appendPQExpBuffer(q, "CONSTRAINT %s ",
10713                                                           fmtId(constr->dobj.name));
10714                         appendPQExpBuffer(q, "%s", constr->condef);
10715
10716                         actual_atts++;
10717                 }
10718
10719                 if (actual_atts)
10720                         appendPQExpBuffer(q, "\n)");
10721                 else if (!tbinfo->reloftype)
10722                 {
10723                         /*
10724                          * We must have a parenthesized attribute list, even though empty,
10725                          * when not using the OF TYPE syntax.
10726                          */
10727                         appendPQExpBuffer(q, " (\n)");
10728                 }
10729
10730                 if (numParents > 0 && !binary_upgrade)
10731                 {
10732                         appendPQExpBuffer(q, "\nINHERITS (");
10733                         for (k = 0; k < numParents; k++)
10734                         {
10735                                 TableInfo  *parentRel = parents[k];
10736
10737                                 if (k > 0)
10738                                         appendPQExpBuffer(q, ", ");
10739                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
10740                                         appendPQExpBuffer(q, "%s.",
10741                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
10742                                 appendPQExpBuffer(q, "%s",
10743                                                                   fmtId(parentRel->dobj.name));
10744                         }
10745                         appendPQExpBuffer(q, ")");
10746                 }
10747
10748                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
10749                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
10750                 {
10751                         bool            addcomma = false;
10752
10753                         appendPQExpBuffer(q, "\nWITH (");
10754                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
10755                         {
10756                                 addcomma = true;
10757                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
10758                         }
10759                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
10760                         {
10761                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
10762                                                                   tbinfo->toast_reloptions);
10763                         }
10764                         appendPQExpBuffer(q, ")");
10765                 }
10766
10767                 appendPQExpBuffer(q, ";\n");
10768
10769                 /*
10770                  * To create binary-compatible heap files, we have to ensure the same
10771                  * physical column order, including dropped columns, as in the
10772                  * original.  Therefore, we create dropped columns above and drop them
10773                  * here, also updating their attlen/attalign values so that the
10774                  * dropped column can be skipped properly.      (We do not bother with
10775                  * restoring the original attbyval setting.)  Also, inheritance
10776                  * relationships are set up by doing ALTER INHERIT rather than using
10777                  * an INHERITS clause --- the latter would possibly mess up the column
10778                  * order.  That also means we have to take care about setting
10779                  * attislocal correctly, plus fix up any inherited CHECK constraints.
10780                  */
10781                 if (binary_upgrade)
10782                 {
10783                         for (j = 0; j < tbinfo->numatts; j++)
10784                         {
10785                                 if (tbinfo->attisdropped[j])
10786                                 {
10787                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
10788                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
10789                                                                           "SET attlen = %d, "
10790                                                                           "attalign = '%c', attbyval = false\n"
10791                                                                           "WHERE attname = ",
10792                                                                           tbinfo->attlen[j],
10793                                                                           tbinfo->attalign[j]);
10794                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
10795                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
10796                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10797                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10798
10799                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10800                                                                           fmtId(tbinfo->dobj.name));
10801                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
10802                                                                           fmtId(tbinfo->attnames[j]));
10803                                 }
10804                                 else if (!tbinfo->attislocal[j])
10805                                 {
10806                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
10807                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
10808                                                                           "SET attislocal = false\n"
10809                                                                           "WHERE attname = ");
10810                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
10811                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
10812                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10813                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10814                                 }
10815                         }
10816
10817                         for (k = 0; k < tbinfo->ncheck; k++)
10818                         {
10819                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
10820
10821                                 if (constr->separate || constr->conislocal)
10822                                         continue;
10823
10824                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
10825                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10826                                                                   fmtId(tbinfo->dobj.name));
10827                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
10828                                                                   fmtId(constr->dobj.name));
10829                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
10830                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
10831                                                                   "SET conislocal = false\n"
10832                                                                   "WHERE contype = 'c' AND conname = ");
10833                                 appendStringLiteralAH(q, constr->dobj.name, fout);
10834                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
10835                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10836                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10837                         }
10838
10839                         if (numParents > 0)
10840                         {
10841                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
10842                                 for (k = 0; k < numParents; k++)
10843                                 {
10844                                         TableInfo  *parentRel = parents[k];
10845
10846                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
10847                                                                           fmtId(tbinfo->dobj.name));
10848                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
10849                                                 appendPQExpBuffer(q, "%s.",
10850                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
10851                                         appendPQExpBuffer(q, "%s;\n",
10852                                                                           fmtId(parentRel->dobj.name));
10853                                 }
10854                         }
10855
10856                         appendPQExpBuffer(q, "\n-- For binary upgrade, set relfrozenxid.\n");
10857                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
10858                                                           "SET relfrozenxid = '%u'\n"
10859                                                           "WHERE oid = ",
10860                                                           tbinfo->frozenxid);
10861                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10862                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10863                 }
10864
10865                 /* Loop dumping statistics and storage statements */
10866                 for (j = 0; j < tbinfo->numatts; j++)
10867                 {
10868                         /*
10869                          * Dump per-column statistics information. We only issue an ALTER
10870                          * TABLE statement if the attstattarget entry for this column is
10871                          * non-negative (i.e. it's not the default value)
10872                          */
10873                         if (tbinfo->attstattarget[j] >= 0 &&
10874                                 !tbinfo->attisdropped[j])
10875                         {
10876                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10877                                                                   fmtId(tbinfo->dobj.name));
10878                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
10879                                                                   fmtId(tbinfo->attnames[j]));
10880                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
10881                                                                   tbinfo->attstattarget[j]);
10882                         }
10883
10884                         /*
10885                          * Dump per-column storage information.  The statement is only
10886                          * dumped if the storage has been changed from the type's default.
10887                          */
10888                         if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
10889                         {
10890                                 switch (tbinfo->attstorage[j])
10891                                 {
10892                                         case 'p':
10893                                                 storage = "PLAIN";
10894                                                 break;
10895                                         case 'e':
10896                                                 storage = "EXTERNAL";
10897                                                 break;
10898                                         case 'm':
10899                                                 storage = "MAIN";
10900                                                 break;
10901                                         case 'x':
10902                                                 storage = "EXTENDED";
10903                                                 break;
10904                                         default:
10905                                                 storage = NULL;
10906                                 }
10907
10908                                 /*
10909                                  * Only dump the statement if it's a storage type we recognize
10910                                  */
10911                                 if (storage != NULL)
10912                                 {
10913                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10914                                                                           fmtId(tbinfo->dobj.name));
10915                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
10916                                                                           fmtId(tbinfo->attnames[j]));
10917                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
10918                                                                           storage);
10919                                 }
10920                         }
10921
10922                         /*
10923                          * Dump per-column attributes.
10924                          */
10925                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
10926                         {
10927                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10928                                                                   fmtId(tbinfo->dobj.name));
10929                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
10930                                                                   fmtId(tbinfo->attnames[j]));
10931                                 appendPQExpBuffer(q, "SET (%s);\n",
10932                                                                   tbinfo->attoptions[j]);
10933                         }
10934                 }
10935         }
10936
10937         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
10938                                  tbinfo->dobj.name,
10939                                  tbinfo->dobj.namespace->dobj.name,
10940                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
10941                                  tbinfo->rolname,
10942                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
10943                                  reltypename, SECTION_PRE_DATA,
10944                                  q->data, delq->data, NULL,
10945                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
10946                                  NULL, NULL);
10947
10948
10949         /* Dump Table Comments */
10950         dumpTableComment(fout, tbinfo, reltypename);
10951
10952         /* Dump comments on inlined table constraints */
10953         for (j = 0; j < tbinfo->ncheck; j++)
10954         {
10955                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
10956
10957                 if (constr->separate || !constr->conislocal)
10958                         continue;
10959
10960                 dumpTableConstraintComment(fout, constr);
10961         }
10962
10963         destroyPQExpBuffer(query);
10964         destroyPQExpBuffer(q);
10965         destroyPQExpBuffer(delq);
10966 }
10967
10968 /*
10969  * dumpAttrDef --- dump an attribute's default-value declaration
10970  */
10971 static void
10972 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
10973 {
10974         TableInfo  *tbinfo = adinfo->adtable;
10975         int                     adnum = adinfo->adnum;
10976         PQExpBuffer q;
10977         PQExpBuffer delq;
10978
10979         /* Only print it if "separate" mode is selected */
10980         if (!tbinfo->dobj.dump || !adinfo->separate || dataOnly)
10981                 return;
10982
10983         /* Don't print inherited defaults, either, except for binary upgrade */
10984         if (tbinfo->inhAttrDef[adnum - 1] && !binary_upgrade)
10985                 return;
10986
10987         q = createPQExpBuffer();
10988         delq = createPQExpBuffer();
10989
10990         appendPQExpBuffer(q, "ALTER TABLE %s ",
10991                                           fmtId(tbinfo->dobj.name));
10992         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
10993                                           fmtId(tbinfo->attnames[adnum - 1]),
10994                                           adinfo->adef_expr);
10995
10996         /*
10997          * DROP must be fully qualified in case same name appears in pg_catalog
10998          */
10999         appendPQExpBuffer(delq, "ALTER TABLE %s.",
11000                                           fmtId(tbinfo->dobj.namespace->dobj.name));
11001         appendPQExpBuffer(delq, "%s ",
11002                                           fmtId(tbinfo->dobj.name));
11003         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
11004                                           fmtId(tbinfo->attnames[adnum - 1]));
11005
11006         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
11007                                  tbinfo->attnames[adnum - 1],
11008                                  tbinfo->dobj.namespace->dobj.name,
11009                                  NULL,
11010                                  tbinfo->rolname,
11011                                  false, "DEFAULT", SECTION_PRE_DATA,
11012                                  q->data, delq->data, NULL,
11013                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
11014                                  NULL, NULL);
11015
11016         destroyPQExpBuffer(q);
11017         destroyPQExpBuffer(delq);
11018 }
11019
11020 /*
11021  * getAttrName: extract the correct name for an attribute
11022  *
11023  * The array tblInfo->attnames[] only provides names of user attributes;
11024  * if a system attribute number is supplied, we have to fake it.
11025  * We also do a little bit of bounds checking for safety's sake.
11026  */
11027 static const char *
11028 getAttrName(int attrnum, TableInfo *tblInfo)
11029 {
11030         if (attrnum > 0 && attrnum <= tblInfo->numatts)
11031                 return tblInfo->attnames[attrnum - 1];
11032         switch (attrnum)
11033         {
11034                 case SelfItemPointerAttributeNumber:
11035                         return "ctid";
11036                 case ObjectIdAttributeNumber:
11037                         return "oid";
11038                 case MinTransactionIdAttributeNumber:
11039                         return "xmin";
11040                 case MinCommandIdAttributeNumber:
11041                         return "cmin";
11042                 case MaxTransactionIdAttributeNumber:
11043                         return "xmax";
11044                 case MaxCommandIdAttributeNumber:
11045                         return "cmax";
11046                 case TableOidAttributeNumber:
11047                         return "tableoid";
11048         }
11049         write_msg(NULL, "invalid column number %d for table \"%s\"\n",
11050                           attrnum, tblInfo->dobj.name);
11051         exit_nicely();
11052         return NULL;                            /* keep compiler quiet */
11053 }
11054
11055 /*
11056  * dumpIndex
11057  *        write out to fout a user-defined index
11058  */
11059 static void
11060 dumpIndex(Archive *fout, IndxInfo *indxinfo)
11061 {
11062         TableInfo  *tbinfo = indxinfo->indextable;
11063         PQExpBuffer q;
11064         PQExpBuffer delq;
11065
11066         if (dataOnly)
11067                 return;
11068
11069         q = createPQExpBuffer();
11070         delq = createPQExpBuffer();
11071
11072         /*
11073          * If there's an associated constraint, don't dump the index per se, but
11074          * do dump any comment for it.  (This is safe because dependency ordering
11075          * will have ensured the constraint is emitted first.)
11076          */
11077         if (indxinfo->indexconstraint == 0)
11078         {
11079                 if (binary_upgrade)
11080                         binary_upgrade_set_relfilenodes(q, indxinfo->dobj.catId.oid, true);
11081
11082                 /* Plain secondary index */
11083                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
11084
11085                 /* If the index is clustered, we need to record that. */
11086                 if (indxinfo->indisclustered)
11087                 {
11088                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
11089                                                           fmtId(tbinfo->dobj.name));
11090                         appendPQExpBuffer(q, " ON %s;\n",
11091                                                           fmtId(indxinfo->dobj.name));
11092                 }
11093
11094                 /*
11095                  * DROP must be fully qualified in case same name appears in
11096                  * pg_catalog
11097                  */
11098                 appendPQExpBuffer(delq, "DROP INDEX %s.",
11099                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
11100                 appendPQExpBuffer(delq, "%s;\n",
11101                                                   fmtId(indxinfo->dobj.name));
11102
11103                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
11104                                          indxinfo->dobj.name,
11105                                          tbinfo->dobj.namespace->dobj.name,
11106                                          indxinfo->tablespace,
11107                                          tbinfo->rolname, false,
11108                                          "INDEX", SECTION_POST_DATA,
11109                                          q->data, delq->data, NULL,
11110                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
11111                                          NULL, NULL);
11112         }
11113
11114         /* Dump Index Comments */
11115         resetPQExpBuffer(q);
11116         appendPQExpBuffer(q, "INDEX %s",
11117                                           fmtId(indxinfo->dobj.name));
11118         dumpComment(fout, q->data,
11119                                 tbinfo->dobj.namespace->dobj.name,
11120                                 tbinfo->rolname,
11121                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
11122
11123         destroyPQExpBuffer(q);
11124         destroyPQExpBuffer(delq);
11125 }
11126
11127 /*
11128  * dumpConstraint
11129  *        write out to fout a user-defined constraint
11130  */
11131 static void
11132 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
11133 {
11134         TableInfo  *tbinfo = coninfo->contable;
11135         PQExpBuffer q;
11136         PQExpBuffer delq;
11137
11138         /* Skip if not to be dumped */
11139         if (!coninfo->dobj.dump || dataOnly)
11140                 return;
11141
11142         q = createPQExpBuffer();
11143         delq = createPQExpBuffer();
11144
11145         if (coninfo->contype == 'p' ||
11146                 coninfo->contype == 'u' ||
11147                 coninfo->contype == 'x')
11148         {
11149                 /* Index-related constraint */
11150                 IndxInfo   *indxinfo;
11151                 int                     k;
11152
11153                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
11154
11155                 if (indxinfo == NULL)
11156                 {
11157                         write_msg(NULL, "missing index for constraint \"%s\"\n",
11158                                           coninfo->dobj.name);
11159                         exit_nicely();
11160                 }
11161
11162                 if (binary_upgrade && !coninfo->condef)
11163                         binary_upgrade_set_relfilenodes(q, indxinfo->dobj.catId.oid, true);
11164
11165                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
11166                                                   fmtId(tbinfo->dobj.name));
11167                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
11168                                                   fmtId(coninfo->dobj.name));
11169
11170                 if (coninfo->condef)
11171                 {
11172                         /* pg_get_constraintdef should have provided everything */
11173                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
11174                 }
11175                 else
11176                 {
11177                         appendPQExpBuffer(q, "%s (",
11178                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
11179                         for (k = 0; k < indxinfo->indnkeys; k++)
11180                         {
11181                                 int                     indkey = (int) indxinfo->indkeys[k];
11182                                 const char *attname;
11183
11184                                 if (indkey == InvalidAttrNumber)
11185                                         break;
11186                                 attname = getAttrName(indkey, tbinfo);
11187
11188                                 appendPQExpBuffer(q, "%s%s",
11189                                                                   (k == 0) ? "" : ", ",
11190                                                                   fmtId(attname));
11191                         }
11192
11193                         appendPQExpBuffer(q, ")");
11194
11195                         if (indxinfo->options && strlen(indxinfo->options) > 0)
11196                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
11197
11198                         if (coninfo->condeferrable)
11199                         {
11200                                 appendPQExpBuffer(q, " DEFERRABLE");
11201                                 if (coninfo->condeferred)
11202                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
11203                         }
11204
11205                         appendPQExpBuffer(q, ";\n");
11206                 }
11207
11208                 /* If the index is clustered, we need to record that. */
11209                 if (indxinfo->indisclustered)
11210                 {
11211                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
11212                                                           fmtId(tbinfo->dobj.name));
11213                         appendPQExpBuffer(q, " ON %s;\n",
11214                                                           fmtId(indxinfo->dobj.name));
11215                 }
11216
11217                 /*
11218                  * DROP must be fully qualified in case same name appears in
11219                  * pg_catalog
11220                  */
11221                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
11222                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
11223                 appendPQExpBuffer(delq, "%s ",
11224                                                   fmtId(tbinfo->dobj.name));
11225                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11226                                                   fmtId(coninfo->dobj.name));
11227
11228                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11229                                          coninfo->dobj.name,
11230                                          tbinfo->dobj.namespace->dobj.name,
11231                                          indxinfo->tablespace,
11232                                          tbinfo->rolname, false,
11233                                          "CONSTRAINT", SECTION_POST_DATA,
11234                                          q->data, delq->data, NULL,
11235                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11236                                          NULL, NULL);
11237         }
11238         else if (coninfo->contype == 'f')
11239         {
11240                 /*
11241                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
11242                  * current table data is not processed
11243                  */
11244                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
11245                                                   fmtId(tbinfo->dobj.name));
11246                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
11247                                                   fmtId(coninfo->dobj.name),
11248                                                   coninfo->condef);
11249
11250                 /*
11251                  * DROP must be fully qualified in case same name appears in
11252                  * pg_catalog
11253                  */
11254                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
11255                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
11256                 appendPQExpBuffer(delq, "%s ",
11257                                                   fmtId(tbinfo->dobj.name));
11258                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11259                                                   fmtId(coninfo->dobj.name));
11260
11261                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11262                                          coninfo->dobj.name,
11263                                          tbinfo->dobj.namespace->dobj.name,
11264                                          NULL,
11265                                          tbinfo->rolname, false,
11266                                          "FK CONSTRAINT", SECTION_POST_DATA,
11267                                          q->data, delq->data, NULL,
11268                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11269                                          NULL, NULL);
11270         }
11271         else if (coninfo->contype == 'c' && tbinfo)
11272         {
11273                 /* CHECK constraint on a table */
11274
11275                 /* Ignore if not to be dumped separately */
11276                 if (coninfo->separate)
11277                 {
11278                         /* not ONLY since we want it to propagate to children */
11279                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
11280                                                           fmtId(tbinfo->dobj.name));
11281                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
11282                                                           fmtId(coninfo->dobj.name),
11283                                                           coninfo->condef);
11284
11285                         /*
11286                          * DROP must be fully qualified in case same name appears in
11287                          * pg_catalog
11288                          */
11289                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
11290                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
11291                         appendPQExpBuffer(delq, "%s ",
11292                                                           fmtId(tbinfo->dobj.name));
11293                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11294                                                           fmtId(coninfo->dobj.name));
11295
11296                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11297                                                  coninfo->dobj.name,
11298                                                  tbinfo->dobj.namespace->dobj.name,
11299                                                  NULL,
11300                                                  tbinfo->rolname, false,
11301                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
11302                                                  q->data, delq->data, NULL,
11303                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11304                                                  NULL, NULL);
11305                 }
11306         }
11307         else if (coninfo->contype == 'c' && tbinfo == NULL)
11308         {
11309                 /* CHECK constraint on a domain */
11310                 TypeInfo   *tyinfo = coninfo->condomain;
11311
11312                 /* Ignore if not to be dumped separately */
11313                 if (coninfo->separate)
11314                 {
11315                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
11316                                                           fmtId(tyinfo->dobj.name));
11317                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
11318                                                           fmtId(coninfo->dobj.name),
11319                                                           coninfo->condef);
11320
11321                         /*
11322                          * DROP must be fully qualified in case same name appears in
11323                          * pg_catalog
11324                          */
11325                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
11326                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
11327                         appendPQExpBuffer(delq, "%s ",
11328                                                           fmtId(tyinfo->dobj.name));
11329                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11330                                                           fmtId(coninfo->dobj.name));
11331
11332                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11333                                                  coninfo->dobj.name,
11334                                                  tyinfo->dobj.namespace->dobj.name,
11335                                                  NULL,
11336                                                  tyinfo->rolname, false,
11337                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
11338                                                  q->data, delq->data, NULL,
11339                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11340                                                  NULL, NULL);
11341                 }
11342         }
11343         else
11344         {
11345                 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
11346                 exit_nicely();
11347         }
11348
11349         /* Dump Constraint Comments --- only works for table constraints */
11350         if (tbinfo && coninfo->separate)
11351                 dumpTableConstraintComment(fout, coninfo);
11352
11353         destroyPQExpBuffer(q);
11354         destroyPQExpBuffer(delq);
11355 }
11356
11357 /*
11358  * dumpTableConstraintComment --- dump a constraint's comment if any
11359  *
11360  * This is split out because we need the function in two different places
11361  * depending on whether the constraint is dumped as part of CREATE TABLE
11362  * or as a separate ALTER command.
11363  */
11364 static void
11365 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
11366 {
11367         TableInfo  *tbinfo = coninfo->contable;
11368         PQExpBuffer q = createPQExpBuffer();
11369
11370         appendPQExpBuffer(q, "CONSTRAINT %s ",
11371                                           fmtId(coninfo->dobj.name));
11372         appendPQExpBuffer(q, "ON %s",
11373                                           fmtId(tbinfo->dobj.name));
11374         dumpComment(fout, q->data,
11375                                 tbinfo->dobj.namespace->dobj.name,
11376                                 tbinfo->rolname,
11377                                 coninfo->dobj.catId, 0,
11378                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
11379
11380         destroyPQExpBuffer(q);
11381 }
11382
11383 /*
11384  * findLastBuiltInOid -
11385  * find the last built in oid
11386  *
11387  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
11388  * pg_database entry for the current database
11389  */
11390 static Oid
11391 findLastBuiltinOid_V71(const char *dbname)
11392 {
11393         PGresult   *res;
11394         int                     ntups;
11395         Oid                     last_oid;
11396         PQExpBuffer query = createPQExpBuffer();
11397
11398         resetPQExpBuffer(query);
11399         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
11400         appendStringLiteralAH(query, dbname, g_fout);
11401
11402         res = PQexec(g_conn, query->data);
11403         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11404
11405         ntups = PQntuples(res);
11406         if (ntups < 1)
11407         {
11408                 write_msg(NULL, "missing pg_database entry for this database\n");
11409                 exit_nicely();
11410         }
11411         if (ntups > 1)
11412         {
11413                 write_msg(NULL, "found more than one pg_database entry for this database\n");
11414                 exit_nicely();
11415         }
11416         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
11417         PQclear(res);
11418         destroyPQExpBuffer(query);
11419         return last_oid;
11420 }
11421
11422 /*
11423  * findLastBuiltInOid -
11424  * find the last built in oid
11425  *
11426  * For 7.0, we do this by assuming that the last thing that initdb does is to
11427  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
11428  * initdb won't be changing anymore, it'll do.
11429  */
11430 static Oid
11431 findLastBuiltinOid_V70(void)
11432 {
11433         PGresult   *res;
11434         int                     ntups;
11435         int                     last_oid;
11436
11437         res = PQexec(g_conn,
11438                                  "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
11439         check_sql_result(res, g_conn,
11440                                          "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
11441                                          PGRES_TUPLES_OK);
11442         ntups = PQntuples(res);
11443         if (ntups < 1)
11444         {
11445                 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
11446                 exit_nicely();
11447         }
11448         if (ntups > 1)
11449         {
11450                 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
11451                 exit_nicely();
11452         }
11453         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
11454         PQclear(res);
11455         return last_oid;
11456 }
11457
11458 static void
11459 dumpSequence(Archive *fout, TableInfo *tbinfo)
11460 {
11461         PGresult   *res;
11462         char       *startv,
11463                            *last,
11464                            *incby,
11465                            *maxv = NULL,
11466                            *minv = NULL,
11467                            *cache;
11468         char            bufm[100],
11469                                 bufx[100];
11470         bool            cycled,
11471                                 called;
11472         PQExpBuffer query = createPQExpBuffer();
11473         PQExpBuffer delqry = createPQExpBuffer();
11474
11475         /* Make sure we are in proper schema */
11476         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
11477
11478         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
11479         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
11480
11481         if (g_fout->remoteVersion >= 80400)
11482         {
11483                 appendPQExpBuffer(query,
11484                                                   "SELECT sequence_name, "
11485                                                   "start_value, last_value, increment_by, "
11486                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
11487                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
11488                                                   "     ELSE max_value "
11489                                                   "END AS max_value, "
11490                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
11491                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
11492                                                   "     ELSE min_value "
11493                                                   "END AS min_value, "
11494                                                   "cache_value, is_cycled, is_called from %s",
11495                                                   bufx, bufm,
11496                                                   fmtId(tbinfo->dobj.name));
11497         }
11498         else
11499         {
11500                 appendPQExpBuffer(query,
11501                                                   "SELECT sequence_name, "
11502                                                   "0 AS start_value, last_value, increment_by, "
11503                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
11504                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
11505                                                   "     ELSE max_value "
11506                                                   "END AS max_value, "
11507                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
11508                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
11509                                                   "     ELSE min_value "
11510                                                   "END AS min_value, "
11511                                                   "cache_value, is_cycled, is_called from %s",
11512                                                   bufx, bufm,
11513                                                   fmtId(tbinfo->dobj.name));
11514         }
11515
11516         res = PQexec(g_conn, query->data);
11517         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11518
11519         if (PQntuples(res) != 1)
11520         {
11521                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
11522                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
11523                                                                  PQntuples(res)),
11524                                   tbinfo->dobj.name, PQntuples(res));
11525                 exit_nicely();
11526         }
11527
11528         /* Disable this check: it fails if sequence has been renamed */
11529 #ifdef NOT_USED
11530         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
11531         {
11532                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
11533                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
11534                 exit_nicely();
11535         }
11536 #endif
11537
11538         startv = PQgetvalue(res, 0, 1);
11539         last = PQgetvalue(res, 0, 2);
11540         incby = PQgetvalue(res, 0, 3);
11541         if (!PQgetisnull(res, 0, 4))
11542                 maxv = PQgetvalue(res, 0, 4);
11543         if (!PQgetisnull(res, 0, 5))
11544                 minv = PQgetvalue(res, 0, 5);
11545         cache = PQgetvalue(res, 0, 6);
11546         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
11547         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
11548
11549         /*
11550          * The logic we use for restoring sequences is as follows:
11551          *
11552          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
11553          * last_val for start if called is false, else use min_val for start_val).
11554          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
11555          * BY command for it.
11556          *
11557          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
11558          */
11559         if (!dataOnly)
11560         {
11561                 resetPQExpBuffer(delqry);
11562
11563                 /*
11564                  * DROP must be fully qualified in case same name appears in
11565                  * pg_catalog
11566                  */
11567                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
11568                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
11569                 appendPQExpBuffer(delqry, "%s;\n",
11570                                                   fmtId(tbinfo->dobj.name));
11571
11572                 resetPQExpBuffer(query);
11573
11574                 if (binary_upgrade)
11575                 {
11576                         binary_upgrade_set_relfilenodes(query, tbinfo->dobj.catId.oid, false);
11577                         binary_upgrade_set_type_oids_by_rel_oid(query, tbinfo->dobj.catId.oid);
11578                 }
11579
11580                 appendPQExpBuffer(query,
11581                                                   "CREATE SEQUENCE %s\n",
11582                                                   fmtId(tbinfo->dobj.name));
11583
11584                 if (g_fout->remoteVersion >= 80400)
11585                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
11586                 else
11587                 {
11588                         /*
11589                          * Versions before 8.4 did not remember the true start value.  If
11590                          * is_called is false then the sequence has never been incremented
11591                          * so we can use last_val.      Otherwise punt and let it default.
11592                          */
11593                         if (!called)
11594                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
11595                 }
11596
11597                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
11598
11599                 if (minv)
11600                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
11601                 else
11602                         appendPQExpBuffer(query, "    NO MINVALUE\n");
11603
11604                 if (maxv)
11605                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
11606                 else
11607                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
11608
11609                 appendPQExpBuffer(query,
11610                                                   "    CACHE %s%s",
11611                                                   cache, (cycled ? "\n    CYCLE" : ""));
11612
11613                 appendPQExpBuffer(query, ";\n");
11614
11615                 /* binary_upgrade:      no need to clear TOAST table oid */
11616
11617                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
11618                                          tbinfo->dobj.name,
11619                                          tbinfo->dobj.namespace->dobj.name,
11620                                          NULL,
11621                                          tbinfo->rolname,
11622                                          false, "SEQUENCE", SECTION_PRE_DATA,
11623                                          query->data, delqry->data, NULL,
11624                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
11625                                          NULL, NULL);
11626
11627                 /*
11628                  * If the sequence is owned by a table column, emit the ALTER for it
11629                  * as a separate TOC entry immediately following the sequence's own
11630                  * entry.  It's OK to do this rather than using full sorting logic,
11631                  * because the dependency that tells us it's owned will have forced
11632                  * the table to be created first.  We can't just include the ALTER in
11633                  * the TOC entry because it will fail if we haven't reassigned the
11634                  * sequence owner to match the table's owner.
11635                  *
11636                  * We need not schema-qualify the table reference because both
11637                  * sequence and table must be in the same schema.
11638                  */
11639                 if (OidIsValid(tbinfo->owning_tab))
11640                 {
11641                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
11642
11643                         if (owning_tab && owning_tab->dobj.dump)
11644                         {
11645                                 resetPQExpBuffer(query);
11646                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
11647                                                                   fmtId(tbinfo->dobj.name));
11648                                 appendPQExpBuffer(query, " OWNED BY %s",
11649                                                                   fmtId(owning_tab->dobj.name));
11650                                 appendPQExpBuffer(query, ".%s;\n",
11651                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
11652
11653                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11654                                                          tbinfo->dobj.name,
11655                                                          tbinfo->dobj.namespace->dobj.name,
11656                                                          NULL,
11657                                                          tbinfo->rolname,
11658                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
11659                                                          query->data, "", NULL,
11660                                                          &(tbinfo->dobj.dumpId), 1,
11661                                                          NULL, NULL);
11662                         }
11663                 }
11664
11665                 /* Dump Sequence Comments */
11666                 resetPQExpBuffer(query);
11667                 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
11668                 dumpComment(fout, query->data,
11669                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
11670                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
11671         }
11672
11673         if (!schemaOnly)
11674         {
11675                 resetPQExpBuffer(query);
11676                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
11677                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
11678                 appendPQExpBuffer(query, ", %s, %s);\n",
11679                                                   last, (called ? "true" : "false"));
11680
11681                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11682                                          tbinfo->dobj.name,
11683                                          tbinfo->dobj.namespace->dobj.name,
11684                                          NULL,
11685                                          tbinfo->rolname,
11686                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
11687                                          query->data, "", NULL,
11688                                          &(tbinfo->dobj.dumpId), 1,
11689                                          NULL, NULL);
11690         }
11691
11692         PQclear(res);
11693
11694         destroyPQExpBuffer(query);
11695         destroyPQExpBuffer(delqry);
11696 }
11697
11698 static void
11699 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
11700 {
11701         TableInfo  *tbinfo = tginfo->tgtable;
11702         PQExpBuffer query;
11703         PQExpBuffer delqry;
11704         char       *tgargs;
11705         size_t          lentgargs;
11706         const char *p;
11707         int                     findx;
11708
11709         if (dataOnly)
11710                 return;
11711
11712         query = createPQExpBuffer();
11713         delqry = createPQExpBuffer();
11714
11715         /*
11716          * DROP must be fully qualified in case same name appears in pg_catalog
11717          */
11718         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
11719                                           fmtId(tginfo->dobj.name));
11720         appendPQExpBuffer(delqry, "ON %s.",
11721                                           fmtId(tbinfo->dobj.namespace->dobj.name));
11722         appendPQExpBuffer(delqry, "%s;\n",
11723                                           fmtId(tbinfo->dobj.name));
11724
11725         if (tginfo->tgdef)
11726         {
11727                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
11728         }
11729         else
11730         {
11731                 if (tginfo->tgisconstraint)
11732                 {
11733                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
11734                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
11735                 }
11736                 else
11737                 {
11738                         appendPQExpBuffer(query, "CREATE TRIGGER ");
11739                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
11740                 }
11741                 appendPQExpBuffer(query, "\n    ");
11742
11743                 /* Trigger type */
11744                 findx = 0;
11745                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
11746                         appendPQExpBuffer(query, "BEFORE");
11747                 else
11748                         appendPQExpBuffer(query, "AFTER");
11749                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
11750                 {
11751                         appendPQExpBuffer(query, " INSERT");
11752                         findx++;
11753                 }
11754                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
11755                 {
11756                         if (findx > 0)
11757                                 appendPQExpBuffer(query, " OR DELETE");
11758                         else
11759                                 appendPQExpBuffer(query, " DELETE");
11760                         findx++;
11761                 }
11762                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
11763                 {
11764                         if (findx > 0)
11765                                 appendPQExpBuffer(query, " OR UPDATE");
11766                         else
11767                                 appendPQExpBuffer(query, " UPDATE");
11768                         findx++;
11769                 }
11770                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
11771                 {
11772                         if (findx > 0)
11773                                 appendPQExpBuffer(query, " OR TRUNCATE");
11774                         else
11775                                 appendPQExpBuffer(query, " TRUNCATE");
11776                         findx++;
11777                 }
11778                 appendPQExpBuffer(query, " ON %s\n",
11779                                                   fmtId(tbinfo->dobj.name));
11780
11781                 if (tginfo->tgisconstraint)
11782                 {
11783                         if (OidIsValid(tginfo->tgconstrrelid))
11784                         {
11785                                 /* If we are using regclass, name is already quoted */
11786                                 if (g_fout->remoteVersion >= 70300)
11787                                         appendPQExpBuffer(query, "    FROM %s\n    ",
11788                                                                           tginfo->tgconstrrelname);
11789                                 else
11790                                         appendPQExpBuffer(query, "    FROM %s\n    ",
11791                                                                           fmtId(tginfo->tgconstrrelname));
11792                         }
11793                         if (!tginfo->tgdeferrable)
11794                                 appendPQExpBuffer(query, "NOT ");
11795                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
11796                         if (tginfo->tginitdeferred)
11797                                 appendPQExpBuffer(query, "DEFERRED\n");
11798                         else
11799                                 appendPQExpBuffer(query, "IMMEDIATE\n");
11800                 }
11801
11802                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
11803                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
11804                 else
11805                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
11806
11807                 /* In 7.3, result of regproc is already quoted */
11808                 if (g_fout->remoteVersion >= 70300)
11809                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
11810                                                           tginfo->tgfname);
11811                 else
11812                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
11813                                                           fmtId(tginfo->tgfname));
11814
11815                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
11816                                                                                   &lentgargs);
11817                 p = tgargs;
11818                 for (findx = 0; findx < tginfo->tgnargs; findx++)
11819                 {
11820                         /* find the embedded null that terminates this trigger argument */
11821                         size_t          tlen = strlen(p);
11822
11823                         if (p + tlen >= tgargs + lentgargs)
11824                         {
11825                                 /* hm, not found before end of bytea value... */
11826                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
11827                                                   tginfo->tgargs,
11828                                                   tginfo->dobj.name,
11829                                                   tbinfo->dobj.name);
11830                                 exit_nicely();
11831                         }
11832
11833                         if (findx > 0)
11834                                 appendPQExpBuffer(query, ", ");
11835                         appendStringLiteralAH(query, p, fout);
11836                         p += tlen + 1;
11837                 }
11838                 free(tgargs);
11839                 appendPQExpBuffer(query, ");\n");
11840         }
11841
11842         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
11843         {
11844                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
11845                                                   fmtId(tbinfo->dobj.name));
11846                 switch (tginfo->tgenabled)
11847                 {
11848                         case 'D':
11849                         case 'f':
11850                                 appendPQExpBuffer(query, "DISABLE");
11851                                 break;
11852                         case 'A':
11853                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
11854                                 break;
11855                         case 'R':
11856                                 appendPQExpBuffer(query, "ENABLE REPLICA");
11857                                 break;
11858                         default:
11859                                 appendPQExpBuffer(query, "ENABLE");
11860                                 break;
11861                 }
11862                 appendPQExpBuffer(query, " TRIGGER %s;\n",
11863                                                   fmtId(tginfo->dobj.name));
11864         }
11865
11866         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
11867                                  tginfo->dobj.name,
11868                                  tbinfo->dobj.namespace->dobj.name,
11869                                  NULL,
11870                                  tbinfo->rolname, false,
11871                                  "TRIGGER", SECTION_POST_DATA,
11872                                  query->data, delqry->data, NULL,
11873                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
11874                                  NULL, NULL);
11875
11876         resetPQExpBuffer(query);
11877         appendPQExpBuffer(query, "TRIGGER %s ",
11878                                           fmtId(tginfo->dobj.name));
11879         appendPQExpBuffer(query, "ON %s",
11880                                           fmtId(tbinfo->dobj.name));
11881
11882         dumpComment(fout, query->data,
11883                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
11884                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
11885
11886         destroyPQExpBuffer(query);
11887         destroyPQExpBuffer(delqry);
11888 }
11889
11890 /*
11891  * dumpRule
11892  *              Dump a rule
11893  */
11894 static void
11895 dumpRule(Archive *fout, RuleInfo *rinfo)
11896 {
11897         TableInfo  *tbinfo = rinfo->ruletable;
11898         PQExpBuffer query;
11899         PQExpBuffer cmd;
11900         PQExpBuffer delcmd;
11901         PGresult   *res;
11902
11903         /* Skip if not to be dumped */
11904         if (!rinfo->dobj.dump || dataOnly)
11905                 return;
11906
11907         /*
11908          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
11909          * we do not want to dump it as a separate object.
11910          */
11911         if (!rinfo->separate)
11912                 return;
11913
11914         /*
11915          * Make sure we are in proper schema.
11916          */
11917         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
11918
11919         query = createPQExpBuffer();
11920         cmd = createPQExpBuffer();
11921         delcmd = createPQExpBuffer();
11922
11923         if (g_fout->remoteVersion >= 70300)
11924         {
11925                 appendPQExpBuffer(query,
11926                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
11927                                                   rinfo->dobj.catId.oid);
11928         }
11929         else
11930         {
11931                 /* Rule name was unique before 7.3 ... */
11932                 appendPQExpBuffer(query,
11933                                                   "SELECT pg_get_ruledef('%s') AS definition",
11934                                                   rinfo->dobj.name);
11935         }
11936
11937         res = PQexec(g_conn, query->data);
11938         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11939
11940         if (PQntuples(res) != 1)
11941         {
11942                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
11943                                   rinfo->dobj.name, tbinfo->dobj.name);
11944                 exit_nicely();
11945         }
11946
11947         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
11948
11949         /*
11950          * Add the command to alter the rules replication firing semantics if it
11951          * differs from the default.
11952          */
11953         if (rinfo->ev_enabled != 'O')
11954         {
11955                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
11956                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
11957                 appendPQExpBuffer(cmd, "%s ",
11958                                                   fmtId(tbinfo->dobj.name));
11959                 switch (rinfo->ev_enabled)
11960                 {
11961                         case 'A':
11962                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
11963                                                                   fmtId(rinfo->dobj.name));
11964                                 break;
11965                         case 'R':
11966                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
11967                                                                   fmtId(rinfo->dobj.name));
11968                                 break;
11969                         case 'D':
11970                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
11971                                                                   fmtId(rinfo->dobj.name));
11972                                 break;
11973                 }
11974         }
11975
11976         /*
11977          * DROP must be fully qualified in case same name appears in pg_catalog
11978          */
11979         appendPQExpBuffer(delcmd, "DROP RULE %s ",
11980                                           fmtId(rinfo->dobj.name));
11981         appendPQExpBuffer(delcmd, "ON %s.",
11982                                           fmtId(tbinfo->dobj.namespace->dobj.name));
11983         appendPQExpBuffer(delcmd, "%s;\n",
11984                                           fmtId(tbinfo->dobj.name));
11985
11986         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
11987                                  rinfo->dobj.name,
11988                                  tbinfo->dobj.namespace->dobj.name,
11989                                  NULL,
11990                                  tbinfo->rolname, false,
11991                                  "RULE", SECTION_POST_DATA,
11992                                  cmd->data, delcmd->data, NULL,
11993                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
11994                                  NULL, NULL);
11995
11996         /* Dump rule comments */
11997         resetPQExpBuffer(query);
11998         appendPQExpBuffer(query, "RULE %s",
11999                                           fmtId(rinfo->dobj.name));
12000         appendPQExpBuffer(query, " ON %s",
12001                                           fmtId(tbinfo->dobj.name));
12002         dumpComment(fout, query->data,
12003                                 tbinfo->dobj.namespace->dobj.name,
12004                                 tbinfo->rolname,
12005                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
12006
12007         PQclear(res);
12008
12009         destroyPQExpBuffer(query);
12010         destroyPQExpBuffer(cmd);
12011         destroyPQExpBuffer(delcmd);
12012 }
12013
12014 /*
12015  * getDependencies --- obtain available dependency data
12016  */
12017 static void
12018 getDependencies(void)
12019 {
12020         PQExpBuffer query;
12021         PGresult   *res;
12022         int                     ntups,
12023                                 i;
12024         int                     i_classid,
12025                                 i_objid,
12026                                 i_refclassid,
12027                                 i_refobjid,
12028                                 i_deptype;
12029         DumpableObject *dobj,
12030                            *refdobj;
12031
12032         /* No dependency info available before 7.3 */
12033         if (g_fout->remoteVersion < 70300)
12034                 return;
12035
12036         if (g_verbose)
12037                 write_msg(NULL, "reading dependency data\n");
12038
12039         /* Make sure we are in proper schema */
12040         selectSourceSchema("pg_catalog");
12041
12042         query = createPQExpBuffer();
12043
12044         appendPQExpBuffer(query, "SELECT "
12045                                           "classid, objid, refclassid, refobjid, deptype "
12046                                           "FROM pg_depend "
12047                                           "WHERE deptype != 'p' "
12048                                           "ORDER BY 1,2");
12049
12050         res = PQexec(g_conn, query->data);
12051         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12052
12053         ntups = PQntuples(res);
12054
12055         i_classid = PQfnumber(res, "classid");
12056         i_objid = PQfnumber(res, "objid");
12057         i_refclassid = PQfnumber(res, "refclassid");
12058         i_refobjid = PQfnumber(res, "refobjid");
12059         i_deptype = PQfnumber(res, "deptype");
12060
12061         /*
12062          * Since we ordered the SELECT by referencing ID, we can expect that
12063          * multiple entries for the same object will appear together; this saves
12064          * on searches.
12065          */
12066         dobj = NULL;
12067
12068         for (i = 0; i < ntups; i++)
12069         {
12070                 CatalogId       objId;
12071                 CatalogId       refobjId;
12072                 char            deptype;
12073
12074                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
12075                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
12076                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
12077                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
12078                 deptype = *(PQgetvalue(res, i, i_deptype));
12079
12080                 if (dobj == NULL ||
12081                         dobj->catId.tableoid != objId.tableoid ||
12082                         dobj->catId.oid != objId.oid)
12083                         dobj = findObjectByCatalogId(objId);
12084
12085                 /*
12086                  * Failure to find objects mentioned in pg_depend is not unexpected,
12087                  * since for example we don't collect info about TOAST tables.
12088                  */
12089                 if (dobj == NULL)
12090                 {
12091 #ifdef NOT_USED
12092                         fprintf(stderr, "no referencing object %u %u\n",
12093                                         objId.tableoid, objId.oid);
12094 #endif
12095                         continue;
12096                 }
12097
12098                 refdobj = findObjectByCatalogId(refobjId);
12099
12100                 if (refdobj == NULL)
12101                 {
12102 #ifdef NOT_USED
12103                         fprintf(stderr, "no referenced object %u %u\n",
12104                                         refobjId.tableoid, refobjId.oid);
12105 #endif
12106                         continue;
12107                 }
12108
12109                 /*
12110                  * Ordinarily, table rowtypes have implicit dependencies on their
12111                  * tables.      However, for a composite type the implicit dependency goes
12112                  * the other way in pg_depend; which is the right thing for DROP but
12113                  * it doesn't produce the dependency ordering we need. So in that one
12114                  * case, we reverse the direction of the dependency.
12115                  */
12116                 if (deptype == 'i' &&
12117                         dobj->objType == DO_TABLE &&
12118                         refdobj->objType == DO_TYPE)
12119                         addObjectDependency(refdobj, dobj->dumpId);
12120                 else
12121                         /* normal case */
12122                         addObjectDependency(dobj, refdobj->dumpId);
12123         }
12124
12125         PQclear(res);
12126
12127         destroyPQExpBuffer(query);
12128 }
12129
12130
12131 /*
12132  * selectSourceSchema - make the specified schema the active search path
12133  * in the source database.
12134  *
12135  * NB: pg_catalog is explicitly searched after the specified schema;
12136  * so user names are only qualified if they are cross-schema references,
12137  * and system names are only qualified if they conflict with a user name
12138  * in the current schema.
12139  *
12140  * Whenever the selected schema is not pg_catalog, be careful to qualify
12141  * references to system catalogs and types in our emitted commands!
12142  */
12143 static void
12144 selectSourceSchema(const char *schemaName)
12145 {
12146         static char *curSchemaName = NULL;
12147         PQExpBuffer query;
12148
12149         /* Not relevant if fetching from pre-7.3 DB */
12150         if (g_fout->remoteVersion < 70300)
12151                 return;
12152         /* Ignore null schema names */
12153         if (schemaName == NULL || *schemaName == '\0')
12154                 return;
12155         /* Optimize away repeated selection of same schema */
12156         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
12157                 return;
12158
12159         query = createPQExpBuffer();
12160         appendPQExpBuffer(query, "SET search_path = %s",
12161                                           fmtId(schemaName));
12162         if (strcmp(schemaName, "pg_catalog") != 0)
12163                 appendPQExpBuffer(query, ", pg_catalog");
12164
12165         do_sql_command(g_conn, query->data);
12166
12167         destroyPQExpBuffer(query);
12168         if (curSchemaName)
12169                 free(curSchemaName);
12170         curSchemaName = strdup(schemaName);
12171 }
12172
12173 /*
12174  * getFormattedTypeName - retrieve a nicely-formatted type name for the
12175  * given type name.
12176  *
12177  * NB: in 7.3 and up the result may depend on the currently-selected
12178  * schema; this is why we don't try to cache the names.
12179  */
12180 static char *
12181 getFormattedTypeName(Oid oid, OidOptions opts)
12182 {
12183         char       *result;
12184         PQExpBuffer query;
12185         PGresult   *res;
12186         int                     ntups;
12187
12188         if (oid == 0)
12189         {
12190                 if ((opts & zeroAsOpaque) != 0)
12191                         return strdup(g_opaque_type);
12192                 else if ((opts & zeroAsAny) != 0)
12193                         return strdup("'any'");
12194                 else if ((opts & zeroAsStar) != 0)
12195                         return strdup("*");
12196                 else if ((opts & zeroAsNone) != 0)
12197                         return strdup("NONE");
12198         }
12199
12200         query = createPQExpBuffer();
12201         if (g_fout->remoteVersion >= 70300)
12202         {
12203                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
12204                                                   oid);
12205         }
12206         else if (g_fout->remoteVersion >= 70100)
12207         {
12208                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
12209                                                   oid);
12210         }
12211         else
12212         {
12213                 appendPQExpBuffer(query, "SELECT typname "
12214                                                   "FROM pg_type "
12215                                                   "WHERE oid = '%u'::oid",
12216                                                   oid);
12217         }
12218
12219         res = PQexec(g_conn, query->data);
12220         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12221
12222         /* Expecting a single result only */
12223         ntups = PQntuples(res);
12224         if (ntups != 1)
12225         {
12226                 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
12227                                                            "query returned %d rows instead of one: %s\n",
12228                                                                  ntups),
12229                                   ntups, query->data);
12230                 exit_nicely();
12231         }
12232
12233         if (g_fout->remoteVersion >= 70100)
12234         {
12235                 /* already quoted */
12236                 result = strdup(PQgetvalue(res, 0, 0));
12237         }
12238         else
12239         {
12240                 /* may need to quote it */
12241                 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
12242         }
12243
12244         PQclear(res);
12245         destroyPQExpBuffer(query);
12246
12247         return result;
12248 }
12249
12250 /*
12251  * myFormatType --- local implementation of format_type for use with 7.0.
12252  */
12253 static char *
12254 myFormatType(const char *typname, int32 typmod)
12255 {
12256         char       *result;
12257         bool            isarray = false;
12258         PQExpBuffer buf = createPQExpBuffer();
12259
12260         /* Handle array types */
12261         if (typname[0] == '_')
12262         {
12263                 isarray = true;
12264                 typname++;
12265         }
12266
12267         /* Show lengths on bpchar and varchar */
12268         if (!strcmp(typname, "bpchar"))
12269         {
12270                 int                     len = (typmod - VARHDRSZ);
12271
12272                 appendPQExpBuffer(buf, "character");
12273                 if (len > 1)
12274                         appendPQExpBuffer(buf, "(%d)",
12275                                                           typmod - VARHDRSZ);
12276         }
12277         else if (!strcmp(typname, "varchar"))
12278         {
12279                 appendPQExpBuffer(buf, "character varying");
12280                 if (typmod != -1)
12281                         appendPQExpBuffer(buf, "(%d)",
12282                                                           typmod - VARHDRSZ);
12283         }
12284         else if (!strcmp(typname, "numeric"))
12285         {
12286                 appendPQExpBuffer(buf, "numeric");
12287                 if (typmod != -1)
12288                 {
12289                         int32           tmp_typmod;
12290                         int                     precision;
12291                         int                     scale;
12292
12293                         tmp_typmod = typmod - VARHDRSZ;
12294                         precision = (tmp_typmod >> 16) & 0xffff;
12295                         scale = tmp_typmod & 0xffff;
12296                         appendPQExpBuffer(buf, "(%d,%d)",
12297                                                           precision, scale);
12298                 }
12299         }
12300
12301         /*
12302          * char is an internal single-byte data type; Let's make sure we force it
12303          * through with quotes. - thomas 1998-12-13
12304          */
12305         else if (strcmp(typname, "char") == 0)
12306                 appendPQExpBuffer(buf, "\"char\"");
12307         else
12308                 appendPQExpBuffer(buf, "%s", fmtId(typname));
12309
12310         /* Append array qualifier for array types */
12311         if (isarray)
12312                 appendPQExpBuffer(buf, "[]");
12313
12314         result = strdup(buf->data);
12315         destroyPQExpBuffer(buf);
12316
12317         return result;
12318 }
12319
12320 /*
12321  * fmtQualifiedId - convert a qualified name to the proper format for
12322  * the source database.
12323  *
12324  * Like fmtId, use the result before calling again.
12325  */
12326 static const char *
12327 fmtQualifiedId(const char *schema, const char *id)
12328 {
12329         static PQExpBuffer id_return = NULL;
12330
12331         if (id_return)                          /* first time through? */
12332                 resetPQExpBuffer(id_return);
12333         else
12334                 id_return = createPQExpBuffer();
12335
12336         /* Suppress schema name if fetching from pre-7.3 DB */
12337         if (g_fout->remoteVersion >= 70300 && schema && *schema)
12338         {
12339                 appendPQExpBuffer(id_return, "%s.",
12340                                                   fmtId(schema));
12341         }
12342         appendPQExpBuffer(id_return, "%s",
12343                                           fmtId(id));
12344
12345         return id_return->data;
12346 }
12347
12348 /*
12349  * Return a column list clause for the given relation.
12350  *
12351  * Special case: if there are no undropped columns in the relation, return
12352  * "", not an invalid "()" column list.
12353  */
12354 static const char *
12355 fmtCopyColumnList(const TableInfo *ti)
12356 {
12357         static PQExpBuffer q = NULL;
12358         int                     numatts = ti->numatts;
12359         char      **attnames = ti->attnames;
12360         bool       *attisdropped = ti->attisdropped;
12361         bool            needComma;
12362         int                     i;
12363
12364         if (q)                                          /* first time through? */
12365                 resetPQExpBuffer(q);
12366         else
12367                 q = createPQExpBuffer();
12368
12369         appendPQExpBuffer(q, "(");
12370         needComma = false;
12371         for (i = 0; i < numatts; i++)
12372         {
12373                 if (attisdropped[i])
12374                         continue;
12375                 if (needComma)
12376                         appendPQExpBuffer(q, ", ");
12377                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
12378                 needComma = true;
12379         }
12380
12381         if (!needComma)
12382                 return "";                              /* no undropped columns */
12383
12384         appendPQExpBuffer(q, ")");
12385         return q->data;
12386 }
12387
12388 /*
12389  * Convenience subroutine to execute a SQL command and check for
12390  * COMMAND_OK status.
12391  */
12392 static void
12393 do_sql_command(PGconn *conn, const char *query)
12394 {
12395         PGresult   *res;
12396
12397         res = PQexec(conn, query);
12398         check_sql_result(res, conn, query, PGRES_COMMAND_OK);
12399         PQclear(res);
12400 }
12401
12402 /*
12403  * Convenience subroutine to verify a SQL command succeeded,
12404  * and exit with a useful error message if not.
12405  */
12406 static void
12407 check_sql_result(PGresult *res, PGconn *conn, const char *query,
12408                                  ExecStatusType expected)
12409 {
12410         const char *err;
12411
12412         if (res && PQresultStatus(res) == expected)
12413                 return;                                 /* A-OK */
12414
12415         write_msg(NULL, "SQL command failed\n");
12416         if (res)
12417                 err = PQresultErrorMessage(res);
12418         else
12419                 err = PQerrorMessage(conn);
12420         write_msg(NULL, "Error message from server: %s", err);
12421         write_msg(NULL, "The command was: %s\n", query);
12422         exit_nicely();
12423 }