]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Pgindent run for 8.0.
[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-2004, 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  * IDENTIFICATION
15  *        $PostgreSQL: pgsql/src/bin/pg_dump/pg_dump.c,v 1.386 2004/08/29 05:06:53 momjian Exp $
16  *
17  *-------------------------------------------------------------------------
18  */
19
20 /*
21  * Although this is not a backend module, we must include postgres.h anyway
22  * so that we can include a bunch of backend include files.  pg_dump has
23  * never pretended to be very independent of the backend anyhow ...
24  */
25 #include "postgres.h"
26
27 #include <unistd.h>
28 #include <ctype.h>
29 #ifdef ENABLE_NLS
30 #include <locale.h>
31 #endif
32 #ifdef HAVE_TERMIOS_H
33 #include <termios.h>
34 #endif
35 #include <time.h>
36
37 #ifndef HAVE_STRDUP
38 #include "strdup.h"
39 #endif
40
41 #include "getopt_long.h"
42
43 #ifndef HAVE_OPTRESET
44 int                     optreset;
45 #endif
46
47 #include "access/attnum.h"
48 #include "access/htup.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_proc.h"
51 #include "catalog/pg_trigger.h"
52 #include "catalog/pg_type.h"
53
54 #include "commands/sequence.h"
55
56 #include "libpq-fe.h"
57 #include "libpq/libpq-fs.h"
58
59 #include "pg_dump.h"
60 #include "pg_backup.h"
61 #include "pg_backup_archiver.h"
62 #include "dumputils.h"
63
64 #define _(x) gettext((x))
65
66 extern char *optarg;
67 extern int      optind,
68                         opterr;
69
70
71 typedef struct
72 {
73         const char *descr;                      /* comment for an object */
74         Oid                     classoid;               /* object class (catalog OID) */
75         Oid                     objoid;                 /* object OID */
76         int                     objsubid;               /* subobject (table column #) */
77 } CommentItem;
78
79
80 /* global decls */
81 bool            g_verbose;                      /* User wants verbose narration of our
82                                                                  * activities. */
83 Archive    *g_fout;                             /* the script file */
84 PGconn     *g_conn;                             /* the database connection */
85
86 /* various user-settable parameters */
87 bool            dumpInserts;            /* dump data using proper insert strings */
88 bool            attrNames;                      /* put attr names into insert strings */
89 bool            schemaOnly;
90 bool            dataOnly;
91 bool            aclsSkip;
92
93 /* obsolete as of 7.3: */
94 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
95
96 static char *selectTableName = NULL;    /* name of a single table to dump */
97 static char *selectSchemaName = NULL;   /* name of a single schema to dump */
98
99 char            g_opaque_type[10];      /* name for the opaque type */
100
101 /* placeholders for the delimiters for comments */
102 char            g_comment_start[10];
103 char            g_comment_end[10];
104
105 static const CatalogId nilCatalogId = {0, 0};
106
107 /* these are to avoid passing around info for findNamespace() */
108 static NamespaceInfo *g_namespaces;
109 static int      g_numNamespaces;
110
111 /* flag to turn on/off dollar quoting */
112 static int      disable_dollar_quoting = 0;
113
114
115 static void help(const char *progname);
116 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
117 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
118 static void dumpComment(Archive *fout, const char *target,
119                         const char *namespace, const char *owner,
120                         CatalogId catalogId, int subid, DumpId dumpId);
121 static int findComments(Archive *fout, Oid classoid, Oid objoid,
122                          CommentItem **items);
123 static int      collectComments(Archive *fout, CommentItem **items);
124 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
125 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
126 static void dumpType(Archive *fout, TypeInfo *tinfo);
127 static void dumpBaseType(Archive *fout, TypeInfo *tinfo);
128 static void dumpDomain(Archive *fout, TypeInfo *tinfo);
129 static void dumpCompositeType(Archive *fout, TypeInfo *tinfo);
130 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
131 static void dumpFunc(Archive *fout, FuncInfo *finfo);
132 static void dumpCast(Archive *fout, CastInfo *cast);
133 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
134 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
135 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
136 static void dumpRule(Archive *fout, RuleInfo *rinfo);
137 static void dumpAgg(Archive *fout, AggInfo *agginfo);
138 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
139 static void dumpTable(Archive *fout, TableInfo *tbinfo);
140 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
141 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
142 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
143 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
144 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
145
146 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
147                 const char *type, const char *name,
148                 const char *tag, const char *nspname, const char *owner,
149                 const char *acls);
150
151 static void getDependencies(void);
152 static void getDomainConstraints(TypeInfo *tinfo);
153 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
154 static char *format_function_signature(FuncInfo *finfo, char **argnames,
155                                                   bool honor_quotes);
156 static const char *convertRegProcReference(const char *proc);
157 static const char *convertOperatorReference(const char *opr);
158 static Oid      findLastBuiltinOid_V71(const char *);
159 static Oid      findLastBuiltinOid_V70(void);
160 static void setMaxOid(Archive *fout);
161 static void selectSourceSchema(const char *schemaName);
162 static char *getFormattedTypeName(Oid oid, OidOptions opts);
163 static char *myFormatType(const char *typname, int32 typmod);
164 static const char *fmtQualifiedId(const char *schema, const char *id);
165 static int      dumpBlobs(Archive *AH, void *arg);
166 static void dumpDatabase(Archive *AH);
167 static void dumpTimestamp(Archive *AH, char *msg);
168 static void dumpEncoding(Archive *AH);
169 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
170 static const char *fmtCopyColumnList(const TableInfo *ti);
171 static void do_sql_command(PGconn *conn, const char *query);
172 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
173                                  ExecStatusType expected);
174
175
176 int
177 main(int argc, char **argv)
178 {
179         int                     c;
180         const char *filename = NULL;
181         const char *format = "p";
182         const char *dbname = NULL;
183         const char *pghost = NULL;
184         const char *pgport = NULL;
185         const char *username = NULL;
186         bool            oids = false;
187         TableInfo  *tblinfo;
188         int                     numTables;
189         DumpableObject **dobjs;
190         int                     numObjs;
191         int                     i;
192         bool            force_password = false;
193         int                     compressLevel = -1;
194         bool            ignore_version = false;
195         int                     plainText = 0;
196         int                     outputClean = 0;
197         int                     outputCreate = 0;
198         int                     outputBlobs = 0;
199         int                     outputNoOwner = 0;
200         static int      use_setsessauth = 0;
201         static int      disable_triggers = 0;
202         char       *outputSuperuser = NULL;
203
204         RestoreOptions *ropt;
205
206         static struct option long_options[] = {
207                 {"data-only", no_argument, NULL, 'a'},
208                 {"blobs", no_argument, NULL, 'b'},
209                 {"clean", no_argument, NULL, 'c'},
210                 {"create", no_argument, NULL, 'C'},
211                 {"file", required_argument, NULL, 'f'},
212                 {"format", required_argument, NULL, 'F'},
213                 {"inserts", no_argument, NULL, 'd'},
214                 {"attribute-inserts", no_argument, NULL, 'D'},
215                 {"column-inserts", no_argument, NULL, 'D'},
216                 {"host", required_argument, NULL, 'h'},
217                 {"ignore-version", no_argument, NULL, 'i'},
218                 {"no-reconnect", no_argument, NULL, 'R'},
219                 {"oids", no_argument, NULL, 'o'},
220                 {"no-owner", no_argument, NULL, 'O'},
221                 {"port", required_argument, NULL, 'p'},
222                 {"schema", required_argument, NULL, 'n'},
223                 {"schema-only", no_argument, NULL, 's'},
224                 {"superuser", required_argument, NULL, 'S'},
225                 {"table", required_argument, NULL, 't'},
226                 {"password", no_argument, NULL, 'W'},
227                 {"username", required_argument, NULL, 'U'},
228                 {"verbose", no_argument, NULL, 'v'},
229                 {"no-privileges", no_argument, NULL, 'x'},
230                 {"no-acl", no_argument, NULL, 'x'},
231                 {"compress", required_argument, NULL, 'Z'},
232                 {"help", no_argument, NULL, '?'},
233                 {"version", no_argument, NULL, 'V'},
234
235                 /*
236                  * the following options don't have an equivalent short option
237                  * letter, but are available as '-X long-name'
238                  */
239                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
240                 {"disable-triggers", no_argument, &disable_triggers, 1},
241                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
242
243                 {NULL, 0, NULL, 0}
244         };
245         int                     optindex;
246
247         set_pglocale_pgservice(argv[0], "pg_dump");
248
249         g_verbose = false;
250
251         strcpy(g_comment_start, "-- ");
252         g_comment_end[0] = '\0';
253         strcpy(g_opaque_type, "opaque");
254
255         dataOnly = schemaOnly = dumpInserts = attrNames = false;
256
257         progname = get_progname(argv[0]);
258
259         /* Set default options based on progname */
260         if (strcmp(progname, "pg_backup") == 0)
261         {
262                 format = "c";
263                 outputBlobs = true;
264         }
265
266         if (argc > 1)
267         {
268                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
269                 {
270                         help(progname);
271                         exit(0);
272                 }
273                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
274                 {
275                         puts("pg_dump (PostgreSQL) " PG_VERSION);
276                         exit(0);
277                 }
278         }
279
280         while ((c = getopt_long(argc, argv, "abcCdDf:F:h:in:oOp:RsS:t:uU:vWxX:Z:",
281                                                         long_options, &optindex)) != -1)
282         {
283                 switch (c)
284                 {
285                         case 'a':                       /* Dump data only */
286                                 dataOnly = true;
287                                 break;
288
289                         case 'b':                       /* Dump blobs */
290                                 outputBlobs = true;
291                                 break;
292
293                         case 'c':                       /* clean (i.e., drop) schema prior to
294                                                                  * create */
295                                 outputClean = 1;
296                                 break;
297
298                         case 'C':                       /* Create DB */
299                                 outputCreate = 1;
300                                 break;
301
302                         case 'd':                       /* dump data as proper insert strings */
303                                 dumpInserts = true;
304                                 break;
305
306                         case 'D':                       /* dump data as proper insert strings with
307                                                                  * attr names */
308                                 dumpInserts = true;
309                                 attrNames = true;
310                                 break;
311
312                         case 'f':
313                                 filename = optarg;
314                                 break;
315
316                         case 'F':
317                                 format = optarg;
318                                 break;
319
320                         case 'h':                       /* server host */
321                                 pghost = optarg;
322                                 break;
323
324                         case 'i':                       /* ignore database version mismatch */
325                                 ignore_version = true;
326                                 break;
327
328                         case 'n':                       /* Dump data for this schema only */
329                                 selectSchemaName = strdup(optarg);
330                                 break;
331
332                         case 'o':                       /* Dump oids */
333                                 oids = true;
334                                 break;
335
336                         case 'O':                       /* Don't reconnect to match owner */
337                                 outputNoOwner = 1;
338                                 break;
339
340                         case 'p':                       /* server port */
341                                 pgport = optarg;
342                                 break;
343
344                         case 'R':
345                                 /* no-op, still accepted for backwards compatibility */
346                                 break;
347
348                         case 's':                       /* dump schema only */
349                                 schemaOnly = true;
350                                 break;
351
352                         case 'S':                       /* Username for superuser in plain text
353                                                                  * output */
354                                 outputSuperuser = strdup(optarg);
355                                 break;
356
357                         case 't':                       /* Dump data for this table only */
358                                 selectTableName = strdup(optarg);
359                                 break;
360
361                         case 'u':
362                                 force_password = true;
363                                 username = simple_prompt("User name: ", 100, true);
364                                 break;
365
366                         case 'U':
367                                 username = optarg;
368                                 break;
369
370                         case 'v':                       /* verbose */
371                                 g_verbose = true;
372                                 break;
373
374                         case 'W':
375                                 force_password = true;
376                                 break;
377
378                         case 'x':                       /* skip ACL dump */
379                                 aclsSkip = true;
380                                 break;
381
382                                 /*
383                                  * Option letters were getting scarce, so I invented this
384                                  * new scheme: '-X feature' turns on some feature. Compare
385                                  * to the -f option in GCC.  You should also add an
386                                  * equivalent GNU-style option --feature.  Features that
387                                  * require arguments should use '-X feature=foo'.
388                                  */
389                         case 'X':
390                                 if (strcmp(optarg, "disable-dollar-quoting") == 0)
391                                         disable_dollar_quoting = 1;
392                                 else if (strcmp(optarg, "disable-triggers") == 0)
393                                         disable_triggers = 1;
394                                 else if (strcmp(optarg, "use-set-session-authorization") == 0)
395                                         use_setsessauth = 1;
396                                 else
397                                 {
398                                         fprintf(stderr,
399                                                         _("%s: invalid -X option -- %s\n"),
400                                                         progname, optarg);
401                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
402                                         exit(1);
403                                 }
404                                 break;
405
406                         case 'Z':                       /* Compression Level */
407                                 compressLevel = atoi(optarg);
408                                 break;
409                                 /* This covers the long options equivalent to -X xxx. */
410
411                         case 0:
412                                 break;
413
414                         default:
415                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
416                                 exit(1);
417                 }
418         }
419
420         if (optind < (argc - 1))
421         {
422                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
423                                 progname, argv[optind + 1]);
424                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
425                                 progname);
426                 exit(1);
427         }
428
429         /* Get database name from command line */
430         if (optind < argc)
431                 dbname = argv[optind];
432
433         if (dataOnly && schemaOnly)
434         {
435                 write_msg(NULL, "options \"schema only\" (-s) and \"data only\" (-a) cannot be used together\n");
436                 exit(1);
437         }
438
439         if (dataOnly && outputClean)
440         {
441                 write_msg(NULL, "options \"clean\" (-c) and \"data only\" (-a) cannot be used together\n");
442                 exit(1);
443         }
444
445         if (outputBlobs && selectTableName != NULL)
446         {
447                 write_msg(NULL, "large-object output not supported for a single table\n");
448                 write_msg(NULL, "use a full dump instead\n");
449                 exit(1);
450         }
451
452         if (outputBlobs && selectSchemaName != NULL)
453         {
454                 write_msg(NULL, "large-object output not supported for a single schema\n");
455                 write_msg(NULL, "use a full dump instead\n");
456                 exit(1);
457         }
458
459         if (dumpInserts == true && oids == true)
460         {
461                 write_msg(NULL, "INSERT (-d, -D) and OID (-o) options cannot be used together\n");
462                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
463                 exit(1);
464         }
465
466         if (outputBlobs == true && (format[0] == 'p' || format[0] == 'P'))
467         {
468                 write_msg(NULL, "large-object output is not supported for plain-text dump files\n");
469                 write_msg(NULL, "(Use a different output format.)\n");
470                 exit(1);
471         }
472
473         /* open the output file */
474         switch (format[0])
475         {
476                 case 'c':
477                 case 'C':
478                         g_fout = CreateArchive(filename, archCustom, compressLevel);
479                         break;
480
481                 case 'f':
482                 case 'F':
483                         g_fout = CreateArchive(filename, archFiles, compressLevel);
484                         break;
485
486                 case 'p':
487                 case 'P':
488                         plainText = 1;
489                         g_fout = CreateArchive(filename, archNull, 0);
490                         break;
491
492                 case 't':
493                 case 'T':
494                         g_fout = CreateArchive(filename, archTar, compressLevel);
495                         break;
496
497                 default:
498                         write_msg(NULL, "invalid output format \"%s\" specified\n", format);
499                         exit(1);
500         }
501
502         if (g_fout == NULL)
503         {
504                 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
505                 exit(1);
506         }
507
508         /* Let the archiver know how noisy to be */
509         g_fout->verbose = g_verbose;
510
511         g_fout->minRemoteVersion = 70000;       /* we can handle back to 7.0 */
512         g_fout->maxRemoteVersion = parse_version(PG_VERSION);
513         if (g_fout->maxRemoteVersion < 0)
514         {
515                 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
516                 exit(1);
517         }
518
519         /*
520          * Open the database using the Archiver, so it knows about it. Errors
521          * mean death.
522          */
523         g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
524                                                          username, force_password, ignore_version);
525
526         /*
527          * Start serializable transaction to dump consistent data.
528          */
529         do_sql_command(g_conn, "BEGIN");
530
531         do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
532
533         /* Set the datestyle to ISO to ensure the dump's portability */
534         do_sql_command(g_conn, "SET DATESTYLE = ISO");
535
536         /*
537          * If supported, set extra_float_digits so that we can dump float data
538          * exactly (given correctly implemented float I/O code, anyway)
539          */
540         if (g_fout->remoteVersion >= 70400)
541                 do_sql_command(g_conn, "SET extra_float_digits TO 2");
542
543         /* Find the last built-in OID, if needed */
544         if (g_fout->remoteVersion < 70300)
545         {
546                 if (g_fout->remoteVersion >= 70100)
547                         g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
548                 else
549                         g_last_builtin_oid = findLastBuiltinOid_V70();
550                 if (g_verbose)
551                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
552         }
553
554         /*
555          * Now scan the database and create DumpableObject structs for all the
556          * objects we intend to dump.
557          */
558         tblinfo = getSchemaData(&numTables, schemaOnly, dataOnly);
559
560         if (!schemaOnly)
561                 getTableData(tblinfo, numTables, oids);
562
563         if (outputBlobs)
564         {
565                 /* This is just a placeholder to allow correct sorting of blobs */
566                 DumpableObject *blobobj;
567
568                 blobobj = (DumpableObject *) malloc(sizeof(DumpableObject));
569                 blobobj->objType = DO_BLOBS;
570                 blobobj->catId = nilCatalogId;
571                 AssignDumpId(blobobj);
572                 blobobj->name = strdup("BLOBS");
573         }
574
575         /*
576          * Collect dependency data to assist in ordering the objects.
577          */
578         getDependencies();
579
580         /*
581          * Sort the objects into a safe dump order (no forward references).
582          *
583          * In 7.3 or later, we can rely on dependency information to help us
584          * determine a safe order, so the initial sort is mostly for cosmetic
585          * purposes: we sort by name to ensure that logically identical
586          * schemas will dump identically.  Before 7.3 we don't have
587          * dependencies and we use OID ordering as an (unreliable) guide to
588          * creation order.
589          */
590         getDumpableObjects(&dobjs, &numObjs);
591
592         if (g_fout->remoteVersion >= 70300)
593                 sortDumpableObjectsByTypeName(dobjs, numObjs);
594         else
595                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
596
597         sortDumpableObjects(dobjs, numObjs);
598
599         /*
600          * Create archive TOC entries for all the objects to be dumped, in a
601          * safe order.
602          */
603
604         if (g_fout->verbose)
605                 dumpTimestamp(g_fout, "Started on");
606
607         /* First the special encoding entry. */
608         dumpEncoding(g_fout);
609
610         /* The database item is always second. */
611         if (!dataOnly)
612                 dumpDatabase(g_fout);
613
614         /* Max OID is next. */
615         if (oids == true)
616                 setMaxOid(g_fout);
617
618         /* Now the rearrangeable objects. */
619         for (i = 0; i < numObjs; i++)
620                 dumpDumpableObject(g_fout, dobjs[i]);
621
622         if (g_fout->verbose)
623                 dumpTimestamp(g_fout, "Completed on");
624
625         /*
626          * And finally we can do the actual output.
627          */
628         if (plainText)
629         {
630                 ropt = NewRestoreOptions();
631                 ropt->filename = (char *) filename;
632                 ropt->dropSchema = outputClean;
633                 ropt->aclsSkip = aclsSkip;
634                 ropt->superuser = outputSuperuser;
635                 ropt->create = outputCreate;
636                 ropt->noOwner = outputNoOwner;
637                 ropt->disable_triggers = disable_triggers;
638                 ropt->use_setsessauth = use_setsessauth;
639
640                 if (compressLevel == -1)
641                         ropt->compression = 0;
642                 else
643                         ropt->compression = compressLevel;
644
645                 ropt->suppressDumpWarnings = true;              /* We've already shown
646                                                                                                  * them */
647
648                 RestoreArchive(g_fout, ropt);
649         }
650
651         CloseArchive(g_fout);
652
653         PQfinish(g_conn);
654
655         exit(0);
656 }
657
658
659 static void
660 help(const char *progname)
661 {
662         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
663         printf(_("Usage:\n"));
664         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
665
666         printf(_("\nGeneral options:\n"));
667         printf(_("  -f, --file=FILENAME      output file name\n"));
668         printf(_("  -F, --format=c|t|p       output file format (custom, tar, plain text)\n"));
669         printf(_("  -i, --ignore-version     proceed even when server version mismatches\n"
670                          "                           pg_dump version\n"));
671         printf(_("  -v, --verbose            verbose mode\n"));
672         printf(_("  -Z, --compress=0-9       compression level for compressed formats\n"));
673         printf(_("  --help                   show this help, then exit\n"));
674         printf(_("  --version                output version information, then exit\n"));
675
676         printf(_("\nOptions controlling the output content:\n"));
677         printf(_("  -a, --data-only          dump only the data, not the schema\n"));
678         printf(_("  -b, --blobs              include large objects in dump\n"));
679         printf(_("  -c, --clean              clean (drop) schema prior to create\n"));
680         printf(_("  -C, --create             include commands to create database in dump\n"));
681         printf(_("  -d, --inserts            dump data as INSERT, rather than COPY, commands\n"));
682         printf(_("  -D, --column-inserts     dump data as INSERT commands with column names\n"));
683         printf(_("  -n, --schema=SCHEMA      dump the named schema only\n"));
684         printf(_("  -o, --oids               include OIDs in dump\n"));
685         printf(_("  -O, --no-owner           do not output commands to set object ownership\n"
686                          "                           in plain text format\n"));
687         printf(_("  -s, --schema-only        dump only the schema, no data\n"));
688         printf(_("  -S, --superuser=NAME     specify the superuser user name to use in\n"
689                          "                           plain text format\n"));
690         printf(_("  -t, --table=TABLE        dump the named table only\n"));
691         printf(_("  -x, --no-privileges      do not dump privileges (grant/revoke)\n"));
692         printf(_("  -X disable-dollar-quoting, --disable-dollar-quoting\n"
693                          "                           disable dollar quoting, use SQL standard quoting\n"));
694         printf(_("  -X disable-triggers, --disable-triggers\n"
695                          "                           disable triggers during data-only restore\n"));
696         printf(_("  -X use-set-session-authorization, --use-set-session-authorization\n"
697                          "                           use SESSION AUTHORIZATION commands instead of\n"
698                          "                           OWNER TO commands\n"));
699
700         printf(_("\nConnection options:\n"));
701         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
702         printf(_("  -p, --port=PORT          database server port number\n"));
703         printf(_("  -U, --username=NAME      connect as specified database user\n"));
704         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
705
706         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
707                          "variable value is used.\n\n"));
708         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
709 }
710
711 void
712 exit_nicely(void)
713 {
714         PQfinish(g_conn);
715         if (g_verbose)
716                 write_msg(NULL, "*** aborted because of error\n");
717         exit(1);
718 }
719
720 /*
721  * selectDumpableNamespace: policy-setting subroutine
722  *              Mark a namespace as to be dumped or not
723  */
724 static void
725 selectDumpableNamespace(NamespaceInfo *nsinfo)
726 {
727         /*
728          * If a specific table is being dumped, do not dump any complete
729          * namespaces.  If a specific namespace is being dumped, dump just
730          * that namespace. Otherwise, dump all non-system namespaces.
731          */
732         if (selectTableName != NULL)
733                 nsinfo->dump = false;
734         else if (selectSchemaName != NULL)
735         {
736                 if (strcmp(nsinfo->dobj.name, selectSchemaName) == 0)
737                         nsinfo->dump = true;
738                 else
739                         nsinfo->dump = false;
740         }
741         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
742                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
743                 nsinfo->dump = false;
744         else
745                 nsinfo->dump = true;
746 }
747
748 /*
749  * selectDumpableTable: policy-setting subroutine
750  *              Mark a table as to be dumped or not
751  */
752 static void
753 selectDumpableTable(TableInfo *tbinfo)
754 {
755         /*
756          * Always dump if dumping parent namespace; else, if a particular
757          * tablename has been specified, dump matching table name; else, do
758          * not dump.
759          */
760         tbinfo->dump = false;
761         if (tbinfo->dobj.namespace->dump)
762                 tbinfo->dump = true;
763         else if (selectTableName != NULL &&
764                          strcmp(tbinfo->dobj.name, selectTableName) == 0)
765         {
766                 /* If both -s and -t specified, must match both to dump */
767                 if (selectSchemaName == NULL)
768                         tbinfo->dump = true;
769                 else if (strcmp(tbinfo->dobj.namespace->dobj.name, selectSchemaName) == 0)
770                         tbinfo->dump = true;
771         }
772 }
773
774 /*
775  *      Dump a table's contents for loading using the COPY command
776  *      - this routine is called by the Archiver when it wants the table
777  *        to be dumped.
778  */
779
780 #define COPYBUFSIZ              8192
781
782 static int
783 dumpTableData_copy(Archive *fout, void *dcontext)
784 {
785         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
786         TableInfo  *tbinfo = tdinfo->tdtable;
787         const char *classname = tbinfo->dobj.name;
788         const bool      hasoids = tbinfo->hasoids;
789         const bool      oids = tdinfo->oids;
790         PQExpBuffer q = createPQExpBuffer();
791         PGresult   *res;
792         int                     ret;
793         bool            copydone;
794         char            copybuf[COPYBUFSIZ];
795         const char *column_list;
796
797         if (g_verbose)
798                 write_msg(NULL, "dumping contents of table %s\n", classname);
799
800         /*
801          * Make sure we are in proper schema.  We will qualify the table name
802          * below anyway (in case its name conflicts with a pg_catalog table);
803          * but this ensures reproducible results in case the table contains
804          * regproc, regclass, etc columns.
805          */
806         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
807
808         /*
809          * If possible, specify the column list explicitly so that we have no
810          * possibility of retrieving data in the wrong column order.  (The
811          * default column ordering of COPY will not be what we want in certain
812          * corner cases involving ADD COLUMN and inheritance.)
813          */
814         if (g_fout->remoteVersion >= 70300)
815                 column_list = fmtCopyColumnList(tbinfo);
816         else
817                 column_list = "";               /* can't select columns in COPY */
818
819         if (oids && hasoids)
820         {
821                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
822                                                 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
823                                                                            classname),
824                                                   column_list);
825         }
826         else
827         {
828                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
829                                                 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
830                                                                            classname),
831                                                   column_list);
832         }
833         res = PQexec(g_conn, q->data);
834         check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
835
836         copydone = false;
837
838         while (!copydone)
839         {
840                 ret = PQgetline(g_conn, copybuf, COPYBUFSIZ);
841
842                 if (copybuf[0] == '\\' &&
843                         copybuf[1] == '.' &&
844                         copybuf[2] == '\0')
845                 {
846                         copydone = true;        /* don't print this... */
847                 }
848                 else
849                 {
850                         archputs(copybuf, fout);
851                         switch (ret)
852                         {
853                                 case EOF:
854                                         copydone = true;
855                                         /* FALLTHROUGH */
856                                 case 0:
857                                         archputs("\n", fout);
858                                         break;
859                                 case 1:
860                                         break;
861                         }
862                 }
863
864                 /*
865                  * THROTTLE:
866                  *
867                  * There was considerable discussion in late July, 2000 regarding
868                  * slowing down pg_dump when backing up large tables. Users with
869                  * both slow & fast (muti-processor) machines experienced
870                  * performance degradation when doing a backup.
871                  *
872                  * Initial attempts based on sleeping for a number of ms for each ms
873                  * of work were deemed too complex, then a simple 'sleep in each
874                  * loop' implementation was suggested. The latter failed because
875                  * the loop was too tight. Finally, the following was implemented:
876                  *
877                  * If throttle is non-zero, then See how long since the last sleep.
878                  * Work out how long to sleep (based on ratio). If sleep is more
879                  * than 100ms, then sleep reset timer EndIf EndIf
880                  *
881                  * where the throttle value was the number of ms to sleep per ms of
882                  * work. The calculation was done in each loop.
883                  *
884                  * Most of the hard work is done in the backend, and this solution
885                  * still did not work particularly well: on slow machines, the
886                  * ratio was 50:1, and on medium paced machines, 1:1, and on fast
887                  * multi-processor machines, it had little or no effect, for
888                  * reasons that were unclear.
889                  *
890                  * Further discussion ensued, and the proposal was dropped.
891                  *
892                  * For those people who want this feature, it can be implemented
893                  * using gettimeofday in each loop, calculating the time since
894                  * last sleep, multiplying that by the sleep ratio, then if the
895                  * result is more than a preset 'minimum sleep time' (say 100ms),
896                  * call the 'select' function to sleep for a subsecond period ie.
897                  *
898                  * select(0, NULL, NULL, NULL, &tvi);
899                  *
900                  * This will return after the interval specified in the structure
901                  * tvi. Finally, call gettimeofday again to save the 'last sleep
902                  * time'.
903                  */
904         }
905         archprintf(fout, "\\.\n\n\n");
906
907         ret = PQendcopy(g_conn);
908         if (ret != 0)
909         {
910                 write_msg(NULL, "SQL command to dump the contents of table \"%s\" failed: PQendcopy() failed.\n", classname);
911                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
912                 write_msg(NULL, "The command was: %s\n", q->data);
913                 exit_nicely();
914         }
915
916         PQclear(res);
917         destroyPQExpBuffer(q);
918         return 1;
919 }
920
921 static int
922 dumpTableData_insert(Archive *fout, void *dcontext)
923 {
924         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
925         TableInfo  *tbinfo = tdinfo->tdtable;
926         const char *classname = tbinfo->dobj.name;
927         PQExpBuffer q = createPQExpBuffer();
928         PGresult   *res;
929         int                     tuple;
930         int                     nfields;
931         int                     field;
932
933         /*
934          * Make sure we are in proper schema.  We will qualify the table name
935          * below anyway (in case its name conflicts with a pg_catalog table);
936          * but this ensures reproducible results in case the table contains
937          * regproc, regclass, etc columns.
938          */
939         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
940
941         if (fout->remoteVersion >= 70100)
942         {
943                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
944                                                   "SELECT * FROM ONLY %s",
945                                                 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
946                                                                            classname));
947         }
948         else
949         {
950                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
951                                                   "SELECT * FROM %s",
952                                                 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
953                                                                            classname));
954         }
955
956         res = PQexec(g_conn, q->data);
957         check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
958
959         do
960         {
961                 PQclear(res);
962
963                 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
964                 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
965                                                  PGRES_TUPLES_OK);
966                 nfields = PQnfields(res);
967                 for (tuple = 0; tuple < PQntuples(res); tuple++)
968                 {
969                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
970                         if (nfields == 0)
971                         {
972                                 /* corner case for zero-column table */
973                                 archprintf(fout, "DEFAULT VALUES;\n");
974                                 continue;
975                         }
976                         if (attrNames == true)
977                         {
978                                 resetPQExpBuffer(q);
979                                 appendPQExpBuffer(q, "(");
980                                 for (field = 0; field < nfields; field++)
981                                 {
982                                         if (field > 0)
983                                                 appendPQExpBuffer(q, ", ");
984                                         appendPQExpBuffer(q, fmtId(PQfname(res, field)));
985                                 }
986                                 appendPQExpBuffer(q, ") ");
987                                 archprintf(fout, "%s", q->data);
988                         }
989                         archprintf(fout, "VALUES (");
990                         for (field = 0; field < nfields; field++)
991                         {
992                                 if (field > 0)
993                                         archprintf(fout, ", ");
994                                 if (PQgetisnull(res, tuple, field))
995                                 {
996                                         archprintf(fout, "NULL");
997                                         continue;
998                                 }
999
1000                                 /* XXX This code is partially duplicated in ruleutils.c */
1001                                 switch (PQftype(res, field))
1002                                 {
1003                                         case INT2OID:
1004                                         case INT4OID:
1005                                         case INT8OID:
1006                                         case OIDOID:
1007                                         case FLOAT4OID:
1008                                         case FLOAT8OID:
1009                                         case NUMERICOID:
1010                                                 {
1011                                                         /*
1012                                                          * These types are printed without quotes
1013                                                          * unless they contain values that aren't
1014                                                          * accepted by the scanner unquoted (e.g.,
1015                                                          * 'NaN').      Note that strtod() and friends
1016                                                          * might accept NaN, so we can't use that to
1017                                                          * test.
1018                                                          *
1019                                                          * In reality we only need to defend against
1020                                                          * infinity and NaN, so we need not get too
1021                                                          * crazy about pattern matching here.
1022                                                          */
1023                                                         const char *s = PQgetvalue(res, tuple, field);
1024
1025                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1026                                                                 archprintf(fout, "%s", s);
1027                                                         else
1028                                                                 archprintf(fout, "'%s'", s);
1029                                                 }
1030                                                 break;
1031
1032                                         case BITOID:
1033                                         case VARBITOID:
1034                                                 archprintf(fout, "B'%s'",
1035                                                                    PQgetvalue(res, tuple, field));
1036                                                 break;
1037
1038                                         case BOOLOID:
1039                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1040                                                         archprintf(fout, "true");
1041                                                 else
1042                                                         archprintf(fout, "false");
1043                                                 break;
1044
1045                                         default:
1046                                                 /* All other types are printed as string literals. */
1047                                                 resetPQExpBuffer(q);
1048                                                 appendStringLiteral(q, PQgetvalue(res, tuple, field), false);
1049                                                 archprintf(fout, "%s", q->data);
1050                                                 break;
1051                                 }
1052                         }
1053                         archprintf(fout, ");\n");
1054                 }
1055         } while (PQntuples(res) > 0);
1056
1057         PQclear(res);
1058
1059         archprintf(fout, "\n\n");
1060
1061         do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1062
1063         destroyPQExpBuffer(q);
1064         return 1;
1065 }
1066
1067
1068 /*
1069  * dumpTableData -
1070  *        dump the contents of a single table
1071  *
1072  * Actually, this just makes an ArchiveEntry for the table contents.
1073  */
1074 static void
1075 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1076 {
1077         TableInfo  *tbinfo = tdinfo->tdtable;
1078         PQExpBuffer copyBuf = createPQExpBuffer();
1079         DataDumperPtr dumpFn;
1080         char       *copyStmt;
1081
1082         if (!dumpInserts)
1083         {
1084                 /* Dump/restore using COPY */
1085                 dumpFn = dumpTableData_copy;
1086                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1087                 appendPQExpBuffer(copyBuf, "COPY %s ",
1088                                                   fmtId(tbinfo->dobj.name));
1089                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1090                                                   fmtCopyColumnList(tbinfo),
1091                                   (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1092                 copyStmt = copyBuf->data;
1093         }
1094         else
1095         {
1096                 /* Restore using INSERT */
1097                 dumpFn = dumpTableData_insert;
1098                 copyStmt = NULL;
1099         }
1100
1101         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1102                                  tbinfo->dobj.name,
1103                                  tbinfo->dobj.namespace->dobj.name,
1104                                  tbinfo->usename, false,
1105                                  "TABLE DATA", "", "", copyStmt,
1106                                  tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1107                                  dumpFn, tdinfo);
1108
1109         destroyPQExpBuffer(copyBuf);
1110 }
1111
1112 /*
1113  * getTableData -
1114  *        set up dumpable objects representing the contents of tables
1115  */
1116 static void
1117 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1118 {
1119         int                     i;
1120
1121         for (i = 0; i < numTables; i++)
1122         {
1123                 /* Skip VIEWs (no data to dump) */
1124                 if (tblinfo[i].relkind == RELKIND_VIEW)
1125                         continue;
1126                 /* Skip SEQUENCEs (handled elsewhere) */
1127                 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1128                         continue;
1129
1130                 if (tblinfo[i].dump)
1131                 {
1132                         TableDataInfo *tdinfo;
1133
1134                         tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1135
1136                         tdinfo->dobj.objType = DO_TABLE_DATA;
1137
1138                         /*
1139                          * Note: use tableoid 0 so that this object won't be mistaken
1140                          * for something that pg_depend entries apply to.
1141                          */
1142                         tdinfo->dobj.catId.tableoid = 0;
1143                         tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1144                         AssignDumpId(&tdinfo->dobj);
1145                         tdinfo->dobj.name = tblinfo[i].dobj.name;
1146                         tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1147                         tdinfo->tdtable = &(tblinfo[i]);
1148                         tdinfo->oids = oids;
1149                         addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1150                 }
1151         }
1152 }
1153
1154
1155 /*
1156  * dumpDatabase:
1157  *      dump the database definition
1158  */
1159 static void
1160 dumpDatabase(Archive *AH)
1161 {
1162         PQExpBuffer dbQry = createPQExpBuffer();
1163         PQExpBuffer delQry = createPQExpBuffer();
1164         PQExpBuffer creaQry = createPQExpBuffer();
1165         PGresult   *res;
1166         int                     ntups;
1167         int                     i_tableoid,
1168                                 i_oid,
1169                                 i_dba,
1170                                 i_encoding,
1171                                 i_tablespace;
1172         CatalogId       dbCatId;
1173         DumpId          dbDumpId;
1174         const char *datname,
1175                            *dba,
1176                            *encoding,
1177                            *tablespace;
1178
1179         datname = PQdb(g_conn);
1180
1181         if (g_verbose)
1182                 write_msg(NULL, "saving database definition\n");
1183
1184         /* Make sure we are in proper schema */
1185         selectSourceSchema("pg_catalog");
1186
1187         /* Get the database owner and parameters from pg_database */
1188         if (g_fout->remoteVersion >= 80000)
1189         {
1190                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1191                  "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1192                                                   "pg_encoding_to_char(encoding) as encoding, "
1193                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) as tablespace "
1194                                                   "FROM pg_database "
1195                                                   "WHERE datname = ");
1196                 appendStringLiteral(dbQry, datname, true);
1197         }
1198         else if (g_fout->remoteVersion >= 70100)
1199         {
1200                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1201                  "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1202                                                   "pg_encoding_to_char(encoding) as encoding, "
1203                                                   "NULL as tablespace "
1204                                                   "FROM pg_database "
1205                                                   "WHERE datname = ");
1206                 appendStringLiteral(dbQry, datname, true);
1207         }
1208         else
1209         {
1210                 appendPQExpBuffer(dbQry, "SELECT "
1211                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1212                                                   "oid, "
1213                  "(SELECT usename FROM pg_user WHERE usesysid = datdba) as dba, "
1214                                                   "pg_encoding_to_char(encoding) as encoding, "
1215                                                   "NULL as tablespace "
1216                                                   "FROM pg_database "
1217                                                   "WHERE datname = ");
1218                 appendStringLiteral(dbQry, datname, true);
1219         }
1220
1221         res = PQexec(g_conn, dbQry->data);
1222         check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1223
1224         ntups = PQntuples(res);
1225
1226         if (ntups <= 0)
1227         {
1228                 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1229                                   datname);
1230                 exit_nicely();
1231         }
1232
1233         if (ntups != 1)
1234         {
1235                 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1236                                   ntups, datname);
1237                 exit_nicely();
1238         }
1239
1240         i_tableoid = PQfnumber(res, "tableoid");
1241         i_oid = PQfnumber(res, "oid");
1242         i_dba = PQfnumber(res, "dba");
1243         i_encoding = PQfnumber(res, "encoding");
1244         i_tablespace = PQfnumber(res, "tablespace");
1245
1246         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1247         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1248         dba = PQgetvalue(res, 0, i_dba);
1249         encoding = PQgetvalue(res, 0, i_encoding);
1250         tablespace = PQgetvalue(res, 0, i_tablespace);
1251
1252         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1253                                           fmtId(datname));
1254         if (strlen(encoding) > 0)
1255         {
1256                 appendPQExpBuffer(creaQry, " ENCODING = ");
1257                 appendStringLiteral(creaQry, encoding, true);
1258         }
1259         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1260                 appendPQExpBuffer(creaQry, " TABLESPACE = %s", fmtId(tablespace));
1261         appendPQExpBuffer(creaQry, ";\n");
1262
1263         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1264                                           fmtId(datname));
1265
1266         dbDumpId = createDumpId();
1267
1268         ArchiveEntry(AH,
1269                                  dbCatId,               /* catalog ID */
1270                                  dbDumpId,              /* dump ID */
1271                                  datname,               /* Name */
1272                                  NULL,                  /* Namespace */
1273                                  dba,                   /* Owner */
1274                                  false,                 /* with oids */
1275                                  "DATABASE",    /* Desc */
1276                                  creaQry->data, /* Create */
1277                                  delQry->data,  /* Del */
1278                                  NULL,                  /* Copy */
1279                                  NULL,                  /* Deps */
1280                                  0,                             /* # Deps */
1281                                  NULL,                  /* Dumper */
1282                                  NULL);                 /* Dumper Arg */
1283
1284         /* Dump DB comment if any */
1285         resetPQExpBuffer(dbQry);
1286         appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1287         dumpComment(AH, dbQry->data, NULL, "",
1288                                 dbCatId, 0, dbDumpId);
1289
1290         PQclear(res);
1291
1292         destroyPQExpBuffer(dbQry);
1293         destroyPQExpBuffer(delQry);
1294         destroyPQExpBuffer(creaQry);
1295 }
1296
1297
1298 /*
1299  * dumpTimestamp
1300  */
1301 static void
1302 dumpTimestamp(Archive *AH, char *msg)
1303 {
1304         char            buf[256];
1305         time_t          now = time(NULL);
1306
1307         if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&now)) != 0)
1308         {
1309                 PQExpBuffer qry = createPQExpBuffer();
1310
1311                 appendPQExpBuffer(qry, "-- ");
1312                 appendPQExpBuffer(qry, msg);
1313                 appendPQExpBuffer(qry, " ");
1314                 appendPQExpBuffer(qry, buf);
1315                 appendPQExpBuffer(qry, "\n");
1316
1317                 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1318                                          "DUMP TIMESTAMP", NULL, "",
1319                                          false, "DUMP TIMESTAMP", qry->data, "", NULL,
1320                                          NULL, 0,
1321                                          NULL, NULL);
1322                 destroyPQExpBuffer(qry);
1323         }
1324 }
1325
1326
1327 /*
1328  * dumpEncoding: put the correct encoding into the archive
1329  */
1330 static void
1331 dumpEncoding(Archive *AH)
1332 {
1333         PQExpBuffer qry;
1334         PGresult   *res;
1335
1336         /* Can't read the encoding from pre-7.3 servers (SHOW isn't a query) */
1337         if (AH->remoteVersion < 70300)
1338                 return;
1339
1340         if (g_verbose)
1341                 write_msg(NULL, "saving encoding\n");
1342
1343         qry = createPQExpBuffer();
1344
1345         appendPQExpBuffer(qry, "SHOW client_encoding");
1346
1347         res = PQexec(g_conn, qry->data);
1348
1349         check_sql_result(res, g_conn, qry->data, PGRES_TUPLES_OK);
1350
1351         resetPQExpBuffer(qry);
1352
1353         appendPQExpBuffer(qry, "SET client_encoding = ");
1354         appendStringLiteral(qry, PQgetvalue(res, 0, 0), true);
1355         appendPQExpBuffer(qry, ";\n");
1356
1357         ArchiveEntry(AH, nilCatalogId, createDumpId(),
1358                                  "ENCODING", NULL, "",
1359                                  false, "ENCODING", qry->data, "", NULL,
1360                                  NULL, 0,
1361                                  NULL, NULL);
1362
1363         PQclear(res);
1364
1365         destroyPQExpBuffer(qry);
1366 }
1367
1368
1369 /*
1370  * dumpBlobs:
1371  *      dump all blobs
1372  *
1373  */
1374
1375 #define loBufSize 16384
1376 #define loFetchSize 1000
1377
1378 static int
1379 dumpBlobs(Archive *AH, void *arg)
1380 {
1381         PQExpBuffer oidQry = createPQExpBuffer();
1382         PQExpBuffer oidFetchQry = createPQExpBuffer();
1383         PGresult   *res;
1384         int                     i;
1385         int                     loFd;
1386         char            buf[loBufSize];
1387         int                     cnt;
1388         Oid                     blobOid;
1389
1390         if (g_verbose)
1391                 write_msg(NULL, "saving large objects\n");
1392
1393         /* Make sure we are in proper schema */
1394         selectSourceSchema("pg_catalog");
1395
1396         /* Cursor to get all BLOB tables */
1397         if (AH->remoteVersion >= 70100)
1398                 appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT DISTINCT loid FROM pg_largeobject");
1399         else
1400                 appendPQExpBuffer(oidQry, "Declare blobOid Cursor for SELECT oid from pg_class where relkind = 'l'");
1401
1402         res = PQexec(g_conn, oidQry->data);
1403         check_sql_result(res, g_conn, oidQry->data, PGRES_COMMAND_OK);
1404
1405         /* Fetch for cursor */
1406         appendPQExpBuffer(oidFetchQry, "Fetch %d in blobOid", loFetchSize);
1407
1408         do
1409         {
1410                 /* Do a fetch */
1411                 PQclear(res);
1412
1413                 res = PQexec(g_conn, oidFetchQry->data);
1414                 check_sql_result(res, g_conn, oidFetchQry->data, PGRES_TUPLES_OK);
1415
1416                 /* Process the tuples, if any */
1417                 for (i = 0; i < PQntuples(res); i++)
1418                 {
1419                         blobOid = atooid(PQgetvalue(res, i, 0));
1420                         /* Open the BLOB */
1421                         loFd = lo_open(g_conn, blobOid, INV_READ);
1422                         if (loFd == -1)
1423                         {
1424                                 write_msg(NULL, "dumpBlobs(): could not open large object: %s",
1425                                                   PQerrorMessage(g_conn));
1426                                 exit_nicely();
1427                         }
1428
1429                         StartBlob(AH, blobOid);
1430
1431                         /* Now read it in chunks, sending data to archive */
1432                         do
1433                         {
1434                                 cnt = lo_read(g_conn, loFd, buf, loBufSize);
1435                                 if (cnt < 0)
1436                                 {
1437                                         write_msg(NULL, "dumpBlobs(): error reading large object: %s",
1438                                                           PQerrorMessage(g_conn));
1439                                         exit_nicely();
1440                                 }
1441
1442                                 WriteData(AH, buf, cnt);
1443
1444                         } while (cnt > 0);
1445
1446                         lo_close(g_conn, loFd);
1447
1448                         EndBlob(AH, blobOid);
1449
1450                 }
1451         } while (PQntuples(res) > 0);
1452
1453         destroyPQExpBuffer(oidQry);
1454         destroyPQExpBuffer(oidFetchQry);
1455
1456         return 1;
1457 }
1458
1459 /*
1460  * getNamespaces:
1461  *        read all namespaces in the system catalogs and return them in the
1462  * NamespaceInfo* structure
1463  *
1464  *      numNamespaces is set to the number of namespaces read in
1465  */
1466 NamespaceInfo *
1467 getNamespaces(int *numNamespaces)
1468 {
1469         PGresult   *res;
1470         int                     ntups;
1471         int                     i;
1472         PQExpBuffer query;
1473         NamespaceInfo *nsinfo;
1474         int                     i_tableoid;
1475         int                     i_oid;
1476         int                     i_nspname;
1477         int                     i_usename;
1478         int                     i_nsptablespace;
1479         int                     i_nspacl;
1480
1481         /*
1482          * Before 7.3, there are no real namespaces; create two dummy entries,
1483          * one for user stuff and one for system stuff.
1484          */
1485         if (g_fout->remoteVersion < 70300)
1486         {
1487                 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
1488
1489                 nsinfo[0].dobj.objType = DO_NAMESPACE;
1490                 nsinfo[0].dobj.catId.tableoid = 0;
1491                 nsinfo[0].dobj.catId.oid = 0;
1492                 AssignDumpId(&nsinfo[0].dobj);
1493                 nsinfo[0].dobj.name = strdup("public");
1494                 nsinfo[0].usename = strdup("");
1495                 nsinfo[0].nspacl = strdup("");
1496                 nsinfo[0].nsptablespace = strdup("");
1497
1498                 selectDumpableNamespace(&nsinfo[0]);
1499
1500                 nsinfo[1].dobj.objType = DO_NAMESPACE;
1501                 nsinfo[1].dobj.catId.tableoid = 0;
1502                 nsinfo[1].dobj.catId.oid = 1;
1503                 AssignDumpId(&nsinfo[1].dobj);
1504                 nsinfo[1].dobj.name = strdup("pg_catalog");
1505                 nsinfo[1].usename = strdup("");
1506                 nsinfo[1].nspacl = strdup("");
1507                 nsinfo[0].nsptablespace = strdup("");
1508
1509                 selectDumpableNamespace(&nsinfo[1]);
1510
1511                 g_namespaces = nsinfo;
1512                 g_numNamespaces = *numNamespaces = 2;
1513
1514                 return nsinfo;
1515         }
1516
1517         query = createPQExpBuffer();
1518
1519         /* Make sure we are in proper schema */
1520         selectSourceSchema("pg_catalog");
1521
1522         /*
1523          * we fetch all namespaces including system ones, so that every object
1524          * we read in can be linked to a containing namespace.
1525          */
1526         if (g_fout->remoteVersion >= 80000)
1527         {
1528                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1529                                                   "(select usename from pg_user where nspowner = usesysid) as usename, "
1530                                                   "nspacl, "
1531                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = nsptablespace) AS nsptablespace "
1532                                                   "FROM pg_namespace");
1533         }
1534         else
1535         {
1536                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
1537                                                   "(select usename from pg_user where nspowner = usesysid) as usename, "
1538                                                   "nspacl, NULL AS nsptablespace "
1539                                                   "FROM pg_namespace");
1540         }
1541
1542         res = PQexec(g_conn, query->data);
1543         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1544
1545         ntups = PQntuples(res);
1546
1547         nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
1548
1549         i_tableoid = PQfnumber(res, "tableoid");
1550         i_oid = PQfnumber(res, "oid");
1551         i_nspname = PQfnumber(res, "nspname");
1552         i_usename = PQfnumber(res, "usename");
1553         i_nspacl = PQfnumber(res, "nspacl");
1554         i_nsptablespace = PQfnumber(res, "nsptablespace");
1555
1556         for (i = 0; i < ntups; i++)
1557         {
1558                 nsinfo[i].dobj.objType = DO_NAMESPACE;
1559                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1560                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1561                 AssignDumpId(&nsinfo[i].dobj);
1562                 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
1563                 nsinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1564                 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
1565                 nsinfo[i].nsptablespace = strdup(PQgetvalue(res, i, i_nsptablespace));
1566
1567                 /* Decide whether to dump this namespace */
1568                 selectDumpableNamespace(&nsinfo[i]);
1569
1570                 if (strlen(nsinfo[i].usename) == 0)
1571                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
1572                                           nsinfo[i].dobj.name);
1573         }
1574
1575         /*
1576          * If the user attempted to dump a specific namespace, check to ensure
1577          * that the specified namespace actually exists.
1578          */
1579         if (selectSchemaName)
1580         {
1581                 for (i = 0; i < ntups; i++)
1582                         if (strcmp(nsinfo[i].dobj.name, selectSchemaName) == 0)
1583                                 break;
1584
1585                 /* Didn't find a match */
1586                 if (i == ntups)
1587                 {
1588                         write_msg(NULL, "specified schema \"%s\" does not exist\n",
1589                                           selectSchemaName);
1590                         exit_nicely();
1591                 }
1592         }
1593
1594         PQclear(res);
1595         destroyPQExpBuffer(query);
1596
1597         g_namespaces = nsinfo;
1598         g_numNamespaces = *numNamespaces = ntups;
1599
1600         return nsinfo;
1601 }
1602
1603 /*
1604  * findNamespace:
1605  *              given a namespace OID and an object OID, look up the info read by
1606  *              getNamespaces
1607  *
1608  * NB: for pre-7.3 source database, we use object OID to guess whether it's
1609  * a system object or not.      In 7.3 and later there is no guessing.
1610  */
1611 static NamespaceInfo *
1612 findNamespace(Oid nsoid, Oid objoid)
1613 {
1614         int                     i;
1615
1616         if (g_fout->remoteVersion >= 70300)
1617         {
1618                 for (i = 0; i < g_numNamespaces; i++)
1619                 {
1620                         NamespaceInfo *nsinfo = &g_namespaces[i];
1621
1622                         if (nsoid == nsinfo->dobj.catId.oid)
1623                                 return nsinfo;
1624                 }
1625                 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
1626                 exit_nicely();
1627         }
1628         else
1629         {
1630                 /* This code depends on the layout set up by getNamespaces. */
1631                 if (objoid > g_last_builtin_oid)
1632                         i = 0;                          /* user object */
1633                 else
1634                         i = 1;                          /* system object */
1635                 return &g_namespaces[i];
1636         }
1637
1638         return NULL;                            /* keep compiler quiet */
1639 }
1640
1641 /*
1642  * getTypes:
1643  *        read all types in the system catalogs and return them in the
1644  * TypeInfo* structure
1645  *
1646  *      numTypes is set to the number of types read in
1647  *
1648  * NB: this must run after getFuncs() because we assume we can do
1649  * findFuncByOid().
1650  */
1651 TypeInfo *
1652 getTypes(int *numTypes)
1653 {
1654         PGresult   *res;
1655         int                     ntups;
1656         int                     i;
1657         PQExpBuffer query = createPQExpBuffer();
1658         TypeInfo   *tinfo;
1659         int                     i_tableoid;
1660         int                     i_oid;
1661         int                     i_typname;
1662         int                     i_typnamespace;
1663         int                     i_usename;
1664         int                     i_typinput;
1665         int                     i_typoutput;
1666         int                     i_typelem;
1667         int                     i_typrelid;
1668         int                     i_typrelkind;
1669         int                     i_typtype;
1670         int                     i_typisdefined;
1671
1672         /*
1673          * we include even the built-in types because those may be used as
1674          * array elements by user-defined types
1675          *
1676          * we filter out the built-in types when we dump out the types
1677          *
1678          * same approach for undefined (shell) types
1679          */
1680
1681         /* Make sure we are in proper schema */
1682         selectSourceSchema("pg_catalog");
1683
1684         if (g_fout->remoteVersion >= 70300)
1685         {
1686                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1687                                                   "typnamespace, "
1688                                                   "(select usename from pg_user where typowner = usesysid) as usename, "
1689                                                   "typinput::oid as typinput, "
1690                                            "typoutput::oid as typoutput, typelem, typrelid, "
1691                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1692                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1693                                                   "typtype, typisdefined "
1694                                                   "FROM pg_type");
1695         }
1696         else if (g_fout->remoteVersion >= 70100)
1697         {
1698                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
1699                                                   "0::oid as typnamespace, "
1700                                                   "(select usename from pg_user where typowner = usesysid) as usename, "
1701                                                   "typinput::oid as typinput, "
1702                                            "typoutput::oid as typoutput, typelem, typrelid, "
1703                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1704                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1705                                                   "typtype, typisdefined "
1706                                                   "FROM pg_type");
1707         }
1708         else
1709         {
1710                 appendPQExpBuffer(query, "SELECT "
1711                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
1712                                                   "oid, typname, "
1713                                                   "0::oid as typnamespace, "
1714                                                   "(select usename from pg_user where typowner = usesysid) as usename, "
1715                                                   "typinput::oid as typinput, "
1716                                            "typoutput::oid as typoutput, typelem, typrelid, "
1717                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
1718                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END as typrelkind, "
1719                                                   "typtype, typisdefined "
1720                                                   "FROM pg_type");
1721         }
1722
1723         res = PQexec(g_conn, query->data);
1724         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1725
1726         ntups = PQntuples(res);
1727
1728         tinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
1729
1730         i_tableoid = PQfnumber(res, "tableoid");
1731         i_oid = PQfnumber(res, "oid");
1732         i_typname = PQfnumber(res, "typname");
1733         i_typnamespace = PQfnumber(res, "typnamespace");
1734         i_usename = PQfnumber(res, "usename");
1735         i_typinput = PQfnumber(res, "typinput");
1736         i_typoutput = PQfnumber(res, "typoutput");
1737         i_typelem = PQfnumber(res, "typelem");
1738         i_typrelid = PQfnumber(res, "typrelid");
1739         i_typrelkind = PQfnumber(res, "typrelkind");
1740         i_typtype = PQfnumber(res, "typtype");
1741         i_typisdefined = PQfnumber(res, "typisdefined");
1742
1743         for (i = 0; i < ntups; i++)
1744         {
1745                 Oid                     typoutput;
1746                 FuncInfo   *funcInfo;
1747
1748                 tinfo[i].dobj.objType = DO_TYPE;
1749                 tinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1750                 tinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1751                 AssignDumpId(&tinfo[i].dobj);
1752                 tinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
1753                 tinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
1754                                                                                                 tinfo[i].dobj.catId.oid);
1755                 tinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1756                 tinfo[i].typinput = atooid(PQgetvalue(res, i, i_typinput));
1757                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
1758                 tinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
1759                 tinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
1760                 tinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
1761                 tinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
1762
1763                 /*
1764                  * If it's a table's rowtype, use special type code to facilitate
1765                  * sorting into the desired order.      (We don't want to consider it
1766                  * an ordinary type because that would bring the table up into the
1767                  * datatype part of the dump order.)
1768                  */
1769                 if (OidIsValid(tinfo[i].typrelid) && tinfo[i].typrelkind != 'c')
1770                         tinfo[i].dobj.objType = DO_TABLE_TYPE;
1771
1772                 /*
1773                  * check for user-defined array types, omit system generated ones
1774                  */
1775                 if (OidIsValid(tinfo[i].typelem) &&
1776                         tinfo[i].dobj.name[0] != '_')
1777                         tinfo[i].isArray = true;
1778                 else
1779                         tinfo[i].isArray = false;
1780
1781                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
1782                         tinfo[i].isDefined = true;
1783                 else
1784                         tinfo[i].isDefined = false;
1785
1786                 /*
1787                  * If it's a domain, fetch info about its constraints, if any
1788                  */
1789                 tinfo[i].nDomChecks = 0;
1790                 tinfo[i].domChecks = NULL;
1791                 if (tinfo[i].typtype == 'd')
1792                         getDomainConstraints(&(tinfo[i]));
1793
1794                 /*
1795                  * Make sure there are dependencies from the type to its input and
1796                  * output functions.  (We don't worry about typsend, typreceive,
1797                  * or typanalyze since those are only valid in 7.4 and later,
1798                  * wherein the standard dependency mechanism will pick them up.)
1799                  */
1800                 funcInfo = findFuncByOid(tinfo[i].typinput);
1801                 if (funcInfo)
1802                         addObjectDependency(&tinfo[i].dobj,
1803                                                                 funcInfo->dobj.dumpId);
1804                 funcInfo = findFuncByOid(typoutput);
1805                 if (funcInfo)
1806                         addObjectDependency(&tinfo[i].dobj,
1807                                                                 funcInfo->dobj.dumpId);
1808
1809                 if (strlen(tinfo[i].usename) == 0 && tinfo[i].isDefined)
1810                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
1811                                           tinfo[i].dobj.name);
1812         }
1813
1814         *numTypes = ntups;
1815
1816         PQclear(res);
1817
1818         destroyPQExpBuffer(query);
1819
1820         return tinfo;
1821 }
1822
1823 /*
1824  * getOperators:
1825  *        read all operators in the system catalogs and return them in the
1826  * OprInfo* structure
1827  *
1828  *      numOprs is set to the number of operators read in
1829  */
1830 OprInfo *
1831 getOperators(int *numOprs)
1832 {
1833         PGresult   *res;
1834         int                     ntups;
1835         int                     i;
1836         PQExpBuffer query = createPQExpBuffer();
1837         OprInfo    *oprinfo;
1838         int                     i_tableoid;
1839         int                     i_oid;
1840         int                     i_oprname;
1841         int                     i_oprnamespace;
1842         int                     i_usename;
1843         int                     i_oprcode;
1844
1845         /*
1846          * find all operators, including builtin operators; we filter out
1847          * system-defined operators at dump-out time.
1848          */
1849
1850         /* Make sure we are in proper schema */
1851         selectSourceSchema("pg_catalog");
1852
1853         if (g_fout->remoteVersion >= 70300)
1854         {
1855                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1856                                                   "oprnamespace, "
1857                                                   "(select usename from pg_user where oprowner = usesysid) as usename, "
1858                                                   "oprcode::oid as oprcode "
1859                                                   "FROM pg_operator");
1860         }
1861         else if (g_fout->remoteVersion >= 70100)
1862         {
1863                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
1864                                                   "0::oid as oprnamespace, "
1865                                                   "(select usename from pg_user where oprowner = usesysid) as usename, "
1866                                                   "oprcode::oid as oprcode "
1867                                                   "FROM pg_operator");
1868         }
1869         else
1870         {
1871                 appendPQExpBuffer(query, "SELECT "
1872                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
1873                                                   "oid, oprname, "
1874                                                   "0::oid as oprnamespace, "
1875                                                   "(select usename from pg_user where oprowner = usesysid) as usename, "
1876                                                   "oprcode::oid as oprcode "
1877                                                   "FROM pg_operator");
1878         }
1879
1880         res = PQexec(g_conn, query->data);
1881         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1882
1883         ntups = PQntuples(res);
1884         *numOprs = ntups;
1885
1886         oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
1887
1888         i_tableoid = PQfnumber(res, "tableoid");
1889         i_oid = PQfnumber(res, "oid");
1890         i_oprname = PQfnumber(res, "oprname");
1891         i_oprnamespace = PQfnumber(res, "oprnamespace");
1892         i_usename = PQfnumber(res, "usename");
1893         i_oprcode = PQfnumber(res, "oprcode");
1894
1895         for (i = 0; i < ntups; i++)
1896         {
1897                 oprinfo[i].dobj.objType = DO_OPERATOR;
1898                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1899                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1900                 AssignDumpId(&oprinfo[i].dobj);
1901                 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
1902                 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
1903                                                                                           oprinfo[i].dobj.catId.oid);
1904                 oprinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1905                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
1906
1907                 if (strlen(oprinfo[i].usename) == 0)
1908                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
1909                                           oprinfo[i].dobj.name);
1910         }
1911
1912         PQclear(res);
1913
1914         destroyPQExpBuffer(query);
1915
1916         return oprinfo;
1917 }
1918
1919 /*
1920  * getConversions:
1921  *        read all conversions in the system catalogs and return them in the
1922  * ConvInfo* structure
1923  *
1924  *      numConversions is set to the number of conversions read in
1925  */
1926 ConvInfo *
1927 getConversions(int *numConversions)
1928 {
1929         PGresult   *res;
1930         int                     ntups;
1931         int                     i;
1932         PQExpBuffer query = createPQExpBuffer();
1933         ConvInfo   *convinfo;
1934         int                     i_tableoid;
1935         int                     i_oid;
1936         int                     i_conname;
1937         int                     i_connamespace;
1938         int                     i_usename;
1939
1940         /* Conversions didn't exist pre-7.3 */
1941         if (g_fout->remoteVersion < 70300)
1942         {
1943                 *numConversions = 0;
1944                 return NULL;
1945         }
1946
1947         /*
1948          * find all conversions, including builtin conversions; we filter out
1949          * system-defined conversions at dump-out time.
1950          */
1951
1952         /* Make sure we are in proper schema */
1953         selectSourceSchema("pg_catalog");
1954
1955         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
1956                                           "connamespace, "
1957         "(select usename from pg_user where conowner = usesysid) as usename "
1958                                           "FROM pg_conversion");
1959
1960         res = PQexec(g_conn, query->data);
1961         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1962
1963         ntups = PQntuples(res);
1964         *numConversions = ntups;
1965
1966         convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
1967
1968         i_tableoid = PQfnumber(res, "tableoid");
1969         i_oid = PQfnumber(res, "oid");
1970         i_conname = PQfnumber(res, "conname");
1971         i_connamespace = PQfnumber(res, "connamespace");
1972         i_usename = PQfnumber(res, "usename");
1973
1974         for (i = 0; i < ntups; i++)
1975         {
1976                 convinfo[i].dobj.objType = DO_CONVERSION;
1977                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
1978                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
1979                 AssignDumpId(&convinfo[i].dobj);
1980                 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
1981                 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
1982                                                                                          convinfo[i].dobj.catId.oid);
1983                 convinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
1984         }
1985
1986         PQclear(res);
1987
1988         destroyPQExpBuffer(query);
1989
1990         return convinfo;
1991 }
1992
1993 /*
1994  * getOpclasses:
1995  *        read all opclasses in the system catalogs and return them in the
1996  * OpclassInfo* structure
1997  *
1998  *      numOpclasses is set to the number of opclasses read in
1999  */
2000 OpclassInfo *
2001 getOpclasses(int *numOpclasses)
2002 {
2003         PGresult   *res;
2004         int                     ntups;
2005         int                     i;
2006         PQExpBuffer query = createPQExpBuffer();
2007         OpclassInfo *opcinfo;
2008         int                     i_tableoid;
2009         int                     i_oid;
2010         int                     i_opcname;
2011         int                     i_opcnamespace;
2012         int                     i_usename;
2013
2014         /*
2015          * find all opclasses, including builtin opclasses; we filter out
2016          * system-defined opclasses at dump-out time.
2017          */
2018
2019         /* Make sure we are in proper schema */
2020         selectSourceSchema("pg_catalog");
2021
2022         if (g_fout->remoteVersion >= 70300)
2023         {
2024                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2025                                                   "opcnamespace, "
2026                                                   "(select usename from pg_user where opcowner = usesysid) as usename "
2027                                                   "FROM pg_opclass");
2028         }
2029         else if (g_fout->remoteVersion >= 70100)
2030         {
2031                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2032                                                   "0::oid as opcnamespace, "
2033                                                   "''::name as usename "
2034                                                   "FROM pg_opclass");
2035         }
2036         else
2037         {
2038                 appendPQExpBuffer(query, "SELECT "
2039                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2040                                                   "oid, opcname, "
2041                                                   "0::oid as opcnamespace, "
2042                                                   "''::name as usename "
2043                                                   "FROM pg_opclass");
2044         }
2045
2046         res = PQexec(g_conn, query->data);
2047         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2048
2049         ntups = PQntuples(res);
2050         *numOpclasses = ntups;
2051
2052         opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2053
2054         i_tableoid = PQfnumber(res, "tableoid");
2055         i_oid = PQfnumber(res, "oid");
2056         i_opcname = PQfnumber(res, "opcname");
2057         i_opcnamespace = PQfnumber(res, "opcnamespace");
2058         i_usename = PQfnumber(res, "usename");
2059
2060         for (i = 0; i < ntups; i++)
2061         {
2062                 opcinfo[i].dobj.objType = DO_OPCLASS;
2063                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2064                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2065                 AssignDumpId(&opcinfo[i].dobj);
2066                 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
2067                 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
2068                                                                                           opcinfo[i].dobj.catId.oid);
2069                 opcinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2070
2071                 if (g_fout->remoteVersion >= 70300)
2072                 {
2073                         if (strlen(opcinfo[i].usename) == 0)
2074                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
2075                                                   opcinfo[i].dobj.name);
2076                 }
2077         }
2078
2079         PQclear(res);
2080
2081         destroyPQExpBuffer(query);
2082
2083         return opcinfo;
2084 }
2085
2086 /*
2087  * getAggregates:
2088  *        read all the user-defined aggregates in the system catalogs and
2089  * return them in the AggInfo* structure
2090  *
2091  * numAggs is set to the number of aggregates read in
2092  */
2093 AggInfo *
2094 getAggregates(int *numAggs)
2095 {
2096         PGresult   *res;
2097         int                     ntups;
2098         int                     i;
2099         PQExpBuffer query = createPQExpBuffer();
2100         AggInfo    *agginfo;
2101         int                     i_tableoid;
2102         int                     i_oid;
2103         int                     i_aggname;
2104         int                     i_aggnamespace;
2105         int                     i_aggbasetype;
2106         int                     i_usename;
2107         int                     i_aggacl;
2108
2109         /* Make sure we are in proper schema */
2110         selectSourceSchema("pg_catalog");
2111
2112         /* find all user-defined aggregates */
2113
2114         if (g_fout->remoteVersion >= 70300)
2115         {
2116                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname as aggname, "
2117                                                   "pronamespace as aggnamespace, "
2118                                                   "proargtypes[0] as aggbasetype, "
2119                                                   "(select usename from pg_user where proowner = usesysid) as usename, "
2120                                                   "proacl as aggacl "
2121                                                   "FROM pg_proc "
2122                                                   "WHERE proisagg "
2123                                                   "AND pronamespace != "
2124                   "(select oid from pg_namespace where nspname = 'pg_catalog')");
2125         }
2126         else if (g_fout->remoteVersion >= 70100)
2127         {
2128                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
2129                                                   "0::oid as aggnamespace, "
2130                                                   "aggbasetype, "
2131                                                   "(select usename from pg_user where aggowner = usesysid) as usename, "
2132                                                   "'{=X}' as aggacl "
2133                                                   "FROM pg_aggregate "
2134                                                   "where oid > '%u'::oid",
2135                                                   g_last_builtin_oid);
2136         }
2137         else
2138         {
2139                 appendPQExpBuffer(query, "SELECT "
2140                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
2141                                                   "oid, aggname, "
2142                                                   "0::oid as aggnamespace, "
2143                                                   "aggbasetype, "
2144                                                   "(select usename from pg_user where aggowner = usesysid) as usename, "
2145                                                   "'{=X}' as aggacl "
2146                                                   "FROM pg_aggregate "
2147                                                   "where oid > '%u'::oid",
2148                                                   g_last_builtin_oid);
2149         }
2150
2151         res = PQexec(g_conn, query->data);
2152         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2153
2154         ntups = PQntuples(res);
2155         *numAggs = ntups;
2156
2157         agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
2158
2159         i_tableoid = PQfnumber(res, "tableoid");
2160         i_oid = PQfnumber(res, "oid");
2161         i_aggname = PQfnumber(res, "aggname");
2162         i_aggnamespace = PQfnumber(res, "aggnamespace");
2163         i_aggbasetype = PQfnumber(res, "aggbasetype");
2164         i_usename = PQfnumber(res, "usename");
2165         i_aggacl = PQfnumber(res, "aggacl");
2166
2167         for (i = 0; i < ntups; i++)
2168         {
2169                 agginfo[i].aggfn.dobj.objType = DO_AGG;
2170                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2171                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2172                 AssignDumpId(&agginfo[i].aggfn.dobj);
2173                 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
2174                 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
2175                                                                                 agginfo[i].aggfn.dobj.catId.oid);
2176                 agginfo[i].aggfn.usename = strdup(PQgetvalue(res, i, i_usename));
2177                 if (strlen(agginfo[i].aggfn.usename) == 0)
2178                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
2179                                           agginfo[i].aggfn.dobj.name);
2180                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently
2181                                                                                                  * interesting */
2182                 agginfo[i].aggfn.nargs = 1;
2183                 agginfo[i].aggfn.argtypes = (Oid *) malloc(sizeof(Oid));
2184                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_aggbasetype));
2185                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
2186                 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
2187                 agginfo[i].anybasetype = false; /* computed when it's dumped */
2188                 agginfo[i].fmtbasetype = NULL;  /* computed when it's dumped */
2189         }
2190
2191         PQclear(res);
2192
2193         destroyPQExpBuffer(query);
2194
2195         return agginfo;
2196 }
2197
2198 /*
2199  * getFuncs:
2200  *        read all the user-defined functions in the system catalogs and
2201  * return them in the FuncInfo* structure
2202  *
2203  * numFuncs is set to the number of functions read in
2204  */
2205 FuncInfo *
2206 getFuncs(int *numFuncs)
2207 {
2208         PGresult   *res;
2209         int                     ntups;
2210         int                     i;
2211         PQExpBuffer query = createPQExpBuffer();
2212         FuncInfo   *finfo;
2213         int                     i_tableoid;
2214         int                     i_oid;
2215         int                     i_proname;
2216         int                     i_pronamespace;
2217         int                     i_usename;
2218         int                     i_prolang;
2219         int                     i_pronargs;
2220         int                     i_proargtypes;
2221         int                     i_prorettype;
2222         int                     i_proacl;
2223
2224         /* Make sure we are in proper schema */
2225         selectSourceSchema("pg_catalog");
2226
2227         /* find all user-defined funcs */
2228
2229         if (g_fout->remoteVersion >= 70300)
2230         {
2231                 appendPQExpBuffer(query,
2232                                                   "SELECT tableoid, oid, proname, prolang, "
2233                                                   "pronargs, proargtypes, prorettype, proacl, "
2234                                                   "pronamespace, "
2235                                                   "(select usename from pg_user where proowner = usesysid) as usename "
2236                                                   "FROM pg_proc "
2237                                                   "WHERE NOT proisagg "
2238                                                   "AND pronamespace != "
2239                   "(select oid from pg_namespace where nspname = 'pg_catalog')");
2240         }
2241         else if (g_fout->remoteVersion >= 70100)
2242         {
2243                 appendPQExpBuffer(query,
2244                                                   "SELECT tableoid, oid, proname, prolang, "
2245                                                   "pronargs, proargtypes, prorettype, "
2246                                                   "'{=X}' as proacl, "
2247                                                   "0::oid as pronamespace, "
2248                                                   "(select usename from pg_user where proowner = usesysid) as usename "
2249                                                   "FROM pg_proc "
2250                                                   "where pg_proc.oid > '%u'::oid",
2251                                                   g_last_builtin_oid);
2252         }
2253         else
2254         {
2255                 appendPQExpBuffer(query,
2256                                                   "SELECT "
2257                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_proc') AS tableoid, "
2258                                                   "oid, proname, prolang, "
2259                                                   "pronargs, proargtypes, prorettype, "
2260                                                   "'{=X}' as proacl, "
2261                                                   "0::oid as pronamespace, "
2262                                                   "(select usename from pg_user where proowner = usesysid) as usename "
2263                                                   "FROM pg_proc "
2264                                                   "where pg_proc.oid > '%u'::oid",
2265                                                   g_last_builtin_oid);
2266         }
2267
2268         res = PQexec(g_conn, query->data);
2269         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2270
2271         ntups = PQntuples(res);
2272
2273         *numFuncs = ntups;
2274
2275         finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
2276
2277         i_tableoid = PQfnumber(res, "tableoid");
2278         i_oid = PQfnumber(res, "oid");
2279         i_proname = PQfnumber(res, "proname");
2280         i_pronamespace = PQfnumber(res, "pronamespace");
2281         i_usename = PQfnumber(res, "usename");
2282         i_prolang = PQfnumber(res, "prolang");
2283         i_pronargs = PQfnumber(res, "pronargs");
2284         i_proargtypes = PQfnumber(res, "proargtypes");
2285         i_prorettype = PQfnumber(res, "prorettype");
2286         i_proacl = PQfnumber(res, "proacl");
2287
2288         for (i = 0; i < ntups; i++)
2289         {
2290                 finfo[i].dobj.objType = DO_FUNC;
2291                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2292                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2293                 AssignDumpId(&finfo[i].dobj);
2294                 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
2295                 finfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
2296                                                                                                 finfo[i].dobj.catId.oid);
2297                 finfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2298                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
2299                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
2300                 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
2301                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
2302                 if (finfo[i].nargs == 0)
2303                         finfo[i].argtypes = NULL;
2304                 else
2305                 {
2306                         finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
2307                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
2308                                                   finfo[i].argtypes, finfo[i].nargs);
2309                 }
2310
2311                 if (strlen(finfo[i].usename) == 0)
2312                         write_msg(NULL, "WARNING: owner of function \"%s\" appears to be invalid\n",
2313                                           finfo[i].dobj.name);
2314         }
2315
2316         PQclear(res);
2317
2318         destroyPQExpBuffer(query);
2319
2320         return finfo;
2321 }
2322
2323 /*
2324  * getTables
2325  *        read all the user-defined tables (no indexes, no catalogs)
2326  * in the system catalogs return them in the TableInfo* structure
2327  *
2328  * numTables is set to the number of tables read in
2329  */
2330 TableInfo *
2331 getTables(int *numTables)
2332 {
2333         PGresult   *res;
2334         int                     ntups;
2335         int                     i;
2336         PQExpBuffer query = createPQExpBuffer();
2337         PQExpBuffer delqry = createPQExpBuffer();
2338         PQExpBuffer lockquery = createPQExpBuffer();
2339         TableInfo  *tblinfo;
2340         int                     i_reltableoid;
2341         int                     i_reloid;
2342         int                     i_relname;
2343         int                     i_relnamespace;
2344         int                     i_relkind;
2345         int                     i_relacl;
2346         int                     i_usename;
2347         int                     i_relchecks;
2348         int                     i_reltriggers;
2349         int                     i_relhasindex;
2350         int                     i_relhasrules;
2351         int                     i_relhasoids;
2352         int                     i_owning_tab;
2353         int                     i_owning_col;
2354         int                     i_reltablespace;
2355
2356         /* Make sure we are in proper schema */
2357         selectSourceSchema("pg_catalog");
2358
2359         /*
2360          * Find all the tables (including views and sequences).
2361          *
2362          * We include system catalogs, so that we can work if a user table is
2363          * defined to inherit from a system catalog (pretty weird, but...)
2364          *
2365          * We ignore tables that are not type 'r' (ordinary relation) or 'S'
2366          * (sequence) or 'v' (view).
2367          *
2368          * Note: in this phase we should collect only a minimal amount of
2369          * information about each table, basically just enough to decide if it
2370          * is interesting.      We must fetch all tables in this phase because
2371          * otherwise we cannot correctly identify inherited columns, serial
2372          * columns, etc.
2373          */
2374
2375         if (g_fout->remoteVersion >= 80000)
2376         {
2377                 /*
2378                  * Left join to pick up dependency info linking sequences to their
2379                  * serial column, if any
2380                  */
2381                 appendPQExpBuffer(query,
2382                                                   "SELECT c.tableoid, c.oid, relname, "
2383                                                   "relacl, relkind, relnamespace, "
2384                                                   "(select usename from pg_user where relowner = usesysid) as usename, "
2385                                                   "relchecks, reltriggers, "
2386                                                   "relhasindex, relhasrules, relhasoids, "
2387                                                   "d.refobjid as owning_tab, "
2388                                                   "d.refobjsubid as owning_col, "
2389                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace "
2390                                                   "from pg_class c "
2391                                                   "left join pg_depend d on "
2392                                                   "(c.relkind = '%c' and "
2393                                                 "d.classid = c.tableoid and d.objid = c.oid and "
2394                                                   "d.objsubid = 0 and "
2395                                                 "d.refclassid = c.tableoid and d.deptype = 'i') "
2396                                                   "where relkind in ('%c', '%c', '%c') "
2397                                                   "order by c.oid",
2398                                                   RELKIND_SEQUENCE,
2399                                            RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2400         }
2401         else if (g_fout->remoteVersion >= 70300)
2402         {
2403                 /*
2404                  * Left join to pick up dependency info linking sequences to their
2405                  * serial column, if any
2406                  */
2407                 appendPQExpBuffer(query,
2408                                                   "SELECT c.tableoid, c.oid, relname, "
2409                                                   "relacl, relkind, relnamespace, "
2410                                                   "(select usename from pg_user where relowner = usesysid) as usename, "
2411                                                   "relchecks, reltriggers, "
2412                                                   "relhasindex, relhasrules, relhasoids, "
2413                                                   "d.refobjid as owning_tab, "
2414                                                   "d.refobjsubid as owning_col, "
2415                                                   "NULL as reltablespace "
2416                                                   "from pg_class c "
2417                                                   "left join pg_depend d on "
2418                                                   "(c.relkind = '%c' and "
2419                                                 "d.classid = c.tableoid and d.objid = c.oid and "
2420                                                   "d.objsubid = 0 and "
2421                                                 "d.refclassid = c.tableoid and d.deptype = 'i') "
2422                                                   "where relkind in ('%c', '%c', '%c') "
2423                                                   "order by c.oid",
2424                                                   RELKIND_SEQUENCE,
2425                                            RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2426         }
2427         else if (g_fout->remoteVersion >= 70200)
2428         {
2429                 appendPQExpBuffer(query,
2430                                            "SELECT tableoid, oid, relname, relacl, relkind, "
2431                                                   "0::oid as relnamespace, "
2432                                                   "(select usename from pg_user where relowner = usesysid) as usename, "
2433                                                   "relchecks, reltriggers, "
2434                                                   "relhasindex, relhasrules, relhasoids, "
2435                                                   "NULL::oid as owning_tab, "
2436                                                   "NULL::int4 as owning_col, "
2437                                                   "NULL as reltablespace "
2438                                                   "from pg_class "
2439                                                   "where relkind in ('%c', '%c', '%c') "
2440                                                   "order by oid",
2441                                            RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2442         }
2443         else if (g_fout->remoteVersion >= 70100)
2444         {
2445                 /* all tables have oids in 7.1 */
2446                 appendPQExpBuffer(query,
2447                                            "SELECT tableoid, oid, relname, relacl, relkind, "
2448                                                   "0::oid as relnamespace, "
2449                                                   "(select usename from pg_user where relowner = usesysid) as usename, "
2450                                                   "relchecks, reltriggers, "
2451                                                   "relhasindex, relhasrules, "
2452                                                   "'t'::bool as relhasoids, "
2453                                                   "NULL::oid as owning_tab, "
2454                                                   "NULL::int4 as owning_col, "
2455                                                   "NULL as reltablespace "
2456                                                   "from pg_class "
2457                                                   "where relkind in ('%c', '%c', '%c') "
2458                                                   "order by oid",
2459                                            RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
2460         }
2461         else
2462         {
2463                 /*
2464                  * Before 7.1, view relkind was not set to 'v', so we must check
2465                  * if we have a view by looking for a rule in pg_rewrite.
2466                  */
2467                 appendPQExpBuffer(query,
2468                                                   "SELECT "
2469                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2470                                                   "oid, relname, relacl, "
2471                                                   "CASE WHEN relhasrules and relkind = 'r' "
2472                                   "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
2473                                   "             r.ev_class = c.oid AND r.ev_type = '1') "
2474                                                   "THEN '%c'::\"char\" "
2475                                                   "ELSE relkind END AS relkind,"
2476                                                   "0::oid as relnamespace, "
2477                                                   "(select usename from pg_user where relowner = usesysid) as usename, "
2478                                                   "relchecks, reltriggers, "
2479                                                   "relhasindex, relhasrules, "
2480                                                   "'t'::bool as relhasoids, "
2481                                                   "NULL::oid as owning_tab, "
2482                                                   "NULL::int4 as owning_col, "
2483                                                   "NULL as reltablespace "
2484                                                   "from pg_class c "
2485                                                   "where relkind in ('%c', '%c') "
2486                                                   "order by oid",
2487                                                   RELKIND_VIEW,
2488                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
2489         }
2490
2491         res = PQexec(g_conn, query->data);
2492         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2493
2494         ntups = PQntuples(res);
2495
2496         *numTables = ntups;
2497
2498         /*
2499          * Extract data from result and lock dumpable tables.  We do the
2500          * locking before anything else, to minimize the window wherein a
2501          * table could disappear under us.
2502          *
2503          * Note that we have to save info about all tables here, even when
2504          * dumping only one, because we don't yet know which tables might be
2505          * inheritance ancestors of the target table.
2506          */
2507         tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
2508
2509         i_reltableoid = PQfnumber(res, "tableoid");
2510         i_reloid = PQfnumber(res, "oid");
2511         i_relname = PQfnumber(res, "relname");
2512         i_relnamespace = PQfnumber(res, "relnamespace");
2513         i_relacl = PQfnumber(res, "relacl");
2514         i_relkind = PQfnumber(res, "relkind");
2515         i_usename = PQfnumber(res, "usename");
2516         i_relchecks = PQfnumber(res, "relchecks");
2517         i_reltriggers = PQfnumber(res, "reltriggers");
2518         i_relhasindex = PQfnumber(res, "relhasindex");
2519         i_relhasrules = PQfnumber(res, "relhasrules");
2520         i_relhasoids = PQfnumber(res, "relhasoids");
2521         i_owning_tab = PQfnumber(res, "owning_tab");
2522         i_owning_col = PQfnumber(res, "owning_col");
2523         i_reltablespace = PQfnumber(res, "reltablespace");
2524
2525         for (i = 0; i < ntups; i++)
2526         {
2527                 tblinfo[i].dobj.objType = DO_TABLE;
2528                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
2529                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
2530                 AssignDumpId(&tblinfo[i].dobj);
2531                 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
2532                 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
2533                                                                                           tblinfo[i].dobj.catId.oid);
2534                 tblinfo[i].usename = strdup(PQgetvalue(res, i, i_usename));
2535                 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
2536                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
2537                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
2538                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
2539                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
2540                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
2541                 tblinfo[i].ntrig = atoi(PQgetvalue(res, i, i_reltriggers));
2542                 if (PQgetisnull(res, i, i_owning_tab))
2543                 {
2544                         tblinfo[i].owning_tab = InvalidOid;
2545                         tblinfo[i].owning_col = 0;
2546                 }
2547                 else
2548                 {
2549                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
2550                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
2551                 }
2552                 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
2553
2554                 /* other fields were zeroed above */
2555
2556                 /*
2557                  * Decide whether we want to dump this table.  Sequences owned by
2558                  * serial columns are never dumpable on their own; we will
2559                  * transpose their owning table's dump flag to them below.
2560                  */
2561                 if (OidIsValid(tblinfo[i].owning_tab))
2562                         tblinfo[i].dump = false;
2563                 else
2564                         selectDumpableTable(&tblinfo[i]);
2565                 tblinfo[i].interesting = tblinfo[i].dump;
2566
2567                 /*
2568                  * Read-lock target tables to make sure they aren't DROPPED or
2569                  * altered in schema before we get around to dumping them.
2570                  *
2571                  * Note that we don't explicitly lock parents of the target tables;
2572                  * we assume our lock on the child is enough to prevent schema
2573                  * alterations to parent tables.
2574                  *
2575                  * NOTE: it'd be kinda nice to lock views and sequences too, not only
2576                  * plain tables, but the backend doesn't presently allow that.
2577                  */
2578                 if (tblinfo[i].dump && tblinfo[i].relkind == RELKIND_RELATION)
2579                 {
2580                         resetPQExpBuffer(lockquery);
2581                         appendPQExpBuffer(lockquery,
2582                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
2583                                          fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
2584                                                                         tblinfo[i].dobj.name));
2585                         do_sql_command(g_conn, lockquery->data);
2586                 }
2587
2588                 /* Emit notice if join for owner failed */
2589                 if (strlen(tblinfo[i].usename) == 0)
2590                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
2591                                           tblinfo[i].dobj.name);
2592         }
2593
2594         /*
2595          * If the user is attempting to dump a specific table, check to ensure
2596          * that the specified table actually exists.  (This is a bit
2597          * simplistic since we don't fully check the combination of -n and -t
2598          * switches.)
2599          */
2600         if (selectTableName)
2601         {
2602                 for (i = 0; i < ntups; i++)
2603                         if (strcmp(tblinfo[i].dobj.name, selectTableName) == 0)
2604                                 break;
2605
2606                 /* Didn't find a match */
2607                 if (i == ntups)
2608                 {
2609                         write_msg(NULL, "specified table \"%s\" does not exist\n",
2610                                           selectTableName);
2611                         exit_nicely();
2612                 }
2613         }
2614
2615         PQclear(res);
2616         destroyPQExpBuffer(query);
2617         destroyPQExpBuffer(delqry);
2618         destroyPQExpBuffer(lockquery);
2619
2620         return tblinfo;
2621 }
2622
2623 /*
2624  * getInherits
2625  *        read all the inheritance information
2626  * from the system catalogs return them in the InhInfo* structure
2627  *
2628  * numInherits is set to the number of pairs read in
2629  */
2630 InhInfo *
2631 getInherits(int *numInherits)
2632 {
2633         PGresult   *res;
2634         int                     ntups;
2635         int                     i;
2636         PQExpBuffer query = createPQExpBuffer();
2637         InhInfo    *inhinfo;
2638
2639         int                     i_inhrelid;
2640         int                     i_inhparent;
2641
2642         /* Make sure we are in proper schema */
2643         selectSourceSchema("pg_catalog");
2644
2645         /* find all the inheritance information */
2646
2647         appendPQExpBuffer(query, "SELECT inhrelid, inhparent from pg_inherits");
2648
2649         res = PQexec(g_conn, query->data);
2650         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2651
2652         ntups = PQntuples(res);
2653
2654         *numInherits = ntups;
2655
2656         inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
2657
2658         i_inhrelid = PQfnumber(res, "inhrelid");
2659         i_inhparent = PQfnumber(res, "inhparent");
2660
2661         for (i = 0; i < ntups; i++)
2662         {
2663                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
2664                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
2665         }
2666
2667         PQclear(res);
2668
2669         destroyPQExpBuffer(query);
2670
2671         return inhinfo;
2672 }
2673
2674 /*
2675  * getIndexes
2676  *        get information about every index on a dumpable table
2677  *
2678  * Note: index data is not returned directly to the caller, but it
2679  * does get entered into the DumpableObject tables.
2680  */
2681 void
2682 getIndexes(TableInfo tblinfo[], int numTables)
2683 {
2684         int                     i,
2685                                 j;
2686         PQExpBuffer query = createPQExpBuffer();
2687         PGresult   *res;
2688         IndxInfo   *indxinfo;
2689         ConstraintInfo *constrinfo;
2690         int                     i_tableoid,
2691                                 i_oid,
2692                                 i_indexname,
2693                                 i_indexdef,
2694                                 i_indnkeys,
2695                                 i_indkey,
2696                                 i_indisclustered,
2697                                 i_contype,
2698                                 i_conname,
2699                                 i_contableoid,
2700                                 i_conoid,
2701                                 i_tablespace;
2702         int                     ntups;
2703
2704         for (i = 0; i < numTables; i++)
2705         {
2706                 TableInfo  *tbinfo = &tblinfo[i];
2707
2708                 /* Only plain tables have indexes */
2709                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
2710                         continue;
2711
2712                 if (!tbinfo->dump)
2713                         continue;
2714
2715                 if (g_verbose)
2716                         write_msg(NULL, "reading indexes for table \"%s\"\n",
2717                                           tbinfo->dobj.name);
2718
2719                 /* Make sure we are in proper schema so indexdef is right */
2720                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2721
2722                 /*
2723                  * The point of the messy-looking outer join is to find a
2724                  * constraint that is related by an internal dependency link to
2725                  * the index. If we find one, create a CONSTRAINT entry linked to
2726                  * the INDEX entry.  We assume an index won't have more than one
2727                  * internal dependency.
2728                  */
2729                 resetPQExpBuffer(query);
2730                 if (g_fout->remoteVersion >= 80000)
2731                 {
2732                         appendPQExpBuffer(query,
2733                                                           "SELECT t.tableoid, t.oid, "
2734                                                           "t.relname as indexname, "
2735                                  "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2736                                                           "t.relnatts as indnkeys, "
2737                                                           "i.indkey, i.indisclustered, "
2738                                                           "c.contype, c.conname, "
2739                                                           "c.tableoid as contableoid, "
2740                                                           "c.oid as conoid, "
2741                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) as tablespace "
2742                                                           "FROM pg_catalog.pg_index i "
2743                                   "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2744                                                           "LEFT JOIN pg_catalog.pg_depend d "
2745                                                           "ON (d.classid = t.tableoid "
2746                                                           "AND d.objid = t.oid "
2747                                                           "AND d.deptype = 'i') "
2748                                                           "LEFT JOIN pg_catalog.pg_constraint c "
2749                                                           "ON (d.refclassid = c.tableoid "
2750                                                           "AND d.refobjid = c.oid) "
2751                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
2752                                                           "ORDER BY indexname",
2753                                                           tbinfo->dobj.catId.oid);
2754                 }
2755                 else if (g_fout->remoteVersion >= 70300)
2756                 {
2757                         appendPQExpBuffer(query,
2758                                                           "SELECT t.tableoid, t.oid, "
2759                                                           "t.relname as indexname, "
2760                                  "pg_catalog.pg_get_indexdef(i.indexrelid) as indexdef, "
2761                                                           "t.relnatts as indnkeys, "
2762                                                           "i.indkey, i.indisclustered, "
2763                                                           "c.contype, c.conname, "
2764                                                           "c.tableoid as contableoid, "
2765                                                           "c.oid as conoid, "
2766                                                           "NULL as tablespace "
2767                                                           "FROM pg_catalog.pg_index i "
2768                                   "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
2769                                                           "LEFT JOIN pg_catalog.pg_depend d "
2770                                                           "ON (d.classid = t.tableoid "
2771                                                           "AND d.objid = t.oid "
2772                                                           "AND d.deptype = 'i') "
2773                                                           "LEFT JOIN pg_catalog.pg_constraint c "
2774                                                           "ON (d.refclassid = c.tableoid "
2775                                                           "AND d.refobjid = c.oid) "
2776                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
2777                                                           "ORDER BY indexname",
2778                                                           tbinfo->dobj.catId.oid);
2779                 }
2780                 else if (g_fout->remoteVersion >= 70100)
2781                 {
2782                         appendPQExpBuffer(query,
2783                                                           "SELECT t.tableoid, t.oid, "
2784                                                           "t.relname as indexname, "
2785                                                         "pg_get_indexdef(i.indexrelid) as indexdef, "
2786                                                           "t.relnatts as indnkeys, "
2787                                                           "i.indkey, false as indisclustered, "
2788                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
2789                                                           "ELSE '0'::char END as contype, "
2790                                                           "t.relname as conname, "
2791                                                           "0::oid as contableoid, "
2792                                                           "t.oid as conoid, "
2793                                                           "NULL as tablespace "
2794                                                           "FROM pg_index i, pg_class t "
2795                                                           "WHERE t.oid = i.indexrelid "
2796                                                           "AND i.indrelid = '%u'::oid "
2797                                                           "ORDER BY indexname",
2798                                                           tbinfo->dobj.catId.oid);
2799                 }
2800                 else
2801                 {
2802                         appendPQExpBuffer(query,
2803                                                           "SELECT "
2804                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
2805                                                           "t.oid, "
2806                                                           "t.relname as indexname, "
2807                                                         "pg_get_indexdef(i.indexrelid) as indexdef, "
2808                                                           "t.relnatts as indnkeys, "
2809                                                           "i.indkey, false as indisclustered, "
2810                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
2811                                                           "ELSE '0'::char END as contype, "
2812                                                           "t.relname as conname, "
2813                                                           "0::oid as contableoid, "
2814                                                           "t.oid as conoid, "
2815                                                           "NULL as tablespace "
2816                                                           "FROM pg_index i, pg_class t "
2817                                                           "WHERE t.oid = i.indexrelid "
2818                                                           "AND i.indrelid = '%u'::oid "
2819                                                           "ORDER BY indexname",
2820                                                           tbinfo->dobj.catId.oid);
2821                 }
2822
2823                 res = PQexec(g_conn, query->data);
2824                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2825
2826                 ntups = PQntuples(res);
2827
2828                 i_tableoid = PQfnumber(res, "tableoid");
2829                 i_oid = PQfnumber(res, "oid");
2830                 i_indexname = PQfnumber(res, "indexname");
2831                 i_indexdef = PQfnumber(res, "indexdef");
2832                 i_indnkeys = PQfnumber(res, "indnkeys");
2833                 i_indkey = PQfnumber(res, "indkey");
2834                 i_indisclustered = PQfnumber(res, "indisclustered");
2835                 i_contype = PQfnumber(res, "contype");
2836                 i_conname = PQfnumber(res, "conname");
2837                 i_contableoid = PQfnumber(res, "contableoid");
2838                 i_conoid = PQfnumber(res, "conoid");
2839                 i_tablespace = PQfnumber(res, "tablespace");
2840
2841                 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
2842                 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2843
2844                 for (j = 0; j < ntups; j++)
2845                 {
2846                         char            contype;
2847
2848                         indxinfo[j].dobj.objType = DO_INDEX;
2849                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
2850                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
2851                         AssignDumpId(&indxinfo[j].dobj);
2852                         indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
2853                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2854                         indxinfo[j].indextable = tbinfo;
2855                         indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
2856                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
2857                         indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
2858
2859                         /*
2860                          * In pre-7.4 releases, indkeys may contain more entries than
2861                          * indnkeys says (since indnkeys will be 1 for a functional
2862                          * index).      We don't actually care about this case since we
2863                          * don't examine indkeys except for indexes associated with
2864                          * PRIMARY and UNIQUE constraints, which are never functional
2865                          * indexes. But we have to allocate enough space to keep
2866                          * parseOidArray from complaining.
2867                          */
2868                         indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
2869                         parseOidArray(PQgetvalue(res, j, i_indkey),
2870                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
2871                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
2872                         contype = *(PQgetvalue(res, j, i_contype));
2873
2874                         if (contype == 'p' || contype == 'u')
2875                         {
2876                                 /*
2877                                  * If we found a constraint matching the index, create an
2878                                  * entry for it.
2879                                  *
2880                                  * In a pre-7.3 database, we take this path iff the index was
2881                                  * marked indisprimary.
2882                                  */
2883                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
2884                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2885                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2886                                 AssignDumpId(&constrinfo[j].dobj);
2887                                 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2888                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2889                                 constrinfo[j].contable = tbinfo;
2890                                 constrinfo[j].condomain = NULL;
2891                                 constrinfo[j].contype = contype;
2892                                 constrinfo[j].condef = NULL;
2893                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
2894                                 constrinfo[j].coninherited = false;
2895                                 constrinfo[j].separate = true;
2896
2897                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
2898
2899                                 /* If pre-7.3 DB, better make sure table comes first */
2900                                 addObjectDependency(&constrinfo[j].dobj,
2901                                                                         tbinfo->dobj.dumpId);
2902                         }
2903                         else
2904                         {
2905                                 /* Plain secondary index */
2906                                 indxinfo[j].indexconstraint = 0;
2907                         }
2908                 }
2909
2910                 PQclear(res);
2911         }
2912
2913         destroyPQExpBuffer(query);
2914 }
2915
2916 /*
2917  * getConstraints
2918  *
2919  * Get info about constraints on dumpable tables.
2920  *
2921  * Currently handles foreign keys only.
2922  * Unique and primary key constraints are handled with indexes,
2923  * while check constraints are processed in getTableAttrs().
2924  */
2925 void
2926 getConstraints(TableInfo tblinfo[], int numTables)
2927 {
2928         int                     i,
2929                                 j;
2930         ConstraintInfo *constrinfo;
2931         PQExpBuffer query;
2932         PGresult   *res;
2933         int                     i_condef,
2934                                 i_contableoid,
2935                                 i_conoid,
2936                                 i_conname;
2937         int                     ntups;
2938
2939         /* pg_constraint was created in 7.3, so nothing to do if older */
2940         if (g_fout->remoteVersion < 70300)
2941                 return;
2942
2943         query = createPQExpBuffer();
2944
2945         for (i = 0; i < numTables; i++)
2946         {
2947                 TableInfo  *tbinfo = &tblinfo[i];
2948
2949                 if (tbinfo->ntrig == 0 || !tbinfo->dump)
2950                         continue;
2951
2952                 if (g_verbose)
2953                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
2954                                           tbinfo->dobj.name);
2955
2956                 /*
2957                  * select table schema to ensure constraint expr is qualified if
2958                  * needed
2959                  */
2960                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
2961
2962                 resetPQExpBuffer(query);
2963                 appendPQExpBuffer(query,
2964                                                   "SELECT tableoid, oid, conname, "
2965                                                 "pg_catalog.pg_get_constraintdef(oid) as condef "
2966                                                   "FROM pg_catalog.pg_constraint "
2967                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
2968                                                   "AND contype = 'f'",
2969                                                   tbinfo->dobj.catId.oid);
2970                 res = PQexec(g_conn, query->data);
2971                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2972
2973                 ntups = PQntuples(res);
2974
2975                 i_contableoid = PQfnumber(res, "tableoid");
2976                 i_conoid = PQfnumber(res, "oid");
2977                 i_conname = PQfnumber(res, "conname");
2978                 i_condef = PQfnumber(res, "condef");
2979
2980                 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
2981
2982                 for (j = 0; j < ntups; j++)
2983                 {
2984                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
2985                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
2986                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
2987                         AssignDumpId(&constrinfo[j].dobj);
2988                         constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
2989                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
2990                         constrinfo[j].contable = tbinfo;
2991                         constrinfo[j].condomain = NULL;
2992                         constrinfo[j].contype = 'f';
2993                         constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
2994                         constrinfo[j].conindex = 0;
2995                         constrinfo[j].coninherited = false;
2996                         constrinfo[j].separate = true;
2997                 }
2998
2999                 PQclear(res);
3000         }
3001
3002         destroyPQExpBuffer(query);
3003 }
3004
3005 /*
3006  * getDomainConstraints
3007  *
3008  * Get info about constraints on a domain.
3009  */
3010 static void
3011 getDomainConstraints(TypeInfo *tinfo)
3012 {
3013         int                     i;
3014         ConstraintInfo *constrinfo;
3015         PQExpBuffer query;
3016         PGresult   *res;
3017         int                     i_tableoid,
3018                                 i_oid,
3019                                 i_conname,
3020                                 i_consrc;
3021         int                     ntups;
3022
3023         /* pg_constraint was created in 7.3, so nothing to do if older */
3024         if (g_fout->remoteVersion < 70300)
3025                 return;
3026
3027         /*
3028          * select appropriate schema to ensure names in constraint are
3029          * properly qualified
3030          */
3031         selectSourceSchema(tinfo->dobj.namespace->dobj.name);
3032
3033         query = createPQExpBuffer();
3034
3035         if (g_fout->remoteVersion >= 70400)
3036                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3037                                                 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3038                                                   "FROM pg_catalog.pg_constraint "
3039                                                   "WHERE contypid = '%u'::pg_catalog.oid "
3040                                                   "ORDER BY conname",
3041                                                   tinfo->dobj.catId.oid);
3042         else
3043                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3044                                                   "'CHECK (' || consrc || ')' AS consrc "
3045                                                   "FROM pg_catalog.pg_constraint "
3046                                                   "WHERE contypid = '%u'::pg_catalog.oid "
3047                                                   "ORDER BY conname",
3048                                                   tinfo->dobj.catId.oid);
3049
3050         res = PQexec(g_conn, query->data);
3051         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3052
3053         ntups = PQntuples(res);
3054
3055         i_tableoid = PQfnumber(res, "tableoid");
3056         i_oid = PQfnumber(res, "oid");
3057         i_conname = PQfnumber(res, "conname");
3058         i_consrc = PQfnumber(res, "consrc");
3059
3060         constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
3061
3062         tinfo->nDomChecks = ntups;
3063         tinfo->domChecks = constrinfo;
3064
3065         for (i = 0; i < ntups; i++)
3066         {
3067                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
3068                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3069                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3070                 AssignDumpId(&constrinfo[i].dobj);
3071                 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
3072                 constrinfo[i].dobj.namespace = tinfo->dobj.namespace;
3073                 constrinfo[i].contable = NULL;
3074                 constrinfo[i].condomain = tinfo;
3075                 constrinfo[i].contype = 'c';
3076                 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
3077                 constrinfo[i].conindex = 0;
3078                 constrinfo[i].coninherited = false;
3079                 constrinfo[i].separate = false;
3080
3081                 /*
3082                  * Make the domain depend on the constraint, ensuring it won't be
3083                  * output till any constraint dependencies are OK.
3084                  */
3085                 addObjectDependency(&tinfo->dobj,
3086                                                         constrinfo[i].dobj.dumpId);
3087         }
3088
3089         PQclear(res);
3090
3091         destroyPQExpBuffer(query);
3092 }
3093
3094 /*
3095  * getRules
3096  *        get basic information about every rule in the system
3097  *
3098  * numRules is set to the number of rules read in
3099  */
3100 RuleInfo *
3101 getRules(int *numRules)
3102 {
3103         PGresult   *res;
3104         int                     ntups;
3105         int                     i;
3106         PQExpBuffer query = createPQExpBuffer();
3107         RuleInfo   *ruleinfo;
3108         int                     i_tableoid;
3109         int                     i_oid;
3110         int                     i_rulename;
3111         int                     i_ruletable;
3112         int                     i_ev_type;
3113         int                     i_is_instead;
3114
3115         /* Make sure we are in proper schema */
3116         selectSourceSchema("pg_catalog");
3117
3118         if (g_fout->remoteVersion >= 70100)
3119         {
3120                 appendPQExpBuffer(query, "SELECT "
3121                                                   "tableoid, oid, rulename, "
3122                                                   "ev_class as ruletable, ev_type, is_instead "
3123                                                   "FROM pg_rewrite "
3124                                                   "ORDER BY oid");
3125         }
3126         else
3127         {
3128                 appendPQExpBuffer(query, "SELECT "
3129                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
3130                                                   "oid, rulename, "
3131                                                   "ev_class as ruletable, ev_type, is_instead "
3132                                                   "FROM pg_rewrite "
3133                                                   "ORDER BY oid");
3134         }
3135
3136         res = PQexec(g_conn, query->data);
3137         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3138
3139         ntups = PQntuples(res);
3140
3141         *numRules = ntups;
3142
3143         ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
3144
3145         i_tableoid = PQfnumber(res, "tableoid");
3146         i_oid = PQfnumber(res, "oid");
3147         i_rulename = PQfnumber(res, "rulename");
3148         i_ruletable = PQfnumber(res, "ruletable");
3149         i_ev_type = PQfnumber(res, "ev_type");
3150         i_is_instead = PQfnumber(res, "is_instead");
3151
3152         for (i = 0; i < ntups; i++)
3153         {
3154                 Oid                     ruletableoid;
3155
3156                 ruleinfo[i].dobj.objType = DO_RULE;
3157                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3158                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3159                 AssignDumpId(&ruleinfo[i].dobj);
3160                 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
3161                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
3162                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
3163                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
3164                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
3165                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
3166                 if (ruleinfo[i].ruletable)
3167                 {
3168                         /*
3169                          * If the table is a view, force its ON SELECT rule to be
3170                          * sorted before the view itself --- this ensures that any
3171                          * dependencies for the rule affect the table's positioning.
3172                          * Other rules are forced to appear after their table.
3173                          */
3174                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
3175                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
3176                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
3177                                                                         ruleinfo[i].dobj.dumpId);
3178                         else
3179                                 addObjectDependency(&ruleinfo[i].dobj,
3180                                                                         ruleinfo[i].ruletable->dobj.dumpId);
3181                 }
3182         }
3183
3184         PQclear(res);
3185
3186         destroyPQExpBuffer(query);
3187
3188         return ruleinfo;
3189 }
3190
3191 /*
3192  * getTriggers
3193  *        get information about every trigger on a dumpable table
3194  *
3195  * Note: trigger data is not returned directly to the caller, but it
3196  * does get entered into the DumpableObject tables.
3197  */
3198 void
3199 getTriggers(TableInfo tblinfo[], int numTables)
3200 {
3201         int                     i,
3202                                 j;
3203         PQExpBuffer query = createPQExpBuffer();
3204         PGresult   *res;
3205         TriggerInfo *tginfo;
3206         int                     i_tableoid,
3207                                 i_oid,
3208                                 i_tgname,
3209                                 i_tgfname,
3210                                 i_tgtype,
3211                                 i_tgnargs,
3212                                 i_tgargs,
3213                                 i_tgisconstraint,
3214                                 i_tgconstrname,
3215                                 i_tgconstrrelid,
3216                                 i_tgconstrrelname,
3217                                 i_tgdeferrable,
3218                                 i_tginitdeferred;
3219         int                     ntups;
3220
3221         for (i = 0; i < numTables; i++)
3222         {
3223                 TableInfo  *tbinfo = &tblinfo[i];
3224
3225                 if (tbinfo->ntrig == 0 || !tbinfo->dump)
3226                         continue;
3227
3228                 if (g_verbose)
3229                         write_msg(NULL, "reading triggers for table \"%s\"\n",
3230                                           tbinfo->dobj.name);
3231
3232                 /*
3233                  * select table schema to ensure regproc name is qualified if
3234                  * needed
3235                  */
3236                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3237
3238                 resetPQExpBuffer(query);
3239                 if (g_fout->remoteVersion >= 70300)
3240                 {
3241                         /*
3242                          * We ignore triggers that are tied to a foreign-key
3243                          * constraint
3244                          */
3245                         appendPQExpBuffer(query,
3246                                                           "SELECT tgname, "
3247                                                           "tgfoid::pg_catalog.regproc as tgfname, "
3248                                                           "tgtype, tgnargs, tgargs, "
3249                                                    "tgisconstraint, tgconstrname, tgdeferrable, "
3250                                                  "tgconstrrelid, tginitdeferred, tableoid, oid, "
3251                                  "tgconstrrelid::pg_catalog.regclass as tgconstrrelname "
3252                                                           "from pg_catalog.pg_trigger t "
3253                                                           "where tgrelid = '%u'::pg_catalog.oid "
3254                                                           "and (not tgisconstraint "
3255                                                           " OR NOT EXISTS"
3256                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
3257                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
3258                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
3259                                                           tbinfo->dobj.catId.oid);
3260                 }
3261                 else if (g_fout->remoteVersion >= 70100)
3262                 {
3263                         appendPQExpBuffer(query,
3264                                                         "SELECT tgname, tgfoid::regproc as tgfname, "
3265                                                           "tgtype, tgnargs, tgargs, "
3266                                                    "tgisconstraint, tgconstrname, tgdeferrable, "
3267                                                  "tgconstrrelid, tginitdeferred, tableoid, oid, "
3268                           "(select relname from pg_class where oid = tgconstrrelid) "
3269                                                           "             as tgconstrrelname "
3270                                                           "from pg_trigger "
3271                                                           "where tgrelid = '%u'::oid",
3272                                                           tbinfo->dobj.catId.oid);
3273                 }
3274                 else
3275                 {
3276                         appendPQExpBuffer(query,
3277                                                         "SELECT tgname, tgfoid::regproc as tgfname, "
3278                                                           "tgtype, tgnargs, tgargs, "
3279                                                    "tgisconstraint, tgconstrname, tgdeferrable, "
3280                                                           "tgconstrrelid, tginitdeferred, "
3281                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
3282
3283                                                           "oid, "
3284                           "(select relname from pg_class where oid = tgconstrrelid) "
3285                                                           "             as tgconstrrelname "
3286                                                           "from pg_trigger "
3287                                                           "where tgrelid = '%u'::oid",
3288                                                           tbinfo->dobj.catId.oid);
3289                 }
3290                 res = PQexec(g_conn, query->data);
3291                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3292
3293                 ntups = PQntuples(res);
3294
3295                 /*
3296                  * We may have less triggers than recorded due to having ignored
3297                  * foreign-key triggers
3298                  */
3299                 if (ntups > tbinfo->ntrig)
3300                 {
3301                         write_msg(NULL, "expected %d triggers on table \"%s\" but found %d\n",
3302                                           tbinfo->ntrig, tbinfo->dobj.name, ntups);
3303                         exit_nicely();
3304                 }
3305                 i_tableoid = PQfnumber(res, "tableoid");
3306                 i_oid = PQfnumber(res, "oid");
3307                 i_tgname = PQfnumber(res, "tgname");
3308                 i_tgfname = PQfnumber(res, "tgfname");
3309                 i_tgtype = PQfnumber(res, "tgtype");
3310                 i_tgnargs = PQfnumber(res, "tgnargs");
3311                 i_tgargs = PQfnumber(res, "tgargs");
3312                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
3313                 i_tgconstrname = PQfnumber(res, "tgconstrname");
3314                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
3315                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
3316                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
3317                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
3318
3319                 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
3320
3321                 for (j = 0; j < ntups; j++)
3322                 {
3323                         tginfo[j].dobj.objType = DO_TRIGGER;
3324                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
3325                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3326                         AssignDumpId(&tginfo[j].dobj);
3327                         tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
3328                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
3329                         tginfo[j].tgtable = tbinfo;
3330                         tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
3331                         tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
3332                         tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
3333                         tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
3334                         tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
3335                         tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
3336                         tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
3337
3338                         if (tginfo[j].tgisconstraint)
3339                         {
3340                                 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
3341                                 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
3342                                 if (OidIsValid(tginfo[j].tgconstrrelid))
3343                                 {
3344                                         if (PQgetisnull(res, j, i_tgconstrrelname))
3345                                         {
3346                                                 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
3347                                                                   tginfo[j].dobj.name, tbinfo->dobj.name,
3348                                                                   tginfo[j].tgconstrrelid);
3349                                                 exit_nicely();
3350                                         }
3351                                         tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
3352                                 }
3353                                 else
3354                                         tginfo[j].tgconstrrelname = NULL;
3355                         }
3356                         else
3357                         {
3358                                 tginfo[j].tgconstrname = NULL;
3359                                 tginfo[j].tgconstrrelid = InvalidOid;
3360                                 tginfo[j].tgconstrrelname = NULL;
3361                         }
3362                 }
3363
3364                 PQclear(res);
3365         }
3366
3367         destroyPQExpBuffer(query);
3368 }
3369
3370 /*
3371  * getProcLangs
3372  *        get basic information about every procedural language in the system
3373  *
3374  * numProcLangs is set to the number of langs read in
3375  *
3376  * NB: this must run after getFuncs() because we assume we can do
3377  * findFuncByOid().
3378  */
3379 ProcLangInfo *
3380 getProcLangs(int *numProcLangs)
3381 {
3382         PGresult   *res;
3383         int                     ntups;
3384         int                     i;
3385         PQExpBuffer query = createPQExpBuffer();
3386         ProcLangInfo *planginfo;
3387         int                     i_tableoid;
3388         int                     i_oid;
3389         int                     i_lanname;
3390         int                     i_lanpltrusted;
3391         int                     i_lanplcallfoid;
3392         int                     i_lanvalidator = -1;
3393         int                     i_lanacl = -1;
3394
3395         /* Make sure we are in proper schema */
3396         selectSourceSchema("pg_catalog");
3397
3398         if (g_fout->remoteVersion >= 70100)
3399         {
3400                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
3401                                                   "WHERE lanispl "
3402                                                   "ORDER BY oid");
3403         }
3404         else
3405         {
3406                 appendPQExpBuffer(query, "SELECT "
3407                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
3408                                                   "oid, * FROM pg_language "
3409                                                   "WHERE lanispl "
3410                                                   "ORDER BY oid");
3411         }
3412
3413         res = PQexec(g_conn, query->data);
3414         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3415
3416         ntups = PQntuples(res);
3417
3418         *numProcLangs = ntups;
3419
3420         planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
3421
3422         i_tableoid = PQfnumber(res, "tableoid");
3423         i_oid = PQfnumber(res, "oid");
3424         i_lanname = PQfnumber(res, "lanname");
3425         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
3426         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
3427         if (g_fout->remoteVersion >= 70300)
3428         {
3429                 i_lanvalidator = PQfnumber(res, "lanvalidator");
3430                 i_lanacl = PQfnumber(res, "lanacl");
3431         }
3432
3433         for (i = 0; i < ntups; i++)
3434         {
3435                 planginfo[i].dobj.objType = DO_PROCLANG;
3436                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3437                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3438                 AssignDumpId(&planginfo[i].dobj);
3439
3440                 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
3441                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
3442                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
3443                 if (g_fout->remoteVersion >= 70300)
3444                 {
3445                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
3446                         planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
3447                 }
3448                 else
3449                 {
3450                         FuncInfo   *funcInfo;
3451
3452                         planginfo[i].lanvalidator = InvalidOid;
3453                         planginfo[i].lanacl = strdup("{=U}");
3454
3455                         /*
3456                          * We need to make a dependency to ensure the function will be
3457                          * dumped first.  (In 7.3 and later the regular dependency
3458                          * mechanism will handle this for us.)
3459                          */
3460                         funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
3461                         if (funcInfo)
3462                                 addObjectDependency(&planginfo[i].dobj,
3463                                                                         funcInfo->dobj.dumpId);
3464                 }
3465         }
3466
3467         PQclear(res);
3468
3469         destroyPQExpBuffer(query);
3470
3471         return planginfo;
3472 }
3473
3474 /*
3475  * getCasts
3476  *        get basic information about every cast in the system
3477  *
3478  * numCasts is set to the number of casts read in
3479  */
3480 CastInfo *
3481 getCasts(int *numCasts)
3482 {
3483         PGresult   *res;
3484         int                     ntups;
3485         int                     i;
3486         PQExpBuffer query = createPQExpBuffer();
3487         CastInfo   *castinfo;
3488         int                     i_tableoid;
3489         int                     i_oid;
3490         int                     i_castsource;
3491         int                     i_casttarget;
3492         int                     i_castfunc;
3493         int                     i_castcontext;
3494
3495         /* Make sure we are in proper schema */
3496         selectSourceSchema("pg_catalog");
3497
3498         if (g_fout->remoteVersion >= 70300)
3499         {
3500                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
3501                                                   "castsource, casttarget, castfunc, castcontext "
3502                                                   "FROM pg_cast ORDER BY 3,4");
3503         }
3504         else
3505         {
3506                 appendPQExpBuffer(query, "SELECT 0 as tableoid, p.oid, "
3507                                                   "t1.oid as castsource, t2.oid as casttarget, "
3508                                                   "p.oid as castfunc, 'e' as castcontext "
3509                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
3510                                                   "WHERE p.pronargs = 1 AND "
3511                                                   "p.proargtypes[0] = t1.oid AND "
3512                                           "p.prorettype = t2.oid AND p.proname = t2.typname "
3513                                                   "ORDER BY 3,4");
3514         }
3515
3516         res = PQexec(g_conn, query->data);
3517         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3518
3519         ntups = PQntuples(res);
3520
3521         *numCasts = ntups;
3522
3523         castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
3524
3525         i_tableoid = PQfnumber(res, "tableoid");
3526         i_oid = PQfnumber(res, "oid");
3527         i_castsource = PQfnumber(res, "castsource");
3528         i_casttarget = PQfnumber(res, "casttarget");
3529         i_castfunc = PQfnumber(res, "castfunc");
3530         i_castcontext = PQfnumber(res, "castcontext");
3531
3532         for (i = 0; i < ntups; i++)
3533         {
3534                 PQExpBufferData namebuf;
3535                 TypeInfo   *sTypeInfo;
3536                 TypeInfo   *tTypeInfo;
3537
3538                 castinfo[i].dobj.objType = DO_CAST;
3539                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3540                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3541                 AssignDumpId(&castinfo[i].dobj);
3542                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
3543                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
3544                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
3545                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
3546
3547                 /*
3548                  * Try to name cast as concatenation of typnames.  This is only
3549                  * used for purposes of sorting.  If we fail to find either type,
3550                  * the name will be an empty string.
3551                  */
3552                 initPQExpBuffer(&namebuf);
3553                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
3554                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
3555                 if (sTypeInfo && tTypeInfo)
3556                         appendPQExpBuffer(&namebuf, "%s %s",
3557                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
3558                 castinfo[i].dobj.name = namebuf.data;
3559
3560                 if (OidIsValid(castinfo[i].castfunc))
3561                 {
3562                         /*
3563                          * We need to make a dependency to ensure the function will be
3564                          * dumped first.  (In 7.3 and later the regular dependency
3565                          * mechanism will handle this for us.)
3566                          */
3567                         FuncInfo   *funcInfo;
3568
3569                         funcInfo = findFuncByOid(castinfo[i].castfunc);
3570                         if (funcInfo)
3571                                 addObjectDependency(&castinfo[i].dobj,
3572                                                                         funcInfo->dobj.dumpId);
3573                 }
3574         }
3575
3576         PQclear(res);
3577
3578         destroyPQExpBuffer(query);
3579
3580         return castinfo;
3581 }
3582
3583 /*
3584  * getTableAttrs -
3585  *        for each interesting table, read info about its attributes
3586  *        (names, types, default values, CHECK constraints, etc)
3587  *
3588  * This is implemented in a very inefficient way right now, looping
3589  * through the tblinfo and doing a join per table to find the attrs and their
3590  * types.  However, because we want type names and so forth to be named
3591  * relative to the schema of each table, we couldn't do it in just one
3592  * query.  (Maybe one query per schema?)
3593  *
3594  *      modifies tblinfo
3595  */
3596 void
3597 getTableAttrs(TableInfo *tblinfo, int numTables)
3598 {
3599         int                     i,
3600                                 j,
3601                                 k;
3602         PQExpBuffer q = createPQExpBuffer();
3603         int                     i_attnum;
3604         int                     i_attname;
3605         int                     i_atttypname;
3606         int                     i_atttypmod;
3607         int                     i_attstattarget;
3608         int                     i_attstorage;
3609         int                     i_typstorage;
3610         int                     i_attnotnull;
3611         int                     i_atthasdef;
3612         int                     i_attisdropped;
3613         int                     i_attislocal;
3614         PGresult   *res;
3615         int                     ntups;
3616         bool            hasdefaults;
3617
3618         for (i = 0; i < numTables; i++)
3619         {
3620                 TableInfo  *tbinfo = &tblinfo[i];
3621
3622                 /* Don't bother to collect info for sequences */
3623                 if (tbinfo->relkind == RELKIND_SEQUENCE)
3624                         continue;
3625
3626                 /* Don't bother with uninteresting tables, either */
3627                 if (!tbinfo->interesting)
3628                         continue;
3629
3630                 /*
3631                  * Make sure we are in proper schema for this table; this allows
3632                  * correct retrieval of formatted type names and default exprs
3633                  */
3634                 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3635
3636                 /* find all the user attributes and their types */
3637
3638                 /*
3639                  * we must read the attribute names in attribute number order!
3640                  * because we will use the attnum to index into the attnames array
3641                  * later.  We actually ask to order by "attrelid, attnum" because
3642                  * (at least up to 7.3) the planner is not smart enough to realize
3643                  * it needn't re-sort the output of an indexscan on
3644                  * pg_attribute_relid_attnum_index.
3645                  */
3646                 if (g_verbose)
3647                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
3648                                           tbinfo->dobj.name);
3649
3650                 resetPQExpBuffer(q);
3651
3652                 if (g_fout->remoteVersion >= 70300)
3653                 {
3654                         /* need left join here to not fail on dropped columns ... */
3655                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, "
3656                           "a.attnotnull, a.atthasdef, a.attisdropped, a.attislocal, "
3657                            "pg_catalog.format_type(t.oid,a.atttypmod) as atttypname "
3658                                                           "from pg_catalog.pg_attribute a left join pg_catalog.pg_type t "
3659                                                           "on a.atttypid = t.oid "
3660                                                           "where a.attrelid = '%u'::pg_catalog.oid "
3661                                                           "and a.attnum > 0::pg_catalog.int2 "
3662                                                           "order by a.attrelid, a.attnum",
3663                                                           tbinfo->dobj.catId.oid);
3664                 }
3665                 else if (g_fout->remoteVersion >= 70100)
3666                 {
3667                         /*
3668                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2,
3669                          * but we don't dump it because we can't tell whether it's
3670                          * been explicitly set or was just a default.
3671                          */
3672                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, -1 as attstattarget, a.attstorage, t.typstorage, "
3673                                                           "a.attnotnull, a.atthasdef, false as attisdropped, false as attislocal, "
3674                                                   "format_type(t.oid,a.atttypmod) as atttypname "
3675                                                           "from pg_attribute a left join pg_type t "
3676                                                           "on a.atttypid = t.oid "
3677                                                           "where a.attrelid = '%u'::oid "
3678                                                           "and a.attnum > 0::int2 "
3679                                                           "order by a.attrelid, a.attnum",
3680                                                           tbinfo->dobj.catId.oid);
3681                 }
3682                 else
3683                 {
3684                         /* format_type not available before 7.1 */
3685                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, -1 as attstattarget, attstorage, attstorage as typstorage, "
3686                                                           "attnotnull, atthasdef, false as attisdropped, false as attislocal, "
3687                                                           "(select typname from pg_type where oid = atttypid) as atttypname "
3688                                                           "from pg_attribute a "
3689                                                           "where attrelid = '%u'::oid "
3690                                                           "and attnum > 0::int2 "
3691                                                           "order by attrelid, attnum",
3692                                                           tbinfo->dobj.catId.oid);
3693                 }
3694
3695                 res = PQexec(g_conn, q->data);
3696                 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3697
3698                 ntups = PQntuples(res);
3699
3700                 i_attnum = PQfnumber(res, "attnum");
3701                 i_attname = PQfnumber(res, "attname");
3702                 i_atttypname = PQfnumber(res, "atttypname");
3703                 i_atttypmod = PQfnumber(res, "atttypmod");
3704                 i_attstattarget = PQfnumber(res, "attstattarget");
3705                 i_attstorage = PQfnumber(res, "attstorage");
3706                 i_typstorage = PQfnumber(res, "typstorage");
3707                 i_attnotnull = PQfnumber(res, "attnotnull");
3708                 i_atthasdef = PQfnumber(res, "atthasdef");
3709                 i_attisdropped = PQfnumber(res, "attisdropped");
3710                 i_attislocal = PQfnumber(res, "attislocal");
3711
3712                 tbinfo->numatts = ntups;
3713                 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
3714                 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
3715                 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
3716                 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
3717                 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
3718                 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
3719                 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
3720                 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
3721                 tbinfo->attisserial = (bool *) malloc(ntups * sizeof(bool));
3722                 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
3723                 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
3724                 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
3725                 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
3726                 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
3727                 hasdefaults = false;
3728
3729                 for (j = 0; j < ntups; j++)
3730                 {
3731                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
3732                         {
3733                                 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
3734                                                   tbinfo->dobj.name);
3735                                 exit_nicely();
3736                         }
3737                         tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
3738                         tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
3739                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
3740                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
3741                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
3742                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
3743                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
3744                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
3745                         tbinfo->attisserial[j] = false;         /* fix below */
3746                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
3747                         tbinfo->attrdefs[j] = NULL; /* fix below */
3748                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
3749                                 hasdefaults = true;
3750                         /* these flags will be set in flagInhAttrs() */
3751                         tbinfo->inhAttrs[j] = false;
3752                         tbinfo->inhAttrDef[j] = false;
3753                         tbinfo->inhNotNull[j] = false;
3754                 }
3755
3756                 PQclear(res);
3757
3758                 /*
3759                  * Get info about column defaults
3760                  */
3761                 if (hasdefaults)
3762                 {
3763                         AttrDefInfo *attrdefs;
3764                         int                     numDefaults;
3765
3766                         if (g_verbose)
3767                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
3768                                                   tbinfo->dobj.name);
3769
3770                         resetPQExpBuffer(q);
3771                         if (g_fout->remoteVersion >= 70300)
3772                         {
3773                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
3774                                            "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
3775                                                                   "FROM pg_catalog.pg_attrdef "
3776                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
3777                                                                   tbinfo->dobj.catId.oid);
3778                         }
3779                         else if (g_fout->remoteVersion >= 70200)
3780                         {
3781                                 /* 7.2 did not have OIDs in pg_attrdef */
3782                                 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, adnum, "
3783                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
3784                                                                   "FROM pg_attrdef "
3785                                                                   "WHERE adrelid = '%u'::oid",
3786                                                                   tbinfo->dobj.catId.oid);
3787                         }
3788                         else if (g_fout->remoteVersion >= 70100)
3789                         {
3790                                 /* no pg_get_expr, so must rely on adsrc */
3791                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
3792                                                                   "FROM pg_attrdef "
3793                                                                   "WHERE adrelid = '%u'::oid",
3794                                                                   tbinfo->dobj.catId.oid);
3795                         }
3796                         else
3797                         {
3798                                 /* no pg_get_expr, no tableoid either */
3799                                 appendPQExpBuffer(q, "SELECT "
3800                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
3801                                                                   "oid, adnum, adsrc "
3802                                                                   "FROM pg_attrdef "
3803                                                                   "WHERE adrelid = '%u'::oid",
3804                                                                   tbinfo->dobj.catId.oid);
3805                         }
3806                         res = PQexec(g_conn, q->data);
3807                         check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3808
3809                         numDefaults = PQntuples(res);
3810                         attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
3811
3812                         for (j = 0; j < numDefaults; j++)
3813                         {
3814                                 int                     adnum;
3815
3816                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
3817                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3818                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3819                                 AssignDumpId(&attrdefs[j].dobj);
3820                                 attrdefs[j].adtable = tbinfo;
3821                                 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
3822                                 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
3823
3824                                 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
3825                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
3826
3827                                 /*
3828                                  * Defaults on a VIEW must always be dumped as separate
3829                                  * ALTER TABLE commands.  Defaults on regular tables are
3830                                  * dumped as part of the CREATE TABLE if possible.      To
3831                                  * check if it's safe, we mark the default as needing to
3832                                  * appear before the CREATE.
3833                                  */
3834                                 if (tbinfo->relkind == RELKIND_VIEW)
3835                                 {
3836                                         attrdefs[j].separate = true;
3837                                         /* needed in case pre-7.3 DB: */
3838                                         addObjectDependency(&attrdefs[j].dobj,
3839                                                                                 tbinfo->dobj.dumpId);
3840                                 }
3841                                 else
3842                                 {
3843                                         attrdefs[j].separate = false;
3844                                         addObjectDependency(&tbinfo->dobj,
3845                                                                                 attrdefs[j].dobj.dumpId);
3846                                 }
3847
3848                                 if (adnum <= 0 || adnum > ntups)
3849                                 {
3850                                         write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
3851                                                           adnum, tbinfo->dobj.name);
3852                                         exit_nicely();
3853                                 }
3854                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
3855                         }
3856                         PQclear(res);
3857                 }
3858
3859                 /*
3860                  * Get info about table CHECK constraints
3861                  */
3862                 if (tbinfo->ncheck > 0)
3863                 {
3864                         ConstraintInfo *constrs;
3865                         int                     numConstrs;
3866
3867                         if (g_verbose)
3868                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
3869                                                   tbinfo->dobj.name);
3870
3871                         resetPQExpBuffer(q);
3872                         if (g_fout->remoteVersion >= 70400)
3873                         {
3874                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3875                                                 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
3876                                                                   "FROM pg_catalog.pg_constraint "
3877                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
3878                                                                   "   AND contype = 'c' "
3879                                                                   "ORDER BY conname",
3880                                                                   tbinfo->dobj.catId.oid);
3881                         }
3882                         else if (g_fout->remoteVersion >= 70300)
3883                         {
3884                                 /* no pg_get_constraintdef, must use consrc */
3885                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
3886                                                                   "'CHECK (' || consrc || ')' AS consrc "
3887                                                                   "FROM pg_catalog.pg_constraint "
3888                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
3889                                                                   "   AND contype = 'c' "
3890                                                                   "ORDER BY conname",
3891                                                                   tbinfo->dobj.catId.oid);
3892                         }
3893                         else if (g_fout->remoteVersion >= 70200)
3894                         {
3895                                 /* 7.2 did not have OIDs in pg_relcheck */
3896                                 appendPQExpBuffer(q, "SELECT tableoid, 0 as oid, "
3897                                                                   "rcname AS conname, "
3898                                                                   "'CHECK (' || rcsrc || ')' AS consrc "
3899                                                                   "FROM pg_relcheck "
3900                                                                   "WHERE rcrelid = '%u'::oid "
3901                                                                   "ORDER BY rcname",
3902                                                                   tbinfo->dobj.catId.oid);
3903                         }
3904                         else if (g_fout->remoteVersion >= 70100)
3905                         {
3906                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
3907                                                                   "rcname AS conname, "
3908                                                                   "'CHECK (' || rcsrc || ')' AS consrc "
3909                                                                   "FROM pg_relcheck "
3910                                                                   "WHERE rcrelid = '%u'::oid "
3911                                                                   "ORDER BY rcname",
3912                                                                   tbinfo->dobj.catId.oid);
3913                         }
3914                         else
3915                         {
3916                                 /* no tableoid in 7.0 */
3917                                 appendPQExpBuffer(q, "SELECT "
3918                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
3919                                                                   "oid, rcname AS conname, "
3920                                                                   "'CHECK (' || rcsrc || ')' AS consrc "
3921                                                                   "FROM pg_relcheck "
3922                                                                   "WHERE rcrelid = '%u'::oid "
3923                                                                   "ORDER BY rcname",
3924                                                                   tbinfo->dobj.catId.oid);
3925                         }
3926                         res = PQexec(g_conn, q->data);
3927                         check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
3928
3929                         numConstrs = PQntuples(res);
3930                         if (numConstrs != tbinfo->ncheck)
3931                         {
3932                                 write_msg(NULL, "expected %d check constraints on table \"%s\" but found %d\n",
3933                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
3934                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
3935                                 exit_nicely();
3936                         }
3937
3938                         constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
3939                         tbinfo->checkexprs = constrs;
3940
3941                         for (j = 0; j < numConstrs; j++)
3942                         {
3943                                 constrs[j].dobj.objType = DO_CONSTRAINT;
3944                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
3945                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
3946                                 AssignDumpId(&constrs[j].dobj);
3947                                 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
3948                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
3949                                 constrs[j].contable = tbinfo;
3950                                 constrs[j].condomain = NULL;
3951                                 constrs[j].contype = 'c';
3952                                 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
3953                                 constrs[j].conindex = 0;
3954                                 constrs[j].coninherited = false;
3955                                 constrs[j].separate = false;
3956                                 addObjectDependency(&tbinfo->dobj,
3957                                                                         constrs[j].dobj.dumpId);
3958
3959                                 /*
3960                                  * If the constraint is inherited, this will be detected
3961                                  * later.  We also detect later if the constraint must be
3962                                  * split out from the table definition.
3963                                  */
3964                         }
3965                         PQclear(res);
3966                 }
3967
3968                 /*
3969                  * Check to see if any columns are serial columns.      Our first
3970                  * quick filter is that it must be integer or bigint with a
3971                  * default.  If so, we scan to see if we found a sequence linked
3972                  * to this column. If we did, mark the column and sequence
3973                  * appropriately.
3974                  */
3975                 for (j = 0; j < ntups; j++)
3976                 {
3977                         /*
3978                          * Note assumption that format_type will show these types as
3979                          * exactly "integer" and "bigint" regardless of schema path.
3980                          * This is correct in 7.3 but needs to be watched.
3981                          */
3982                         if (strcmp(tbinfo->atttypnames[j], "integer") != 0 &&
3983                                 strcmp(tbinfo->atttypnames[j], "bigint") != 0)
3984                                 continue;
3985                         if (tbinfo->attrdefs[j] == NULL)
3986                                 continue;
3987                         for (k = 0; k < numTables; k++)
3988                         {
3989                                 TableInfo  *seqinfo = &tblinfo[k];
3990
3991                                 if (OidIsValid(seqinfo->owning_tab) &&
3992                                         seqinfo->owning_tab == tbinfo->dobj.catId.oid &&
3993                                         seqinfo->owning_col == j + 1)
3994                                 {
3995                                         /*
3996                                          * Found a match.  Copy the table's interesting and
3997                                          * dumpable flags to the sequence.
3998                                          */
3999                                         tbinfo->attisserial[j] = true;
4000                                         seqinfo->interesting = tbinfo->interesting;
4001                                         seqinfo->dump = tbinfo->dump;
4002                                         break;
4003                                 }
4004                         }
4005                 }
4006         }
4007
4008         destroyPQExpBuffer(q);
4009 }
4010
4011
4012 /*
4013  * dumpComment --
4014  *
4015  * This routine is used to dump any comments associated with the
4016  * object handed to this routine. The routine takes a constant character
4017  * string for the target part of the comment-creation command, plus
4018  * the namespace and owner of the object (for labeling the ArchiveEntry),
4019  * plus catalog ID and subid which are the lookup key for pg_description,
4020  * plus the dump ID for the object (for setting a dependency).
4021  * If a matching pg_description entry is found, it is dumped.
4022  */
4023 static void
4024 dumpComment(Archive *fout, const char *target,
4025                         const char *namespace, const char *owner,
4026                         CatalogId catalogId, int subid, DumpId dumpId)
4027 {
4028         CommentItem *comments;
4029         int                     ncomments;
4030
4031         /* Comments are SCHEMA not data */
4032         if (dataOnly)
4033                 return;
4034
4035         /* Search for comments associated with catalogId, using table */
4036         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
4037                                                          &comments);
4038
4039         /* Is there one matching the subid? */
4040         while (ncomments > 0)
4041         {
4042                 if (comments->objsubid == subid)
4043                         break;
4044                 comments++;
4045                 ncomments--;
4046         }
4047
4048         /* If a comment exists, build COMMENT ON statement */
4049         if (ncomments > 0)
4050         {
4051                 PQExpBuffer query = createPQExpBuffer();
4052
4053                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
4054                 appendStringLiteral(query, comments->descr, false);
4055                 appendPQExpBuffer(query, ";\n");
4056
4057                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
4058                                          target, namespace, owner, false,
4059                                          "COMMENT", query->data, "", NULL,
4060                                          &(dumpId), 1,
4061                                          NULL, NULL);
4062
4063                 destroyPQExpBuffer(query);
4064         }
4065 }
4066
4067 /*
4068  * dumpTableComment --
4069  *
4070  * As above, but dump comments for both the specified table (or view)
4071  * and its columns.
4072  */
4073 static void
4074 dumpTableComment(Archive *fout, TableInfo *tbinfo,
4075                                  const char *reltypename)
4076 {
4077         CommentItem *comments;
4078         int                     ncomments;
4079         PQExpBuffer query;
4080         PQExpBuffer target;
4081
4082         /* Comments are SCHEMA not data */
4083         if (dataOnly)
4084                 return;
4085
4086         /* Search for comments associated with relation, using table */
4087         ncomments = findComments(fout,
4088                                                          tbinfo->dobj.catId.tableoid,
4089                                                          tbinfo->dobj.catId.oid,
4090                                                          &comments);
4091
4092         /* If comments exist, build COMMENT ON statements */
4093         if (ncomments <= 0)
4094                 return;
4095
4096         query = createPQExpBuffer();
4097         target = createPQExpBuffer();
4098
4099         while (ncomments > 0)
4100         {
4101                 const char *descr = comments->descr;
4102                 int                     objsubid = comments->objsubid;
4103
4104                 if (objsubid == 0)
4105                 {
4106                         resetPQExpBuffer(target);
4107                         appendPQExpBuffer(target, "%s %s", reltypename,
4108                                                           fmtId(tbinfo->dobj.name));
4109
4110                         resetPQExpBuffer(query);
4111                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4112                         appendStringLiteral(query, descr, false);
4113                         appendPQExpBuffer(query, ";\n");
4114
4115                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
4116                                                  target->data,
4117                                           tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
4118                                                  false, "COMMENT", query->data, "", NULL,
4119                                                  &(tbinfo->dobj.dumpId), 1,
4120                                                  NULL, NULL);
4121                 }
4122                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
4123                 {
4124                         resetPQExpBuffer(target);
4125                         appendPQExpBuffer(target, "COLUMN %s.",
4126                                                           fmtId(tbinfo->dobj.name));
4127                         appendPQExpBuffer(target, "%s",
4128                                                           fmtId(tbinfo->attnames[objsubid - 1]));
4129
4130                         resetPQExpBuffer(query);
4131                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
4132                         appendStringLiteral(query, descr, false);
4133                         appendPQExpBuffer(query, ";\n");
4134
4135                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
4136                                                  target->data,
4137                                           tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
4138                                                  false, "COMMENT", query->data, "", NULL,
4139                                                  &(tbinfo->dobj.dumpId), 1,
4140                                                  NULL, NULL);
4141                 }
4142
4143                 comments++;
4144                 ncomments--;
4145         }
4146
4147         destroyPQExpBuffer(query);
4148         destroyPQExpBuffer(target);
4149 }
4150
4151 /*
4152  * findComments --
4153  *
4154  * Find the comment(s), if any, associated with the given object.  All the
4155  * objsubid values associated with the given classoid/objoid are found with
4156  * one search.
4157  */
4158 static int
4159 findComments(Archive *fout, Oid classoid, Oid objoid,
4160                          CommentItem **items)
4161 {
4162         /* static storage for table of comments */
4163         static CommentItem *comments = NULL;
4164         static int      ncomments = -1;
4165
4166         CommentItem *middle = NULL;
4167         CommentItem *low;
4168         CommentItem *high;
4169         int                     nmatch;
4170
4171         /* Get comments if we didn't already */
4172         if (ncomments < 0)
4173                 ncomments = collectComments(fout, &comments);
4174
4175         /*
4176          * Pre-7.2, pg_description does not contain classoid, so
4177          * collectComments just stores a zero.  If there's a collision on
4178          * object OID, well, you get duplicate comments.
4179          */
4180         if (fout->remoteVersion < 70200)
4181                 classoid = 0;
4182
4183         /*
4184          * Do binary search to find some item matching the object.
4185          */
4186         low = &comments[0];
4187         high = &comments[ncomments - 1];
4188         while (low <= high)
4189         {
4190                 middle = low + (high - low) / 2;
4191
4192                 if (classoid < middle->classoid)
4193                         high = middle - 1;
4194                 else if (classoid > middle->classoid)
4195                         low = middle + 1;
4196                 else if (objoid < middle->objoid)
4197                         high = middle - 1;
4198                 else if (objoid > middle->objoid)
4199                         low = middle + 1;
4200                 else
4201                         break;                          /* found a match */
4202         }
4203
4204         if (low > high)                         /* no matches */
4205         {
4206                 *items = NULL;
4207                 return 0;
4208         }
4209
4210         /*
4211          * Now determine how many items match the object.  The search loop
4212          * invariant still holds: only items between low and high inclusive
4213          * could match.
4214          */
4215         nmatch = 1;
4216         while (middle > low)
4217         {
4218                 if (classoid != middle[-1].classoid ||
4219                         objoid != middle[-1].objoid)
4220                         break;
4221                 middle--;
4222                 nmatch++;
4223         }
4224
4225         *items = middle;
4226
4227         middle += nmatch;
4228         while (middle <= high)
4229         {
4230                 if (classoid != middle->classoid ||
4231                         objoid != middle->objoid)
4232                         break;
4233                 middle++;
4234                 nmatch++;
4235         }
4236
4237         return nmatch;
4238 }
4239
4240 /*
4241  * collectComments --
4242  *
4243  * Construct a table of all comments available for database objects.
4244  * We used to do per-object queries for the comments, but it's much faster
4245  * to pull them all over at once, and on most databases the memory cost
4246  * isn't high.
4247  *
4248  * The table is sorted by classoid/objid/objsubid for speed in lookup.
4249  */
4250 static int
4251 collectComments(Archive *fout, CommentItem **items)
4252 {
4253         PGresult   *res;
4254         PQExpBuffer query;
4255         int                     i_description;
4256         int                     i_classoid;
4257         int                     i_objoid;
4258         int                     i_objsubid;
4259         int                     ntups;
4260         int                     i;
4261         CommentItem *comments;
4262
4263         /*
4264          * Note we do NOT change source schema here; preserve the caller's
4265          * setting, instead.
4266          */
4267
4268         query = createPQExpBuffer();
4269
4270         if (fout->remoteVersion >= 70300)
4271         {
4272                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4273                                                   "FROM pg_catalog.pg_description "
4274                                                   "ORDER BY classoid, objoid, objsubid");
4275         }
4276         else if (fout->remoteVersion >= 70200)
4277         {
4278                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
4279                                                   "FROM pg_description "
4280                                                   "ORDER BY classoid, objoid, objsubid");
4281         }
4282         else
4283         {
4284                 /* Note: this will fail to find attribute comments in pre-7.2... */
4285                 appendPQExpBuffer(query, "SELECT description, 0 as classoid, objoid, 0 as objsubid "
4286                                                   "FROM pg_description "
4287                                                   "ORDER BY objoid");
4288         }
4289
4290         res = PQexec(g_conn, query->data);
4291         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4292
4293         /* Construct lookup table containing OIDs in numeric form */
4294
4295         i_description = PQfnumber(res, "description");
4296         i_classoid = PQfnumber(res, "classoid");
4297         i_objoid = PQfnumber(res, "objoid");
4298         i_objsubid = PQfnumber(res, "objsubid");
4299
4300         ntups = PQntuples(res);
4301
4302         comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
4303
4304         for (i = 0; i < ntups; i++)
4305         {
4306                 comments[i].descr = PQgetvalue(res, i, i_description);
4307                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
4308                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
4309                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
4310         }
4311
4312         /* Do NOT free the PGresult since we are keeping pointers into it */
4313         destroyPQExpBuffer(query);
4314
4315         *items = comments;
4316         return ntups;
4317 }
4318
4319 /*
4320  * dumpDumpableObject
4321  *
4322  * This routine and its subsidiaries are responsible for creating
4323  * ArchiveEntries (TOC objects) for each object to be dumped.
4324  */
4325 static void
4326 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
4327 {
4328         switch (dobj->objType)
4329         {
4330                 case DO_NAMESPACE:
4331                         dumpNamespace(fout, (NamespaceInfo *) dobj);
4332                         break;
4333                 case DO_TYPE:
4334                         dumpType(fout, (TypeInfo *) dobj);
4335                         break;
4336                 case DO_FUNC:
4337                         dumpFunc(fout, (FuncInfo *) dobj);
4338                         break;
4339                 case DO_AGG:
4340                         dumpAgg(fout, (AggInfo *) dobj);
4341                         break;
4342                 case DO_OPERATOR:
4343                         dumpOpr(fout, (OprInfo *) dobj);
4344                         break;
4345                 case DO_OPCLASS:
4346                         dumpOpclass(fout, (OpclassInfo *) dobj);
4347                         break;
4348                 case DO_CONVERSION:
4349                         dumpConversion(fout, (ConvInfo *) dobj);
4350                         break;
4351                 case DO_TABLE:
4352                         dumpTable(fout, (TableInfo *) dobj);
4353                         break;
4354                 case DO_ATTRDEF:
4355                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
4356                         break;
4357                 case DO_INDEX:
4358                         dumpIndex(fout, (IndxInfo *) dobj);
4359                         break;
4360                 case DO_RULE:
4361                         dumpRule(fout, (RuleInfo *) dobj);
4362                         break;
4363                 case DO_TRIGGER:
4364                         dumpTrigger(fout, (TriggerInfo *) dobj);
4365                         break;
4366                 case DO_CONSTRAINT:
4367                         dumpConstraint(fout, (ConstraintInfo *) dobj);
4368                         break;
4369                 case DO_FK_CONSTRAINT:
4370                         dumpConstraint(fout, (ConstraintInfo *) dobj);
4371                         break;
4372                 case DO_PROCLANG:
4373                         dumpProcLang(fout, (ProcLangInfo *) dobj);
4374                         break;
4375                 case DO_CAST:
4376                         dumpCast(fout, (CastInfo *) dobj);
4377                         break;
4378                 case DO_TABLE_DATA:
4379                         dumpTableData(fout, (TableDataInfo *) dobj);
4380                         break;
4381                 case DO_TABLE_TYPE:
4382                         /* table rowtypes are never dumped separately */
4383                         break;
4384                 case DO_BLOBS:
4385                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
4386                                                  dobj->name, NULL, "",
4387                                                  false, "BLOBS", "", "", NULL,
4388                                                  NULL, 0,
4389                                                  dumpBlobs, NULL);
4390                         break;
4391         }
4392 }
4393
4394 /*
4395  * dumpNamespace
4396  *        writes out to fout the queries to recreate a user-defined namespace
4397  */
4398 static void
4399 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
4400 {
4401         PQExpBuffer q;
4402         PQExpBuffer delq;
4403         char       *qnspname;
4404
4405         /* skip if not to be dumped */
4406         if (!nspinfo->dump || dataOnly)
4407                 return;
4408
4409         /* don't dump dummy namespace from pre-7.3 source */
4410         if (strlen(nspinfo->dobj.name) == 0)
4411                 return;
4412
4413         q = createPQExpBuffer();
4414         delq = createPQExpBuffer();
4415
4416         qnspname = strdup(fmtId(nspinfo->dobj.name));
4417
4418         /*
4419          * Note that ownership is shown in the AUTHORIZATION clause, while the
4420          * archive entry is listed with empty owner (causing it to be emitted
4421          * with SET SESSION AUTHORIZATION DEFAULT). This seems the best way of
4422          * dealing with schemas owned by users without CREATE SCHEMA
4423          * privilege.  Further hacking has to be applied for --no-owner mode,
4424          * though!
4425          */
4426         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
4427
4428         appendPQExpBuffer(q, "CREATE SCHEMA %s AUTHORIZATION %s",
4429                                           qnspname, fmtId(nspinfo->usename));
4430
4431         /* Add tablespace qualifier, if not default */
4432         if (strlen(nspinfo->nsptablespace) != 0)
4433                 appendPQExpBuffer(q, " TABLESPACE %s",
4434                                                   fmtId(nspinfo->nsptablespace));
4435
4436         appendPQExpBuffer(q, ";\n");
4437
4438         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
4439                                  nspinfo->dobj.name,
4440                                  NULL, strcmp(nspinfo->dobj.name, "public") == 0 ? nspinfo->usename : "",
4441                                  false, "SCHEMA", q->data, delq->data, NULL,
4442                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
4443                                  NULL, NULL);
4444
4445         /* Dump Schema Comments */
4446         resetPQExpBuffer(q);
4447         appendPQExpBuffer(q, "SCHEMA %s", qnspname);
4448         dumpComment(fout, q->data,
4449                                 NULL, nspinfo->usename,
4450                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
4451
4452         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
4453                         qnspname, nspinfo->dobj.name, NULL,
4454                         nspinfo->usename, nspinfo->nspacl);
4455
4456         free(qnspname);
4457
4458         destroyPQExpBuffer(q);
4459         destroyPQExpBuffer(delq);
4460 }
4461
4462 /*
4463  * dumpType
4464  *        writes out to fout the queries to recreate a user-defined type
4465  */
4466 static void
4467 dumpType(Archive *fout, TypeInfo *tinfo)
4468 {
4469         /* Dump only types in dumpable namespaces */
4470         if (!tinfo->dobj.namespace->dump || dataOnly)
4471                 return;
4472
4473         /* skip complex types, except for standalone composite types */
4474         /* (note: this test should now be unnecessary) */
4475         if (OidIsValid(tinfo->typrelid) && tinfo->typrelkind != 'c')
4476                 return;
4477
4478         /* skip undefined placeholder types */
4479         if (!tinfo->isDefined)
4480                 return;
4481
4482         /* skip all array types that start w/ underscore */
4483         if ((tinfo->dobj.name[0] == '_') &&
4484                 OidIsValid(tinfo->typelem))
4485                 return;
4486
4487         /* Dump out in proper style */
4488         if (tinfo->typtype == 'b')
4489                 dumpBaseType(fout, tinfo);
4490         else if (tinfo->typtype == 'd')
4491                 dumpDomain(fout, tinfo);
4492         else if (tinfo->typtype == 'c')
4493                 dumpCompositeType(fout, tinfo);
4494 }
4495
4496 /*
4497  * dumpBaseType
4498  *        writes out to fout the queries to recreate a user-defined base type
4499  */
4500 static void
4501 dumpBaseType(Archive *fout, TypeInfo *tinfo)
4502 {
4503         PQExpBuffer q = createPQExpBuffer();
4504         PQExpBuffer delq = createPQExpBuffer();
4505         PQExpBuffer query = createPQExpBuffer();
4506         PGresult   *res;
4507         int                     ntups;
4508         char       *typlen;
4509         char       *typinput;
4510         char       *typoutput;
4511         char       *typreceive;
4512         char       *typsend;
4513         char       *typanalyze;
4514         Oid                     typinputoid;
4515         Oid                     typoutputoid;
4516         Oid                     typreceiveoid;
4517         Oid                     typsendoid;
4518         Oid                     typanalyzeoid;
4519         char       *typdelim;
4520         char       *typdefault;
4521         char       *typbyval;
4522         char       *typalign;
4523         char       *typstorage;
4524
4525         /* Set proper schema search path so regproc references list correctly */
4526         selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4527
4528         /* Fetch type-specific details */
4529         if (fout->remoteVersion >= 80000)
4530         {
4531                 appendPQExpBuffer(query, "SELECT typlen, "
4532                                                   "typinput, typoutput, typreceive, typsend, "
4533                                                   "typanalyze, "
4534                                                   "typinput::pg_catalog.oid as typinputoid, "
4535                                                   "typoutput::pg_catalog.oid as typoutputoid, "
4536                                                   "typreceive::pg_catalog.oid as typreceiveoid, "
4537                                                   "typsend::pg_catalog.oid as typsendoid, "
4538                                                   "typanalyze::pg_catalog.oid as typanalyzeoid, "
4539                                                   "typdelim, typdefault, typbyval, typalign, "
4540                                                   "typstorage "
4541                                                   "FROM pg_catalog.pg_type "
4542                                                   "WHERE oid = '%u'::pg_catalog.oid",
4543                                                   tinfo->dobj.catId.oid);
4544         }
4545         else if (fout->remoteVersion >= 70400)
4546         {
4547                 appendPQExpBuffer(query, "SELECT typlen, "
4548                                                   "typinput, typoutput, typreceive, typsend, "
4549                                                   "'-' as typanalyze, "
4550                                                   "typinput::pg_catalog.oid as typinputoid, "
4551                                                   "typoutput::pg_catalog.oid as typoutputoid, "
4552                                                   "typreceive::pg_catalog.oid as typreceiveoid, "
4553                                                   "typsend::pg_catalog.oid as typsendoid, "
4554                                                   "0 as typanalyzeoid, "
4555                                                   "typdelim, typdefault, typbyval, typalign, "
4556                                                   "typstorage "
4557                                                   "FROM pg_catalog.pg_type "
4558                                                   "WHERE oid = '%u'::pg_catalog.oid",
4559                                                   tinfo->dobj.catId.oid);
4560         }
4561         else if (fout->remoteVersion >= 70300)
4562         {
4563                 appendPQExpBuffer(query, "SELECT typlen, "
4564                                                   "typinput, typoutput, "
4565                                                   "'-' as typreceive, '-' as typsend, "
4566                                                   "'-' as typanalyze, "
4567                                                   "typinput::pg_catalog.oid as typinputoid, "
4568                                                   "typoutput::pg_catalog.oid as typoutputoid, "
4569                                                   "0 as typreceiveoid, 0 as typsendoid, "
4570                                                   "0 as typanalyzeoid, "
4571                                                   "typdelim, typdefault, typbyval, typalign, "
4572                                                   "typstorage "
4573                                                   "FROM pg_catalog.pg_type "
4574                                                   "WHERE oid = '%u'::pg_catalog.oid",
4575                                                   tinfo->dobj.catId.oid);
4576         }
4577         else if (fout->remoteVersion >= 70100)
4578         {
4579                 /*
4580                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
4581                  * ignore them because they are not right.
4582                  */
4583                 appendPQExpBuffer(query, "SELECT typlen, "
4584                                                   "typinput, typoutput, "
4585                                                   "'-' as typreceive, '-' as typsend, "
4586                                                   "'-' as typanalyze, "
4587                                                   "typinput::oid as typinputoid, "
4588                                                   "typoutput::oid as typoutputoid, "
4589                                                   "0 as typreceiveoid, 0 as typsendoid, "
4590                                                   "0 as typanalyzeoid, "
4591                                                   "typdelim, typdefault, typbyval, typalign, "
4592                                                   "typstorage "
4593                                                   "FROM pg_type "
4594                                                   "WHERE oid = '%u'::oid",
4595                                                   tinfo->dobj.catId.oid);
4596         }
4597         else
4598         {
4599                 appendPQExpBuffer(query, "SELECT typlen, "
4600                                                   "typinput, typoutput, "
4601                                                   "'-' as typreceive, '-' as typsend, "
4602                                                   "'-' as typanalyze, "
4603                                                   "typinput::oid as typinputoid, "
4604                                                   "typoutput::oid as typoutputoid, "
4605                                                   "0 as typreceiveoid, 0 as typsendoid, "
4606                                                   "0 as typanalyzeoid, "
4607                                                   "typdelim, typdefault, typbyval, typalign, "
4608                                                   "'p'::char as typstorage "
4609                                                   "FROM pg_type "
4610                                                   "WHERE oid = '%u'::oid",
4611                                                   tinfo->dobj.catId.oid);
4612         }
4613
4614         res = PQexec(g_conn, query->data);
4615         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4616
4617         /* Expecting a single result only */
4618         ntups = PQntuples(res);
4619         if (ntups != 1)
4620         {
4621                 write_msg(NULL, "Got %d rows instead of one from: %s",
4622                                   ntups, query->data);
4623                 exit_nicely();
4624         }
4625
4626         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
4627         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
4628         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
4629         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
4630         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
4631         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
4632         typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
4633         typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
4634         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
4635         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
4636         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
4637         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
4638         if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4639                 typdefault = NULL;
4640         else
4641                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4642         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
4643         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
4644         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
4645
4646         /*
4647          * DROP must be fully qualified in case same name appears in
4648          * pg_catalog
4649          */
4650         appendPQExpBuffer(delq, "DROP TYPE %s.",
4651                                           fmtId(tinfo->dobj.namespace->dobj.name));
4652         appendPQExpBuffer(delq, "%s CASCADE;\n",
4653                                           fmtId(tinfo->dobj.name));
4654
4655         appendPQExpBuffer(q,
4656                                           "CREATE TYPE %s (\n"
4657                                           "    INTERNALLENGTH = %s",
4658                                           fmtId(tinfo->dobj.name),
4659                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
4660
4661         if (fout->remoteVersion >= 70300)
4662         {
4663                 /* regproc result is correctly quoted as of 7.3 */
4664                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
4665                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
4666                 if (OidIsValid(typreceiveoid))
4667                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
4668                 if (OidIsValid(typsendoid))
4669                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
4670                 if (OidIsValid(typanalyzeoid))
4671                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
4672         }
4673         else
4674         {
4675                 /* regproc delivers an unquoted name before 7.3 */
4676                 /* cannot combine these because fmtId uses static result area */
4677                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
4678                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
4679                 /* no chance that receive/send/analyze need be printed */
4680         }
4681
4682         if (typdefault != NULL)
4683         {
4684                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
4685                 appendStringLiteral(q, typdefault, true);
4686         }
4687
4688         if (tinfo->isArray)
4689         {
4690                 char       *elemType;
4691
4692                 /* reselect schema in case changed by function dump */
4693                 selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4694                 elemType = getFormattedTypeName(tinfo->typelem, zeroAsOpaque);
4695                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
4696                 free(elemType);
4697         }
4698
4699         if (typdelim && strcmp(typdelim, ",") != 0)
4700         {
4701                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
4702                 appendStringLiteral(q, typdelim, true);
4703         }
4704
4705         if (strcmp(typalign, "c") == 0)
4706                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
4707         else if (strcmp(typalign, "s") == 0)
4708                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
4709         else if (strcmp(typalign, "i") == 0)
4710                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
4711         else if (strcmp(typalign, "d") == 0)
4712                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
4713
4714         if (strcmp(typstorage, "p") == 0)
4715                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
4716         else if (strcmp(typstorage, "e") == 0)
4717                 appendPQExpBuffer(q, ",\n    STORAGE = external");
4718         else if (strcmp(typstorage, "x") == 0)
4719                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
4720         else if (strcmp(typstorage, "m") == 0)
4721                 appendPQExpBuffer(q, ",\n    STORAGE = main");
4722
4723         if (strcmp(typbyval, "t") == 0)
4724                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
4725
4726         appendPQExpBuffer(q, "\n);\n");
4727
4728         ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4729                                  tinfo->dobj.name,
4730                                  tinfo->dobj.namespace->dobj.name,
4731                                  tinfo->usename, false,
4732                                  "TYPE", q->data, delq->data, NULL,
4733                                  tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4734                                  NULL, NULL);
4735
4736         /* Dump Type Comments */
4737         resetPQExpBuffer(q);
4738
4739         appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4740         dumpComment(fout, q->data,
4741                                 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4742                                 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4743
4744         PQclear(res);
4745         destroyPQExpBuffer(q);
4746         destroyPQExpBuffer(delq);
4747         destroyPQExpBuffer(query);
4748 }
4749
4750 /*
4751  * dumpDomain
4752  *        writes out to fout the queries to recreate a user-defined domain
4753  */
4754 static void
4755 dumpDomain(Archive *fout, TypeInfo *tinfo)
4756 {
4757         PQExpBuffer q = createPQExpBuffer();
4758         PQExpBuffer delq = createPQExpBuffer();
4759         PQExpBuffer query = createPQExpBuffer();
4760         PGresult   *res;
4761         int                     ntups;
4762         int                     i;
4763         char       *typnotnull;
4764         char       *typdefn;
4765         char       *typdefault;
4766
4767         /* Set proper schema search path so type references list correctly */
4768         selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4769
4770         /* Fetch domain specific details */
4771         /* We assume here that remoteVersion must be at least 70300 */
4772         appendPQExpBuffer(query, "SELECT typnotnull, "
4773                         "pg_catalog.format_type(typbasetype, typtypmod) as typdefn, "
4774                                           "typdefault "
4775                                           "FROM pg_catalog.pg_type "
4776                                           "WHERE oid = '%u'::pg_catalog.oid",
4777                                           tinfo->dobj.catId.oid);
4778
4779         res = PQexec(g_conn, query->data);
4780         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4781
4782         /* Expecting a single result only */
4783         ntups = PQntuples(res);
4784         if (ntups != 1)
4785         {
4786                 write_msg(NULL, "Got %d rows instead of one from: %s",
4787                                   ntups, query->data);
4788                 exit_nicely();
4789         }
4790
4791         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
4792         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
4793         if (PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
4794                 typdefault = NULL;
4795         else
4796                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
4797
4798         appendPQExpBuffer(q,
4799                                           "CREATE DOMAIN %s AS %s",
4800                                           fmtId(tinfo->dobj.name),
4801                                           typdefn);
4802
4803         if (typnotnull[0] == 't')
4804                 appendPQExpBuffer(q, " NOT NULL");
4805
4806         if (typdefault)
4807                 appendPQExpBuffer(q, " DEFAULT %s", typdefault);
4808
4809         PQclear(res);
4810
4811         /*
4812          * Add any CHECK constraints for the domain
4813          */
4814         for (i = 0; i < tinfo->nDomChecks; i++)
4815         {
4816                 ConstraintInfo *domcheck = &(tinfo->domChecks[i]);
4817
4818                 if (!domcheck->separate)
4819                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
4820                                                    fmtId(domcheck->dobj.name), domcheck->condef);
4821         }
4822
4823         appendPQExpBuffer(q, ";\n");
4824
4825         /*
4826          * DROP must be fully qualified in case same name appears in
4827          * pg_catalog
4828          */
4829         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
4830                                           fmtId(tinfo->dobj.namespace->dobj.name));
4831         appendPQExpBuffer(delq, "%s;\n",
4832                                           fmtId(tinfo->dobj.name));
4833
4834         ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4835                                  tinfo->dobj.name,
4836                                  tinfo->dobj.namespace->dobj.name,
4837                                  tinfo->usename, false,
4838                                  "DOMAIN", q->data, delq->data, NULL,
4839                                  tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4840                                  NULL, NULL);
4841
4842         /* Dump Domain Comments */
4843         resetPQExpBuffer(q);
4844
4845         appendPQExpBuffer(q, "DOMAIN %s", fmtId(tinfo->dobj.name));
4846         dumpComment(fout, q->data,
4847                                 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4848                                 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4849
4850         destroyPQExpBuffer(q);
4851         destroyPQExpBuffer(delq);
4852         destroyPQExpBuffer(query);
4853 }
4854
4855 /*
4856  * dumpCompositeType
4857  *        writes out to fout the queries to recreate a user-defined stand-alone
4858  *        composite type
4859  */
4860 static void
4861 dumpCompositeType(Archive *fout, TypeInfo *tinfo)
4862 {
4863         PQExpBuffer q = createPQExpBuffer();
4864         PQExpBuffer delq = createPQExpBuffer();
4865         PQExpBuffer query = createPQExpBuffer();
4866         PGresult   *res;
4867         int                     ntups;
4868         int                     i_attname;
4869         int                     i_atttypdefn;
4870         int                     i;
4871
4872         /* Set proper schema search path so type references list correctly */
4873         selectSourceSchema(tinfo->dobj.namespace->dobj.name);
4874
4875         /* Fetch type specific details */
4876         /* We assume here that remoteVersion must be at least 70300 */
4877
4878         appendPQExpBuffer(query, "SELECT a.attname, "
4879                  "pg_catalog.format_type(a.atttypid, a.atttypmod) as atttypdefn "
4880                                   "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
4881                                           "WHERE t.oid = '%u'::pg_catalog.oid "
4882                                           "AND a.attrelid = t.typrelid "
4883                                           "AND NOT a.attisdropped "
4884                                           "ORDER BY a.attnum ",
4885                                           tinfo->dobj.catId.oid);
4886
4887         res = PQexec(g_conn, query->data);
4888         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4889
4890         /* Expecting at least a single result */
4891         ntups = PQntuples(res);
4892         if (ntups < 1)
4893         {
4894                 write_msg(NULL, "query yielded no rows: %s\n", query->data);
4895                 exit_nicely();
4896         }
4897
4898         i_attname = PQfnumber(res, "attname");
4899         i_atttypdefn = PQfnumber(res, "atttypdefn");
4900
4901         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
4902                                           fmtId(tinfo->dobj.name));
4903
4904         for (i = 0; i < ntups; i++)
4905         {
4906                 char       *attname;
4907                 char       *atttypdefn;
4908
4909                 attname = PQgetvalue(res, i, i_attname);
4910                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
4911
4912                 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
4913                 if (i < ntups - 1)
4914                         appendPQExpBuffer(q, ",");
4915         }
4916         appendPQExpBuffer(q, "\n);\n");
4917
4918         /*
4919          * DROP must be fully qualified in case same name appears in
4920          * pg_catalog
4921          */
4922         appendPQExpBuffer(delq, "DROP TYPE %s.",
4923                                           fmtId(tinfo->dobj.namespace->dobj.name));
4924         appendPQExpBuffer(delq, "%s;\n",
4925                                           fmtId(tinfo->dobj.name));
4926
4927         ArchiveEntry(fout, tinfo->dobj.catId, tinfo->dobj.dumpId,
4928                                  tinfo->dobj.name,
4929                                  tinfo->dobj.namespace->dobj.name,
4930                                  tinfo->usename, false,
4931                                  "TYPE", q->data, delq->data, NULL,
4932                                  tinfo->dobj.dependencies, tinfo->dobj.nDeps,
4933                                  NULL, NULL);
4934
4935
4936         /* Dump Type Comments */
4937         resetPQExpBuffer(q);
4938
4939         appendPQExpBuffer(q, "TYPE %s", fmtId(tinfo->dobj.name));
4940         dumpComment(fout, q->data,
4941                                 tinfo->dobj.namespace->dobj.name, tinfo->usename,
4942                                 tinfo->dobj.catId, 0, tinfo->dobj.dumpId);
4943
4944         PQclear(res);
4945         destroyPQExpBuffer(q);
4946         destroyPQExpBuffer(delq);
4947         destroyPQExpBuffer(query);
4948 }
4949
4950 /*
4951  * dumpProcLang
4952  *                writes out to fout the queries to recreate a user-defined
4953  *                procedural language
4954  */
4955 static void
4956 dumpProcLang(Archive *fout, ProcLangInfo *plang)
4957 {
4958         PQExpBuffer defqry;
4959         PQExpBuffer delqry;
4960         char       *qlanname;
4961         FuncInfo   *funcInfo;
4962         FuncInfo   *validatorInfo = NULL;
4963
4964         if (dataOnly)
4965                 return;
4966
4967         /*
4968          * Current theory is to dump PLs iff their underlying functions will
4969          * be dumped (are in a dumpable namespace, or have a non-system OID in
4970          * pre-7.3 databases).  Actually, we treat the PL itself as being in
4971          * the underlying function's namespace, though it isn't really.  This
4972          * avoids searchpath problems for the HANDLER clause.
4973          *
4974          * If the underlying function is in the pg_catalog namespace, we won't
4975          * have loaded it into finfo[] at all; therefore, treat failure to
4976          * find it in finfo[] as indicating we shouldn't dump it, not as an
4977          * error condition.  Ditto for the validator.
4978          */
4979
4980         funcInfo = findFuncByOid(plang->lanplcallfoid);
4981         if (funcInfo == NULL)
4982                 return;
4983
4984         if (!funcInfo->dobj.namespace->dump)
4985                 return;
4986
4987         if (OidIsValid(plang->lanvalidator))
4988         {
4989                 validatorInfo = findFuncByOid(plang->lanvalidator);
4990                 if (validatorInfo == NULL)
4991                         return;
4992         }
4993
4994         defqry = createPQExpBuffer();
4995         delqry = createPQExpBuffer();
4996
4997         qlanname = strdup(fmtId(plang->dobj.name));
4998
4999         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
5000                                           qlanname);
5001
5002         appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
5003                                           plang->lanpltrusted ? "TRUSTED " : "",
5004                                           qlanname);
5005         appendPQExpBuffer(defqry, " HANDLER %s",
5006                                           fmtId(funcInfo->dobj.name));
5007         if (OidIsValid(plang->lanvalidator))
5008         {
5009                 appendPQExpBuffer(defqry, " VALIDATOR ");
5010                 /* Cope with possibility that validator is in different schema */
5011                 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
5012                         appendPQExpBuffer(defqry, "%s.",
5013                                                 fmtId(validatorInfo->dobj.namespace->dobj.name));
5014                 appendPQExpBuffer(defqry, "%s",
5015                                                   fmtId(validatorInfo->dobj.name));
5016         }
5017         appendPQExpBuffer(defqry, ";\n");
5018
5019         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
5020                                  plang->dobj.name,
5021                                  funcInfo->dobj.namespace->dobj.name, "",
5022                                  false, "PROCEDURAL LANGUAGE",
5023                                  defqry->data, delqry->data, NULL,
5024                                  plang->dobj.dependencies, plang->dobj.nDeps,
5025                                  NULL, NULL);
5026
5027         /* Dump Proc Lang Comments */
5028         resetPQExpBuffer(defqry);
5029
5030         appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
5031         dumpComment(fout, defqry->data,
5032                                 NULL, "",
5033                                 plang->dobj.catId, 0, plang->dobj.dumpId);
5034
5035         if (plang->lanpltrusted)
5036                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
5037                                 qlanname, plang->dobj.name,
5038                                 funcInfo->dobj.namespace->dobj.name,
5039                                 NULL, plang->lanacl);
5040
5041         free(qlanname);
5042
5043         destroyPQExpBuffer(defqry);
5044         destroyPQExpBuffer(delqry);
5045 }
5046
5047 /*
5048  * format_function_signature: generate function name and argument list
5049  *
5050  * The argument type names are qualified if needed.  The function name
5051  * is never qualified.
5052  *
5053  * argnames may be NULL if no names are available.
5054  */
5055 static char *
5056 format_function_signature(FuncInfo *finfo, char **argnames,
5057                                                   bool honor_quotes)
5058 {
5059         PQExpBufferData fn;
5060         int                     j;
5061
5062         initPQExpBuffer(&fn);
5063         if (honor_quotes)
5064                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
5065         else
5066                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
5067         for (j = 0; j < finfo->nargs; j++)
5068         {
5069                 char       *typname;
5070                 char       *argname;
5071
5072                 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
5073
5074                 argname = argnames ? argnames[j] : (char *) NULL;
5075                 if (argname && argname[0] == '\0')
5076                         argname = NULL;
5077
5078                 appendPQExpBuffer(&fn, "%s%s%s%s",
5079                                                   (j > 0) ? ", " : "",
5080                                                   argname ? fmtId(argname) : "",
5081                                                   argname ? " " : "",
5082                                                   typname);
5083                 free(typname);
5084         }
5085         appendPQExpBuffer(&fn, ")");
5086         return fn.data;
5087 }
5088
5089
5090 /*
5091  * dumpFunc:
5092  *        dump out one function
5093  */
5094 static void
5095 dumpFunc(Archive *fout, FuncInfo *finfo)
5096 {
5097         PQExpBuffer query;
5098         PQExpBuffer q;
5099         PQExpBuffer delqry;
5100         PQExpBuffer asPart;
5101         PGresult   *res;
5102         char       *funcsig;
5103         char       *funcsig_tag;
5104         int                     ntups;
5105         char       *proretset;
5106         char       *prosrc;
5107         char       *probin;
5108         char       *proargnames;
5109         char       *provolatile;
5110         char       *proisstrict;
5111         char       *prosecdef;
5112         char       *lanname;
5113         char       *rettypename;
5114         char      **argnamearray = NULL;
5115
5116         /* Dump only funcs in dumpable namespaces */
5117         if (!finfo->dobj.namespace->dump || dataOnly)
5118                 return;
5119
5120         query = createPQExpBuffer();
5121         q = createPQExpBuffer();
5122         delqry = createPQExpBuffer();
5123         asPart = createPQExpBuffer();
5124
5125         /* Set proper schema search path so type references list correctly */
5126         selectSourceSchema(finfo->dobj.namespace->dobj.name);
5127
5128         /* Fetch function-specific details */
5129         if (g_fout->remoteVersion >= 80000)
5130         {
5131                 appendPQExpBuffer(query,
5132                                                   "SELECT proretset, prosrc, probin, "
5133                                                   "proargnames, "
5134                                                   "provolatile, proisstrict, prosecdef, "
5135                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5136                                                   "FROM pg_catalog.pg_proc "
5137                                                   "WHERE oid = '%u'::pg_catalog.oid",
5138                                                   finfo->dobj.catId.oid);
5139         }
5140         else if (g_fout->remoteVersion >= 70300)
5141         {
5142                 appendPQExpBuffer(query,
5143                                                   "SELECT proretset, prosrc, probin, "
5144                                                   "null::text as proargnames, "
5145                                                   "provolatile, proisstrict, prosecdef, "
5146                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) as lanname "
5147                                                   "FROM pg_catalog.pg_proc "
5148                                                   "WHERE oid = '%u'::pg_catalog.oid",
5149                                                   finfo->dobj.catId.oid);
5150         }
5151         else if (g_fout->remoteVersion >= 70100)
5152         {
5153                 appendPQExpBuffer(query,
5154                                                   "SELECT proretset, prosrc, probin, "
5155                                                   "null::text as proargnames, "
5156                  "case when proiscachable then 'i' else 'v' end as provolatile, "
5157                                                   "proisstrict, "
5158                                                   "'f'::boolean as prosecdef, "
5159                                                   "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5160                                                   "FROM pg_proc "
5161                                                   "WHERE oid = '%u'::oid",
5162                                                   finfo->dobj.catId.oid);
5163         }
5164         else
5165         {
5166                 appendPQExpBuffer(query,
5167                                                   "SELECT proretset, prosrc, probin, "
5168                                                   "null::text as proargnames, "
5169                  "case when proiscachable then 'i' else 'v' end as provolatile, "
5170                                                   "'f'::boolean as proisstrict, "
5171                                                   "'f'::boolean as prosecdef, "
5172                                                   "(SELECT lanname FROM pg_language WHERE oid = prolang) as lanname "
5173                                                   "FROM pg_proc "
5174                                                   "WHERE oid = '%u'::oid",
5175                                                   finfo->dobj.catId.oid);
5176         }
5177
5178         res = PQexec(g_conn, query->data);
5179         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5180
5181         /* Expecting a single result only */
5182         ntups = PQntuples(res);
5183         if (ntups != 1)
5184         {
5185                 write_msg(NULL, "Got %d rows instead of one from: %s",
5186                                   ntups, query->data);
5187                 exit_nicely();
5188         }
5189
5190         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
5191         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
5192         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
5193         proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
5194         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
5195         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
5196         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
5197         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
5198
5199         /*
5200          * See backend/commands/define.c for details of how the 'AS' clause is
5201          * used.
5202          */
5203         if (strcmp(probin, "-") != 0)
5204         {
5205                 appendPQExpBuffer(asPart, "AS ");
5206                 appendStringLiteral(asPart, probin, true);
5207                 if (strcmp(prosrc, "-") != 0)
5208                 {
5209                         appendPQExpBuffer(asPart, ", ");
5210
5211                         /*
5212                          * where we have bin, use dollar quoting if allowed and src
5213                          * contains quote or backslash; else use regular quoting.
5214                          */
5215                         if (disable_dollar_quoting)
5216                                 appendStringLiteral(asPart, prosrc, false);
5217                         else
5218                                 appendStringLiteralDQOpt(asPart, prosrc, false, NULL);
5219                 }
5220         }
5221         else
5222         {
5223                 if (strcmp(prosrc, "-") != 0)
5224                 {
5225                         appendPQExpBuffer(asPart, "AS ");
5226                         /* with no bin, dollar quote src unconditionally if allowed */
5227                         if (disable_dollar_quoting)
5228                                 appendStringLiteral(asPart, prosrc, false);
5229                         else
5230                                 appendStringLiteralDQ(asPart, prosrc, NULL);
5231                 }
5232         }
5233
5234         if (proargnames && *proargnames)
5235         {
5236                 int                     nitems = 0;
5237
5238                 if (!parsePGArray(proargnames, &argnamearray, &nitems) ||
5239                         nitems != finfo->nargs)
5240                 {
5241                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
5242                         if (argnamearray)
5243                                 free(argnamearray);
5244                         argnamearray = NULL;
5245                 }
5246         }
5247
5248         funcsig = format_function_signature(finfo, argnamearray, true);
5249         funcsig_tag = format_function_signature(finfo, NULL, false);
5250
5251         /*
5252          * DROP must be fully qualified in case same name appears in
5253          * pg_catalog
5254          */
5255         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
5256                                           fmtId(finfo->dobj.namespace->dobj.name),
5257                                           funcsig);
5258
5259         rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
5260
5261         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcsig);
5262         appendPQExpBuffer(q, "RETURNS %s%s\n    %s\n    LANGUAGE %s",
5263                                           (proretset[0] == 't') ? "SETOF " : "",
5264                                           rettypename,
5265                                           asPart->data,
5266                                           fmtId(lanname));
5267
5268         free(rettypename);
5269
5270         if (provolatile[0] != PROVOLATILE_VOLATILE)
5271         {
5272                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
5273                         appendPQExpBuffer(q, " IMMUTABLE");
5274                 else if (provolatile[0] == PROVOLATILE_STABLE)
5275                         appendPQExpBuffer(q, " STABLE");
5276                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
5277                 {
5278                         write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
5279                                           finfo->dobj.name);
5280                         exit_nicely();
5281                 }
5282         }
5283
5284         if (proisstrict[0] == 't')
5285                 appendPQExpBuffer(q, " STRICT");
5286
5287         if (prosecdef[0] == 't')
5288                 appendPQExpBuffer(q, " SECURITY DEFINER");
5289
5290         appendPQExpBuffer(q, ";\n");
5291
5292         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
5293                                  funcsig_tag,
5294                                  finfo->dobj.namespace->dobj.name,
5295                                  finfo->usename, false,
5296                                  "FUNCTION", q->data, delqry->data, NULL,
5297                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
5298                                  NULL, NULL);
5299
5300         /* Dump Function Comments */
5301         resetPQExpBuffer(q);
5302         appendPQExpBuffer(q, "FUNCTION %s", funcsig);
5303         dumpComment(fout, q->data,
5304                                 finfo->dobj.namespace->dobj.name, finfo->usename,
5305                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
5306
5307         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
5308                         funcsig, funcsig_tag,
5309                         finfo->dobj.namespace->dobj.name,
5310                         finfo->usename, finfo->proacl);
5311
5312         PQclear(res);
5313
5314         destroyPQExpBuffer(query);
5315         destroyPQExpBuffer(q);
5316         destroyPQExpBuffer(delqry);
5317         destroyPQExpBuffer(asPart);
5318         free(funcsig);
5319         free(funcsig_tag);
5320         if (argnamearray)
5321                 free(argnamearray);
5322 }
5323
5324
5325 /*
5326  * Dump a user-defined cast
5327  */
5328 static void
5329 dumpCast(Archive *fout, CastInfo *cast)
5330 {
5331         PQExpBuffer defqry;
5332         PQExpBuffer delqry;
5333         PQExpBuffer castsig;
5334         FuncInfo   *funcInfo = NULL;
5335         TypeInfo   *sourceInfo;
5336         TypeInfo   *targetInfo;
5337
5338         if (dataOnly)
5339                 return;
5340
5341         if (OidIsValid(cast->castfunc))
5342         {
5343                 funcInfo = findFuncByOid(cast->castfunc);
5344                 if (funcInfo == NULL)
5345                         return;
5346         }
5347
5348         /*
5349          * As per discussion we dump casts if one or more of the underlying
5350          * objects (the conversion function and the two data types) are not
5351          * builtin AND if all of the non-builtin objects namespaces are
5352          * included in the dump. Builtin meaning, the namespace name does not
5353          * start with "pg_".
5354          */
5355         sourceInfo = findTypeByOid(cast->castsource);
5356         targetInfo = findTypeByOid(cast->casttarget);
5357
5358         if (sourceInfo == NULL || targetInfo == NULL)
5359                 return;
5360
5361         /*
5362          * Skip this cast if all objects are from pg_
5363          */
5364         if ((funcInfo == NULL ||
5365                  strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
5366                 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
5367                 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
5368                 return;
5369
5370         /*
5371          * Skip cast if function isn't from pg_ and that namespace is not
5372          * dumped.
5373          */
5374         if (funcInfo &&
5375                 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5376                 !funcInfo->dobj.namespace->dump)
5377                 return;
5378
5379         /*
5380          * Same for the Source type
5381          */
5382         if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5383                 !sourceInfo->dobj.namespace->dump)
5384                 return;
5385
5386         /*
5387          * and the target type.
5388          */
5389         if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
5390                 !targetInfo->dobj.namespace->dump)
5391                 return;
5392
5393         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
5394         selectSourceSchema("pg_catalog");
5395
5396         defqry = createPQExpBuffer();
5397         delqry = createPQExpBuffer();
5398         castsig = createPQExpBuffer();
5399
5400         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
5401                                           getFormattedTypeName(cast->castsource, zeroAsNone),
5402                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
5403
5404         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
5405                                           getFormattedTypeName(cast->castsource, zeroAsNone),
5406                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
5407
5408         if (!OidIsValid(cast->castfunc))
5409                 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
5410         else
5411         {
5412                 /*
5413                  * Always qualify the function name, in case it is not in
5414                  * pg_catalog schema (format_function_signature won't qualify it).
5415                  */
5416                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
5417                                                   fmtId(funcInfo->dobj.namespace->dobj.name));
5418                 appendPQExpBuffer(defqry, "%s",
5419                                                 format_function_signature(funcInfo, NULL, true));
5420         }
5421
5422         if (cast->castcontext == 'a')
5423                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
5424         else if (cast->castcontext == 'i')
5425                 appendPQExpBuffer(defqry, " AS IMPLICIT");
5426         appendPQExpBuffer(defqry, ";\n");
5427
5428         appendPQExpBuffer(castsig, "CAST (%s AS %s)",
5429                                           getFormattedTypeName(cast->castsource, zeroAsNone),
5430                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
5431
5432         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
5433                                  castsig->data,
5434                                  "pg_catalog", "",
5435                                  false, "CAST", defqry->data, delqry->data, NULL,
5436                                  cast->dobj.dependencies, cast->dobj.nDeps,
5437                                  NULL, NULL);
5438
5439         /* Dump Cast Comments */
5440         resetPQExpBuffer(defqry);
5441         appendPQExpBuffer(defqry, "CAST (%s AS %s)",
5442                                           getFormattedTypeName(cast->castsource, zeroAsNone),
5443                                           getFormattedTypeName(cast->casttarget, zeroAsNone));
5444         dumpComment(fout, defqry->data,
5445                                 NULL, "",
5446                                 cast->dobj.catId, 0, cast->dobj.dumpId);
5447
5448         destroyPQExpBuffer(defqry);
5449         destroyPQExpBuffer(delqry);
5450         destroyPQExpBuffer(castsig);
5451 }
5452
5453 /*
5454  * dumpOpr
5455  *        write out a single operator definition
5456  */
5457 static void
5458 dumpOpr(Archive *fout, OprInfo *oprinfo)
5459 {
5460         PQExpBuffer query;
5461         PQExpBuffer q;
5462         PQExpBuffer delq;
5463         PQExpBuffer oprid;
5464         PQExpBuffer details;
5465         const char *name;
5466         PGresult   *res;
5467         int                     ntups;
5468         int                     i_oprkind;
5469         int                     i_oprcode;
5470         int                     i_oprleft;
5471         int                     i_oprright;
5472         int                     i_oprcom;
5473         int                     i_oprnegate;
5474         int                     i_oprrest;
5475         int                     i_oprjoin;
5476         int                     i_oprcanhash;
5477         int                     i_oprlsortop;
5478         int                     i_oprrsortop;
5479         int                     i_oprltcmpop;
5480         int                     i_oprgtcmpop;
5481         char       *oprkind;
5482         char       *oprcode;
5483         char       *oprleft;
5484         char       *oprright;
5485         char       *oprcom;
5486         char       *oprnegate;
5487         char       *oprrest;
5488         char       *oprjoin;
5489         char       *oprcanhash;
5490         char       *oprlsortop;
5491         char       *oprrsortop;
5492         char       *oprltcmpop;
5493         char       *oprgtcmpop;
5494
5495         /* Dump only operators in dumpable namespaces */
5496         if (!oprinfo->dobj.namespace->dump || dataOnly)
5497                 return;
5498
5499         /*
5500          * some operators are invalid because they were the result of user
5501          * defining operators before commutators exist
5502          */
5503         if (!OidIsValid(oprinfo->oprcode))
5504                 return;
5505
5506         query = createPQExpBuffer();
5507         q = createPQExpBuffer();
5508         delq = createPQExpBuffer();
5509         oprid = createPQExpBuffer();
5510         details = createPQExpBuffer();
5511
5512         /* Make sure we are in proper schema so regoperator works correctly */
5513         selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
5514
5515         if (g_fout->remoteVersion >= 70300)
5516         {
5517                 appendPQExpBuffer(query, "SELECT oprkind, "
5518                                                   "oprcode::pg_catalog.regprocedure, "
5519                                                   "oprleft::pg_catalog.regtype, "
5520                                                   "oprright::pg_catalog.regtype, "
5521                                                   "oprcom::pg_catalog.regoperator, "
5522                                                   "oprnegate::pg_catalog.regoperator, "
5523                                                   "oprrest::pg_catalog.regprocedure, "
5524                                                   "oprjoin::pg_catalog.regprocedure, "
5525                                                   "oprcanhash, "
5526                                                   "oprlsortop::pg_catalog.regoperator, "
5527                                                   "oprrsortop::pg_catalog.regoperator, "
5528                                                   "oprltcmpop::pg_catalog.regoperator, "
5529                                                   "oprgtcmpop::pg_catalog.regoperator "
5530                                                   "from pg_catalog.pg_operator "
5531                                                   "where oid = '%u'::pg_catalog.oid",
5532                                                   oprinfo->dobj.catId.oid);
5533         }
5534         else if (g_fout->remoteVersion >= 70100)
5535         {
5536                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5537                                                   "CASE WHEN oprleft = 0 THEN '-' "
5538                                            "ELSE format_type(oprleft, NULL) END as oprleft, "
5539                                                   "CASE WHEN oprright = 0 THEN '-' "
5540                                          "ELSE format_type(oprright, NULL) END as oprright, "
5541                                                   "oprcom, oprnegate, oprrest, oprjoin, "
5542                                                   "oprcanhash, oprlsortop, oprrsortop, "
5543                                                   "0 as oprltcmpop, 0 as oprgtcmpop "
5544                                                   "from pg_operator "
5545                                                   "where oid = '%u'::oid",
5546                                                   oprinfo->dobj.catId.oid);
5547         }
5548         else
5549         {
5550                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
5551                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
5552                                                   "ELSE (select typname from pg_type where oid = oprleft) END as oprleft, "
5553                                                   "CASE WHEN oprright = 0 THEN '-'::name "
5554                                                   "ELSE (select typname from pg_type where oid = oprright) END as oprright, "
5555                                                   "oprcom, oprnegate, oprrest, oprjoin, "
5556                                                   "oprcanhash, oprlsortop, oprrsortop, "
5557                                                   "0 as oprltcmpop, 0 as oprgtcmpop "
5558                                                   "from pg_operator "
5559                                                   "where oid = '%u'::oid",
5560                                                   oprinfo->dobj.catId.oid);
5561         }
5562
5563         res = PQexec(g_conn, query->data);
5564         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5565
5566         /* Expecting a single result only */
5567         ntups = PQntuples(res);
5568         if (ntups != 1)
5569         {
5570                 write_msg(NULL, "Got %d rows instead of one from: %s",
5571                                   ntups, query->data);
5572                 exit_nicely();
5573         }
5574
5575         i_oprkind = PQfnumber(res, "oprkind");
5576         i_oprcode = PQfnumber(res, "oprcode");
5577         i_oprleft = PQfnumber(res, "oprleft");
5578         i_oprright = PQfnumber(res, "oprright");
5579         i_oprcom = PQfnumber(res, "oprcom");
5580         i_oprnegate = PQfnumber(res, "oprnegate");
5581         i_oprrest = PQfnumber(res, "oprrest");
5582         i_oprjoin = PQfnumber(res, "oprjoin");
5583         i_oprcanhash = PQfnumber(res, "oprcanhash");
5584         i_oprlsortop = PQfnumber(res, "oprlsortop");
5585         i_oprrsortop = PQfnumber(res, "oprrsortop");
5586         i_oprltcmpop = PQfnumber(res, "oprltcmpop");
5587         i_oprgtcmpop = PQfnumber(res, "oprgtcmpop");
5588
5589         oprkind = PQgetvalue(res, 0, i_oprkind);
5590         oprcode = PQgetvalue(res, 0, i_oprcode);
5591         oprleft = PQgetvalue(res, 0, i_oprleft);
5592         oprright = PQgetvalue(res, 0, i_oprright);
5593         oprcom = PQgetvalue(res, 0, i_oprcom);
5594         oprnegate = PQgetvalue(res, 0, i_oprnegate);
5595         oprrest = PQgetvalue(res, 0, i_oprrest);
5596         oprjoin = PQgetvalue(res, 0, i_oprjoin);
5597         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
5598         oprlsortop = PQgetvalue(res, 0, i_oprlsortop);
5599         oprrsortop = PQgetvalue(res, 0, i_oprrsortop);
5600         oprltcmpop = PQgetvalue(res, 0, i_oprltcmpop);
5601         oprgtcmpop = PQgetvalue(res, 0, i_oprgtcmpop);
5602
5603         appendPQExpBuffer(details, "    PROCEDURE = %s",
5604                                           convertRegProcReference(oprcode));
5605
5606         appendPQExpBuffer(oprid, "%s (",
5607                                           oprinfo->dobj.name);
5608
5609         /*
5610          * right unary means there's a left arg and left unary means there's a
5611          * right arg
5612          */
5613         if (strcmp(oprkind, "r") == 0 ||
5614                 strcmp(oprkind, "b") == 0)
5615         {
5616                 if (g_fout->remoteVersion >= 70100)
5617                         name = oprleft;
5618                 else
5619                         name = fmtId(oprleft);
5620                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
5621                 appendPQExpBuffer(oprid, "%s", name);
5622         }
5623         else
5624                 appendPQExpBuffer(oprid, "NONE");
5625
5626         if (strcmp(oprkind, "l") == 0 ||
5627                 strcmp(oprkind, "b") == 0)
5628         {
5629                 if (g_fout->remoteVersion >= 70100)
5630                         name = oprright;
5631                 else
5632                         name = fmtId(oprright);
5633                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
5634                 appendPQExpBuffer(oprid, ", %s)", name);
5635         }
5636         else
5637                 appendPQExpBuffer(oprid, ", NONE)");
5638
5639         name = convertOperatorReference(oprcom);
5640         if (name)
5641                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
5642
5643         name = convertOperatorReference(oprnegate);
5644         if (name)
5645                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
5646
5647         if (strcmp(oprcanhash, "t") == 0)
5648                 appendPQExpBuffer(details, ",\n    HASHES");
5649
5650         name = convertRegProcReference(oprrest);
5651         if (name)
5652                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
5653
5654         name = convertRegProcReference(oprjoin);
5655         if (name)
5656                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
5657
5658         name = convertOperatorReference(oprlsortop);
5659         if (name)
5660                 appendPQExpBuffer(details, ",\n    SORT1 = %s", name);
5661
5662         name = convertOperatorReference(oprrsortop);
5663         if (name)
5664                 appendPQExpBuffer(details, ",\n    SORT2 = %s", name);
5665
5666         name = convertOperatorReference(oprltcmpop);
5667         if (name)
5668                 appendPQExpBuffer(details, ",\n    LTCMP = %s", name);
5669
5670         name = convertOperatorReference(oprgtcmpop);
5671         if (name)
5672                 appendPQExpBuffer(details, ",\n    GTCMP = %s", name);
5673
5674         /*
5675          * DROP must be fully qualified in case same name appears in
5676          * pg_catalog
5677          */
5678         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
5679                                           fmtId(oprinfo->dobj.namespace->dobj.name),
5680                                           oprid->data);
5681
5682         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
5683                                           oprinfo->dobj.name, details->data);
5684
5685         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
5686                                  oprinfo->dobj.name,
5687                                  oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5688                                  false, "OPERATOR", q->data, delq->data, NULL,
5689                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
5690                                  NULL, NULL);
5691
5692         /* Dump Operator Comments */
5693         resetPQExpBuffer(q);
5694         appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
5695         dumpComment(fout, q->data,
5696                                 oprinfo->dobj.namespace->dobj.name, oprinfo->usename,
5697                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
5698
5699         PQclear(res);
5700
5701         destroyPQExpBuffer(query);
5702         destroyPQExpBuffer(q);
5703         destroyPQExpBuffer(delq);
5704         destroyPQExpBuffer(oprid);
5705         destroyPQExpBuffer(details);
5706 }
5707
5708 /*
5709  * Convert a function reference obtained from pg_operator
5710  *
5711  * Returns what to print, or NULL if function references is InvalidOid
5712  *
5713  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
5714  * argument-types part.  In prior versions, the input is a REGPROC display.
5715  */
5716 static const char *
5717 convertRegProcReference(const char *proc)
5718 {
5719         /* In all cases "-" means a null reference */
5720         if (strcmp(proc, "-") == 0)
5721                 return NULL;
5722
5723         if (g_fout->remoteVersion >= 70300)
5724         {
5725                 char       *name;
5726                 char       *paren;
5727                 bool            inquote;
5728
5729                 name = strdup(proc);
5730                 /* find non-double-quoted left paren */
5731                 inquote = false;
5732                 for (paren = name; *paren; paren++)
5733                 {
5734                         if (*paren == '(' && !inquote)
5735                         {
5736                                 *paren = '\0';
5737                                 break;
5738                         }
5739                         if (*paren == '"')
5740                                 inquote = !inquote;
5741                 }
5742                 return name;
5743         }
5744
5745         /* REGPROC before 7.3 does not quote its result */
5746         return fmtId(proc);
5747 }
5748
5749 /*
5750  * Convert an operator cross-reference obtained from pg_operator
5751  *
5752  * Returns what to print, or NULL to print nothing
5753  *
5754  * In 7.3 the input is a REGOPERATOR display; we have to strip the
5755  * argument-types part.  In prior versions, the input is just a
5756  * numeric OID, which we search our operator list for.
5757  */
5758 static const char *
5759 convertOperatorReference(const char *opr)
5760 {
5761         OprInfo    *oprInfo;
5762
5763         /* In all cases "0" means a null reference */
5764         if (strcmp(opr, "0") == 0)
5765                 return NULL;
5766
5767         if (g_fout->remoteVersion >= 70300)
5768         {
5769                 char       *name;
5770                 char       *paren;
5771                 bool            inquote;
5772
5773                 name = strdup(opr);
5774                 /* find non-double-quoted left paren */
5775                 inquote = false;
5776                 for (paren = name; *paren; paren++)
5777                 {
5778                         if (*paren == '(' && !inquote)
5779                         {
5780                                 *paren = '\0';
5781                                 break;
5782                         }
5783                         if (*paren == '"')
5784                                 inquote = !inquote;
5785                 }
5786                 return name;
5787         }
5788
5789         oprInfo = findOprByOid(atooid(opr));
5790         if (oprInfo == NULL)
5791         {
5792                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
5793                                   opr);
5794                 return NULL;
5795         }
5796         return oprInfo->dobj.name;
5797 }
5798
5799 /*
5800  * dumpOpclass
5801  *        write out a single operator class definition
5802  */
5803 static void
5804 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
5805 {
5806         PQExpBuffer query;
5807         PQExpBuffer q;
5808         PQExpBuffer delq;
5809         PGresult   *res;
5810         int                     ntups;
5811         int                     i_opcintype;
5812         int                     i_opckeytype;
5813         int                     i_opcdefault;
5814         int                     i_amname;
5815         int                     i_amopstrategy;
5816         int                     i_amopreqcheck;
5817         int                     i_amopopr;
5818         int                     i_amprocnum;
5819         int                     i_amproc;
5820         char       *opcintype;
5821         char       *opckeytype;
5822         char       *opcdefault;
5823         char       *amname;
5824         char       *amopstrategy;
5825         char       *amopreqcheck;
5826         char       *amopopr;
5827         char       *amprocnum;
5828         char       *amproc;
5829         bool            needComma;
5830         int                     i;
5831
5832         /* Dump only opclasses in dumpable namespaces */
5833         if (!opcinfo->dobj.namespace->dump || dataOnly)
5834                 return;
5835
5836         /*
5837          * XXX currently we do not implement dumping of operator classes from
5838          * pre-7.3 databases.  This could be done but it seems not worth the
5839          * trouble.
5840          */
5841         if (g_fout->remoteVersion < 70300)
5842                 return;
5843
5844         query = createPQExpBuffer();
5845         q = createPQExpBuffer();
5846         delq = createPQExpBuffer();
5847
5848         /* Make sure we are in proper schema so regoperator works correctly */
5849         selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
5850
5851         /* Get additional fields from the pg_opclass row */
5852         appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
5853                                           "opckeytype::pg_catalog.regtype, "
5854                                           "opcdefault, "
5855         "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
5856                                           "FROM pg_catalog.pg_opclass "
5857                                           "WHERE oid = '%u'::pg_catalog.oid",
5858                                           opcinfo->dobj.catId.oid);
5859
5860         res = PQexec(g_conn, query->data);
5861         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5862
5863         /* Expecting a single result only */
5864         ntups = PQntuples(res);
5865         if (ntups != 1)
5866         {
5867                 write_msg(NULL, "Got %d rows instead of one from: %s",
5868                                   ntups, query->data);
5869                 exit_nicely();
5870         }
5871
5872         i_opcintype = PQfnumber(res, "opcintype");
5873         i_opckeytype = PQfnumber(res, "opckeytype");
5874         i_opcdefault = PQfnumber(res, "opcdefault");
5875         i_amname = PQfnumber(res, "amname");
5876
5877         opcintype = PQgetvalue(res, 0, i_opcintype);
5878         opckeytype = PQgetvalue(res, 0, i_opckeytype);
5879         opcdefault = PQgetvalue(res, 0, i_opcdefault);
5880         /* amname will still be needed after we PQclear res */
5881         amname = strdup(PQgetvalue(res, 0, i_amname));
5882
5883         /*
5884          * DROP must be fully qualified in case same name appears in
5885          * pg_catalog
5886          */
5887         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
5888                                           fmtId(opcinfo->dobj.namespace->dobj.name));
5889         appendPQExpBuffer(delq, ".%s",
5890                                           fmtId(opcinfo->dobj.name));
5891         appendPQExpBuffer(delq, " USING %s;\n",
5892                                           fmtId(amname));
5893
5894         /* Build the fixed portion of the CREATE command */
5895         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
5896                                           fmtId(opcinfo->dobj.name));
5897         if (strcmp(opcdefault, "t") == 0)
5898                 appendPQExpBuffer(q, "DEFAULT ");
5899         appendPQExpBuffer(q, "FOR TYPE %s USING %s AS\n    ",
5900                                           opcintype,
5901                                           fmtId(amname));
5902
5903         needComma = false;
5904
5905         if (strcmp(opckeytype, "-") != 0)
5906         {
5907                 appendPQExpBuffer(q, "STORAGE %s",
5908                                                   opckeytype);
5909                 needComma = true;
5910         }
5911
5912         PQclear(res);
5913
5914         /*
5915          * Now fetch and print the OPERATOR entries (pg_amop rows).
5916          */
5917         resetPQExpBuffer(query);
5918
5919         appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
5920                                           "amopopr::pg_catalog.regoperator "
5921                                           "FROM pg_catalog.pg_amop "
5922                                           "WHERE amopclaid = '%u'::pg_catalog.oid "
5923                                           "ORDER BY amopstrategy",
5924                                           opcinfo->dobj.catId.oid);
5925
5926         res = PQexec(g_conn, query->data);
5927         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5928
5929         ntups = PQntuples(res);
5930
5931         i_amopstrategy = PQfnumber(res, "amopstrategy");
5932         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
5933         i_amopopr = PQfnumber(res, "amopopr");
5934
5935         for (i = 0; i < ntups; i++)
5936         {
5937                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
5938                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
5939                 amopopr = PQgetvalue(res, i, i_amopopr);
5940
5941                 if (needComma)
5942                         appendPQExpBuffer(q, " ,\n    ");
5943
5944                 appendPQExpBuffer(q, "OPERATOR %s %s",
5945                                                   amopstrategy, amopopr);
5946                 if (strcmp(amopreqcheck, "t") == 0)
5947                         appendPQExpBuffer(q, " RECHECK");
5948
5949                 needComma = true;
5950         }
5951
5952         PQclear(res);
5953
5954         /*
5955          * Now fetch and print the FUNCTION entries (pg_amproc rows).
5956          */
5957         resetPQExpBuffer(query);
5958
5959         appendPQExpBuffer(query, "SELECT amprocnum, "
5960                                           "amproc::pg_catalog.regprocedure "
5961                                           "FROM pg_catalog.pg_amproc "
5962                                           "WHERE amopclaid = '%u'::pg_catalog.oid "
5963                                           "ORDER BY amprocnum",
5964                                           opcinfo->dobj.catId.oid);
5965
5966         res = PQexec(g_conn, query->data);
5967         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5968
5969         ntups = PQntuples(res);
5970
5971         i_amprocnum = PQfnumber(res, "amprocnum");
5972         i_amproc = PQfnumber(res, "amproc");
5973
5974         for (i = 0; i < ntups; i++)
5975         {
5976                 amprocnum = PQgetvalue(res, i, i_amprocnum);
5977                 amproc = PQgetvalue(res, i, i_amproc);
5978
5979                 if (needComma)
5980                         appendPQExpBuffer(q, " ,\n    ");
5981
5982                 appendPQExpBuffer(q, "FUNCTION %s %s",
5983                                                   amprocnum, amproc);
5984
5985                 needComma = true;
5986         }
5987
5988         PQclear(res);
5989
5990         appendPQExpBuffer(q, ";\n");
5991
5992         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
5993                                  opcinfo->dobj.name,
5994                                  opcinfo->dobj.namespace->dobj.name, opcinfo->usename,
5995                                  false, "OPERATOR CLASS", q->data, delq->data, NULL,
5996                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
5997                                  NULL, NULL);
5998
5999         /* Dump Operator Class Comments */
6000         resetPQExpBuffer(q);
6001         appendPQExpBuffer(q, "OPERATOR CLASS %s",
6002                                           fmtId(opcinfo->dobj.name));
6003         appendPQExpBuffer(q, " USING %s",
6004                                           fmtId(amname));
6005         dumpComment(fout, q->data,
6006                                 NULL, opcinfo->usename,
6007                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
6008
6009         free(amname);
6010         destroyPQExpBuffer(query);
6011         destroyPQExpBuffer(q);
6012         destroyPQExpBuffer(delq);
6013 }
6014
6015 /*
6016  * dumpConversion
6017  *        write out a single conversion definition
6018  */
6019 static void
6020 dumpConversion(Archive *fout, ConvInfo *convinfo)
6021 {
6022         PQExpBuffer query;
6023         PQExpBuffer q;
6024         PQExpBuffer delq;
6025         PQExpBuffer details;
6026         PGresult   *res;
6027         int                     ntups;
6028         int                     i_conname;
6029         int                     i_conforencoding;
6030         int                     i_contoencoding;
6031         int                     i_conproc;
6032         int                     i_condefault;
6033         const char *conname;
6034         const char *conforencoding;
6035         const char *contoencoding;
6036         const char *conproc;
6037         bool            condefault;
6038
6039         /* Dump only conversions in dumpable namespaces */
6040         if (!convinfo->dobj.namespace->dump || dataOnly)
6041                 return;
6042
6043         query = createPQExpBuffer();
6044         q = createPQExpBuffer();
6045         delq = createPQExpBuffer();
6046         details = createPQExpBuffer();
6047
6048         /* Make sure we are in proper schema */
6049         selectSourceSchema(convinfo->dobj.namespace->dobj.name);
6050
6051         /* Get conversion-specific details */
6052         appendPQExpBuffer(query, "SELECT conname, "
6053          "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
6054            "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
6055                                           "conproc, condefault "
6056                                           "FROM pg_catalog.pg_conversion c "
6057                                           "WHERE c.oid = '%u'::pg_catalog.oid",
6058                                           convinfo->dobj.catId.oid);
6059
6060         res = PQexec(g_conn, query->data);
6061         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6062
6063         /* Expecting a single result only */
6064         ntups = PQntuples(res);
6065         if (ntups != 1)
6066         {
6067                 write_msg(NULL, "Got %d rows instead of one from: %s",
6068                                   ntups, query->data);
6069                 exit_nicely();
6070         }
6071
6072         i_conname = PQfnumber(res, "conname");
6073         i_conforencoding = PQfnumber(res, "conforencoding");
6074         i_contoencoding = PQfnumber(res, "contoencoding");
6075         i_conproc = PQfnumber(res, "conproc");
6076         i_condefault = PQfnumber(res, "condefault");
6077
6078         conname = PQgetvalue(res, 0, i_conname);
6079         conforencoding = PQgetvalue(res, 0, i_conforencoding);
6080         contoencoding = PQgetvalue(res, 0, i_contoencoding);
6081         conproc = PQgetvalue(res, 0, i_conproc);
6082         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
6083
6084         /*
6085          * DROP must be fully qualified in case same name appears in
6086          * pg_catalog
6087          */
6088         appendPQExpBuffer(delq, "DROP CONVERSION %s",
6089                                           fmtId(convinfo->dobj.namespace->dobj.name));
6090         appendPQExpBuffer(delq, ".%s;\n",
6091                                           fmtId(convinfo->dobj.name));
6092
6093         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
6094                                           (condefault) ? "DEFAULT " : "",
6095                                           fmtId(convinfo->dobj.name));
6096         appendStringLiteral(q, conforencoding, true);
6097         appendPQExpBuffer(q, " TO ");
6098         appendStringLiteral(q, contoencoding, true);
6099         /* regproc is automatically quoted in 7.3 and above */
6100         appendPQExpBuffer(q, " FROM %s;\n", conproc);
6101
6102         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
6103                                  convinfo->dobj.name,
6104                                  convinfo->dobj.namespace->dobj.name, convinfo->usename,
6105                                  false, "CONVERSION", q->data, delq->data, NULL,
6106                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
6107                                  NULL, NULL);
6108
6109         /* Dump Conversion Comments */
6110         resetPQExpBuffer(q);
6111         appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
6112         dumpComment(fout, q->data,
6113                                 convinfo->dobj.namespace->dobj.name, convinfo->usename,
6114                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
6115
6116         PQclear(res);
6117
6118         destroyPQExpBuffer(query);
6119         destroyPQExpBuffer(q);
6120         destroyPQExpBuffer(delq);
6121         destroyPQExpBuffer(details);
6122 }
6123
6124 /*
6125  * format_aggregate_signature: generate aggregate name and argument list
6126  *
6127  * The argument type names are qualified if needed.  The aggregate name
6128  * is never qualified.
6129  */
6130 static char *
6131 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
6132 {
6133         PQExpBufferData buf;
6134
6135         initPQExpBuffer(&buf);
6136         if (honor_quotes)
6137                 appendPQExpBuffer(&buf, "%s",
6138                                                   fmtId(agginfo->aggfn.dobj.name));
6139         else
6140                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
6141
6142         /* If using regtype or format_type, fmtbasetype is already quoted */
6143         if (fout->remoteVersion >= 70100)
6144         {
6145                 if (agginfo->anybasetype)
6146                         appendPQExpBuffer(&buf, "(*)");
6147                 else
6148                         appendPQExpBuffer(&buf, "(%s)", agginfo->fmtbasetype);
6149         }
6150         else
6151         {
6152                 if (agginfo->anybasetype)
6153                         appendPQExpBuffer(&buf, "(*)");
6154                 else
6155                         appendPQExpBuffer(&buf, "(%s)",
6156                                                           fmtId(agginfo->fmtbasetype));
6157         }
6158
6159         return buf.data;
6160 }
6161
6162 /*
6163  * dumpAgg
6164  *        write out a single aggregate definition
6165  */
6166 static void
6167 dumpAgg(Archive *fout, AggInfo *agginfo)
6168 {
6169         PQExpBuffer query;
6170         PQExpBuffer q;
6171         PQExpBuffer delq;
6172         PQExpBuffer details;
6173         char       *aggsig;
6174         char       *aggsig_tag;
6175         PGresult   *res;
6176         int                     ntups;
6177         int                     i_aggtransfn;
6178         int                     i_aggfinalfn;
6179         int                     i_aggtranstype;
6180         int                     i_agginitval;
6181         int                     i_anybasetype;
6182         int                     i_fmtbasetype;
6183         int                     i_convertok;
6184         const char *aggtransfn;
6185         const char *aggfinalfn;
6186         const char *aggtranstype;
6187         const char *agginitval;
6188         bool            convertok;
6189
6190         /* Dump only aggs in dumpable namespaces */
6191         if (!agginfo->aggfn.dobj.namespace->dump || dataOnly)
6192                 return;
6193
6194         query = createPQExpBuffer();
6195         q = createPQExpBuffer();
6196         delq = createPQExpBuffer();
6197         details = createPQExpBuffer();
6198
6199         /* Make sure we are in proper schema */
6200         selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
6201
6202         /* Get aggregate-specific details */
6203         if (g_fout->remoteVersion >= 70300)
6204         {
6205                 appendPQExpBuffer(query, "SELECT aggtransfn, "
6206                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
6207                                                   "agginitval, "
6208                                                   "proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype as anybasetype, "
6209                                         "proargtypes[0]::pg_catalog.regtype as fmtbasetype, "
6210                                                   "'t'::boolean as convertok "
6211                                   "from pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
6212                                                   "where a.aggfnoid = p.oid "
6213                                                   "and p.oid = '%u'::pg_catalog.oid",
6214                                                   agginfo->aggfn.dobj.catId.oid);
6215         }
6216         else if (g_fout->remoteVersion >= 70100)
6217         {
6218                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
6219                                           "format_type(aggtranstype, NULL) as aggtranstype, "
6220                                                   "agginitval, "
6221                                                   "aggbasetype = 0 as anybasetype, "
6222                                                   "CASE WHEN aggbasetype = 0 THEN '-' "
6223                            "ELSE format_type(aggbasetype, NULL) END as fmtbasetype, "
6224                                                   "'t'::boolean as convertok "
6225                                                   "from pg_aggregate "
6226                                                   "where oid = '%u'::oid",
6227                                                   agginfo->aggfn.dobj.catId.oid);
6228         }
6229         else
6230         {
6231                 appendPQExpBuffer(query, "SELECT aggtransfn1 as aggtransfn, "
6232                                                   "aggfinalfn, "
6233                                                   "(select typname from pg_type where oid = aggtranstype1) as aggtranstype, "
6234                                                   "agginitval1 as agginitval, "
6235                                                   "aggbasetype = 0 as anybasetype, "
6236                                                   "(select typname from pg_type where oid = aggbasetype) as fmtbasetype, "
6237                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) as convertok "
6238                                                   "from pg_aggregate "
6239                                                   "where oid = '%u'::oid",
6240                                                   agginfo->aggfn.dobj.catId.oid);
6241         }
6242
6243         res = PQexec(g_conn, query->data);
6244         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6245
6246         /* Expecting a single result only */
6247         ntups = PQntuples(res);
6248         if (ntups != 1)
6249         {
6250                 write_msg(NULL, "Got %d rows instead of one from: %s",
6251                                   ntups, query->data);
6252                 exit_nicely();
6253         }
6254
6255         i_aggtransfn = PQfnumber(res, "aggtransfn");
6256         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
6257         i_aggtranstype = PQfnumber(res, "aggtranstype");
6258         i_agginitval = PQfnumber(res, "agginitval");
6259         i_anybasetype = PQfnumber(res, "anybasetype");
6260         i_fmtbasetype = PQfnumber(res, "fmtbasetype");
6261         i_convertok = PQfnumber(res, "convertok");
6262
6263         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
6264         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
6265         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
6266         agginitval = PQgetvalue(res, 0, i_agginitval);
6267         /* we save anybasetype for format_aggregate_signature */
6268         agginfo->anybasetype = (PQgetvalue(res, 0, i_anybasetype)[0] == 't');
6269         /* we save fmtbasetype for format_aggregate_signature */
6270         agginfo->fmtbasetype = strdup(PQgetvalue(res, 0, i_fmtbasetype));
6271         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
6272
6273         aggsig = format_aggregate_signature(agginfo, fout, true);
6274         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
6275
6276         if (!convertok)
6277         {
6278                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
6279                                   aggsig);
6280                 return;
6281         }
6282
6283         if (g_fout->remoteVersion >= 70300)
6284         {
6285                 /* If using 7.3's regproc or regtype, data is already quoted */
6286                 appendPQExpBuffer(details, "    BASETYPE = %s,\n    SFUNC = %s,\n    STYPE = %s",
6287                                                   agginfo->anybasetype ? "'any'" :
6288                                                   agginfo->fmtbasetype,
6289                                                   aggtransfn,
6290                                                   aggtranstype);
6291         }
6292         else if (g_fout->remoteVersion >= 70100)
6293         {
6294                 /* format_type quotes, regproc does not */
6295                 appendPQExpBuffer(details, "    BASETYPE = %s,\n    SFUNC = %s,\n    STYPE = %s",
6296                                                   agginfo->anybasetype ? "'any'" :
6297                                                   agginfo->fmtbasetype,
6298                                                   fmtId(aggtransfn),
6299                                                   aggtranstype);
6300         }
6301         else
6302         {
6303                 /* need quotes all around */
6304                 appendPQExpBuffer(details, "    BASETYPE = %s,\n",
6305                                                   agginfo->anybasetype ? "'any'" :
6306                                                   fmtId(agginfo->fmtbasetype));
6307                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
6308                                                   fmtId(aggtransfn));
6309                 appendPQExpBuffer(details, "    STYPE = %s",
6310                                                   fmtId(aggtranstype));
6311         }
6312
6313         if (!PQgetisnull(res, 0, i_agginitval))
6314         {
6315                 appendPQExpBuffer(details, ",\n    INITCOND = ");
6316                 appendStringLiteral(details, agginitval, true);
6317         }
6318
6319         if (strcmp(aggfinalfn, "-") != 0)
6320         {
6321                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
6322                                                   aggfinalfn);
6323         }
6324
6325         /*
6326          * DROP must be fully qualified in case same name appears in
6327          * pg_catalog
6328          */
6329         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
6330                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
6331                                           aggsig);
6332
6333         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
6334                                           fmtId(agginfo->aggfn.dobj.name),
6335                                           details->data);
6336
6337         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6338                                  aggsig_tag,
6339                 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6340                                  false, "AGGREGATE", q->data, delq->data, NULL,
6341                          agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
6342                                  NULL, NULL);
6343
6344         /* Dump Aggregate Comments */
6345         resetPQExpBuffer(q);
6346         appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
6347         dumpComment(fout, q->data,
6348                 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.usename,
6349                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
6350
6351         /*
6352          * Since there is no GRANT ON AGGREGATE syntax, we have to make the
6353          * ACL command look like a function's GRANT; in particular this
6354          * affects the syntax for aggregates on ANY.
6355          */
6356         free(aggsig);
6357         free(aggsig_tag);
6358
6359         aggsig = format_function_signature(&agginfo->aggfn, NULL, true);
6360         aggsig_tag = format_function_signature(&agginfo->aggfn, NULL, false);
6361
6362         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
6363                         "FUNCTION",
6364                         aggsig, aggsig_tag,
6365                         agginfo->aggfn.dobj.namespace->dobj.name,
6366                         agginfo->aggfn.usename, agginfo->aggfn.proacl);
6367
6368         free(aggsig);
6369         free(aggsig_tag);
6370
6371         PQclear(res);
6372
6373         destroyPQExpBuffer(query);
6374         destroyPQExpBuffer(q);
6375         destroyPQExpBuffer(delq);
6376         destroyPQExpBuffer(details);
6377 }
6378
6379
6380 /*----------
6381  * Write out grant/revoke information
6382  *
6383  * 'objCatId' is the catalog ID of the underlying object.
6384  * 'objDumpId' is the dump ID of the underlying object.
6385  * 'type' must be TABLE, FUNCTION, LANGUAGE, or SCHEMA.
6386  * 'name' is the formatted name of the object.  Must be quoted etc. already.
6387  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
6388  * 'nspname' is the namespace the object is in (NULL if none).
6389  * 'owner' is the owner, NULL if there is no owner (for languages).
6390  * 'acls' is the string read out of the fooacl system catalog field;
6391  * it will be parsed here.
6392  *----------
6393  */
6394 static void
6395 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
6396                 const char *type, const char *name,
6397                 const char *tag, const char *nspname, const char *owner,
6398                 const char *acls)
6399 {
6400         PQExpBuffer sql;
6401
6402         /* Do nothing if ACL dump is not enabled */
6403         if (dataOnly || aclsSkip)
6404                 return;
6405
6406         sql = createPQExpBuffer();
6407
6408         if (!buildACLCommands(name, type, acls, owner, fout->remoteVersion, sql))
6409         {
6410                 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
6411                                   acls, name, type);
6412                 exit_nicely();
6413         }
6414
6415         if (sql->len > 0)
6416                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6417                                          tag, nspname,
6418                                          owner ? owner : "",
6419                                          false, "ACL", sql->data, "", NULL,
6420                                          &(objDumpId), 1,
6421                                          NULL, NULL);
6422
6423         destroyPQExpBuffer(sql);
6424 }
6425
6426 /*
6427  * dumpTable
6428  *        write out to fout the declarations (not data) of a user-defined table
6429  */
6430 static void
6431 dumpTable(Archive *fout, TableInfo *tbinfo)
6432 {
6433         char       *namecopy;
6434
6435         if (tbinfo->dump)
6436         {
6437                 if (tbinfo->relkind == RELKIND_SEQUENCE)
6438                         dumpSequence(fout, tbinfo);
6439                 else if (!dataOnly)
6440                         dumpTableSchema(fout, tbinfo);
6441
6442                 /* Handle the ACL here */
6443                 namecopy = strdup(fmtId(tbinfo->dobj.name));
6444                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
6445                                 namecopy, tbinfo->dobj.name,
6446                                 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6447                                 tbinfo->relacl);
6448                 free(namecopy);
6449         }
6450 }
6451
6452 /*
6453  * dumpTableSchema
6454  *        write the declaration (not data) of one user-defined table or view
6455  */
6456 static void
6457 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
6458 {
6459         PQExpBuffer query = createPQExpBuffer();
6460         PQExpBuffer q = createPQExpBuffer();
6461         PQExpBuffer delq = createPQExpBuffer();
6462         PGresult   *res;
6463         int                     numParents;
6464         TableInfo **parents;
6465         int                     actual_atts;    /* number of attrs in this CREATE statment */
6466         char       *reltypename;
6467         char       *storage;
6468         int                     j,
6469                                 k;
6470
6471         /* Make sure we are in proper schema */
6472         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
6473
6474         /* Is it a table or a view? */
6475         if (tbinfo->relkind == RELKIND_VIEW)
6476         {
6477                 char       *viewdef;
6478
6479                 reltypename = "VIEW";
6480
6481                 /* Fetch the view definition */
6482                 if (g_fout->remoteVersion >= 70300)
6483                 {
6484                         /* Beginning in 7.3, viewname is not unique; rely on OID */
6485                         appendPQExpBuffer(query,
6486                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) as viewdef",
6487                                                           tbinfo->dobj.catId.oid);
6488                 }
6489                 else
6490                 {
6491                         appendPQExpBuffer(query, "SELECT definition as viewdef "
6492                                                           " from pg_views where viewname = ");
6493                         appendStringLiteral(query, tbinfo->dobj.name, true);
6494                         appendPQExpBuffer(query, ";");
6495                 }
6496
6497                 res = PQexec(g_conn, query->data);
6498                 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6499
6500                 if (PQntuples(res) != 1)
6501                 {
6502                         if (PQntuples(res) < 1)
6503                                 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
6504                                                   tbinfo->dobj.name);
6505                         else
6506                                 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
6507                                                   tbinfo->dobj.name);
6508                         exit_nicely();
6509                 }
6510
6511                 viewdef = PQgetvalue(res, 0, 0);
6512
6513                 if (strlen(viewdef) == 0)
6514                 {
6515                         write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
6516                                           tbinfo->dobj.name);
6517                         exit_nicely();
6518                 }
6519
6520                 /*
6521                  * DROP must be fully qualified in case same name appears in
6522                  * pg_catalog
6523                  */
6524                 appendPQExpBuffer(delq, "DROP VIEW %s.",
6525                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
6526                 appendPQExpBuffer(delq, "%s;\n",
6527                                                   fmtId(tbinfo->dobj.name));
6528
6529                 appendPQExpBuffer(q, "CREATE VIEW %s AS\n    %s\n",
6530                                                   fmtId(tbinfo->dobj.name), viewdef);
6531
6532                 PQclear(res);
6533         }
6534         else
6535         {
6536                 reltypename = "TABLE";
6537                 numParents = tbinfo->numParents;
6538                 parents = tbinfo->parents;
6539
6540                 /*
6541                  * DROP must be fully qualified in case same name appears in
6542                  * pg_catalog
6543                  */
6544                 appendPQExpBuffer(delq, "DROP TABLE %s.",
6545                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
6546                 appendPQExpBuffer(delq, "%s;\n",
6547                                                   fmtId(tbinfo->dobj.name));
6548
6549                 appendPQExpBuffer(q, "CREATE TABLE %s (",
6550                                                   fmtId(tbinfo->dobj.name));
6551                 actual_atts = 0;
6552                 for (j = 0; j < tbinfo->numatts; j++)
6553                 {
6554                         /* Is this one of the table's own attrs, and not dropped ? */
6555                         if (!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j])
6556                         {
6557                                 /* Format properly if not first attr */
6558                                 if (actual_atts > 0)
6559                                         appendPQExpBuffer(q, ",");
6560                                 appendPQExpBuffer(q, "\n    ");
6561
6562                                 /* Attribute name */
6563                                 appendPQExpBuffer(q, "%s ",
6564                                                                   fmtId(tbinfo->attnames[j]));
6565
6566                                 /* Attribute type */
6567                                 if (g_fout->remoteVersion >= 70100)
6568                                 {
6569                                         char       *typname = tbinfo->atttypnames[j];
6570
6571                                         if (tbinfo->attisserial[j])
6572                                         {
6573                                                 if (strcmp(typname, "integer") == 0)
6574                                                         typname = "serial";
6575                                                 else if (strcmp(typname, "bigint") == 0)
6576                                                         typname = "bigserial";
6577                                         }
6578                                         appendPQExpBuffer(q, "%s", typname);
6579                                 }
6580                                 else
6581                                 {
6582                                         /* If no format_type, fake it */
6583                                         appendPQExpBuffer(q, "%s",
6584                                                                           myFormatType(tbinfo->atttypnames[j],
6585                                                                                                    tbinfo->atttypmod[j]));
6586                                 }
6587
6588                                 /*
6589                                  * Default value --- suppress if inherited, serial, or to
6590                                  * be printed separately.
6591                                  */
6592                                 if (tbinfo->attrdefs[j] != NULL &&
6593                                         !tbinfo->inhAttrDef[j] &&
6594                                         !tbinfo->attisserial[j] &&
6595                                         !tbinfo->attrdefs[j]->separate)
6596                                         appendPQExpBuffer(q, " DEFAULT %s",
6597                                                                           tbinfo->attrdefs[j]->adef_expr);
6598
6599                                 /*
6600                                  * Not Null constraint --- suppress if inherited
6601                                  *
6602                                  * Note: we could suppress this for serial columns since
6603                                  * SERIAL implies NOT NULL.  We choose not to for forward
6604                                  * compatibility, since there has been some talk of making
6605                                  * SERIAL not imply NOT NULL, in which case the explicit
6606                                  * specification would be needed.
6607                                  */
6608                                 if (tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
6609                                         appendPQExpBuffer(q, " NOT NULL");
6610
6611                                 actual_atts++;
6612                         }
6613                 }
6614
6615                 /*
6616                  * Add non-inherited CHECK constraints, if any.
6617                  */
6618                 for (j = 0; j < tbinfo->ncheck; j++)
6619                 {
6620                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
6621
6622                         if (constr->coninherited || constr->separate)
6623                                 continue;
6624
6625                         if (actual_atts > 0)
6626                                 appendPQExpBuffer(q, ",\n    ");
6627
6628                         appendPQExpBuffer(q, "CONSTRAINT %s ",
6629                                                           fmtId(constr->dobj.name));
6630                         appendPQExpBuffer(q, "%s", constr->condef);
6631
6632                         actual_atts++;
6633                 }
6634
6635                 appendPQExpBuffer(q, "\n)");
6636
6637                 if (numParents > 0)
6638                 {
6639                         appendPQExpBuffer(q, "\nINHERITS (");
6640                         for (k = 0; k < numParents; k++)
6641                         {
6642                                 TableInfo  *parentRel = parents[k];
6643
6644                                 if (k > 0)
6645                                         appendPQExpBuffer(q, ", ");
6646                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
6647                                         appendPQExpBuffer(q, "%s.",
6648                                                         fmtId(parentRel->dobj.namespace->dobj.name));
6649                                 appendPQExpBuffer(q, "%s",
6650                                                                   fmtId(parentRel->dobj.name));
6651                         }
6652                         appendPQExpBuffer(q, ")");
6653                 }
6654
6655                 /* Output tablespace clause if necessary */
6656                 if (strlen(tbinfo->reltablespace) != 0 &&
6657                         strcmp(tbinfo->reltablespace,
6658                                    tbinfo->dobj.namespace->nsptablespace) != 0)
6659                 {
6660                         appendPQExpBuffer(q, " TABLESPACE %s",
6661                                                           fmtId(tbinfo->reltablespace));
6662                 }
6663
6664                 appendPQExpBuffer(q, ";\n");
6665
6666                 /* Loop dumping statistics and storage statements */
6667                 for (j = 0; j < tbinfo->numatts; j++)
6668                 {
6669                         /*
6670                          * Dump per-column statistics information. We only issue an
6671                          * ALTER TABLE statement if the attstattarget entry for this
6672                          * column is non-negative (i.e. it's not the default value)
6673                          */
6674                         if (tbinfo->attstattarget[j] >= 0 &&
6675                                 !tbinfo->attisdropped[j])
6676                         {
6677                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6678                                                                   fmtId(tbinfo->dobj.name));
6679                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
6680                                                                   fmtId(tbinfo->attnames[j]));
6681                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
6682                                                                   tbinfo->attstattarget[j]);
6683                         }
6684
6685                         /*
6686                          * Dump per-column storage information.  The statement is only
6687                          * dumped if the storage has been changed from the type's
6688                          * default.
6689                          */
6690                         if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
6691                         {
6692                                 switch (tbinfo->attstorage[j])
6693                                 {
6694                                         case 'p':
6695                                                 storage = "PLAIN";
6696                                                 break;
6697                                         case 'e':
6698                                                 storage = "EXTERNAL";
6699                                                 break;
6700                                         case 'm':
6701                                                 storage = "MAIN";
6702                                                 break;
6703                                         case 'x':
6704                                                 storage = "EXTENDED";
6705                                                 break;
6706                                         default:
6707                                                 storage = NULL;
6708                                 }
6709
6710                                 /*
6711                                  * Only dump the statement if it's a storage type we
6712                                  * recognize
6713                                  */
6714                                 if (storage != NULL)
6715                                 {
6716                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
6717                                                                           fmtId(tbinfo->dobj.name));
6718                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
6719                                                                           fmtId(tbinfo->attnames[j]));
6720                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
6721                                                                           storage);
6722                                 }
6723                         }
6724                 }
6725         }
6726
6727         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
6728                                  tbinfo->dobj.name,
6729                                  tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6730                    (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
6731                                  reltypename, q->data, delq->data, NULL,
6732                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
6733                                  NULL, NULL);
6734
6735         /* Dump Table Comments */
6736         dumpTableComment(fout, tbinfo, reltypename);
6737
6738         destroyPQExpBuffer(query);
6739         destroyPQExpBuffer(q);
6740         destroyPQExpBuffer(delq);
6741 }
6742
6743 /*
6744  * dumpAttrDef --- dump an attribute's default-value declaration
6745  */
6746 static void
6747 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
6748 {
6749         TableInfo  *tbinfo = adinfo->adtable;
6750         int                     adnum = adinfo->adnum;
6751         PQExpBuffer q;
6752         PQExpBuffer delq;
6753
6754         /* Only print it if "separate" mode is selected */
6755         if (!tbinfo->dump || !adinfo->separate || dataOnly)
6756                 return;
6757
6758         /* Don't print inherited or serial defaults, either */
6759         if (tbinfo->inhAttrDef[adnum - 1] || tbinfo->attisserial[adnum - 1])
6760                 return;
6761
6762         q = createPQExpBuffer();
6763         delq = createPQExpBuffer();
6764
6765         appendPQExpBuffer(q, "ALTER TABLE %s ",
6766                                           fmtId(tbinfo->dobj.name));
6767         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
6768                                           fmtId(tbinfo->attnames[adnum - 1]),
6769                                           adinfo->adef_expr);
6770
6771         /*
6772          * DROP must be fully qualified in case same name appears in
6773          * pg_catalog
6774          */
6775         appendPQExpBuffer(delq, "ALTER TABLE %s.",
6776                                           fmtId(tbinfo->dobj.namespace->dobj.name));
6777         appendPQExpBuffer(delq, "%s ",
6778                                           fmtId(tbinfo->dobj.name));
6779         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
6780                                           fmtId(tbinfo->attnames[adnum - 1]));
6781
6782         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
6783                                  tbinfo->attnames[adnum - 1],
6784                                  tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
6785                                  false, "DEFAULT", q->data, delq->data, NULL,
6786                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
6787                                  NULL, NULL);
6788
6789         destroyPQExpBuffer(q);
6790         destroyPQExpBuffer(delq);
6791 }
6792
6793 /*
6794  * getAttrName: extract the correct name for an attribute
6795  *
6796  * The array tblInfo->attnames[] only provides names of user attributes;
6797  * if a system attribute number is supplied, we have to fake it.
6798  * We also do a little bit of bounds checking for safety's sake.
6799  */
6800 static const char *
6801 getAttrName(int attrnum, TableInfo *tblInfo)
6802 {
6803         if (attrnum > 0 && attrnum <= tblInfo->numatts)
6804                 return tblInfo->attnames[attrnum - 1];
6805         switch (attrnum)
6806         {
6807                 case SelfItemPointerAttributeNumber:
6808                         return "ctid";
6809                 case ObjectIdAttributeNumber:
6810                         return "oid";
6811                 case MinTransactionIdAttributeNumber:
6812                         return "xmin";
6813                 case MinCommandIdAttributeNumber:
6814                         return "cmin";
6815                 case MaxTransactionIdAttributeNumber:
6816                         return "xmax";
6817                 case MaxCommandIdAttributeNumber:
6818                         return "cmax";
6819                 case TableOidAttributeNumber:
6820                         return "tableoid";
6821         }
6822         write_msg(NULL, "invalid column number %d for table \"%s\"\n",
6823                           attrnum, tblInfo->dobj.name);
6824         exit_nicely();
6825         return NULL;                            /* keep compiler quiet */
6826 }
6827
6828 /*
6829  * dumpIndex
6830  *        write out to fout a user-defined index
6831  */
6832 static void
6833 dumpIndex(Archive *fout, IndxInfo *indxinfo)
6834 {
6835         TableInfo  *tbinfo = indxinfo->indextable;
6836         PQExpBuffer q;
6837         PQExpBuffer delq;
6838
6839         if (dataOnly)
6840                 return;
6841
6842         q = createPQExpBuffer();
6843         delq = createPQExpBuffer();
6844
6845         /*
6846          * If there's an associated constraint, don't dump the index per se,
6847          * but do dump any comment for it.
6848          */
6849         if (indxinfo->indexconstraint == 0)
6850         {
6851                 /* Plain secondary index */
6852                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
6853
6854                 /* If the index is clustered, we need to record that. */
6855                 if (indxinfo->indisclustered)
6856                 {
6857                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6858                                                           fmtId(tbinfo->dobj.name));
6859                         appendPQExpBuffer(q, " ON %s;\n",
6860                                                           fmtId(indxinfo->dobj.name));
6861                 }
6862
6863                 /*
6864                  * DROP must be fully qualified in case same name appears in
6865                  * pg_catalog
6866                  */
6867                 appendPQExpBuffer(delq, "DROP INDEX %s.",
6868                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
6869                 appendPQExpBuffer(delq, "%s;\n",
6870                                                   fmtId(indxinfo->dobj.name));
6871
6872                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
6873                                          indxinfo->dobj.name,
6874                                          tbinfo->dobj.namespace->dobj.name,
6875                                          tbinfo->usename, false,
6876                                          "INDEX", q->data, delq->data, NULL,
6877                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
6878                                          NULL, NULL);
6879         }
6880
6881         /* Dump Index Comments */
6882         resetPQExpBuffer(q);
6883         appendPQExpBuffer(q, "INDEX %s",
6884                                           fmtId(indxinfo->dobj.name));
6885         dumpComment(fout, q->data,
6886                                 tbinfo->dobj.namespace->dobj.name,
6887                                 tbinfo->usename,
6888                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
6889
6890         destroyPQExpBuffer(q);
6891         destroyPQExpBuffer(delq);
6892 }
6893
6894 /*
6895  * dumpConstraint
6896  *        write out to fout a user-defined constraint
6897  */
6898 static void
6899 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
6900 {
6901         TableInfo  *tbinfo = coninfo->contable;
6902         PQExpBuffer q;
6903         PQExpBuffer delq;
6904
6905         if (dataOnly)
6906                 return;
6907         if (tbinfo && !tbinfo->dump)
6908                 return;
6909
6910         q = createPQExpBuffer();
6911         delq = createPQExpBuffer();
6912
6913         if (coninfo->contype == 'p' || coninfo->contype == 'u')
6914         {
6915                 /* Index-related constraint */
6916                 IndxInfo   *indxinfo;
6917                 int                     k;
6918
6919                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
6920
6921                 if (indxinfo == NULL)
6922                 {
6923                         write_msg(NULL, "missing index for constraint %s\n",
6924                                           coninfo->dobj.name);
6925                         exit_nicely();
6926                 }
6927
6928                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6929                                                   fmtId(tbinfo->dobj.name));
6930                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s (",
6931                                                   fmtId(coninfo->dobj.name),
6932                                          coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
6933
6934                 for (k = 0; k < indxinfo->indnkeys; k++)
6935                 {
6936                         int                     indkey = (int) indxinfo->indkeys[k];
6937                         const char *attname;
6938
6939                         if (indkey == InvalidAttrNumber)
6940                                 break;
6941                         attname = getAttrName(indkey, tbinfo);
6942
6943                         appendPQExpBuffer(q, "%s%s",
6944                                                           (k == 0) ? "" : ", ",
6945                                                           fmtId(attname));
6946                 }
6947
6948                 appendPQExpBuffer(q, ")");
6949
6950                 /* Output tablespace clause if necessary */
6951                 if (strlen(indxinfo->tablespace) != 0 &&
6952                         strcmp(indxinfo->tablespace,
6953                                    indxinfo->indextable->reltablespace) != 0)
6954                 {
6955                         appendPQExpBuffer(q, " USING INDEX TABLESPACE %s",
6956                                                           fmtId(indxinfo->tablespace));
6957                 }
6958
6959                 appendPQExpBuffer(q, ";\n");
6960
6961                 /* If the index is clustered, we need to record that. */
6962                 if (indxinfo->indisclustered)
6963                 {
6964                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
6965                                                           fmtId(tbinfo->dobj.name));
6966                         appendPQExpBuffer(q, " ON %s;\n",
6967                                                           fmtId(indxinfo->dobj.name));
6968                 }
6969
6970                 /*
6971                  * DROP must be fully qualified in case same name appears in
6972                  * pg_catalog
6973                  */
6974                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
6975                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
6976                 appendPQExpBuffer(delq, "%s ",
6977                                                   fmtId(tbinfo->dobj.name));
6978                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
6979                                                   fmtId(coninfo->dobj.name));
6980
6981                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
6982                                          coninfo->dobj.name,
6983                                          tbinfo->dobj.namespace->dobj.name,
6984                                          tbinfo->usename, false,
6985                                          "CONSTRAINT", q->data, delq->data, NULL,
6986                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
6987                                          NULL, NULL);
6988         }
6989         else if (coninfo->contype == 'f')
6990         {
6991                 /*
6992                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that
6993                  * the current table data is not processed
6994                  */
6995                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
6996                                                   fmtId(tbinfo->dobj.name));
6997                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
6998                                                   fmtId(coninfo->dobj.name),
6999                                                   coninfo->condef);
7000
7001                 /*
7002                  * DROP must be fully qualified in case same name appears in
7003                  * pg_catalog
7004                  */
7005                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
7006                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
7007                 appendPQExpBuffer(delq, "%s ",
7008                                                   fmtId(tbinfo->dobj.name));
7009                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7010                                                   fmtId(coninfo->dobj.name));
7011
7012                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7013                                          coninfo->dobj.name,
7014                                          tbinfo->dobj.namespace->dobj.name,
7015                                          tbinfo->usename, false,
7016                                          "FK CONSTRAINT", q->data, delq->data, NULL,
7017                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7018                                          NULL, NULL);
7019         }
7020         else if (coninfo->contype == 'c' && tbinfo)
7021         {
7022                 /* CHECK constraint on a table */
7023
7024                 /* Ignore if not to be dumped separately */
7025                 if (coninfo->separate)
7026                 {
7027                         /* not ONLY since we want it to propagate to children */
7028                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
7029                                                           fmtId(tbinfo->dobj.name));
7030                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
7031                                                           fmtId(coninfo->dobj.name),
7032                                                           coninfo->condef);
7033
7034                         /*
7035                          * DROP must be fully qualified in case same name appears in
7036                          * pg_catalog
7037                          */
7038                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
7039                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
7040                         appendPQExpBuffer(delq, "%s ",
7041                                                           fmtId(tbinfo->dobj.name));
7042                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7043                                                           fmtId(coninfo->dobj.name));
7044
7045                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7046                                                  coninfo->dobj.name,
7047                                                  tbinfo->dobj.namespace->dobj.name,
7048                                                  tbinfo->usename, false,
7049                                                  "CHECK CONSTRAINT", q->data, delq->data, NULL,
7050                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7051                                                  NULL, NULL);
7052                 }
7053         }
7054         else if (coninfo->contype == 'c' && tbinfo == NULL)
7055         {
7056                 /* CHECK constraint on a domain */
7057                 TypeInfo   *tinfo = coninfo->condomain;
7058
7059                 /* Ignore if not to be dumped separately, or if not dumping domain */
7060                 if (coninfo->separate && tinfo->dobj.namespace->dump)
7061                 {
7062                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
7063                                                           fmtId(tinfo->dobj.name));
7064                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
7065                                                           fmtId(coninfo->dobj.name),
7066                                                           coninfo->condef);
7067
7068                         /*
7069                          * DROP must be fully qualified in case same name appears in
7070                          * pg_catalog
7071                          */
7072                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
7073                                                           fmtId(tinfo->dobj.namespace->dobj.name));
7074                         appendPQExpBuffer(delq, "%s ",
7075                                                           fmtId(tinfo->dobj.name));
7076                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
7077                                                           fmtId(coninfo->dobj.name));
7078
7079                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
7080                                                  coninfo->dobj.name,
7081                                                  tinfo->dobj.namespace->dobj.name,
7082                                                  tinfo->usename, false,
7083                                                  "CHECK CONSTRAINT", q->data, delq->data, NULL,
7084                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
7085                                                  NULL, NULL);
7086                 }
7087         }
7088         else
7089         {
7090                 write_msg(NULL, "unexpected constraint type\n");
7091                 exit_nicely();
7092         }
7093
7094         /* Dump Constraint Comments --- only works for table constraints */
7095         if (tbinfo)
7096         {
7097                 resetPQExpBuffer(q);
7098                 appendPQExpBuffer(q, "CONSTRAINT %s ",
7099                                                   fmtId(coninfo->dobj.name));
7100                 appendPQExpBuffer(q, "ON %s",
7101                                                   fmtId(tbinfo->dobj.name));
7102                 dumpComment(fout, q->data,
7103                                         tbinfo->dobj.namespace->dobj.name,
7104                                         tbinfo->usename,
7105                                         coninfo->dobj.catId, 0, coninfo->dobj.dumpId);
7106         }
7107
7108         destroyPQExpBuffer(q);
7109         destroyPQExpBuffer(delq);
7110 }
7111
7112 /*
7113  * setMaxOid -
7114  * find the maximum oid and generate a COPY statement to set it
7115 */
7116
7117 static void
7118 setMaxOid(Archive *fout)
7119 {
7120         PGresult   *res;
7121         Oid                     max_oid;
7122         char            sql[1024];
7123
7124         do_sql_command(g_conn,
7125                                    "CREATE TEMPORARY TABLE pgdump_oid (dummy integer)");
7126         res = PQexec(g_conn, "INSERT INTO pgdump_oid VALUES (0)");
7127         check_sql_result(res, g_conn, "INSERT INTO pgdump_oid VALUES (0)",
7128                                          PGRES_COMMAND_OK);
7129         max_oid = PQoidValue(res);
7130         if (max_oid == 0)
7131         {
7132                 write_msg(NULL, "inserted invalid OID\n");
7133                 exit_nicely();
7134         }
7135         PQclear(res);
7136         do_sql_command(g_conn, "DROP TABLE pgdump_oid;");
7137         if (g_verbose)
7138                 write_msg(NULL, "maximum system OID is %u\n", max_oid);
7139         snprintf(sql, sizeof(sql),
7140                          "CREATE TEMPORARY TABLE pgdump_oid (dummy integer);\n"
7141                          "COPY pgdump_oid WITH OIDS FROM stdin;\n"
7142                          "%u\t0\n"
7143                          "\\.\n"
7144                          "DROP TABLE pgdump_oid;\n",
7145                          max_oid);
7146
7147         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7148                                  "Max OID", NULL, "",
7149                                  false, "<Init>", sql, "", NULL,
7150                                  NULL, 0,
7151                                  NULL, NULL);
7152 }
7153
7154 /*
7155  * findLastBuiltInOid -
7156  * find the last built in oid
7157  *
7158  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
7159  * pg_database entry for the current database
7160  */
7161 static Oid
7162 findLastBuiltinOid_V71(const char *dbname)
7163 {
7164         PGresult   *res;
7165         int                     ntups;
7166         Oid                     last_oid;
7167         PQExpBuffer query = createPQExpBuffer();
7168
7169         resetPQExpBuffer(query);
7170         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
7171         appendStringLiteral(query, dbname, true);
7172
7173         res = PQexec(g_conn, query->data);
7174         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7175
7176         ntups = PQntuples(res);
7177         if (ntups < 1)
7178         {
7179                 write_msg(NULL, "missing pg_database entry for this database\n");
7180                 exit_nicely();
7181         }
7182         if (ntups > 1)
7183         {
7184                 write_msg(NULL, "found more than one pg_database entry for this database\n");
7185                 exit_nicely();
7186         }
7187         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
7188         PQclear(res);
7189         destroyPQExpBuffer(query);
7190         return last_oid;
7191 }
7192
7193 /*
7194  * findLastBuiltInOid -
7195  * find the last built in oid
7196  *
7197  * For 7.0, we do this by assuming that the last thing that initdb does is to
7198  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
7199  * initdb won't be changing anymore, it'll do.
7200  */
7201 static Oid
7202 findLastBuiltinOid_V70(void)
7203 {
7204         PGresult   *res;
7205         int                     ntups;
7206         int                     last_oid;
7207
7208         res = PQexec(g_conn,
7209                                  "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
7210         check_sql_result(res, g_conn,
7211                                  "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
7212                                          PGRES_TUPLES_OK);
7213         ntups = PQntuples(res);
7214         if (ntups < 1)
7215         {
7216                 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
7217                 exit_nicely();
7218         }
7219         if (ntups > 1)
7220         {
7221                 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
7222                 exit_nicely();
7223         }
7224         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
7225         PQclear(res);
7226         return last_oid;
7227 }
7228
7229 static void
7230 dumpSequence(Archive *fout, TableInfo *tbinfo)
7231 {
7232         PGresult   *res;
7233         char       *last,
7234                            *incby,
7235                            *maxv = NULL,
7236                            *minv = NULL,
7237                            *cache;
7238         char            bufm[100],
7239                                 bufx[100];
7240         bool            cycled,
7241                                 called;
7242         PQExpBuffer query = createPQExpBuffer();
7243         PQExpBuffer delqry = createPQExpBuffer();
7244
7245         /* Make sure we are in proper schema */
7246         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7247
7248         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
7249         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
7250
7251         appendPQExpBuffer(query,
7252                                           "SELECT sequence_name, last_value, increment_by, "
7253                            "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
7254                            "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
7255                                           "     ELSE max_value "
7256                                           "END AS max_value, "
7257                                 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
7258                            "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
7259                                           "     ELSE min_value "
7260                                           "END AS min_value, "
7261                                           "cache_value, is_cycled, is_called from %s",
7262                                           bufx, bufm,
7263                                           fmtId(tbinfo->dobj.name));
7264
7265         res = PQexec(g_conn, query->data);
7266         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7267
7268         if (PQntuples(res) != 1)
7269         {
7270                 write_msg(NULL, "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
7271                                   tbinfo->dobj.name, PQntuples(res));
7272                 exit_nicely();
7273         }
7274
7275         /* Disable this check: it fails if sequence has been renamed */
7276 #ifdef NOT_USED
7277         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
7278         {
7279                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
7280                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
7281                 exit_nicely();
7282         }
7283 #endif
7284
7285         last = PQgetvalue(res, 0, 1);
7286         incby = PQgetvalue(res, 0, 2);
7287         if (!PQgetisnull(res, 0, 3))
7288                 maxv = PQgetvalue(res, 0, 3);
7289         if (!PQgetisnull(res, 0, 4))
7290                 minv = PQgetvalue(res, 0, 4);
7291         cache = PQgetvalue(res, 0, 5);
7292         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
7293         called = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
7294
7295         /*
7296          * The logic we use for restoring sequences is as follows:
7297          *
7298          * Add a basic CREATE SEQUENCE statement (use last_val for start if
7299          * called is false, else use min_val for start_val).  Skip this if the
7300          * sequence came from a SERIAL column.
7301          *
7302          * Add a 'SETVAL(seq, last_val, iscalled)' at restore-time iff we load
7303          * data.  We do this for serial sequences too.
7304          */
7305
7306         if (!dataOnly && !OidIsValid(tbinfo->owning_tab))
7307         {
7308                 resetPQExpBuffer(delqry);
7309
7310                 /*
7311                  * DROP must be fully qualified in case same name appears in
7312                  * pg_catalog
7313                  */
7314                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
7315                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
7316                 appendPQExpBuffer(delqry, "%s;\n",
7317                                                   fmtId(tbinfo->dobj.name));
7318
7319                 resetPQExpBuffer(query);
7320                 appendPQExpBuffer(query,
7321                                                   "CREATE SEQUENCE %s\n",
7322                                                   fmtId(tbinfo->dobj.name));
7323
7324                 if (!called)
7325                         appendPQExpBuffer(query, "    START WITH %s\n", last);
7326
7327                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
7328
7329                 if (maxv)
7330                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
7331                 else
7332                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
7333
7334                 if (minv)
7335                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
7336                 else
7337                         appendPQExpBuffer(query, "    NO MINVALUE\n");
7338
7339                 appendPQExpBuffer(query,
7340                                                   "    CACHE %s%s",
7341                                                   cache, (cycled ? "\n    CYCLE" : ""));
7342
7343                 appendPQExpBuffer(query, ";\n");
7344
7345                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
7346                                          tbinfo->dobj.name,
7347                                          tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7348                                          false, "SEQUENCE", query->data, delqry->data, NULL,
7349                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
7350                                          NULL, NULL);
7351         }
7352
7353         if (!schemaOnly)
7354         {
7355                 TableInfo  *owning_tab;
7356
7357                 resetPQExpBuffer(query);
7358                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
7359
7360                 /*
7361                  * If this is a SERIAL sequence, then use the
7362                  * pg_get_serial_sequence function to avoid hard-coding the
7363                  * sequence name.  Note that this implicitly assumes that the
7364                  * sequence and its owning table are in the same schema, because
7365                  * we don't schema-qualify the reference.
7366                  */
7367                 if (OidIsValid(tbinfo->owning_tab) &&
7368                         (owning_tab = findTableByOid(tbinfo->owning_tab)) != NULL)
7369                 {
7370                         appendPQExpBuffer(query, "pg_catalog.pg_get_serial_sequence(");
7371                         appendStringLiteral(query, fmtId(owning_tab->dobj.name), true);
7372                         appendPQExpBuffer(query, ", ");
7373                         appendStringLiteral(query, owning_tab->attnames[tbinfo->owning_col - 1], true);
7374                         appendPQExpBuffer(query, ")");
7375                 }
7376                 else
7377                         appendStringLiteral(query, fmtId(tbinfo->dobj.name), true);
7378                 appendPQExpBuffer(query, ", %s, %s);\n",
7379                                                   last, (called ? "true" : "false"));
7380
7381                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7382                                          tbinfo->dobj.name,
7383                                          tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7384                                          false, "SEQUENCE SET", query->data, "", NULL,
7385                                          &(tbinfo->dobj.dumpId), 1,
7386                                          NULL, NULL);
7387         }
7388
7389         if (!dataOnly)
7390         {
7391                 /* Dump Sequence Comments */
7392                 resetPQExpBuffer(query);
7393                 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
7394                 dumpComment(fout, query->data,
7395                                         tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7396                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
7397         }
7398
7399         PQclear(res);
7400
7401         destroyPQExpBuffer(query);
7402         destroyPQExpBuffer(delqry);
7403 }
7404
7405 static void
7406 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
7407 {
7408         TableInfo  *tbinfo = tginfo->tgtable;
7409         PQExpBuffer query;
7410         PQExpBuffer delqry;
7411         const char *p;
7412         int                     findx;
7413
7414         if (dataOnly)
7415                 return;
7416
7417         query = createPQExpBuffer();
7418         delqry = createPQExpBuffer();
7419
7420         /*
7421          * DROP must be fully qualified in case same name appears in
7422          * pg_catalog
7423          */
7424         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
7425                                           fmtId(tginfo->dobj.name));
7426         appendPQExpBuffer(delqry, "ON %s.",
7427                                           fmtId(tbinfo->dobj.namespace->dobj.name));
7428         appendPQExpBuffer(delqry, "%s;\n",
7429                                           fmtId(tbinfo->dobj.name));
7430
7431         if (tginfo->tgisconstraint)
7432         {
7433                 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
7434                 appendPQExpBuffer(query, fmtId(tginfo->tgconstrname));
7435         }
7436         else
7437         {
7438                 appendPQExpBuffer(query, "CREATE TRIGGER ");
7439                 appendPQExpBuffer(query, fmtId(tginfo->dobj.name));
7440         }
7441         appendPQExpBuffer(query, "\n    ");
7442
7443         /* Trigger type */
7444         findx = 0;
7445         if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
7446                 appendPQExpBuffer(query, "BEFORE");
7447         else
7448                 appendPQExpBuffer(query, "AFTER");
7449         if (TRIGGER_FOR_INSERT(tginfo->tgtype))
7450         {
7451                 appendPQExpBuffer(query, " INSERT");
7452                 findx++;
7453         }
7454         if (TRIGGER_FOR_DELETE(tginfo->tgtype))
7455         {
7456                 if (findx > 0)
7457                         appendPQExpBuffer(query, " OR DELETE");
7458                 else
7459                         appendPQExpBuffer(query, " DELETE");
7460                 findx++;
7461         }
7462         if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
7463         {
7464                 if (findx > 0)
7465                         appendPQExpBuffer(query, " OR UPDATE");
7466                 else
7467                         appendPQExpBuffer(query, " UPDATE");
7468         }
7469         appendPQExpBuffer(query, " ON %s\n",
7470                                           fmtId(tbinfo->dobj.name));
7471
7472         if (tginfo->tgisconstraint)
7473         {
7474                 if (OidIsValid(tginfo->tgconstrrelid))
7475                 {
7476                         /* If we are using regclass, name is already quoted */
7477                         if (g_fout->remoteVersion >= 70300)
7478                                 appendPQExpBuffer(query, "    FROM %s\n    ",
7479                                                                   tginfo->tgconstrrelname);
7480                         else
7481                                 appendPQExpBuffer(query, "    FROM %s\n    ",
7482                                                                   fmtId(tginfo->tgconstrrelname));
7483                 }
7484                 if (!tginfo->tgdeferrable)
7485                         appendPQExpBuffer(query, "NOT ");
7486                 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
7487                 if (tginfo->tginitdeferred)
7488                         appendPQExpBuffer(query, "DEFERRED\n");
7489                 else
7490                         appendPQExpBuffer(query, "IMMEDIATE\n");
7491         }
7492
7493         if (TRIGGER_FOR_ROW(tginfo->tgtype))
7494                 appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
7495         else
7496                 appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
7497
7498         /* In 7.3, result of regproc is already quoted */
7499         if (g_fout->remoteVersion >= 70300)
7500                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7501                                                   tginfo->tgfname);
7502         else
7503                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
7504                                                   fmtId(tginfo->tgfname));
7505
7506         p = tginfo->tgargs;
7507         for (findx = 0; findx < tginfo->tgnargs; findx++)
7508         {
7509                 const char *s = p;
7510
7511                 for (;;)
7512                 {
7513                         p = strchr(p, '\\');
7514                         if (p == NULL)
7515                         {
7516                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
7517                                                   tginfo->tgargs,
7518                                                   tginfo->dobj.name,
7519                                                   tbinfo->dobj.name);
7520                                 exit_nicely();
7521                         }
7522                         p++;
7523                         if (*p == '\\')
7524                         {
7525                                 p++;
7526                                 continue;
7527                         }
7528                         if (p[0] == '0' && p[1] == '0' && p[2] == '0')
7529                                 break;
7530                 }
7531                 p--;
7532                 appendPQExpBufferChar(query, '\'');
7533                 while (s < p)
7534                 {
7535                         if (*s == '\'')
7536                                 appendPQExpBufferChar(query, '\\');
7537                         appendPQExpBufferChar(query, *s++);
7538                 }
7539                 appendPQExpBufferChar(query, '\'');
7540                 appendPQExpBuffer(query,
7541                                                   (findx < tginfo->tgnargs - 1) ? ", " : "");
7542                 p = p + 4;
7543         }
7544         appendPQExpBuffer(query, ");\n");
7545
7546         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
7547                                  tginfo->dobj.name,
7548                                  tbinfo->dobj.namespace->dobj.name,
7549                                  tbinfo->usename, false,
7550                                  "TRIGGER", query->data, delqry->data, NULL,
7551                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
7552                                  NULL, NULL);
7553
7554         resetPQExpBuffer(query);
7555         appendPQExpBuffer(query, "TRIGGER %s ",
7556                                           fmtId(tginfo->dobj.name));
7557         appendPQExpBuffer(query, "ON %s",
7558                                           fmtId(tbinfo->dobj.name));
7559
7560         dumpComment(fout, query->data,
7561                                 tbinfo->dobj.namespace->dobj.name, tbinfo->usename,
7562                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
7563
7564         destroyPQExpBuffer(query);
7565         destroyPQExpBuffer(delqry);
7566 }
7567
7568 /*
7569  * dumpRule
7570  *              Dump a rule
7571  */
7572 static void
7573 dumpRule(Archive *fout, RuleInfo *rinfo)
7574 {
7575         TableInfo  *tbinfo = rinfo->ruletable;
7576         PQExpBuffer query;
7577         PQExpBuffer cmd;
7578         PQExpBuffer delcmd;
7579         PGresult   *res;
7580
7581         /*
7582          * Ignore rules for not-to-be-dumped tables
7583          */
7584         if (tbinfo == NULL || !tbinfo->dump || dataOnly)
7585                 return;
7586
7587         /*
7588          * If it is an ON SELECT rule, we do not need to dump it because it
7589          * will be handled via CREATE VIEW for the table.
7590          */
7591         if (rinfo->ev_type == '1' && rinfo->is_instead)
7592                 return;
7593
7594         /*
7595          * Make sure we are in proper schema.
7596          */
7597         selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
7598
7599         query = createPQExpBuffer();
7600         cmd = createPQExpBuffer();
7601         delcmd = createPQExpBuffer();
7602
7603         if (g_fout->remoteVersion >= 70300)
7604         {
7605                 appendPQExpBuffer(query,
7606                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
7607                                                   rinfo->dobj.catId.oid);
7608         }
7609         else
7610         {
7611                 /* Rule name was unique before 7.3 ... */
7612                 appendPQExpBuffer(query,
7613                                                   "SELECT pg_get_ruledef('%s') AS definition",
7614                                                   rinfo->dobj.name);
7615         }
7616
7617         res = PQexec(g_conn, query->data);
7618         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7619
7620         if (PQntuples(res) != 1)
7621         {
7622                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
7623                                   rinfo->dobj.name, tbinfo->dobj.name);
7624                 exit_nicely();
7625         }
7626
7627         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
7628
7629         /*
7630          * DROP must be fully qualified in case same name appears in
7631          * pg_catalog
7632          */
7633         appendPQExpBuffer(delcmd, "DROP RULE %s ",
7634                                           fmtId(rinfo->dobj.name));
7635         appendPQExpBuffer(delcmd, "ON %s.",
7636                                           fmtId(tbinfo->dobj.namespace->dobj.name));
7637         appendPQExpBuffer(delcmd, "%s;\n",
7638                                           fmtId(tbinfo->dobj.name));
7639
7640         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
7641                                  rinfo->dobj.name,
7642                                  tbinfo->dobj.namespace->dobj.name,
7643                                  tbinfo->usename, false,
7644                                  "RULE", cmd->data, delcmd->data, NULL,
7645                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
7646                                  NULL, NULL);
7647
7648         /* Dump rule comments */
7649         resetPQExpBuffer(query);
7650         appendPQExpBuffer(query, "RULE %s",
7651                                           fmtId(rinfo->dobj.name));
7652         appendPQExpBuffer(query, " ON %s",
7653                                           fmtId(tbinfo->dobj.name));
7654         dumpComment(fout, query->data,
7655                                 tbinfo->dobj.namespace->dobj.name,
7656                                 tbinfo->usename,
7657                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
7658
7659         PQclear(res);
7660
7661         destroyPQExpBuffer(query);
7662         destroyPQExpBuffer(cmd);
7663         destroyPQExpBuffer(delcmd);
7664 }
7665
7666 /*
7667  * getDependencies --- obtain available dependency data
7668  */
7669 static void
7670 getDependencies(void)
7671 {
7672         PQExpBuffer query;
7673         PGresult   *res;
7674         int                     ntups,
7675                                 i;
7676         int                     i_classid,
7677                                 i_objid,
7678                                 i_refclassid,
7679                                 i_refobjid,
7680                                 i_deptype;
7681         DumpableObject *dobj,
7682                            *refdobj;
7683
7684         /* No dependency info available before 7.3 */
7685         if (g_fout->remoteVersion < 70300)
7686                 return;
7687
7688         if (g_verbose)
7689                 write_msg(NULL, "fetching dependency data\n");
7690
7691         /* Make sure we are in proper schema */
7692         selectSourceSchema("pg_catalog");
7693
7694         query = createPQExpBuffer();
7695
7696         appendPQExpBuffer(query, "SELECT "
7697                                           "classid, objid, refclassid, refobjid, deptype "
7698                                           "FROM pg_depend "
7699                                           "WHERE deptype != 'p' "
7700                                           "ORDER BY 1,2");
7701
7702         res = PQexec(g_conn, query->data);
7703         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7704
7705         ntups = PQntuples(res);
7706
7707         i_classid = PQfnumber(res, "classid");
7708         i_objid = PQfnumber(res, "objid");
7709         i_refclassid = PQfnumber(res, "refclassid");
7710         i_refobjid = PQfnumber(res, "refobjid");
7711         i_deptype = PQfnumber(res, "deptype");
7712
7713         /*
7714          * Since we ordered the SELECT by referencing ID, we can expect that
7715          * multiple entries for the same object will appear together; this
7716          * saves on searches.
7717          */
7718         dobj = NULL;
7719
7720         for (i = 0; i < ntups; i++)
7721         {
7722                 CatalogId       objId;
7723                 CatalogId       refobjId;
7724                 char            deptype;
7725
7726                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
7727                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
7728                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
7729                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
7730                 deptype = *(PQgetvalue(res, i, i_deptype));
7731
7732                 if (dobj == NULL ||
7733                         dobj->catId.tableoid != objId.tableoid ||
7734                         dobj->catId.oid != objId.oid)
7735                         dobj = findObjectByCatalogId(objId);
7736
7737                 /*
7738                  * Failure to find objects mentioned in pg_depend is not
7739                  * unexpected, since for example we don't collect info about TOAST
7740                  * tables.
7741                  */
7742                 if (dobj == NULL)
7743                 {
7744 #ifdef NOT_USED
7745                         fprintf(stderr, "no referencing object %u %u\n",
7746                                         objId.tableoid, objId.oid);
7747 #endif
7748                         continue;
7749                 }
7750
7751                 refdobj = findObjectByCatalogId(refobjId);
7752
7753                 if (refdobj == NULL)
7754                 {
7755 #ifdef NOT_USED
7756                         fprintf(stderr, "no referenced object %u %u\n",
7757                                         refobjId.tableoid, refobjId.oid);
7758 #endif
7759                         continue;
7760                 }
7761
7762                 addObjectDependency(dobj, refdobj->dumpId);
7763         }
7764
7765         PQclear(res);
7766
7767         destroyPQExpBuffer(query);
7768 }
7769
7770
7771 /*
7772  * selectSourceSchema - make the specified schema the active search path
7773  * in the source database.
7774  *
7775  * NB: pg_catalog is explicitly searched after the specified schema;
7776  * so user names are only qualified if they are cross-schema references,
7777  * and system names are only qualified if they conflict with a user name
7778  * in the current schema.
7779  *
7780  * Whenever the selected schema is not pg_catalog, be careful to qualify
7781  * references to system catalogs and types in our emitted commands!
7782  */
7783 static void
7784 selectSourceSchema(const char *schemaName)
7785 {
7786         static char *curSchemaName = NULL;
7787         PQExpBuffer query;
7788
7789         /* Not relevant if fetching from pre-7.3 DB */
7790         if (g_fout->remoteVersion < 70300)
7791                 return;
7792         /* Ignore null schema names */
7793         if (schemaName == NULL || *schemaName == '\0')
7794                 return;
7795         /* Optimize away repeated selection of same schema */
7796         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
7797                 return;
7798
7799         query = createPQExpBuffer();
7800         appendPQExpBuffer(query, "SET search_path = %s",
7801                                           fmtId(schemaName));
7802         if (strcmp(schemaName, "pg_catalog") != 0)
7803                 appendPQExpBuffer(query, ", pg_catalog");
7804
7805         do_sql_command(g_conn, query->data);
7806
7807         destroyPQExpBuffer(query);
7808         if (curSchemaName)
7809                 free(curSchemaName);
7810         curSchemaName = strdup(schemaName);
7811 }
7812
7813 /*
7814  * getFormattedTypeName - retrieve a nicely-formatted type name for the
7815  * given type name.
7816  *
7817  * NB: in 7.3 and up the result may depend on the currently-selected
7818  * schema; this is why we don't try to cache the names.
7819  */
7820 static char *
7821 getFormattedTypeName(Oid oid, OidOptions opts)
7822 {
7823         char       *result;
7824         PQExpBuffer query;
7825         PGresult   *res;
7826         int                     ntups;
7827
7828         if (oid == 0)
7829         {
7830                 if ((opts & zeroAsOpaque) != 0)
7831                         return strdup(g_opaque_type);
7832                 else if ((opts & zeroAsAny) != 0)
7833                         return strdup("'any'");
7834                 else if ((opts & zeroAsStar) != 0)
7835                         return strdup("*");
7836                 else if ((opts & zeroAsNone) != 0)
7837                         return strdup("NONE");
7838         }
7839
7840         query = createPQExpBuffer();
7841         if (g_fout->remoteVersion >= 70300)
7842         {
7843                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
7844                                                   oid);
7845         }
7846         else if (g_fout->remoteVersion >= 70100)
7847         {
7848                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
7849                                                   oid);
7850         }
7851         else
7852         {
7853                 appendPQExpBuffer(query, "SELECT typname "
7854                                                   "FROM pg_type "
7855                                                   "WHERE oid = '%u'::oid",
7856                                                   oid);
7857         }
7858
7859         res = PQexec(g_conn, query->data);
7860         check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7861
7862         /* Expecting a single result only */
7863         ntups = PQntuples(res);
7864         if (ntups != 1)
7865         {
7866                 write_msg(NULL, "query yielded %d rows instead of one: %s\n",
7867                                   ntups, query->data);
7868                 exit_nicely();
7869         }
7870
7871         if (g_fout->remoteVersion >= 70100)
7872         {
7873                 /* already quoted */
7874                 result = strdup(PQgetvalue(res, 0, 0));
7875         }
7876         else
7877         {
7878                 /* may need to quote it */
7879                 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
7880         }
7881
7882         PQclear(res);
7883         destroyPQExpBuffer(query);
7884
7885         return result;
7886 }
7887
7888 /*
7889  * myFormatType --- local implementation of format_type for use with 7.0.
7890  */
7891 static char *
7892 myFormatType(const char *typname, int32 typmod)
7893 {
7894         char       *result;
7895         bool            isarray = false;
7896         PQExpBuffer buf = createPQExpBuffer();
7897
7898         /* Handle array types */
7899         if (typname[0] == '_')
7900         {
7901                 isarray = true;
7902                 typname++;
7903         }
7904
7905         /* Show lengths on bpchar and varchar */
7906         if (!strcmp(typname, "bpchar"))
7907         {
7908                 int                     len = (typmod - VARHDRSZ);
7909
7910                 appendPQExpBuffer(buf, "character");
7911                 if (len > 1)
7912                         appendPQExpBuffer(buf, "(%d)",
7913                                                           typmod - VARHDRSZ);
7914         }
7915         else if (!strcmp(typname, "varchar"))
7916         {
7917                 appendPQExpBuffer(buf, "character varying");
7918                 if (typmod != -1)
7919                         appendPQExpBuffer(buf, "(%d)",
7920                                                           typmod - VARHDRSZ);
7921         }
7922         else if (!strcmp(typname, "numeric"))
7923         {
7924                 appendPQExpBuffer(buf, "numeric");
7925                 if (typmod != -1)
7926                 {
7927                         int32           tmp_typmod;
7928                         int                     precision;
7929                         int                     scale;
7930
7931                         tmp_typmod = typmod - VARHDRSZ;
7932                         precision = (tmp_typmod >> 16) & 0xffff;
7933                         scale = tmp_typmod & 0xffff;
7934                         appendPQExpBuffer(buf, "(%d,%d)",
7935                                                           precision, scale);
7936                 }
7937         }
7938
7939         /*
7940          * char is an internal single-byte data type; Let's make sure we force
7941          * it through with quotes. - thomas 1998-12-13
7942          */
7943         else if (strcmp(typname, "char") == 0)
7944                 appendPQExpBuffer(buf, "\"char\"");
7945         else
7946                 appendPQExpBuffer(buf, "%s", fmtId(typname));
7947
7948         /* Append array qualifier for array types */
7949         if (isarray)
7950                 appendPQExpBuffer(buf, "[]");
7951
7952         result = strdup(buf->data);
7953         destroyPQExpBuffer(buf);
7954
7955         return result;
7956 }
7957
7958 /*
7959  * fmtQualifiedId - convert a qualified name to the proper format for
7960  * the source database.
7961  *
7962  * Like fmtId, use the result before calling again.
7963  */
7964 static const char *
7965 fmtQualifiedId(const char *schema, const char *id)
7966 {
7967         static PQExpBuffer id_return = NULL;
7968
7969         if (id_return)                          /* first time through? */
7970                 resetPQExpBuffer(id_return);
7971         else
7972                 id_return = createPQExpBuffer();
7973
7974         /* Suppress schema name if fetching from pre-7.3 DB */
7975         if (g_fout->remoteVersion >= 70300 && schema && *schema)
7976         {
7977                 appendPQExpBuffer(id_return, "%s.",
7978                                                   fmtId(schema));
7979         }
7980         appendPQExpBuffer(id_return, "%s",
7981                                           fmtId(id));
7982
7983         return id_return->data;
7984 }
7985
7986 /*
7987  * Return a column list clause for the given relation.
7988  *
7989  * Special case: if there are no undropped columns in the relation, return
7990  * "", not an invalid "()" column list.
7991  */
7992 static const char *
7993 fmtCopyColumnList(const TableInfo *ti)
7994 {
7995         static PQExpBuffer q = NULL;
7996         int                     numatts = ti->numatts;
7997         char      **attnames = ti->attnames;
7998         bool       *attisdropped = ti->attisdropped;
7999         bool            needComma;
8000         int                     i;
8001
8002         if (q)                                          /* first time through? */
8003                 resetPQExpBuffer(q);
8004         else
8005                 q = createPQExpBuffer();
8006
8007         appendPQExpBuffer(q, "(");
8008         needComma = false;
8009         for (i = 0; i < numatts; i++)
8010         {
8011                 if (attisdropped[i])
8012                         continue;
8013                 if (needComma)
8014                         appendPQExpBuffer(q, ", ");
8015                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
8016                 needComma = true;
8017         }
8018
8019         if (!needComma)
8020                 return "";                              /* no undropped columns */
8021
8022         appendPQExpBuffer(q, ")");
8023         return q->data;
8024 }
8025
8026 /*
8027  * Convenience subroutine to execute a SQL command and check for
8028  * COMMAND_OK status.
8029  */
8030 static void
8031 do_sql_command(PGconn *conn, const char *query)
8032 {
8033         PGresult   *res;
8034
8035         res = PQexec(conn, query);
8036         check_sql_result(res, conn, query, PGRES_COMMAND_OK);
8037         PQclear(res);
8038 }
8039
8040 /*
8041  * Convenience subroutine to verify a SQL command succeeded,
8042  * and exit with a useful error message if not.
8043  */
8044 static void
8045 check_sql_result(PGresult *res, PGconn *conn, const char *query,
8046                                  ExecStatusType expected)
8047 {
8048         const char *err;
8049
8050         if (res && PQresultStatus(res) == expected)
8051                 return;                                 /* A-OK */
8052
8053         write_msg(NULL, "SQL command failed\n");
8054         if (res)
8055                 err = PQresultErrorMessage(res);
8056         else
8057                 err = PQerrorMessage(conn);
8058         write_msg(NULL, "Error message from server: %s", err);
8059         write_msg(NULL, "The command was: %s\n", query);
8060         exit_nicely();
8061 }