1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
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
14 * Note that pg_dump runs in a serializable transaction, so it sees a
15 * consistent snapshot of the database including system catalogs.
16 * However, it relies in part on various specialized backend functions
17 * like pg_get_indexdef(), and those things tend to run on SnapshotNow
18 * time, ie they look at the currently committed state. So it is
19 * possible to get 'cache lookup failed' error if someone performs DDL
20 * changes while a dump is happening. The window for this sort of thing
21 * is from the beginning of the serializable transaction to
22 * getSchemaData() (when pg_dump acquires AccessShareLock on every
23 * table it intends to dump). It isn't very large, but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * $PostgreSQL: pgsql/src/bin/pg_dump/pg_dump.c,v 1.584 2010/08/03 19:24:04 tgl Exp $
30 *-------------------------------------------------------------------------
33 #include "postgres_fe.h"
44 #include "getopt_long.h"
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "catalog/pg_cast.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_default_acl.h"
51 #include "catalog/pg_largeobject.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_trigger.h"
54 #include "catalog/pg_type.h"
55 #include "libpq/libpq-fs.h"
57 #include "pg_backup_archiver.h"
58 #include "dumputils.h"
67 const char *descr; /* comment for an object */
68 Oid classoid; /* object class (catalog OID) */
69 Oid objoid; /* object OID */
70 int objsubid; /* subobject (table column #) */
75 bool g_verbose; /* User wants verbose narration of our
77 Archive *g_fout; /* the script file */
78 PGconn *g_conn; /* the database connection */
80 /* various user-settable parameters */
84 const char *lockWaitTimeout;
86 /* subquery used to convert user ID (eg, datdba) to user name */
87 static const char *username_subquery;
89 /* obsolete as of 7.3: */
90 static Oid g_last_builtin_oid; /* value of the last builtin oid */
93 * Object inclusion/exclusion lists
95 * The string lists record the patterns given by command-line switches,
96 * which we then convert to lists of OIDs of matching objects.
98 static SimpleStringList schema_include_patterns = {NULL, NULL};
99 static SimpleOidList schema_include_oids = {NULL, NULL};
100 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
101 static SimpleOidList schema_exclude_oids = {NULL, NULL};
103 static SimpleStringList table_include_patterns = {NULL, NULL};
104 static SimpleOidList table_include_oids = {NULL, NULL};
105 static SimpleStringList table_exclude_patterns = {NULL, NULL};
106 static SimpleOidList table_exclude_oids = {NULL, NULL};
108 /* default, if no "inclusion" switches appear, is to dump everything */
109 static bool include_everything = true;
111 char g_opaque_type[10]; /* name for the opaque type */
113 /* placeholders for the delimiters for comments */
114 char g_comment_start[10];
115 char g_comment_end[10];
117 static const CatalogId nilCatalogId = {0, 0};
119 /* these are to avoid passing around info for findNamespace() */
120 static NamespaceInfo *g_namespaces;
121 static int g_numNamespaces;
123 /* flags for various command-line long options */
124 static int binary_upgrade = 0;
125 static int disable_dollar_quoting = 0;
126 static int dump_inserts = 0;
127 static int column_inserts = 0;
130 static void help(const char *progname);
131 static void expand_schema_name_patterns(SimpleStringList *patterns,
132 SimpleOidList *oids);
133 static void expand_table_name_patterns(SimpleStringList *patterns,
134 SimpleOidList *oids);
135 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
136 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
137 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
138 static void dumpComment(Archive *fout, const char *target,
139 const char *namespace, const char *owner,
140 CatalogId catalogId, int subid, DumpId dumpId);
141 static int findComments(Archive *fout, Oid classoid, Oid objoid,
142 CommentItem **items);
143 static int collectComments(Archive *fout, CommentItem **items);
144 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
145 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
146 static void dumpType(Archive *fout, TypeInfo *tyinfo);
147 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
148 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
149 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
150 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
151 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
152 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
153 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
154 static void dumpFunc(Archive *fout, FuncInfo *finfo);
155 static void dumpCast(Archive *fout, CastInfo *cast);
156 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
157 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
158 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
159 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
160 static void dumpRule(Archive *fout, RuleInfo *rinfo);
161 static void dumpAgg(Archive *fout, AggInfo *agginfo);
162 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
163 static void dumpTable(Archive *fout, TableInfo *tbinfo);
164 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
165 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
166 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
167 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
168 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
169 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
170 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
171 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
172 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
173 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
174 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
175 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
176 static void dumpUserMappings(Archive *fout,
177 const char *servername, const char *namespace,
178 const char *owner, CatalogId catalogId, DumpId dumpId);
179 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
181 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
182 const char *type, const char *name, const char *subname,
183 const char *tag, const char *nspname, const char *owner,
186 static void getDependencies(void);
187 static void getDomainConstraints(TypeInfo *tyinfo);
188 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
189 static void getTableDataFKConstraints(void);
190 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
191 static char *format_function_arguments_old(FuncInfo *finfo, int nallargs,
195 static char *format_function_signature(FuncInfo *finfo, bool honor_quotes);
196 static const char *convertRegProcReference(const char *proc);
197 static const char *convertOperatorReference(const char *opr);
198 static const char *convertTSFunction(Oid funcOid);
199 static Oid findLastBuiltinOid_V71(const char *);
200 static Oid findLastBuiltinOid_V70(void);
201 static void selectSourceSchema(const char *schemaName);
202 static char *getFormattedTypeName(Oid oid, OidOptions opts);
203 static char *myFormatType(const char *typname, int32 typmod);
204 static const char *fmtQualifiedId(const char *schema, const char *id);
205 static void getBlobs(Archive *AH);
206 static void dumpBlob(Archive *AH, BlobInfo *binfo);
207 static int dumpBlobs(Archive *AH, void *arg);
208 static void dumpDatabase(Archive *AH);
209 static void dumpEncoding(Archive *AH);
210 static void dumpStdStrings(Archive *AH);
211 static void binary_upgrade_set_type_oids_by_type_oid(
212 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
213 static bool binary_upgrade_set_type_oids_by_rel_oid(
214 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
215 static void binary_upgrade_set_relfilenodes(PQExpBuffer upgrade_buffer,
216 Oid pg_class_oid, bool is_index);
217 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
218 static const char *fmtCopyColumnList(const TableInfo *ti);
219 static void do_sql_command(PGconn *conn, const char *query);
220 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
221 ExecStatusType expected);
225 main(int argc, char **argv)
228 const char *filename = NULL;
229 const char *format = "p";
230 const char *dbname = NULL;
231 const char *pghost = NULL;
232 const char *pgport = NULL;
233 const char *username = NULL;
234 const char *dumpencoding = NULL;
235 const char *std_strings;
239 DumpableObject **dobjs;
242 enum trivalue prompt_password = TRI_DEFAULT;
243 int compressLevel = -1;
246 int outputCreateDB = 0;
247 bool outputBlobs = false;
248 int outputNoOwner = 0;
249 char *outputSuperuser = NULL;
250 char *use_role = NULL;
253 RestoreOptions *ropt;
255 static int disable_triggers = 0;
256 static int outputNoTablespaces = 0;
257 static int use_setsessauth = 0;
259 static struct option long_options[] = {
260 {"data-only", no_argument, NULL, 'a'},
261 {"blobs", no_argument, NULL, 'b'},
262 {"clean", no_argument, NULL, 'c'},
263 {"create", no_argument, NULL, 'C'},
264 {"file", required_argument, NULL, 'f'},
265 {"format", required_argument, NULL, 'F'},
266 {"host", required_argument, NULL, 'h'},
267 {"ignore-version", no_argument, NULL, 'i'},
268 {"no-reconnect", no_argument, NULL, 'R'},
269 {"oids", no_argument, NULL, 'o'},
270 {"no-owner", no_argument, NULL, 'O'},
271 {"port", required_argument, NULL, 'p'},
272 {"schema", required_argument, NULL, 'n'},
273 {"exclude-schema", required_argument, NULL, 'N'},
274 {"schema-only", no_argument, NULL, 's'},
275 {"superuser", required_argument, NULL, 'S'},
276 {"table", required_argument, NULL, 't'},
277 {"exclude-table", required_argument, NULL, 'T'},
278 {"no-password", no_argument, NULL, 'w'},
279 {"password", no_argument, NULL, 'W'},
280 {"username", required_argument, NULL, 'U'},
281 {"verbose", no_argument, NULL, 'v'},
282 {"no-privileges", no_argument, NULL, 'x'},
283 {"no-acl", no_argument, NULL, 'x'},
284 {"compress", required_argument, NULL, 'Z'},
285 {"encoding", required_argument, NULL, 'E'},
286 {"help", no_argument, NULL, '?'},
287 {"version", no_argument, NULL, 'V'},
290 * the following options don't have an equivalent short option letter
292 {"attribute-inserts", no_argument, &column_inserts, 1},
293 {"binary-upgrade", no_argument, &binary_upgrade, 1},
294 {"column-inserts", no_argument, &column_inserts, 1},
295 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
296 {"disable-triggers", no_argument, &disable_triggers, 1},
297 {"inserts", no_argument, &dump_inserts, 1},
298 {"lock-wait-timeout", required_argument, NULL, 2},
299 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
300 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
301 {"role", required_argument, NULL, 3},
302 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
307 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
311 strcpy(g_comment_start, "-- ");
312 g_comment_end[0] = '\0';
313 strcpy(g_opaque_type, "opaque");
315 dataOnly = schemaOnly = false;
316 lockWaitTimeout = NULL;
318 progname = get_progname(argv[0]);
320 /* Set default options based on progname */
321 if (strcmp(progname, "pg_backup") == 0)
326 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
331 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
333 puts("pg_dump (PostgreSQL) " PG_VERSION);
338 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxX:Z:",
339 long_options, &optindex)) != -1)
343 case 'a': /* Dump data only */
347 case 'b': /* Dump blobs */
351 case 'c': /* clean (i.e., drop) schema prior to create */
355 case 'C': /* Create DB */
359 case 'E': /* Dump encoding */
360 dumpencoding = optarg;
371 case 'h': /* server host */
376 /* ignored, deprecated option */
379 case 'n': /* include schema(s) */
380 simple_string_list_append(&schema_include_patterns, optarg);
381 include_everything = false;
384 case 'N': /* exclude schema(s) */
385 simple_string_list_append(&schema_exclude_patterns, optarg);
388 case 'o': /* Dump oids */
392 case 'O': /* Don't reconnect to match owner */
396 case 'p': /* server port */
401 /* no-op, still accepted for backwards compatibility */
404 case 's': /* dump schema only */
408 case 'S': /* Username for superuser in plain text output */
409 outputSuperuser = strdup(optarg);
412 case 't': /* include table(s) */
413 simple_string_list_append(&table_include_patterns, optarg);
414 include_everything = false;
417 case 'T': /* exclude table(s) */
418 simple_string_list_append(&table_exclude_patterns, optarg);
425 case 'v': /* verbose */
430 prompt_password = TRI_NO;
434 prompt_password = TRI_YES;
437 case 'x': /* skip ACL dump */
442 /* -X is a deprecated alternative to long options */
443 if (strcmp(optarg, "disable-dollar-quoting") == 0)
444 disable_dollar_quoting = 1;
445 else if (strcmp(optarg, "disable-triggers") == 0)
446 disable_triggers = 1;
447 else if (strcmp(optarg, "no-tablespaces") == 0)
448 outputNoTablespaces = 1;
449 else if (strcmp(optarg, "use-set-session-authorization") == 0)
454 _("%s: invalid -X option -- %s\n"),
456 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
461 case 'Z': /* Compression Level */
462 compressLevel = atoi(optarg);
466 /* This covers the long options equivalent to -X xxx. */
469 case 2: /* lock-wait-timeout */
470 lockWaitTimeout = optarg;
473 case 3: /* SET ROLE */
478 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
483 if (optind < (argc - 1))
485 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
486 progname, argv[optind + 1]);
487 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
492 /* Get database name from command line */
494 dbname = argv[optind];
496 /* --column-inserts implies --inserts */
500 if (dataOnly && schemaOnly)
502 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
506 if (dataOnly && outputClean)
508 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
512 if (dump_inserts && oids)
514 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
515 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
519 /* open the output file */
520 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
522 /* This is used by pg_dumpall, and is not documented */
524 g_fout = CreateArchive(filename, archNull, 0, archModeAppend);
526 else if (pg_strcasecmp(format, "c") == 0 || pg_strcasecmp(format, "custom") == 0)
527 g_fout = CreateArchive(filename, archCustom, compressLevel, archModeWrite);
528 else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
531 * Dump files into the current directory; for demonstration only, not
534 g_fout = CreateArchive(filename, archFiles, compressLevel, archModeWrite);
536 else if (pg_strcasecmp(format, "p") == 0 || pg_strcasecmp(format, "plain") == 0)
539 g_fout = CreateArchive(filename, archNull, 0, archModeWrite);
541 else if (pg_strcasecmp(format, "t") == 0 || pg_strcasecmp(format, "tar") == 0)
542 g_fout = CreateArchive(filename, archTar, compressLevel, archModeWrite);
545 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
551 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
555 /* Let the archiver know how noisy to be */
556 g_fout->verbose = g_verbose;
558 my_version = parse_version(PG_VERSION);
561 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
566 * We allow the server to be back to 7.0, and up to any minor release of
567 * our own major version. (See also version check in pg_dumpall.c.)
569 g_fout->minRemoteVersion = 70000;
570 g_fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
573 * Open the database using the Archiver, so it knows about it. Errors mean
576 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
577 username, prompt_password);
579 /* Set the client encoding if requested */
582 if (PQsetClientEncoding(g_conn, dumpencoding) < 0)
584 write_msg(NULL, "invalid client encoding \"%s\" specified\n",
591 * Get the active encoding and the standard_conforming_strings setting, so
592 * we know how to escape strings.
594 g_fout->encoding = PQclientEncoding(g_conn);
596 std_strings = PQparameterStatus(g_conn, "standard_conforming_strings");
597 g_fout->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
599 /* Set the role if requested */
600 if (use_role && g_fout->remoteVersion >= 80100)
602 PQExpBuffer query = createPQExpBuffer();
604 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
605 do_sql_command(g_conn, query->data);
606 destroyPQExpBuffer(query);
609 /* Set the datestyle to ISO to ensure the dump's portability */
610 do_sql_command(g_conn, "SET DATESTYLE = ISO");
612 /* Likewise, avoid using sql_standard intervalstyle */
613 if (g_fout->remoteVersion >= 80400)
614 do_sql_command(g_conn, "SET INTERVALSTYLE = POSTGRES");
617 * If supported, set extra_float_digits so that we can dump float data
618 * exactly (given correctly implemented float I/O code, anyway)
620 if (g_fout->remoteVersion >= 90000)
621 do_sql_command(g_conn, "SET extra_float_digits TO 3");
622 else if (g_fout->remoteVersion >= 70400)
623 do_sql_command(g_conn, "SET extra_float_digits TO 2");
626 * If synchronized scanning is supported, disable it, to prevent
627 * unpredictable changes in row ordering across a dump and reload.
629 if (g_fout->remoteVersion >= 80300)
630 do_sql_command(g_conn, "SET synchronize_seqscans TO off");
633 * Disable timeouts if supported.
635 if (g_fout->remoteVersion >= 70300)
636 do_sql_command(g_conn, "SET statement_timeout = 0");
639 * Quote all identifiers, if requested.
641 if (quote_all_identifiers && g_fout->remoteVersion >= 90100)
642 do_sql_command(g_conn, "SET quote_all_identifiers = true");
645 * Start serializable transaction to dump consistent data.
647 do_sql_command(g_conn, "BEGIN");
649 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
651 /* Select the appropriate subquery to convert user IDs to names */
652 if (g_fout->remoteVersion >= 80100)
653 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
654 else if (g_fout->remoteVersion >= 70300)
655 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
657 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
659 /* Find the last built-in OID, if needed */
660 if (g_fout->remoteVersion < 70300)
662 if (g_fout->remoteVersion >= 70100)
663 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
665 g_last_builtin_oid = findLastBuiltinOid_V70();
667 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
670 /* Expand schema selection patterns into OID lists */
671 if (schema_include_patterns.head != NULL)
673 expand_schema_name_patterns(&schema_include_patterns,
674 &schema_include_oids);
675 if (schema_include_oids.head == NULL)
677 write_msg(NULL, "No matching schemas were found\n");
681 expand_schema_name_patterns(&schema_exclude_patterns,
682 &schema_exclude_oids);
683 /* non-matching exclusion patterns aren't an error */
685 /* Expand table selection patterns into OID lists */
686 if (table_include_patterns.head != NULL)
688 expand_table_name_patterns(&table_include_patterns,
689 &table_include_oids);
690 if (table_include_oids.head == NULL)
692 write_msg(NULL, "No matching tables were found\n");
696 expand_table_name_patterns(&table_exclude_patterns,
697 &table_exclude_oids);
698 /* non-matching exclusion patterns aren't an error */
701 * Dumping blobs is now default unless we saw an inclusion switch or -s
702 * ... but even if we did see one of these, -b turns it back on.
704 if (include_everything && !schemaOnly)
708 * Now scan the database and create DumpableObject structs for all the
709 * objects we intend to dump.
711 tblinfo = getSchemaData(&numTables);
713 if (g_fout->remoteVersion < 80400)
714 guessConstraintInheritance(tblinfo, numTables);
718 getTableData(tblinfo, numTables, oids);
720 getTableDataFKConstraints();
727 * Collect dependency data to assist in ordering the objects.
732 * Sort the objects into a safe dump order (no forward references).
734 * In 7.3 or later, we can rely on dependency information to help us
735 * determine a safe order, so the initial sort is mostly for cosmetic
736 * purposes: we sort by name to ensure that logically identical schemas
737 * will dump identically. Before 7.3 we don't have dependencies and we
738 * use OID ordering as an (unreliable) guide to creation order.
740 getDumpableObjects(&dobjs, &numObjs);
742 if (g_fout->remoteVersion >= 70300)
743 sortDumpableObjectsByTypeName(dobjs, numObjs);
745 sortDumpableObjectsByTypeOid(dobjs, numObjs);
747 sortDumpableObjects(dobjs, numObjs);
750 * Create archive TOC entries for all the objects to be dumped, in a safe
754 /* First the special ENCODING and STDSTRINGS entries. */
755 dumpEncoding(g_fout);
756 dumpStdStrings(g_fout);
758 /* The database item is always next, unless we don't want it at all */
759 if (include_everything && !dataOnly)
760 dumpDatabase(g_fout);
762 /* Now the rearrangeable objects. */
763 for (i = 0; i < numObjs; i++)
764 dumpDumpableObject(g_fout, dobjs[i]);
767 * And finally we can do the actual output.
771 ropt = NewRestoreOptions();
772 ropt->filename = (char *) filename;
773 ropt->dropSchema = outputClean;
774 ropt->aclsSkip = aclsSkip;
775 ropt->superuser = outputSuperuser;
776 ropt->createDB = outputCreateDB;
777 ropt->noOwner = outputNoOwner;
778 ropt->noTablespace = outputNoTablespaces;
779 ropt->disable_triggers = disable_triggers;
780 ropt->use_setsessauth = use_setsessauth;
781 ropt->dataOnly = dataOnly;
783 if (compressLevel == -1)
784 ropt->compression = 0;
786 ropt->compression = compressLevel;
788 ropt->suppressDumpWarnings = true; /* We've already shown them */
790 RestoreArchive(g_fout, ropt);
793 CloseArchive(g_fout);
802 help(const char *progname)
804 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
805 printf(_("Usage:\n"));
806 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
808 printf(_("\nGeneral options:\n"));
809 printf(_(" -f, --file=FILENAME output file name\n"));
810 printf(_(" -F, --format=c|t|p output file format (custom, tar, plain text)\n"));
811 printf(_(" -v, --verbose verbose mode\n"));
812 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
813 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
814 printf(_(" --help show this help, then exit\n"));
815 printf(_(" --version output version information, then exit\n"));
817 printf(_("\nOptions controlling the output content:\n"));
818 printf(_(" -a, --data-only dump only the data, not the schema\n"));
819 printf(_(" -b, --blobs include large objects in dump\n"));
820 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
821 printf(_(" -C, --create include commands to create database in dump\n"));
822 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
823 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
824 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
825 printf(_(" -o, --oids include OIDs in dump\n"));
826 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
827 " plain-text format\n"));
828 printf(_(" -s, --schema-only dump only the schema, no data\n"));
829 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
830 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
831 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
832 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
833 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
834 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
835 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
836 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
837 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
838 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
839 printf(_(" --quote-all-identifiers quote all identifiers, even if not keywords\n"));
840 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
841 printf(_(" --use-set-session-authorization\n"
842 " use SET SESSION AUTHORIZATION commands instead of\n"
843 " ALTER OWNER commands to set ownership\n"));
845 printf(_("\nConnection options:\n"));
846 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
847 printf(_(" -p, --port=PORT database server port number\n"));
848 printf(_(" -U, --username=NAME connect as specified database user\n"));
849 printf(_(" -w, --no-password never prompt for password\n"));
850 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
852 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
853 "variable value is used.\n\n"));
854 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
862 write_msg(NULL, "*** aborted because of error\n");
867 * Find the OIDs of all schemas matching the given list of patterns,
868 * and append them to the given OID list.
871 expand_schema_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
875 SimpleStringListCell *cell;
878 if (patterns->head == NULL)
879 return; /* nothing to do */
881 if (g_fout->remoteVersion < 70300)
883 write_msg(NULL, "server version must be at least 7.3 to use schema selection switches\n");
887 query = createPQExpBuffer();
890 * We use UNION ALL rather than UNION; this might sometimes result in
891 * duplicate entries in the OID list, but we don't care.
894 for (cell = patterns->head; cell; cell = cell->next)
896 if (cell != patterns->head)
897 appendPQExpBuffer(query, "UNION ALL\n");
898 appendPQExpBuffer(query,
899 "SELECT oid FROM pg_catalog.pg_namespace n\n");
900 processSQLNamePattern(g_conn, query, cell->val, false, false,
901 NULL, "n.nspname", NULL,
905 res = PQexec(g_conn, query->data);
906 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
908 for (i = 0; i < PQntuples(res); i++)
910 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
914 destroyPQExpBuffer(query);
918 * Find the OIDs of all tables matching the given list of patterns,
919 * and append them to the given OID list.
922 expand_table_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
926 SimpleStringListCell *cell;
929 if (patterns->head == NULL)
930 return; /* nothing to do */
932 query = createPQExpBuffer();
935 * We use UNION ALL rather than UNION; this might sometimes result in
936 * duplicate entries in the OID list, but we don't care.
939 for (cell = patterns->head; cell; cell = cell->next)
941 if (cell != patterns->head)
942 appendPQExpBuffer(query, "UNION ALL\n");
943 appendPQExpBuffer(query,
945 "\nFROM pg_catalog.pg_class c"
946 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
947 "\nWHERE c.relkind in ('%c', '%c', '%c')\n",
948 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
949 processSQLNamePattern(g_conn, query, cell->val, true, false,
950 "n.nspname", "c.relname", NULL,
951 "pg_catalog.pg_table_is_visible(c.oid)");
954 res = PQexec(g_conn, query->data);
955 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
957 for (i = 0; i < PQntuples(res); i++)
959 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
963 destroyPQExpBuffer(query);
967 * selectDumpableNamespace: policy-setting subroutine
968 * Mark a namespace as to be dumped or not
971 selectDumpableNamespace(NamespaceInfo *nsinfo)
974 * If specific tables are being dumped, do not dump any complete
975 * namespaces. If specific namespaces are being dumped, dump just those
976 * namespaces. Otherwise, dump all non-system namespaces.
978 if (table_include_oids.head != NULL)
979 nsinfo->dobj.dump = false;
980 else if (schema_include_oids.head != NULL)
981 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
982 nsinfo->dobj.catId.oid);
983 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
984 strcmp(nsinfo->dobj.name, "information_schema") == 0)
985 nsinfo->dobj.dump = false;
987 nsinfo->dobj.dump = true;
990 * In any case, a namespace can be excluded by an exclusion switch
992 if (nsinfo->dobj.dump &&
993 simple_oid_list_member(&schema_exclude_oids,
994 nsinfo->dobj.catId.oid))
995 nsinfo->dobj.dump = false;
999 * selectDumpableTable: policy-setting subroutine
1000 * Mark a table as to be dumped or not
1003 selectDumpableTable(TableInfo *tbinfo)
1006 * If specific tables are being dumped, dump just those tables; else, dump
1007 * according to the parent namespace's dump flag.
1009 if (table_include_oids.head != NULL)
1010 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1011 tbinfo->dobj.catId.oid);
1013 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1016 * In any case, a table can be excluded by an exclusion switch
1018 if (tbinfo->dobj.dump &&
1019 simple_oid_list_member(&table_exclude_oids,
1020 tbinfo->dobj.catId.oid))
1021 tbinfo->dobj.dump = false;
1025 * selectDumpableType: policy-setting subroutine
1026 * Mark a type as to be dumped or not
1028 * If it's a table's rowtype or an autogenerated array type, we also apply a
1029 * special type code to facilitate sorting into the desired order. (We don't
1030 * want to consider those to be ordinary types because that would bring tables
1031 * up into the datatype part of the dump order.) Those tests should be made
1032 * first to ensure the objType change is applied regardless of namespace etc.
1035 selectDumpableType(TypeInfo *tyinfo)
1037 /* skip complex types, except for standalone composite types */
1038 if (OidIsValid(tyinfo->typrelid) &&
1039 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1041 tyinfo->dobj.dump = false;
1042 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1045 /* skip auto-generated array types */
1046 else if (tyinfo->isArray)
1048 tyinfo->dobj.dump = false;
1049 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1052 /* dump only types in dumpable namespaces */
1053 else if (!tyinfo->dobj.namespace->dobj.dump)
1054 tyinfo->dobj.dump = false;
1056 /* skip undefined placeholder types */
1057 else if (!tyinfo->isDefined)
1058 tyinfo->dobj.dump = false;
1061 tyinfo->dobj.dump = true;
1065 * selectDumpableDefaultACL: policy-setting subroutine
1066 * Mark a default ACL as to be dumped or not
1068 * For per-schema default ACLs, dump if the schema is to be dumped.
1069 * Otherwise dump if we are dumping "everything". Note that dataOnly
1070 * and aclsSkip are checked separately.
1073 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1075 if (dinfo->dobj.namespace)
1076 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1078 dinfo->dobj.dump = include_everything;
1082 * selectDumpableObject: policy-setting subroutine
1083 * Mark a generic dumpable object as to be dumped or not
1085 * Use this only for object types without a special-case routine above.
1088 selectDumpableObject(DumpableObject *dobj)
1091 * Default policy is to dump if parent namespace is dumpable, or always
1092 * for non-namespace-associated items.
1094 if (dobj->namespace)
1095 dobj->dump = dobj->namespace->dobj.dump;
1101 * Dump a table's contents for loading using the COPY command
1102 * - this routine is called by the Archiver when it wants the table
1107 dumpTableData_copy(Archive *fout, void *dcontext)
1109 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1110 TableInfo *tbinfo = tdinfo->tdtable;
1111 const char *classname = tbinfo->dobj.name;
1112 const bool hasoids = tbinfo->hasoids;
1113 const bool oids = tdinfo->oids;
1114 PQExpBuffer q = createPQExpBuffer();
1118 const char *column_list;
1121 write_msg(NULL, "dumping contents of table %s\n", classname);
1124 * Make sure we are in proper schema. We will qualify the table name
1125 * below anyway (in case its name conflicts with a pg_catalog table); but
1126 * this ensures reproducible results in case the table contains regproc,
1127 * regclass, etc columns.
1129 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1132 * If possible, specify the column list explicitly so that we have no
1133 * possibility of retrieving data in the wrong column order. (The default
1134 * column ordering of COPY will not be what we want in certain corner
1135 * cases involving ADD COLUMN and inheritance.)
1137 if (g_fout->remoteVersion >= 70300)
1138 column_list = fmtCopyColumnList(tbinfo);
1140 column_list = ""; /* can't select columns in COPY */
1142 if (oids && hasoids)
1144 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1145 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1151 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1152 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1156 res = PQexec(g_conn, q->data);
1157 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
1162 ret = PQgetCopyData(g_conn, ©buf, 0);
1165 break; /* done or error */
1169 WriteData(fout, copybuf, ret);
1176 * There was considerable discussion in late July, 2000 regarding
1177 * slowing down pg_dump when backing up large tables. Users with both
1178 * slow & fast (multi-processor) machines experienced performance
1179 * degradation when doing a backup.
1181 * Initial attempts based on sleeping for a number of ms for each ms
1182 * of work were deemed too complex, then a simple 'sleep in each loop'
1183 * implementation was suggested. The latter failed because the loop
1184 * was too tight. Finally, the following was implemented:
1186 * If throttle is non-zero, then
1187 * See how long since the last sleep.
1188 * Work out how long to sleep (based on ratio).
1189 * If sleep is more than 100ms, then
1195 * where the throttle value was the number of ms to sleep per ms of
1196 * work. The calculation was done in each loop.
1198 * Most of the hard work is done in the backend, and this solution
1199 * still did not work particularly well: on slow machines, the ratio
1200 * was 50:1, and on medium paced machines, 1:1, and on fast
1201 * multi-processor machines, it had little or no effect, for reasons
1202 * that were unclear.
1204 * Further discussion ensued, and the proposal was dropped.
1206 * For those people who want this feature, it can be implemented using
1207 * gettimeofday in each loop, calculating the time since last sleep,
1208 * multiplying that by the sleep ratio, then if the result is more
1209 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1210 * function to sleep for a subsecond period ie.
1212 * select(0, NULL, NULL, NULL, &tvi);
1214 * This will return after the interval specified in the structure tvi.
1215 * Finally, call gettimeofday again to save the 'last sleep time'.
1219 archprintf(fout, "\\.\n\n\n");
1223 /* copy data transfer failed */
1224 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1225 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1226 write_msg(NULL, "The command was: %s\n", q->data);
1230 /* Check command status and return to normal libpq state */
1231 res = PQgetResult(g_conn);
1232 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1235 destroyPQExpBuffer(q);
1240 dumpTableData_insert(Archive *fout, void *dcontext)
1242 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1243 TableInfo *tbinfo = tdinfo->tdtable;
1244 const char *classname = tbinfo->dobj.name;
1245 PQExpBuffer q = createPQExpBuffer();
1252 * Make sure we are in proper schema. We will qualify the table name
1253 * below anyway (in case its name conflicts with a pg_catalog table); but
1254 * this ensures reproducible results in case the table contains regproc,
1255 * regclass, etc columns.
1257 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1259 if (fout->remoteVersion >= 70100)
1261 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1262 "SELECT * FROM ONLY %s",
1263 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1268 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1270 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1274 res = PQexec(g_conn, q->data);
1275 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1281 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
1282 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
1284 nfields = PQnfields(res);
1285 for (tuple = 0; tuple < PQntuples(res); tuple++)
1287 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1290 /* corner case for zero-column table */
1291 archprintf(fout, "DEFAULT VALUES;\n");
1296 resetPQExpBuffer(q);
1297 appendPQExpBuffer(q, "(");
1298 for (field = 0; field < nfields; field++)
1301 appendPQExpBuffer(q, ", ");
1302 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1304 appendPQExpBuffer(q, ") ");
1305 archputs(q->data, fout);
1307 archprintf(fout, "VALUES (");
1308 for (field = 0; field < nfields; field++)
1311 archprintf(fout, ", ");
1312 if (PQgetisnull(res, tuple, field))
1314 archprintf(fout, "NULL");
1318 /* XXX This code is partially duplicated in ruleutils.c */
1319 switch (PQftype(res, field))
1330 * These types are printed without quotes unless
1331 * they contain values that aren't accepted by the
1332 * scanner unquoted (e.g., 'NaN'). Note that
1333 * strtod() and friends might accept NaN, so we
1334 * can't use that to test.
1336 * In reality we only need to defend against
1337 * infinity and NaN, so we need not get too crazy
1338 * about pattern matching here.
1340 const char *s = PQgetvalue(res, tuple, field);
1342 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1343 archprintf(fout, "%s", s);
1345 archprintf(fout, "'%s'", s);
1351 archprintf(fout, "B'%s'",
1352 PQgetvalue(res, tuple, field));
1356 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1357 archprintf(fout, "true");
1359 archprintf(fout, "false");
1363 /* All other types are printed as string literals. */
1364 resetPQExpBuffer(q);
1365 appendStringLiteralAH(q,
1366 PQgetvalue(res, tuple, field),
1368 archputs(q->data, fout);
1372 archprintf(fout, ");\n");
1374 } while (PQntuples(res) > 0);
1378 archprintf(fout, "\n\n");
1380 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1382 destroyPQExpBuffer(q);
1389 * dump the contents of a single table
1391 * Actually, this just makes an ArchiveEntry for the table contents.
1394 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1396 TableInfo *tbinfo = tdinfo->tdtable;
1397 PQExpBuffer copyBuf = createPQExpBuffer();
1398 DataDumperPtr dumpFn;
1403 /* Dump/restore using COPY */
1404 dumpFn = dumpTableData_copy;
1405 /* must use 2 steps here 'cause fmtId is nonreentrant */
1406 appendPQExpBuffer(copyBuf, "COPY %s ",
1407 fmtId(tbinfo->dobj.name));
1408 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1409 fmtCopyColumnList(tbinfo),
1410 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1411 copyStmt = copyBuf->data;
1415 /* Restore using INSERT */
1416 dumpFn = dumpTableData_insert;
1420 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1421 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1422 NULL, tbinfo->rolname,
1423 false, "TABLE DATA", SECTION_DATA,
1425 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1428 destroyPQExpBuffer(copyBuf);
1433 * set up dumpable objects representing the contents of tables
1436 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1440 for (i = 0; i < numTables; i++)
1442 /* Skip VIEWs (no data to dump) */
1443 if (tblinfo[i].relkind == RELKIND_VIEW)
1445 /* Skip SEQUENCEs (handled elsewhere) */
1446 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1449 if (tblinfo[i].dobj.dump)
1451 TableDataInfo *tdinfo;
1453 tdinfo = (TableDataInfo *) malloc(sizeof(TableDataInfo));
1455 tdinfo->dobj.objType = DO_TABLE_DATA;
1458 * Note: use tableoid 0 so that this object won't be mistaken for
1459 * something that pg_depend entries apply to.
1461 tdinfo->dobj.catId.tableoid = 0;
1462 tdinfo->dobj.catId.oid = tblinfo[i].dobj.catId.oid;
1463 AssignDumpId(&tdinfo->dobj);
1464 tdinfo->dobj.name = tblinfo[i].dobj.name;
1465 tdinfo->dobj.namespace = tblinfo[i].dobj.namespace;
1466 tdinfo->tdtable = &(tblinfo[i]);
1467 tdinfo->oids = oids;
1468 addObjectDependency(&tdinfo->dobj, tblinfo[i].dobj.dumpId);
1470 tblinfo[i].dataObj = tdinfo;
1476 * getTableDataFKConstraints -
1477 * add dump-order dependencies reflecting foreign key constraints
1479 * This code is executed only in a data-only dump --- in schema+data dumps
1480 * we handle foreign key issues by not creating the FK constraints until
1481 * after the data is loaded. In a data-only dump, however, we want to
1482 * order the table data objects in such a way that a table's referenced
1483 * tables are restored first. (In the presence of circular references or
1484 * self-references this may be impossible; we'll detect and complain about
1485 * that during the dependency sorting step.)
1488 getTableDataFKConstraints(void)
1490 DumpableObject **dobjs;
1494 /* Search through all the dumpable objects for FK constraints */
1495 getDumpableObjects(&dobjs, &numObjs);
1496 for (i = 0; i < numObjs; i++)
1498 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1500 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1503 /* Not interesting unless both tables are to be dumped */
1504 if (cinfo->contable == NULL ||
1505 cinfo->contable->dataObj == NULL)
1507 ftable = findTableByOid(cinfo->confrelid);
1508 if (ftable == NULL ||
1509 ftable->dataObj == NULL)
1513 * Okay, make referencing table's TABLE_DATA object depend on the
1514 * referenced table's TABLE_DATA object.
1516 addObjectDependency(&cinfo->contable->dataObj->dobj,
1517 ftable->dataObj->dobj.dumpId);
1525 * guessConstraintInheritance:
1526 * In pre-8.4 databases, we can't tell for certain which constraints
1527 * are inherited. We assume a CHECK constraint is inherited if its name
1528 * matches the name of any constraint in the parent. Originally this code
1529 * tried to compare the expression texts, but that can fail for various
1530 * reasons --- for example, if the parent and child tables are in different
1531 * schemas, reverse-listing of function calls may produce different text
1532 * (schema-qualified or not) depending on search path.
1534 * In 8.4 and up we can rely on the conislocal field to decide which
1535 * constraints must be dumped; much safer.
1537 * This function assumes all conislocal flags were initialized to TRUE.
1538 * It clears the flag on anything that seems to be inherited.
1541 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1547 for (i = 0; i < numTables; i++)
1549 TableInfo *tbinfo = &(tblinfo[i]);
1551 TableInfo **parents;
1554 /* Sequences and views never have parents */
1555 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1556 tbinfo->relkind == RELKIND_VIEW)
1559 /* Don't bother computing anything for non-target tables, either */
1560 if (!tbinfo->dobj.dump)
1563 numParents = tbinfo->numParents;
1564 parents = tbinfo->parents;
1566 if (numParents == 0)
1567 continue; /* nothing to see here, move along */
1569 /* scan for inherited CHECK constraints */
1570 for (j = 0; j < tbinfo->ncheck; j++)
1572 ConstraintInfo *constr;
1574 constr = &(tbinfo->checkexprs[j]);
1576 for (k = 0; k < numParents; k++)
1580 parent = parents[k];
1581 for (l = 0; l < parent->ncheck; l++)
1583 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1585 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1587 constr->conislocal = false;
1591 if (!constr->conislocal)
1601 * dump the database definition
1604 dumpDatabase(Archive *AH)
1606 PQExpBuffer dbQry = createPQExpBuffer();
1607 PQExpBuffer delQry = createPQExpBuffer();
1608 PQExpBuffer creaQry = createPQExpBuffer();
1621 const char *datname,
1629 datname = PQdb(g_conn);
1632 write_msg(NULL, "saving database definition\n");
1634 /* Make sure we are in proper schema */
1635 selectSourceSchema("pg_catalog");
1637 /* Get the database owner and parameters from pg_database */
1638 if (g_fout->remoteVersion >= 80400)
1640 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1641 "(%s datdba) AS dba, "
1642 "pg_encoding_to_char(encoding) AS encoding, "
1643 "datcollate, datctype, datfrozenxid, "
1644 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1645 "shobj_description(oid, 'pg_database') AS description "
1650 appendStringLiteralAH(dbQry, datname, AH);
1652 else if (g_fout->remoteVersion >= 80200)
1654 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1655 "(%s datdba) AS dba, "
1656 "pg_encoding_to_char(encoding) AS encoding, "
1657 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1658 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1659 "shobj_description(oid, 'pg_database') AS description "
1664 appendStringLiteralAH(dbQry, datname, AH);
1666 else if (g_fout->remoteVersion >= 80000)
1668 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1669 "(%s datdba) AS dba, "
1670 "pg_encoding_to_char(encoding) AS encoding, "
1671 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1672 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1676 appendStringLiteralAH(dbQry, datname, AH);
1678 else if (g_fout->remoteVersion >= 70100)
1680 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1681 "(%s datdba) AS dba, "
1682 "pg_encoding_to_char(encoding) AS encoding, "
1683 "NULL AS datcollate, NULL AS datctype, "
1684 "0 AS datfrozenxid, "
1685 "NULL AS tablespace "
1689 appendStringLiteralAH(dbQry, datname, AH);
1693 appendPQExpBuffer(dbQry, "SELECT "
1694 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1696 "(%s datdba) AS dba, "
1697 "pg_encoding_to_char(encoding) AS encoding, "
1698 "NULL AS datcollate, NULL AS datctype, "
1699 "0 AS datfrozenxid, "
1700 "NULL AS tablespace "
1704 appendStringLiteralAH(dbQry, datname, AH);
1707 res = PQexec(g_conn, dbQry->data);
1708 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1710 ntups = PQntuples(res);
1714 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1721 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1726 i_tableoid = PQfnumber(res, "tableoid");
1727 i_oid = PQfnumber(res, "oid");
1728 i_dba = PQfnumber(res, "dba");
1729 i_encoding = PQfnumber(res, "encoding");
1730 i_collate = PQfnumber(res, "datcollate");
1731 i_ctype = PQfnumber(res, "datctype");
1732 i_frozenxid = PQfnumber(res, "datfrozenxid");
1733 i_tablespace = PQfnumber(res, "tablespace");
1735 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1736 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1737 dba = PQgetvalue(res, 0, i_dba);
1738 encoding = PQgetvalue(res, 0, i_encoding);
1739 collate = PQgetvalue(res, 0, i_collate);
1740 ctype = PQgetvalue(res, 0, i_ctype);
1741 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1742 tablespace = PQgetvalue(res, 0, i_tablespace);
1744 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1746 if (strlen(encoding) > 0)
1748 appendPQExpBuffer(creaQry, " ENCODING = ");
1749 appendStringLiteralAH(creaQry, encoding, AH);
1751 if (strlen(collate) > 0)
1753 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1754 appendStringLiteralAH(creaQry, collate, AH);
1756 if (strlen(ctype) > 0)
1758 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1759 appendStringLiteralAH(creaQry, ctype, AH);
1761 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1762 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1764 appendPQExpBuffer(creaQry, ";\n");
1768 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1769 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1770 "SET datfrozenxid = '%u'\n"
1773 appendStringLiteralAH(creaQry, datname, AH);
1774 appendPQExpBuffer(creaQry, ";\n");
1778 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1781 dbDumpId = createDumpId();
1784 dbCatId, /* catalog ID */
1785 dbDumpId, /* dump ID */
1787 NULL, /* Namespace */
1788 NULL, /* Tablespace */
1790 false, /* with oids */
1791 "DATABASE", /* Desc */
1792 SECTION_PRE_DATA, /* Section */
1793 creaQry->data, /* Create */
1794 delQry->data, /* Del */
1799 NULL); /* Dumper Arg */
1802 * pg_largeobject comes from the old system intact, so set its
1808 PQExpBuffer loFrozenQry = createPQExpBuffer();
1809 PQExpBuffer loOutQry = createPQExpBuffer();
1812 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1813 "FROM pg_catalog.pg_class\n"
1814 "WHERE oid = %u;\n",
1815 LargeObjectRelationId);
1817 lo_res = PQexec(g_conn, loFrozenQry->data);
1818 check_sql_result(lo_res, g_conn, loFrozenQry->data, PGRES_TUPLES_OK);
1820 if (PQntuples(lo_res) != 1)
1822 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
1826 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1828 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid.\n");
1829 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1830 "SET relfrozenxid = '%u'\n"
1831 "WHERE oid = %u;\n",
1832 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1833 LargeObjectRelationId);
1834 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1835 "pg_largeobject", NULL, NULL, "",
1836 false, "pg_largeobject", SECTION_PRE_DATA,
1837 loOutQry->data, "", NULL,
1842 destroyPQExpBuffer(loFrozenQry);
1843 destroyPQExpBuffer(loOutQry);
1846 /* Dump DB comment if any */
1847 if (g_fout->remoteVersion >= 80200)
1850 * 8.2 keeps comments on shared objects in a shared table, so we
1851 * cannot use the dumpComment used for other database objects.
1853 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
1855 if (comment && strlen(comment))
1857 resetPQExpBuffer(dbQry);
1860 * Generates warning when loaded into a differently-named
1863 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
1864 appendStringLiteralAH(dbQry, comment, AH);
1865 appendPQExpBuffer(dbQry, ";\n");
1867 ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
1868 dba, false, "COMMENT", SECTION_NONE,
1869 dbQry->data, "", NULL,
1870 &dbDumpId, 1, NULL, NULL);
1875 resetPQExpBuffer(dbQry);
1876 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
1877 dumpComment(AH, dbQry->data, NULL, "",
1878 dbCatId, 0, dbDumpId);
1883 destroyPQExpBuffer(dbQry);
1884 destroyPQExpBuffer(delQry);
1885 destroyPQExpBuffer(creaQry);
1890 * dumpEncoding: put the correct encoding into the archive
1893 dumpEncoding(Archive *AH)
1895 const char *encname = pg_encoding_to_char(AH->encoding);
1896 PQExpBuffer qry = createPQExpBuffer();
1899 write_msg(NULL, "saving encoding = %s\n", encname);
1901 appendPQExpBuffer(qry, "SET client_encoding = ");
1902 appendStringLiteralAH(qry, encname, AH);
1903 appendPQExpBuffer(qry, ";\n");
1905 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1906 "ENCODING", NULL, NULL, "",
1907 false, "ENCODING", SECTION_PRE_DATA,
1908 qry->data, "", NULL,
1912 destroyPQExpBuffer(qry);
1917 * dumpStdStrings: put the correct escape string behavior into the archive
1920 dumpStdStrings(Archive *AH)
1922 const char *stdstrings = AH->std_strings ? "on" : "off";
1923 PQExpBuffer qry = createPQExpBuffer();
1926 write_msg(NULL, "saving standard_conforming_strings = %s\n",
1929 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
1932 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1933 "STDSTRINGS", NULL, NULL, "",
1934 false, "STDSTRINGS", SECTION_PRE_DATA,
1935 qry->data, "", NULL,
1939 destroyPQExpBuffer(qry);
1945 * Collect schema-level data about large objects
1948 getBlobs(Archive *AH)
1950 PQExpBuffer blobQry = createPQExpBuffer();
1952 DumpableObject *bdata;
1957 /* Verbose message */
1959 write_msg(NULL, "reading large objects\n");
1961 /* Make sure we are in proper schema */
1962 selectSourceSchema("pg_catalog");
1964 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
1965 if (AH->remoteVersion >= 90000)
1966 appendPQExpBuffer(blobQry,
1967 "SELECT oid, (%s lomowner) AS rolname, lomacl"
1968 " FROM pg_largeobject_metadata",
1970 else if (AH->remoteVersion >= 70100)
1971 appendPQExpBuffer(blobQry,
1972 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
1973 " FROM pg_largeobject");
1975 appendPQExpBuffer(blobQry,
1976 "SELECT oid, NULL::oid, NULL::oid"
1977 " FROM pg_class WHERE relkind = 'l'");
1979 res = PQexec(g_conn, blobQry->data);
1980 check_sql_result(res, g_conn, blobQry->data, PGRES_TUPLES_OK);
1982 ntups = PQntuples(res);
1986 * Each large object has its own BLOB archive entry.
1988 binfo = (BlobInfo *) malloc(ntups * sizeof(BlobInfo));
1990 for (i = 0; i < ntups; i++)
1992 binfo[i].dobj.objType = DO_BLOB;
1993 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
1994 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
1995 AssignDumpId(&binfo[i].dobj);
1997 binfo[i].dobj.name = strdup(PQgetvalue(res, i, 0));
1998 if (!PQgetisnull(res, i, 1))
1999 binfo[i].rolname = strdup(PQgetvalue(res, i, 1));
2001 binfo[i].rolname = "";
2002 if (!PQgetisnull(res, i, 2))
2003 binfo[i].blobacl = strdup(PQgetvalue(res, i, 2));
2005 binfo[i].blobacl = NULL;
2009 * If we have any large objects, a "BLOBS" archive entry is needed.
2010 * This is just a placeholder for sorting; it carries no data now.
2012 bdata = (DumpableObject *) malloc(sizeof(DumpableObject));
2013 bdata->objType = DO_BLOB_DATA;
2014 bdata->catId = nilCatalogId;
2015 AssignDumpId(bdata);
2016 bdata->name = strdup("BLOBS");
2020 destroyPQExpBuffer(blobQry);
2026 * dump the definition (metadata) of the given large object
2029 dumpBlob(Archive *AH, BlobInfo *binfo)
2031 PQExpBuffer cquery = createPQExpBuffer();
2032 PQExpBuffer dquery = createPQExpBuffer();
2034 appendPQExpBuffer(cquery,
2035 "SELECT pg_catalog.lo_create('%s');\n",
2038 appendPQExpBuffer(dquery,
2039 "SELECT pg_catalog.lo_unlink('%s');\n",
2042 ArchiveEntry(AH, binfo->dobj.catId, binfo->dobj.dumpId,
2045 binfo->rolname, false,
2046 "BLOB", SECTION_PRE_DATA,
2047 cquery->data, dquery->data, NULL,
2048 binfo->dobj.dependencies, binfo->dobj.nDeps,
2051 /* set up tag for comment and/or ACL */
2052 resetPQExpBuffer(cquery);
2053 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2055 /* Dump comment if any */
2056 dumpComment(AH, cquery->data,
2057 NULL, binfo->rolname,
2058 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2060 /* Dump ACL if any */
2062 dumpACL(AH, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2063 binfo->dobj.name, NULL, cquery->data,
2064 NULL, binfo->rolname, binfo->blobacl);
2066 destroyPQExpBuffer(cquery);
2067 destroyPQExpBuffer(dquery);
2072 * dump the data contents of all large objects
2075 dumpBlobs(Archive *AH, void *arg)
2077 const char *blobQry;
2078 const char *blobFetchQry;
2080 char buf[LOBBUFSIZE];
2086 write_msg(NULL, "saving large objects\n");
2088 /* Make sure we are in proper schema */
2089 selectSourceSchema("pg_catalog");
2092 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2093 * the already-in-memory dumpable objects instead...
2095 if (AH->remoteVersion >= 90000)
2096 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2097 else if (AH->remoteVersion >= 70100)
2098 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2100 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2102 res = PQexec(g_conn, blobQry);
2103 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
2105 /* Command to fetch from cursor */
2106 blobFetchQry = "FETCH 1000 IN bloboid";
2113 res = PQexec(g_conn, blobFetchQry);
2114 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
2116 /* Process the tuples, if any */
2117 ntups = PQntuples(res);
2118 for (i = 0; i < ntups; i++)
2123 blobOid = atooid(PQgetvalue(res, i, 0));
2125 loFd = lo_open(g_conn, blobOid, INV_READ);
2128 write_msg(NULL, "could not open large object %u: %s",
2129 blobOid, PQerrorMessage(g_conn));
2133 StartBlob(AH, blobOid);
2135 /* Now read it in chunks, sending data to archive */
2138 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2141 write_msg(NULL, "error reading large object %u: %s",
2142 blobOid, PQerrorMessage(g_conn));
2146 WriteData(AH, buf, cnt);
2149 lo_close(g_conn, loFd);
2151 EndBlob(AH, blobOid);
2153 } while (ntups > 0);
2161 binary_upgrade_set_type_oids_by_type_oid(PQExpBuffer upgrade_buffer,
2164 PQExpBuffer upgrade_query = createPQExpBuffer();
2166 PGresult *upgrade_res;
2167 Oid pg_type_array_oid;
2169 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2170 appendPQExpBuffer(upgrade_buffer,
2171 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2174 /* we only support old >= 8.3 for binary upgrades */
2175 appendPQExpBuffer(upgrade_query,
2177 "FROM pg_catalog.pg_type "
2178 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2181 upgrade_res = PQexec(g_conn, upgrade_query->data);
2182 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2184 /* Expecting a single result only */
2185 ntups = PQntuples(upgrade_res);
2188 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2189 "query returned %d rows instead of one: %s\n",
2191 ntups, upgrade_query->data);
2195 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2197 if (OidIsValid(pg_type_array_oid))
2199 appendPQExpBuffer(upgrade_buffer,
2200 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2201 appendPQExpBuffer(upgrade_buffer,
2202 "SELECT binary_upgrade.set_next_pg_type_array_oid('%u'::pg_catalog.oid);\n\n",
2206 PQclear(upgrade_res);
2207 destroyPQExpBuffer(upgrade_query);
2211 binary_upgrade_set_type_oids_by_rel_oid(PQExpBuffer upgrade_buffer,
2214 PQExpBuffer upgrade_query = createPQExpBuffer();
2216 PGresult *upgrade_res;
2218 bool toast_set = false;
2220 /* we only support old >= 8.3 for binary upgrades */
2221 appendPQExpBuffer(upgrade_query,
2222 "SELECT c.reltype AS crel, t.reltype AS trel "
2223 "FROM pg_catalog.pg_class c "
2224 "LEFT JOIN pg_catalog.pg_class t ON "
2225 " (c.reltoastrelid = t.oid) "
2226 "WHERE c.oid = '%u'::pg_catalog.oid;",
2229 upgrade_res = PQexec(g_conn, upgrade_query->data);
2230 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2232 /* Expecting a single result only */
2233 ntups = PQntuples(upgrade_res);
2236 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2237 "query returned %d rows instead of one: %s\n",
2239 ntups, upgrade_query->data);
2243 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2245 binary_upgrade_set_type_oids_by_type_oid(upgrade_buffer, pg_type_oid);
2247 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2249 /* Toast tables do not have pg_type array rows */
2250 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2251 PQfnumber(upgrade_res, "trel")));
2253 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2254 appendPQExpBuffer(upgrade_buffer,
2255 "SELECT binary_upgrade.set_next_pg_type_toast_oid('%u'::pg_catalog.oid);\n\n",
2261 PQclear(upgrade_res);
2262 destroyPQExpBuffer(upgrade_query);
2268 binary_upgrade_set_relfilenodes(PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2271 PQExpBuffer upgrade_query = createPQExpBuffer();
2273 PGresult *upgrade_res;
2274 Oid pg_class_relfilenode;
2275 Oid pg_class_reltoastrelid;
2276 Oid pg_class_reltoastidxid;
2279 * Note: we don't need to use pg_relation_filenode() here because this
2280 * function is not intended to be used against system catalogs. Otherwise
2281 * we'd have to worry about which versions pg_relation_filenode is
2284 appendPQExpBuffer(upgrade_query,
2285 "SELECT c.relfilenode, c.reltoastrelid, t.reltoastidxid "
2286 "FROM pg_catalog.pg_class c LEFT JOIN "
2287 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2288 "WHERE c.oid = '%u'::pg_catalog.oid;",
2291 upgrade_res = PQexec(g_conn, upgrade_query->data);
2292 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2294 /* Expecting a single result only */
2295 ntups = PQntuples(upgrade_res);
2298 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2299 "query returned %d rows instead of one: %s\n",
2301 ntups, upgrade_query->data);
2305 pg_class_relfilenode = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "relfilenode")));
2306 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2307 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2309 appendPQExpBuffer(upgrade_buffer,
2310 "\n-- For binary upgrade, must preserve relfilenodes\n");
2313 appendPQExpBuffer(upgrade_buffer,
2314 "SELECT binary_upgrade.set_next_heap_relfilenode('%u'::pg_catalog.oid);\n",
2315 pg_class_relfilenode);
2317 appendPQExpBuffer(upgrade_buffer,
2318 "SELECT binary_upgrade.set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
2319 pg_class_relfilenode);
2321 if (OidIsValid(pg_class_reltoastrelid))
2324 * One complexity is that the table definition might not require the
2325 * creation of a TOAST table, and the TOAST table might have been
2326 * created long after table creation, when the table was loaded with
2327 * wide data. By setting the TOAST relfilenode we force creation of
2328 * the TOAST heap and TOAST index by the backend so we can cleanly
2329 * migrate the files during binary migration.
2332 appendPQExpBuffer(upgrade_buffer,
2333 "SELECT binary_upgrade.set_next_toast_relfilenode('%u'::pg_catalog.oid);\n",
2334 pg_class_reltoastrelid);
2336 /* every toast table has an index */
2337 appendPQExpBuffer(upgrade_buffer,
2338 "SELECT binary_upgrade.set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
2339 pg_class_reltoastidxid);
2341 appendPQExpBuffer(upgrade_buffer, "\n");
2343 PQclear(upgrade_res);
2344 destroyPQExpBuffer(upgrade_query);
2349 * read all namespaces in the system catalogs and return them in the
2350 * NamespaceInfo* structure
2352 * numNamespaces is set to the number of namespaces read in
2355 getNamespaces(int *numNamespaces)
2361 NamespaceInfo *nsinfo;
2369 * Before 7.3, there are no real namespaces; create two dummy entries, one
2370 * for user stuff and one for system stuff.
2372 if (g_fout->remoteVersion < 70300)
2374 nsinfo = (NamespaceInfo *) malloc(2 * sizeof(NamespaceInfo));
2376 nsinfo[0].dobj.objType = DO_NAMESPACE;
2377 nsinfo[0].dobj.catId.tableoid = 0;
2378 nsinfo[0].dobj.catId.oid = 0;
2379 AssignDumpId(&nsinfo[0].dobj);
2380 nsinfo[0].dobj.name = strdup("public");
2381 nsinfo[0].rolname = strdup("");
2382 nsinfo[0].nspacl = strdup("");
2384 selectDumpableNamespace(&nsinfo[0]);
2386 nsinfo[1].dobj.objType = DO_NAMESPACE;
2387 nsinfo[1].dobj.catId.tableoid = 0;
2388 nsinfo[1].dobj.catId.oid = 1;
2389 AssignDumpId(&nsinfo[1].dobj);
2390 nsinfo[1].dobj.name = strdup("pg_catalog");
2391 nsinfo[1].rolname = strdup("");
2392 nsinfo[1].nspacl = strdup("");
2394 selectDumpableNamespace(&nsinfo[1]);
2396 g_namespaces = nsinfo;
2397 g_numNamespaces = *numNamespaces = 2;
2402 query = createPQExpBuffer();
2404 /* Make sure we are in proper schema */
2405 selectSourceSchema("pg_catalog");
2408 * we fetch all namespaces including system ones, so that every object we
2409 * read in can be linked to a containing namespace.
2411 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2412 "(%s nspowner) AS rolname, "
2413 "nspacl FROM pg_namespace",
2416 res = PQexec(g_conn, query->data);
2417 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2419 ntups = PQntuples(res);
2421 nsinfo = (NamespaceInfo *) malloc(ntups * sizeof(NamespaceInfo));
2423 i_tableoid = PQfnumber(res, "tableoid");
2424 i_oid = PQfnumber(res, "oid");
2425 i_nspname = PQfnumber(res, "nspname");
2426 i_rolname = PQfnumber(res, "rolname");
2427 i_nspacl = PQfnumber(res, "nspacl");
2429 for (i = 0; i < ntups; i++)
2431 nsinfo[i].dobj.objType = DO_NAMESPACE;
2432 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2433 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2434 AssignDumpId(&nsinfo[i].dobj);
2435 nsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_nspname));
2436 nsinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2437 nsinfo[i].nspacl = strdup(PQgetvalue(res, i, i_nspacl));
2439 /* Decide whether to dump this namespace */
2440 selectDumpableNamespace(&nsinfo[i]);
2442 if (strlen(nsinfo[i].rolname) == 0)
2443 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2444 nsinfo[i].dobj.name);
2448 destroyPQExpBuffer(query);
2450 g_namespaces = nsinfo;
2451 g_numNamespaces = *numNamespaces = ntups;
2458 * given a namespace OID and an object OID, look up the info read by
2461 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2462 * a system object or not. In 7.3 and later there is no guessing.
2464 static NamespaceInfo *
2465 findNamespace(Oid nsoid, Oid objoid)
2469 if (g_fout->remoteVersion >= 70300)
2471 for (i = 0; i < g_numNamespaces; i++)
2473 NamespaceInfo *nsinfo = &g_namespaces[i];
2475 if (nsoid == nsinfo->dobj.catId.oid)
2478 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2483 /* This code depends on the layout set up by getNamespaces. */
2484 if (objoid > g_last_builtin_oid)
2485 i = 0; /* user object */
2487 i = 1; /* system object */
2488 return &g_namespaces[i];
2491 return NULL; /* keep compiler quiet */
2496 * read all types in the system catalogs and return them in the
2497 * TypeInfo* structure
2499 * numTypes is set to the number of types read in
2501 * NB: this must run after getFuncs() because we assume we can do
2505 getTypes(int *numTypes)
2510 PQExpBuffer query = createPQExpBuffer();
2512 ShellTypeInfo *stinfo;
2528 * we include even the built-in types because those may be used as array
2529 * elements by user-defined types
2531 * we filter out the built-in types when we dump out the types
2533 * same approach for undefined (shell) types and array types
2535 * Note: as of 8.3 we can reliably detect whether a type is an
2536 * auto-generated array type by checking the element type's typarray.
2537 * (Before that the test is capable of generating false positives.) We
2538 * still check for name beginning with '_', though, so as to avoid the
2539 * cost of the subselect probe for all standard types. This would have to
2540 * be revisited if the backend ever allows renaming of array types.
2543 /* Make sure we are in proper schema */
2544 selectSourceSchema("pg_catalog");
2546 if (g_fout->remoteVersion >= 80300)
2548 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2550 "(%s typowner) AS rolname, "
2551 "typinput::oid AS typinput, "
2552 "typoutput::oid AS typoutput, typelem, typrelid, "
2553 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2554 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2555 "typtype, typisdefined, "
2556 "typname[0] = '_' AND typelem != 0 AND "
2557 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2561 else if (g_fout->remoteVersion >= 70300)
2563 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2565 "(%s typowner) AS rolname, "
2566 "typinput::oid AS typinput, "
2567 "typoutput::oid AS typoutput, typelem, typrelid, "
2568 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2569 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2570 "typtype, typisdefined, "
2571 "typname[0] = '_' AND typelem != 0 AS isarray "
2575 else if (g_fout->remoteVersion >= 70100)
2577 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2578 "0::oid AS typnamespace, "
2579 "(%s typowner) AS rolname, "
2580 "typinput::oid AS typinput, "
2581 "typoutput::oid AS typoutput, typelem, typrelid, "
2582 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2583 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2584 "typtype, typisdefined, "
2585 "typname[0] = '_' AND typelem != 0 AS isarray "
2591 appendPQExpBuffer(query, "SELECT "
2592 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2594 "0::oid AS typnamespace, "
2595 "(%s typowner) AS rolname, "
2596 "typinput::oid AS typinput, "
2597 "typoutput::oid AS typoutput, typelem, typrelid, "
2598 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2599 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2600 "typtype, typisdefined, "
2601 "typname[0] = '_' AND typelem != 0 AS isarray "
2606 res = PQexec(g_conn, query->data);
2607 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2609 ntups = PQntuples(res);
2611 tyinfo = (TypeInfo *) malloc(ntups * sizeof(TypeInfo));
2613 i_tableoid = PQfnumber(res, "tableoid");
2614 i_oid = PQfnumber(res, "oid");
2615 i_typname = PQfnumber(res, "typname");
2616 i_typnamespace = PQfnumber(res, "typnamespace");
2617 i_rolname = PQfnumber(res, "rolname");
2618 i_typinput = PQfnumber(res, "typinput");
2619 i_typoutput = PQfnumber(res, "typoutput");
2620 i_typelem = PQfnumber(res, "typelem");
2621 i_typrelid = PQfnumber(res, "typrelid");
2622 i_typrelkind = PQfnumber(res, "typrelkind");
2623 i_typtype = PQfnumber(res, "typtype");
2624 i_typisdefined = PQfnumber(res, "typisdefined");
2625 i_isarray = PQfnumber(res, "isarray");
2627 for (i = 0; i < ntups; i++)
2629 tyinfo[i].dobj.objType = DO_TYPE;
2630 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2631 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2632 AssignDumpId(&tyinfo[i].dobj);
2633 tyinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_typname));
2634 tyinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
2635 tyinfo[i].dobj.catId.oid);
2636 tyinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2637 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2638 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2639 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2640 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2641 tyinfo[i].shellType = NULL;
2643 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2644 tyinfo[i].isDefined = true;
2646 tyinfo[i].isDefined = false;
2648 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2649 tyinfo[i].isArray = true;
2651 tyinfo[i].isArray = false;
2653 /* Decide whether we want to dump it */
2654 selectDumpableType(&tyinfo[i]);
2657 * If it's a domain, fetch info about its constraints, if any
2659 tyinfo[i].nDomChecks = 0;
2660 tyinfo[i].domChecks = NULL;
2661 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2662 getDomainConstraints(&(tyinfo[i]));
2665 * If it's a base type, make a DumpableObject representing a shell
2666 * definition of the type. We will need to dump that ahead of the I/O
2667 * functions for the type.
2669 * Note: the shell type doesn't have a catId. You might think it
2670 * should copy the base type's catId, but then it might capture the
2671 * pg_depend entries for the type, which we don't want.
2673 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_BASE)
2675 stinfo = (ShellTypeInfo *) malloc(sizeof(ShellTypeInfo));
2676 stinfo->dobj.objType = DO_SHELL_TYPE;
2677 stinfo->dobj.catId = nilCatalogId;
2678 AssignDumpId(&stinfo->dobj);
2679 stinfo->dobj.name = strdup(tyinfo[i].dobj.name);
2680 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2681 stinfo->baseType = &(tyinfo[i]);
2682 tyinfo[i].shellType = stinfo;
2685 * Initially mark the shell type as not to be dumped. We'll only
2686 * dump it if the I/O functions need to be dumped; this is taken
2687 * care of while sorting dependencies.
2689 stinfo->dobj.dump = false;
2692 * However, if dumping from pre-7.3, there will be no dependency
2693 * info so we have to fake it here. We only need to worry about
2694 * typinput and typoutput since the other functions only exist
2697 if (g_fout->remoteVersion < 70300)
2703 typinput = atooid(PQgetvalue(res, i, i_typinput));
2704 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
2706 funcInfo = findFuncByOid(typinput);
2707 if (funcInfo && funcInfo->dobj.dump)
2709 /* base type depends on function */
2710 addObjectDependency(&tyinfo[i].dobj,
2711 funcInfo->dobj.dumpId);
2712 /* function depends on shell type */
2713 addObjectDependency(&funcInfo->dobj,
2714 stinfo->dobj.dumpId);
2715 /* mark shell type as to be dumped */
2716 stinfo->dobj.dump = true;
2719 funcInfo = findFuncByOid(typoutput);
2720 if (funcInfo && funcInfo->dobj.dump)
2722 /* base type depends on function */
2723 addObjectDependency(&tyinfo[i].dobj,
2724 funcInfo->dobj.dumpId);
2725 /* function depends on shell type */
2726 addObjectDependency(&funcInfo->dobj,
2727 stinfo->dobj.dumpId);
2728 /* mark shell type as to be dumped */
2729 stinfo->dobj.dump = true;
2734 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
2735 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
2736 tyinfo[i].dobj.name);
2743 destroyPQExpBuffer(query);
2750 * read all operators in the system catalogs and return them in the
2751 * OprInfo* structure
2753 * numOprs is set to the number of operators read in
2756 getOperators(int *numOprs)
2761 PQExpBuffer query = createPQExpBuffer();
2771 * find all operators, including builtin operators; we filter out
2772 * system-defined operators at dump-out time.
2775 /* Make sure we are in proper schema */
2776 selectSourceSchema("pg_catalog");
2778 if (g_fout->remoteVersion >= 70300)
2780 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
2782 "(%s oprowner) AS rolname, "
2783 "oprcode::oid AS oprcode "
2787 else if (g_fout->remoteVersion >= 70100)
2789 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
2790 "0::oid AS oprnamespace, "
2791 "(%s oprowner) AS rolname, "
2792 "oprcode::oid AS oprcode "
2798 appendPQExpBuffer(query, "SELECT "
2799 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
2801 "0::oid AS oprnamespace, "
2802 "(%s oprowner) AS rolname, "
2803 "oprcode::oid AS oprcode "
2808 res = PQexec(g_conn, query->data);
2809 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2811 ntups = PQntuples(res);
2814 oprinfo = (OprInfo *) malloc(ntups * sizeof(OprInfo));
2816 i_tableoid = PQfnumber(res, "tableoid");
2817 i_oid = PQfnumber(res, "oid");
2818 i_oprname = PQfnumber(res, "oprname");
2819 i_oprnamespace = PQfnumber(res, "oprnamespace");
2820 i_rolname = PQfnumber(res, "rolname");
2821 i_oprcode = PQfnumber(res, "oprcode");
2823 for (i = 0; i < ntups; i++)
2825 oprinfo[i].dobj.objType = DO_OPERATOR;
2826 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2827 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2828 AssignDumpId(&oprinfo[i].dobj);
2829 oprinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_oprname));
2830 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
2831 oprinfo[i].dobj.catId.oid);
2832 oprinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2833 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
2835 /* Decide whether we want to dump it */
2836 selectDumpableObject(&(oprinfo[i].dobj));
2838 if (strlen(oprinfo[i].rolname) == 0)
2839 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
2840 oprinfo[i].dobj.name);
2845 destroyPQExpBuffer(query);
2852 * read all conversions in the system catalogs and return them in the
2853 * ConvInfo* structure
2855 * numConversions is set to the number of conversions read in
2858 getConversions(int *numConversions)
2863 PQExpBuffer query = createPQExpBuffer();
2871 /* Conversions didn't exist pre-7.3 */
2872 if (g_fout->remoteVersion < 70300)
2874 *numConversions = 0;
2879 * find all conversions, including builtin conversions; we filter out
2880 * system-defined conversions at dump-out time.
2883 /* Make sure we are in proper schema */
2884 selectSourceSchema("pg_catalog");
2886 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
2888 "(%s conowner) AS rolname "
2889 "FROM pg_conversion",
2892 res = PQexec(g_conn, query->data);
2893 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2895 ntups = PQntuples(res);
2896 *numConversions = ntups;
2898 convinfo = (ConvInfo *) malloc(ntups * sizeof(ConvInfo));
2900 i_tableoid = PQfnumber(res, "tableoid");
2901 i_oid = PQfnumber(res, "oid");
2902 i_conname = PQfnumber(res, "conname");
2903 i_connamespace = PQfnumber(res, "connamespace");
2904 i_rolname = PQfnumber(res, "rolname");
2906 for (i = 0; i < ntups; i++)
2908 convinfo[i].dobj.objType = DO_CONVERSION;
2909 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2910 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2911 AssignDumpId(&convinfo[i].dobj);
2912 convinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
2913 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
2914 convinfo[i].dobj.catId.oid);
2915 convinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
2917 /* Decide whether we want to dump it */
2918 selectDumpableObject(&(convinfo[i].dobj));
2923 destroyPQExpBuffer(query);
2930 * read all opclasses in the system catalogs and return them in the
2931 * OpclassInfo* structure
2933 * numOpclasses is set to the number of opclasses read in
2936 getOpclasses(int *numOpclasses)
2941 PQExpBuffer query = createPQExpBuffer();
2942 OpclassInfo *opcinfo;
2950 * find all opclasses, including builtin opclasses; we filter out
2951 * system-defined opclasses at dump-out time.
2954 /* Make sure we are in proper schema */
2955 selectSourceSchema("pg_catalog");
2957 if (g_fout->remoteVersion >= 70300)
2959 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2961 "(%s opcowner) AS rolname "
2965 else if (g_fout->remoteVersion >= 70100)
2967 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
2968 "0::oid AS opcnamespace, "
2969 "''::name AS rolname "
2974 appendPQExpBuffer(query, "SELECT "
2975 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
2977 "0::oid AS opcnamespace, "
2978 "''::name AS rolname "
2982 res = PQexec(g_conn, query->data);
2983 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2985 ntups = PQntuples(res);
2986 *numOpclasses = ntups;
2988 opcinfo = (OpclassInfo *) malloc(ntups * sizeof(OpclassInfo));
2990 i_tableoid = PQfnumber(res, "tableoid");
2991 i_oid = PQfnumber(res, "oid");
2992 i_opcname = PQfnumber(res, "opcname");
2993 i_opcnamespace = PQfnumber(res, "opcnamespace");
2994 i_rolname = PQfnumber(res, "rolname");
2996 for (i = 0; i < ntups; i++)
2998 opcinfo[i].dobj.objType = DO_OPCLASS;
2999 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3000 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3001 AssignDumpId(&opcinfo[i].dobj);
3002 opcinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opcname));
3003 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
3004 opcinfo[i].dobj.catId.oid);
3005 opcinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3007 /* Decide whether we want to dump it */
3008 selectDumpableObject(&(opcinfo[i].dobj));
3010 if (g_fout->remoteVersion >= 70300)
3012 if (strlen(opcinfo[i].rolname) == 0)
3013 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3014 opcinfo[i].dobj.name);
3020 destroyPQExpBuffer(query);
3027 * read all opfamilies in the system catalogs and return them in the
3028 * OpfamilyInfo* structure
3030 * numOpfamilies is set to the number of opfamilies read in
3033 getOpfamilies(int *numOpfamilies)
3039 OpfamilyInfo *opfinfo;
3046 /* Before 8.3, there is no separate concept of opfamilies */
3047 if (g_fout->remoteVersion < 80300)
3053 query = createPQExpBuffer();
3056 * find all opfamilies, including builtin opfamilies; we filter out
3057 * system-defined opfamilies at dump-out time.
3060 /* Make sure we are in proper schema */
3061 selectSourceSchema("pg_catalog");
3063 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3065 "(%s opfowner) AS rolname "
3069 res = PQexec(g_conn, query->data);
3070 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3072 ntups = PQntuples(res);
3073 *numOpfamilies = ntups;
3075 opfinfo = (OpfamilyInfo *) malloc(ntups * sizeof(OpfamilyInfo));
3077 i_tableoid = PQfnumber(res, "tableoid");
3078 i_oid = PQfnumber(res, "oid");
3079 i_opfname = PQfnumber(res, "opfname");
3080 i_opfnamespace = PQfnumber(res, "opfnamespace");
3081 i_rolname = PQfnumber(res, "rolname");
3083 for (i = 0; i < ntups; i++)
3085 opfinfo[i].dobj.objType = DO_OPFAMILY;
3086 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3087 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3088 AssignDumpId(&opfinfo[i].dobj);
3089 opfinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_opfname));
3090 opfinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opfnamespace)),
3091 opfinfo[i].dobj.catId.oid);
3092 opfinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3094 /* Decide whether we want to dump it */
3095 selectDumpableObject(&(opfinfo[i].dobj));
3097 if (g_fout->remoteVersion >= 70300)
3099 if (strlen(opfinfo[i].rolname) == 0)
3100 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3101 opfinfo[i].dobj.name);
3107 destroyPQExpBuffer(query);
3114 * read all the user-defined aggregates in the system catalogs and
3115 * return them in the AggInfo* structure
3117 * numAggs is set to the number of aggregates read in
3120 getAggregates(int *numAggs)
3125 PQExpBuffer query = createPQExpBuffer();
3136 /* Make sure we are in proper schema */
3137 selectSourceSchema("pg_catalog");
3139 /* find all user-defined aggregates */
3141 if (g_fout->remoteVersion >= 80200)
3143 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3144 "pronamespace AS aggnamespace, "
3145 "pronargs, proargtypes, "
3146 "(%s proowner) AS rolname, "
3150 "AND pronamespace != "
3151 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3154 else if (g_fout->remoteVersion >= 70300)
3156 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3157 "pronamespace AS aggnamespace, "
3158 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3160 "(%s proowner) AS rolname, "
3164 "AND pronamespace != "
3165 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3168 else if (g_fout->remoteVersion >= 70100)
3170 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3171 "0::oid AS aggnamespace, "
3172 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3173 "aggbasetype AS proargtypes, "
3174 "(%s aggowner) AS rolname, "
3176 "FROM pg_aggregate "
3177 "where oid > '%u'::oid",
3179 g_last_builtin_oid);
3183 appendPQExpBuffer(query, "SELECT "
3184 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3186 "0::oid AS aggnamespace, "
3187 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3188 "aggbasetype AS proargtypes, "
3189 "(%s aggowner) AS rolname, "
3191 "FROM pg_aggregate "
3192 "where oid > '%u'::oid",
3194 g_last_builtin_oid);
3197 res = PQexec(g_conn, query->data);
3198 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3200 ntups = PQntuples(res);
3203 agginfo = (AggInfo *) malloc(ntups * sizeof(AggInfo));
3205 i_tableoid = PQfnumber(res, "tableoid");
3206 i_oid = PQfnumber(res, "oid");
3207 i_aggname = PQfnumber(res, "aggname");
3208 i_aggnamespace = PQfnumber(res, "aggnamespace");
3209 i_pronargs = PQfnumber(res, "pronargs");
3210 i_proargtypes = PQfnumber(res, "proargtypes");
3211 i_rolname = PQfnumber(res, "rolname");
3212 i_aggacl = PQfnumber(res, "aggacl");
3214 for (i = 0; i < ntups; i++)
3216 agginfo[i].aggfn.dobj.objType = DO_AGG;
3217 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3218 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3219 AssignDumpId(&agginfo[i].aggfn.dobj);
3220 agginfo[i].aggfn.dobj.name = strdup(PQgetvalue(res, i, i_aggname));
3221 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
3222 agginfo[i].aggfn.dobj.catId.oid);
3223 agginfo[i].aggfn.rolname = strdup(PQgetvalue(res, i, i_rolname));
3224 if (strlen(agginfo[i].aggfn.rolname) == 0)
3225 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3226 agginfo[i].aggfn.dobj.name);
3227 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3228 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3229 agginfo[i].aggfn.proacl = strdup(PQgetvalue(res, i, i_aggacl));
3230 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3231 if (agginfo[i].aggfn.nargs == 0)
3232 agginfo[i].aggfn.argtypes = NULL;
3235 agginfo[i].aggfn.argtypes = (Oid *) malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3236 if (g_fout->remoteVersion >= 70300)
3237 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3238 agginfo[i].aggfn.argtypes,
3239 agginfo[i].aggfn.nargs);
3241 /* it's just aggbasetype */
3242 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3245 /* Decide whether we want to dump it */
3246 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3251 destroyPQExpBuffer(query);
3258 * read all the user-defined functions in the system catalogs and
3259 * return them in the FuncInfo* structure
3261 * numFuncs is set to the number of functions read in
3264 getFuncs(int *numFuncs)
3269 PQExpBuffer query = createPQExpBuffer();
3282 /* Make sure we are in proper schema */
3283 selectSourceSchema("pg_catalog");
3285 /* find all user-defined funcs */
3287 if (g_fout->remoteVersion >= 70300)
3289 appendPQExpBuffer(query,
3290 "SELECT tableoid, oid, proname, prolang, "
3291 "pronargs, proargtypes, prorettype, proacl, "
3293 "(%s proowner) AS rolname "
3295 "WHERE NOT proisagg "
3296 "AND pronamespace != "
3297 "(SELECT oid FROM pg_namespace "
3298 "WHERE nspname = 'pg_catalog')",
3301 else if (g_fout->remoteVersion >= 70100)
3303 appendPQExpBuffer(query,
3304 "SELECT tableoid, oid, proname, prolang, "
3305 "pronargs, proargtypes, prorettype, "
3306 "'{=X}' AS proacl, "
3307 "0::oid AS pronamespace, "
3308 "(%s proowner) AS rolname "
3310 "WHERE pg_proc.oid > '%u'::oid",
3312 g_last_builtin_oid);
3316 appendPQExpBuffer(query,
3318 "(SELECT oid FROM pg_class "
3319 " WHERE relname = 'pg_proc') AS tableoid, "
3320 "oid, proname, prolang, "
3321 "pronargs, proargtypes, prorettype, "
3322 "'{=X}' AS proacl, "
3323 "0::oid AS pronamespace, "
3324 "(%s proowner) AS rolname "
3326 "where pg_proc.oid > '%u'::oid",
3328 g_last_builtin_oid);
3331 res = PQexec(g_conn, query->data);
3332 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3334 ntups = PQntuples(res);
3338 finfo = (FuncInfo *) calloc(ntups, sizeof(FuncInfo));
3340 i_tableoid = PQfnumber(res, "tableoid");
3341 i_oid = PQfnumber(res, "oid");
3342 i_proname = PQfnumber(res, "proname");
3343 i_pronamespace = PQfnumber(res, "pronamespace");
3344 i_rolname = PQfnumber(res, "rolname");
3345 i_prolang = PQfnumber(res, "prolang");
3346 i_pronargs = PQfnumber(res, "pronargs");
3347 i_proargtypes = PQfnumber(res, "proargtypes");
3348 i_prorettype = PQfnumber(res, "prorettype");
3349 i_proacl = PQfnumber(res, "proacl");
3351 for (i = 0; i < ntups; i++)
3353 finfo[i].dobj.objType = DO_FUNC;
3354 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3355 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3356 AssignDumpId(&finfo[i].dobj);
3357 finfo[i].dobj.name = strdup(PQgetvalue(res, i, i_proname));
3358 finfo[i].dobj.namespace =
3359 findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
3360 finfo[i].dobj.catId.oid);
3361 finfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3362 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3363 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3364 finfo[i].proacl = strdup(PQgetvalue(res, i, i_proacl));
3365 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3366 if (finfo[i].nargs == 0)
3367 finfo[i].argtypes = NULL;
3370 finfo[i].argtypes = (Oid *) malloc(finfo[i].nargs * sizeof(Oid));
3371 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3372 finfo[i].argtypes, finfo[i].nargs);
3375 /* Decide whether we want to dump it */
3376 selectDumpableObject(&(finfo[i].dobj));
3378 if (strlen(finfo[i].rolname) == 0)
3380 "WARNING: owner of function \"%s\" appears to be invalid\n",
3381 finfo[i].dobj.name);
3386 destroyPQExpBuffer(query);
3393 * read all the user-defined tables (no indexes, no catalogs)
3394 * in the system catalogs return them in the TableInfo* structure
3396 * numTables is set to the number of tables read in
3399 getTables(int *numTables)
3404 PQExpBuffer query = createPQExpBuffer();
3414 int i_relhastriggers;
3421 int i_reltablespace;
3423 int i_toastreloptions;
3426 /* Make sure we are in proper schema */
3427 selectSourceSchema("pg_catalog");
3430 * Find all the tables (including views and sequences).
3432 * We include system catalogs, so that we can work if a user table is
3433 * defined to inherit from a system catalog (pretty weird, but...)
3435 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3436 * (sequence), 'v' (view), or 'c' (composite type).
3438 * Composite-type table entries won't be dumped as such, but we have to
3439 * make a DumpableObject for them so that we can track dependencies of the
3440 * composite type (pg_depend entries for columns of the composite type
3441 * link to the pg_class entry not the pg_type entry).
3443 * Note: in this phase we should collect only a minimal amount of
3444 * information about each table, basically just enough to decide if it is
3445 * interesting. We must fetch all tables in this phase because otherwise
3446 * we cannot correctly identify inherited columns, owned sequences, etc.
3449 if (g_fout->remoteVersion >= 90000)
3452 * Left join to pick up dependency info linking sequences to their
3453 * owning column, if any (note this dependency is AUTO as of 8.2)
3455 appendPQExpBuffer(query,
3456 "SELECT c.tableoid, c.oid, c.relname, "
3457 "c.relacl, c.relkind, c.relnamespace, "
3458 "(%s c.relowner) AS rolname, "
3459 "c.relchecks, c.relhastriggers, "
3460 "c.relhasindex, c.relhasrules, c.relhasoids, "
3462 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3463 "d.refobjid AS owning_tab, "
3464 "d.refobjsubid AS owning_col, "
3465 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3466 "array_to_string(c.reloptions, ', ') AS reloptions, "
3467 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3469 "LEFT JOIN pg_depend d ON "
3470 "(c.relkind = '%c' AND "
3471 "d.classid = c.tableoid AND d.objid = c.oid AND "
3472 "d.objsubid = 0 AND "
3473 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3474 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3475 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3479 RELKIND_RELATION, RELKIND_SEQUENCE,
3480 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3482 else if (g_fout->remoteVersion >= 80400)
3485 * Left join to pick up dependency info linking sequences to their
3486 * owning column, if any (note this dependency is AUTO as of 8.2)
3488 appendPQExpBuffer(query,
3489 "SELECT c.tableoid, c.oid, c.relname, "
3490 "c.relacl, c.relkind, c.relnamespace, "
3491 "(%s c.relowner) AS rolname, "
3492 "c.relchecks, c.relhastriggers, "
3493 "c.relhasindex, c.relhasrules, c.relhasoids, "
3495 "NULL AS reloftype, "
3496 "d.refobjid AS owning_tab, "
3497 "d.refobjsubid AS owning_col, "
3498 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3499 "array_to_string(c.reloptions, ', ') AS reloptions, "
3500 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3502 "LEFT JOIN pg_depend d ON "
3503 "(c.relkind = '%c' AND "
3504 "d.classid = c.tableoid AND d.objid = c.oid AND "
3505 "d.objsubid = 0 AND "
3506 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3507 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3508 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3512 RELKIND_RELATION, RELKIND_SEQUENCE,
3513 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3515 else if (g_fout->remoteVersion >= 80200)
3518 * Left join to pick up dependency info linking sequences to their
3519 * owning column, if any (note this dependency is AUTO as of 8.2)
3521 appendPQExpBuffer(query,
3522 "SELECT c.tableoid, c.oid, relname, "
3523 "relacl, relkind, relnamespace, "
3524 "(%s relowner) AS rolname, "
3525 "relchecks, (reltriggers <> 0) AS relhastriggers, "
3526 "relhasindex, relhasrules, relhasoids, "
3528 "NULL AS reloftype, "
3529 "d.refobjid AS owning_tab, "
3530 "d.refobjsubid AS owning_col, "
3531 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3532 "array_to_string(c.reloptions, ', ') AS reloptions, "
3533 "NULL AS toast_reloptions "
3535 "LEFT JOIN pg_depend d ON "
3536 "(c.relkind = '%c' AND "
3537 "d.classid = c.tableoid AND d.objid = c.oid AND "
3538 "d.objsubid = 0 AND "
3539 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3540 "WHERE relkind in ('%c', '%c', '%c', '%c') "
3544 RELKIND_RELATION, RELKIND_SEQUENCE,
3545 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3547 else if (g_fout->remoteVersion >= 80000)
3550 * Left join to pick up dependency info linking sequences to their
3551 * owning column, if any
3553 appendPQExpBuffer(query,
3554 "SELECT c.tableoid, c.oid, relname, "
3555 "relacl, relkind, relnamespace, "
3556 "(%s relowner) AS rolname, "
3557 "relchecks, (reltriggers <> 0) AS relhastriggers, "
3558 "relhasindex, relhasrules, relhasoids, "
3559 "0 AS relfrozenxid, "
3560 "NULL AS reloftype, "
3561 "d.refobjid AS owning_tab, "
3562 "d.refobjsubid AS owning_col, "
3563 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3564 "NULL AS reloptions, "
3565 "NULL AS toast_reloptions "
3567 "LEFT JOIN pg_depend d ON "
3568 "(c.relkind = '%c' AND "
3569 "d.classid = c.tableoid AND d.objid = c.oid AND "
3570 "d.objsubid = 0 AND "
3571 "d.refclassid = c.tableoid AND d.deptype = 'i') "
3572 "WHERE relkind in ('%c', '%c', '%c', '%c') "
3576 RELKIND_RELATION, RELKIND_SEQUENCE,
3577 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3579 else if (g_fout->remoteVersion >= 70300)
3582 * Left join to pick up dependency info linking sequences to their
3583 * owning column, if any
3585 appendPQExpBuffer(query,
3586 "SELECT c.tableoid, c.oid, relname, "
3587 "relacl, relkind, relnamespace, "
3588 "(%s relowner) AS rolname, "
3589 "relchecks, (reltriggers <> 0) AS relhastriggers, "
3590 "relhasindex, relhasrules, relhasoids, "
3591 "0 AS relfrozenxid, "
3592 "NULL AS reloftype, "
3593 "d.refobjid AS owning_tab, "
3594 "d.refobjsubid AS owning_col, "
3595 "NULL AS reltablespace, "
3596 "NULL AS reloptions, "
3597 "NULL AS toast_reloptions "
3599 "LEFT JOIN pg_depend d ON "
3600 "(c.relkind = '%c' AND "
3601 "d.classid = c.tableoid AND d.objid = c.oid AND "
3602 "d.objsubid = 0 AND "
3603 "d.refclassid = c.tableoid AND d.deptype = 'i') "
3604 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
3608 RELKIND_RELATION, RELKIND_SEQUENCE,
3609 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3611 else if (g_fout->remoteVersion >= 70200)
3613 appendPQExpBuffer(query,
3614 "SELECT tableoid, oid, relname, relacl, relkind, "
3615 "0::oid AS relnamespace, "
3616 "(%s relowner) AS rolname, "
3617 "relchecks, (reltriggers <> 0) AS relhastriggers, "
3618 "relhasindex, relhasrules, relhasoids, "
3619 "0 AS relfrozenxid, "
3620 "NULL AS reloftype, "
3621 "NULL::oid AS owning_tab, "
3622 "NULL::int4 AS owning_col, "
3623 "NULL AS reltablespace, "
3624 "NULL AS reloptions, "
3625 "NULL AS toast_reloptions "
3627 "WHERE relkind IN ('%c', '%c', '%c') "
3630 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
3632 else if (g_fout->remoteVersion >= 70100)
3634 /* all tables have oids in 7.1 */
3635 appendPQExpBuffer(query,
3636 "SELECT tableoid, oid, relname, relacl, relkind, "
3637 "0::oid AS relnamespace, "
3638 "(%s relowner) AS rolname, "
3639 "relchecks, (reltriggers <> 0) AS relhastriggers, "
3640 "relhasindex, relhasrules, "
3641 "'t'::bool AS relhasoids, "
3642 "0 AS relfrozenxid, "
3643 "NULL AS reloftype, "
3644 "NULL::oid AS owning_tab, "
3645 "NULL::int4 AS owning_col, "
3646 "NULL AS reltablespace, "
3647 "NULL AS reloptions, "
3648 "NULL AS toast_reloptions "
3650 "WHERE relkind IN ('%c', '%c', '%c') "
3653 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
3658 * Before 7.1, view relkind was not set to 'v', so we must check if we
3659 * have a view by looking for a rule in pg_rewrite.
3661 appendPQExpBuffer(query,
3663 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
3664 "oid, relname, relacl, "
3665 "CASE WHEN relhasrules and relkind = 'r' "
3666 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
3667 " r.ev_class = c.oid AND r.ev_type = '1') "
3668 "THEN '%c'::\"char\" "
3669 "ELSE relkind END AS relkind,"
3670 "0::oid AS relnamespace, "
3671 "(%s relowner) AS rolname, "
3672 "relchecks, (reltriggers <> 0) AS relhastriggers, "
3673 "relhasindex, relhasrules, "
3674 "'t'::bool AS relhasoids, "
3675 "0 as relfrozenxid, "
3676 "NULL AS reloftype, "
3677 "NULL::oid AS owning_tab, "
3678 "NULL::int4 AS owning_col, "
3679 "NULL AS reltablespace, "
3680 "NULL AS reloptions, "
3681 "NULL AS toast_reloptions "
3683 "WHERE relkind IN ('%c', '%c') "
3687 RELKIND_RELATION, RELKIND_SEQUENCE);
3690 res = PQexec(g_conn, query->data);
3691 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3693 ntups = PQntuples(res);
3698 * Extract data from result and lock dumpable tables. We do the locking
3699 * before anything else, to minimize the window wherein a table could
3700 * disappear under us.
3702 * Note that we have to save info about all tables here, even when dumping
3703 * only one, because we don't yet know which tables might be inheritance
3704 * ancestors of the target table.
3706 tblinfo = (TableInfo *) calloc(ntups, sizeof(TableInfo));
3708 i_reltableoid = PQfnumber(res, "tableoid");
3709 i_reloid = PQfnumber(res, "oid");
3710 i_relname = PQfnumber(res, "relname");
3711 i_relnamespace = PQfnumber(res, "relnamespace");
3712 i_relacl = PQfnumber(res, "relacl");
3713 i_relkind = PQfnumber(res, "relkind");
3714 i_rolname = PQfnumber(res, "rolname");
3715 i_relchecks = PQfnumber(res, "relchecks");
3716 i_relhastriggers = PQfnumber(res, "relhastriggers");
3717 i_relhasindex = PQfnumber(res, "relhasindex");
3718 i_relhasrules = PQfnumber(res, "relhasrules");
3719 i_relhasoids = PQfnumber(res, "relhasoids");
3720 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
3721 i_owning_tab = PQfnumber(res, "owning_tab");
3722 i_owning_col = PQfnumber(res, "owning_col");
3723 i_reltablespace = PQfnumber(res, "reltablespace");
3724 i_reloptions = PQfnumber(res, "reloptions");
3725 i_toastreloptions = PQfnumber(res, "toast_reloptions");
3726 i_reloftype = PQfnumber(res, "reloftype");
3728 if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
3731 * Arrange to fail instead of waiting forever for a table lock.
3733 * NB: this coding assumes that the only queries issued within the
3734 * following loop are LOCK TABLEs; else the timeout may be undesirably
3735 * applied to other things too.
3737 resetPQExpBuffer(query);
3738 appendPQExpBuffer(query, "SET statement_timeout = ");
3739 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
3740 do_sql_command(g_conn, query->data);
3743 for (i = 0; i < ntups; i++)
3745 tblinfo[i].dobj.objType = DO_TABLE;
3746 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
3747 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
3748 AssignDumpId(&tblinfo[i].dobj);
3749 tblinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_relname));
3750 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
3751 tblinfo[i].dobj.catId.oid);
3752 tblinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
3753 tblinfo[i].relacl = strdup(PQgetvalue(res, i, i_relacl));
3754 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
3755 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
3756 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
3757 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
3758 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
3759 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
3760 if (PQgetisnull(res, i, i_reloftype))
3761 tblinfo[i].reloftype = NULL;
3763 tblinfo[i].reloftype = strdup(PQgetvalue(res, i, i_reloftype));
3764 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
3765 if (PQgetisnull(res, i, i_owning_tab))
3767 tblinfo[i].owning_tab = InvalidOid;
3768 tblinfo[i].owning_col = 0;
3772 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
3773 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
3775 tblinfo[i].reltablespace = strdup(PQgetvalue(res, i, i_reltablespace));
3776 tblinfo[i].reloptions = strdup(PQgetvalue(res, i, i_reloptions));
3777 tblinfo[i].toast_reloptions = strdup(PQgetvalue(res, i, i_toastreloptions));
3779 /* other fields were zeroed above */
3782 * Decide whether we want to dump this table.
3784 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
3785 tblinfo[i].dobj.dump = false;
3787 selectDumpableTable(&tblinfo[i]);
3788 tblinfo[i].interesting = tblinfo[i].dobj.dump;
3791 * Read-lock target tables to make sure they aren't DROPPED or altered
3792 * in schema before we get around to dumping them.
3794 * Note that we don't explicitly lock parents of the target tables; we
3795 * assume our lock on the child is enough to prevent schema
3796 * alterations to parent tables.
3798 * NOTE: it'd be kinda nice to lock views and sequences too, not only
3799 * plain tables, but the backend doesn't presently allow that.
3801 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
3803 resetPQExpBuffer(query);
3804 appendPQExpBuffer(query,
3805 "LOCK TABLE %s IN ACCESS SHARE MODE",
3806 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
3807 tblinfo[i].dobj.name));
3808 do_sql_command(g_conn, query->data);
3811 /* Emit notice if join for owner failed */
3812 if (strlen(tblinfo[i].rolname) == 0)
3813 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
3814 tblinfo[i].dobj.name);
3817 if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
3819 do_sql_command(g_conn, "SET statement_timeout = 0");
3825 * Force sequences that are "owned" by table columns to be dumped whenever
3826 * their owning table is being dumped.
3828 for (i = 0; i < ntups; i++)
3830 TableInfo *seqinfo = &tblinfo[i];
3833 if (!OidIsValid(seqinfo->owning_tab))
3834 continue; /* not an owned sequence */
3835 if (seqinfo->dobj.dump)
3836 continue; /* no need to search */
3838 /* can't use findTableByOid yet, unfortunately */
3839 for (j = 0; j < ntups; j++)
3841 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
3843 if (tblinfo[j].dobj.dump)
3845 seqinfo->interesting = true;
3846 seqinfo->dobj.dump = true;
3853 destroyPQExpBuffer(query);
3860 * read all the inheritance information
3861 * from the system catalogs return them in the InhInfo* structure
3863 * numInherits is set to the number of pairs read in
3866 getInherits(int *numInherits)
3871 PQExpBuffer query = createPQExpBuffer();
3877 /* Make sure we are in proper schema */
3878 selectSourceSchema("pg_catalog");
3880 /* find all the inheritance information */
3882 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
3884 res = PQexec(g_conn, query->data);
3885 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3887 ntups = PQntuples(res);
3889 *numInherits = ntups;
3891 inhinfo = (InhInfo *) malloc(ntups * sizeof(InhInfo));
3893 i_inhrelid = PQfnumber(res, "inhrelid");
3894 i_inhparent = PQfnumber(res, "inhparent");
3896 for (i = 0; i < ntups; i++)
3898 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
3899 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
3904 destroyPQExpBuffer(query);
3911 * get information about every index on a dumpable table
3913 * Note: index data is not returned directly to the caller, but it
3914 * does get entered into the DumpableObject tables.
3917 getIndexes(TableInfo tblinfo[], int numTables)
3921 PQExpBuffer query = createPQExpBuffer();
3924 ConstraintInfo *constrinfo;
3943 for (i = 0; i < numTables; i++)
3945 TableInfo *tbinfo = &tblinfo[i];
3947 /* Only plain tables have indexes */
3948 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
3951 /* Ignore indexes of tables not to be dumped */
3952 if (!tbinfo->dobj.dump)
3956 write_msg(NULL, "reading indexes for table \"%s\"\n",
3959 /* Make sure we are in proper schema so indexdef is right */
3960 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
3963 * The point of the messy-looking outer join is to find a constraint
3964 * that is related by an internal dependency link to the index. If we
3965 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
3966 * assume an index won't have more than one internal dependency.
3968 * As of 9.0 we don't need to look at pg_depend but can check for a
3969 * match to pg_constraint.conindid. The check on conrelid is
3970 * redundant but useful because that column is indexed while conindid
3973 resetPQExpBuffer(query);
3974 if (g_fout->remoteVersion >= 90000)
3976 appendPQExpBuffer(query,
3977 "SELECT t.tableoid, t.oid, "
3978 "t.relname AS indexname, "
3979 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
3980 "t.relnatts AS indnkeys, "
3981 "i.indkey, i.indisclustered, "
3982 "c.contype, c.conname, "
3983 "c.condeferrable, c.condeferred, "
3984 "c.tableoid AS contableoid, "
3986 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
3987 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
3988 "array_to_string(t.reloptions, ', ') AS options "
3989 "FROM pg_catalog.pg_index i "
3990 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
3991 "LEFT JOIN pg_catalog.pg_constraint c "
3992 "ON (i.indrelid = c.conrelid AND "
3993 "i.indexrelid = c.conindid AND "
3994 "c.contype IN ('p','u','x')) "
3995 "WHERE i.indrelid = '%u'::pg_catalog.oid "
3996 "ORDER BY indexname",
3997 tbinfo->dobj.catId.oid);
3999 else if (g_fout->remoteVersion >= 80200)
4001 appendPQExpBuffer(query,
4002 "SELECT t.tableoid, t.oid, "
4003 "t.relname AS indexname, "
4004 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4005 "t.relnatts AS indnkeys, "
4006 "i.indkey, i.indisclustered, "
4007 "c.contype, c.conname, "
4008 "c.condeferrable, c.condeferred, "
4009 "c.tableoid AS contableoid, "
4012 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4013 "array_to_string(t.reloptions, ', ') AS options "
4014 "FROM pg_catalog.pg_index i "
4015 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4016 "LEFT JOIN pg_catalog.pg_depend d "
4017 "ON (d.classid = t.tableoid "
4018 "AND d.objid = t.oid "
4019 "AND d.deptype = 'i') "
4020 "LEFT JOIN pg_catalog.pg_constraint c "
4021 "ON (d.refclassid = c.tableoid "
4022 "AND d.refobjid = c.oid) "
4023 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4024 "ORDER BY indexname",
4025 tbinfo->dobj.catId.oid);
4027 else if (g_fout->remoteVersion >= 80000)
4029 appendPQExpBuffer(query,
4030 "SELECT t.tableoid, t.oid, "
4031 "t.relname AS indexname, "
4032 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4033 "t.relnatts AS indnkeys, "
4034 "i.indkey, i.indisclustered, "
4035 "c.contype, c.conname, "
4036 "c.condeferrable, c.condeferred, "
4037 "c.tableoid AS contableoid, "
4040 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4042 "FROM pg_catalog.pg_index i "
4043 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4044 "LEFT JOIN pg_catalog.pg_depend d "
4045 "ON (d.classid = t.tableoid "
4046 "AND d.objid = t.oid "
4047 "AND d.deptype = 'i') "
4048 "LEFT JOIN pg_catalog.pg_constraint c "
4049 "ON (d.refclassid = c.tableoid "
4050 "AND d.refobjid = c.oid) "
4051 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4052 "ORDER BY indexname",
4053 tbinfo->dobj.catId.oid);
4055 else if (g_fout->remoteVersion >= 70300)
4057 appendPQExpBuffer(query,
4058 "SELECT t.tableoid, t.oid, "
4059 "t.relname AS indexname, "
4060 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4061 "t.relnatts AS indnkeys, "
4062 "i.indkey, i.indisclustered, "
4063 "c.contype, c.conname, "
4064 "c.condeferrable, c.condeferred, "
4065 "c.tableoid AS contableoid, "
4068 "NULL AS tablespace, "
4070 "FROM pg_catalog.pg_index i "
4071 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4072 "LEFT JOIN pg_catalog.pg_depend d "
4073 "ON (d.classid = t.tableoid "
4074 "AND d.objid = t.oid "
4075 "AND d.deptype = 'i') "
4076 "LEFT JOIN pg_catalog.pg_constraint c "
4077 "ON (d.refclassid = c.tableoid "
4078 "AND d.refobjid = c.oid) "
4079 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4080 "ORDER BY indexname",
4081 tbinfo->dobj.catId.oid);
4083 else if (g_fout->remoteVersion >= 70100)
4085 appendPQExpBuffer(query,
4086 "SELECT t.tableoid, t.oid, "
4087 "t.relname AS indexname, "
4088 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4089 "t.relnatts AS indnkeys, "
4090 "i.indkey, false AS indisclustered, "
4091 "CASE WHEN i.indisprimary THEN 'p'::char "
4092 "ELSE '0'::char END AS contype, "
4093 "t.relname AS conname, "
4094 "false AS condeferrable, "
4095 "false AS condeferred, "
4096 "0::oid AS contableoid, "
4099 "NULL AS tablespace, "
4101 "FROM pg_index i, pg_class t "
4102 "WHERE t.oid = i.indexrelid "
4103 "AND i.indrelid = '%u'::oid "
4104 "ORDER BY indexname",
4105 tbinfo->dobj.catId.oid);
4109 appendPQExpBuffer(query,
4111 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4113 "t.relname AS indexname, "
4114 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4115 "t.relnatts AS indnkeys, "
4116 "i.indkey, false AS indisclustered, "
4117 "CASE WHEN i.indisprimary THEN 'p'::char "
4118 "ELSE '0'::char END AS contype, "
4119 "t.relname AS conname, "
4120 "false AS condeferrable, "
4121 "false AS condeferred, "
4122 "0::oid AS contableoid, "
4125 "NULL AS tablespace, "
4127 "FROM pg_index i, pg_class t "
4128 "WHERE t.oid = i.indexrelid "
4129 "AND i.indrelid = '%u'::oid "
4130 "ORDER BY indexname",
4131 tbinfo->dobj.catId.oid);
4134 res = PQexec(g_conn, query->data);
4135 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4137 ntups = PQntuples(res);
4139 i_tableoid = PQfnumber(res, "tableoid");
4140 i_oid = PQfnumber(res, "oid");
4141 i_indexname = PQfnumber(res, "indexname");
4142 i_indexdef = PQfnumber(res, "indexdef");
4143 i_indnkeys = PQfnumber(res, "indnkeys");
4144 i_indkey = PQfnumber(res, "indkey");
4145 i_indisclustered = PQfnumber(res, "indisclustered");
4146 i_contype = PQfnumber(res, "contype");
4147 i_conname = PQfnumber(res, "conname");
4148 i_condeferrable = PQfnumber(res, "condeferrable");
4149 i_condeferred = PQfnumber(res, "condeferred");
4150 i_contableoid = PQfnumber(res, "contableoid");
4151 i_conoid = PQfnumber(res, "conoid");
4152 i_condef = PQfnumber(res, "condef");
4153 i_tablespace = PQfnumber(res, "tablespace");
4154 i_options = PQfnumber(res, "options");
4156 indxinfo = (IndxInfo *) malloc(ntups * sizeof(IndxInfo));
4157 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
4159 for (j = 0; j < ntups; j++)
4163 indxinfo[j].dobj.objType = DO_INDEX;
4164 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4165 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4166 AssignDumpId(&indxinfo[j].dobj);
4167 indxinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_indexname));
4168 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4169 indxinfo[j].indextable = tbinfo;
4170 indxinfo[j].indexdef = strdup(PQgetvalue(res, j, i_indexdef));
4171 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4172 indxinfo[j].tablespace = strdup(PQgetvalue(res, j, i_tablespace));
4173 indxinfo[j].options = strdup(PQgetvalue(res, j, i_options));
4176 * In pre-7.4 releases, indkeys may contain more entries than
4177 * indnkeys says (since indnkeys will be 1 for a functional
4178 * index). We don't actually care about this case since we don't
4179 * examine indkeys except for indexes associated with PRIMARY and
4180 * UNIQUE constraints, which are never functional indexes. But we
4181 * have to allocate enough space to keep parseOidArray from
4184 indxinfo[j].indkeys = (Oid *) malloc(INDEX_MAX_KEYS * sizeof(Oid));
4185 parseOidArray(PQgetvalue(res, j, i_indkey),
4186 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4187 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4188 contype = *(PQgetvalue(res, j, i_contype));
4190 if (contype == 'p' || contype == 'u' || contype == 'x')
4193 * If we found a constraint matching the index, create an
4196 * In a pre-7.3 database, we take this path iff the index was
4197 * marked indisprimary.
4199 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4200 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4201 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4202 AssignDumpId(&constrinfo[j].dobj);
4203 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
4204 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4205 constrinfo[j].contable = tbinfo;
4206 constrinfo[j].condomain = NULL;
4207 constrinfo[j].contype = contype;
4209 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
4211 constrinfo[j].condef = NULL;
4212 constrinfo[j].confrelid = InvalidOid;
4213 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4214 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4215 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4216 constrinfo[j].conislocal = true;
4217 constrinfo[j].separate = true;
4219 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4221 /* If pre-7.3 DB, better make sure table comes first */
4222 addObjectDependency(&constrinfo[j].dobj,
4223 tbinfo->dobj.dumpId);
4227 /* Plain secondary index */
4228 indxinfo[j].indexconstraint = 0;
4235 destroyPQExpBuffer(query);
4241 * Get info about constraints on dumpable tables.
4243 * Currently handles foreign keys only.
4244 * Unique and primary key constraints are handled with indexes,
4245 * while check constraints are processed in getTableAttrs().
4248 getConstraints(TableInfo tblinfo[], int numTables)
4252 ConstraintInfo *constrinfo;
4262 /* pg_constraint was created in 7.3, so nothing to do if older */
4263 if (g_fout->remoteVersion < 70300)
4266 query = createPQExpBuffer();
4268 for (i = 0; i < numTables; i++)
4270 TableInfo *tbinfo = &tblinfo[i];
4272 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4276 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4280 * select table schema to ensure constraint expr is qualified if
4283 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4285 resetPQExpBuffer(query);
4286 appendPQExpBuffer(query,
4287 "SELECT tableoid, oid, conname, confrelid, "
4288 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4289 "FROM pg_catalog.pg_constraint "
4290 "WHERE conrelid = '%u'::pg_catalog.oid "
4291 "AND contype = 'f'",
4292 tbinfo->dobj.catId.oid);
4293 res = PQexec(g_conn, query->data);
4294 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4296 ntups = PQntuples(res);
4298 i_contableoid = PQfnumber(res, "tableoid");
4299 i_conoid = PQfnumber(res, "oid");
4300 i_conname = PQfnumber(res, "conname");
4301 i_confrelid = PQfnumber(res, "confrelid");
4302 i_condef = PQfnumber(res, "condef");
4304 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
4306 for (j = 0; j < ntups; j++)
4308 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4309 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4310 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4311 AssignDumpId(&constrinfo[j].dobj);
4312 constrinfo[j].dobj.name = strdup(PQgetvalue(res, j, i_conname));
4313 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4314 constrinfo[j].contable = tbinfo;
4315 constrinfo[j].condomain = NULL;
4316 constrinfo[j].contype = 'f';
4317 constrinfo[j].condef = strdup(PQgetvalue(res, j, i_condef));
4318 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4319 constrinfo[j].conindex = 0;
4320 constrinfo[j].condeferrable = false;
4321 constrinfo[j].condeferred = false;
4322 constrinfo[j].conislocal = true;
4323 constrinfo[j].separate = true;
4329 destroyPQExpBuffer(query);
4333 * getDomainConstraints
4335 * Get info about constraints on a domain.
4338 getDomainConstraints(TypeInfo *tyinfo)
4341 ConstraintInfo *constrinfo;
4350 /* pg_constraint was created in 7.3, so nothing to do if older */
4351 if (g_fout->remoteVersion < 70300)
4355 * select appropriate schema to ensure names in constraint are properly
4358 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
4360 query = createPQExpBuffer();
4362 if (g_fout->remoteVersion >= 70400)
4363 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4364 "pg_catalog.pg_get_constraintdef(oid) AS consrc "
4365 "FROM pg_catalog.pg_constraint "
4366 "WHERE contypid = '%u'::pg_catalog.oid "
4368 tyinfo->dobj.catId.oid);
4370 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4371 "'CHECK (' || consrc || ')' AS consrc "
4372 "FROM pg_catalog.pg_constraint "
4373 "WHERE contypid = '%u'::pg_catalog.oid "
4375 tyinfo->dobj.catId.oid);
4377 res = PQexec(g_conn, query->data);
4378 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4380 ntups = PQntuples(res);
4382 i_tableoid = PQfnumber(res, "tableoid");
4383 i_oid = PQfnumber(res, "oid");
4384 i_conname = PQfnumber(res, "conname");
4385 i_consrc = PQfnumber(res, "consrc");
4387 constrinfo = (ConstraintInfo *) malloc(ntups * sizeof(ConstraintInfo));
4389 tyinfo->nDomChecks = ntups;
4390 tyinfo->domChecks = constrinfo;
4392 for (i = 0; i < ntups; i++)
4394 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4395 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4396 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4397 AssignDumpId(&constrinfo[i].dobj);
4398 constrinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_conname));
4399 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4400 constrinfo[i].contable = NULL;
4401 constrinfo[i].condomain = tyinfo;
4402 constrinfo[i].contype = 'c';
4403 constrinfo[i].condef = strdup(PQgetvalue(res, i, i_consrc));
4404 constrinfo[i].confrelid = InvalidOid;
4405 constrinfo[i].conindex = 0;
4406 constrinfo[i].condeferrable = false;
4407 constrinfo[i].condeferred = false;
4408 constrinfo[i].conislocal = true;
4409 constrinfo[i].separate = false;
4412 * Make the domain depend on the constraint, ensuring it won't be
4413 * output till any constraint dependencies are OK.
4415 addObjectDependency(&tyinfo->dobj,
4416 constrinfo[i].dobj.dumpId);
4421 destroyPQExpBuffer(query);
4426 * get basic information about every rule in the system
4428 * numRules is set to the number of rules read in
4431 getRules(int *numRules)
4436 PQExpBuffer query = createPQExpBuffer();
4446 /* Make sure we are in proper schema */
4447 selectSourceSchema("pg_catalog");
4449 if (g_fout->remoteVersion >= 80300)
4451 appendPQExpBuffer(query, "SELECT "
4452 "tableoid, oid, rulename, "
4453 "ev_class AS ruletable, ev_type, is_instead, "
4458 else if (g_fout->remoteVersion >= 70100)
4460 appendPQExpBuffer(query, "SELECT "
4461 "tableoid, oid, rulename, "
4462 "ev_class AS ruletable, ev_type, is_instead, "
4463 "'O'::char AS ev_enabled "
4469 appendPQExpBuffer(query, "SELECT "
4470 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4472 "ev_class AS ruletable, ev_type, is_instead, "
4473 "'O'::char AS ev_enabled "
4478 res = PQexec(g_conn, query->data);
4479 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4481 ntups = PQntuples(res);
4485 ruleinfo = (RuleInfo *) malloc(ntups * sizeof(RuleInfo));
4487 i_tableoid = PQfnumber(res, "tableoid");
4488 i_oid = PQfnumber(res, "oid");
4489 i_rulename = PQfnumber(res, "rulename");
4490 i_ruletable = PQfnumber(res, "ruletable");
4491 i_ev_type = PQfnumber(res, "ev_type");
4492 i_is_instead = PQfnumber(res, "is_instead");
4493 i_ev_enabled = PQfnumber(res, "ev_enabled");
4495 for (i = 0; i < ntups; i++)
4499 ruleinfo[i].dobj.objType = DO_RULE;
4500 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4501 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4502 AssignDumpId(&ruleinfo[i].dobj);
4503 ruleinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_rulename));
4504 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
4505 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
4506 if (ruleinfo[i].ruletable == NULL)
4508 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
4510 ruleinfo[i].dobj.catId.oid);
4513 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
4514 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
4515 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
4516 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
4517 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
4518 if (ruleinfo[i].ruletable)
4521 * If the table is a view, force its ON SELECT rule to be sorted
4522 * before the view itself --- this ensures that any dependencies
4523 * for the rule affect the table's positioning. Other rules are
4524 * forced to appear after their table.
4526 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
4527 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
4529 addObjectDependency(&ruleinfo[i].ruletable->dobj,
4530 ruleinfo[i].dobj.dumpId);
4531 /* We'll merge the rule into CREATE VIEW, if possible */
4532 ruleinfo[i].separate = false;
4536 addObjectDependency(&ruleinfo[i].dobj,
4537 ruleinfo[i].ruletable->dobj.dumpId);
4538 ruleinfo[i].separate = true;
4542 ruleinfo[i].separate = true;
4547 destroyPQExpBuffer(query);
4554 * get information about every trigger on a dumpable table
4556 * Note: trigger data is not returned directly to the caller, but it
4557 * does get entered into the DumpableObject tables.
4560 getTriggers(TableInfo tblinfo[], int numTables)
4564 PQExpBuffer query = createPQExpBuffer();
4566 TriggerInfo *tginfo;
4584 for (i = 0; i < numTables; i++)
4586 TableInfo *tbinfo = &tblinfo[i];
4588 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4592 write_msg(NULL, "reading triggers for table \"%s\"\n",
4596 * select table schema to ensure regproc name is qualified if needed
4598 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4600 resetPQExpBuffer(query);
4601 if (g_fout->remoteVersion >= 90000)
4604 * NB: think not to use pretty=true in pg_get_triggerdef. It
4605 * could result in non-forward-compatible dumps of WHEN clauses
4606 * due to under-parenthesization.
4608 appendPQExpBuffer(query,
4610 "tgfoid::pg_catalog.regproc AS tgfname, "
4611 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
4612 "tgenabled, tableoid, oid "
4613 "FROM pg_catalog.pg_trigger t "
4614 "WHERE tgrelid = '%u'::pg_catalog.oid "
4615 "AND NOT tgisinternal",
4616 tbinfo->dobj.catId.oid);
4618 else if (g_fout->remoteVersion >= 80300)
4621 * We ignore triggers that are tied to a foreign-key constraint
4623 appendPQExpBuffer(query,
4625 "tgfoid::pg_catalog.regproc AS tgfname, "
4626 "tgtype, tgnargs, tgargs, tgenabled, "
4627 "tgisconstraint, tgconstrname, tgdeferrable, "
4628 "tgconstrrelid, tginitdeferred, tableoid, oid, "
4629 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
4630 "FROM pg_catalog.pg_trigger t "
4631 "WHERE tgrelid = '%u'::pg_catalog.oid "
4632 "AND tgconstraint = 0",
4633 tbinfo->dobj.catId.oid);
4635 else if (g_fout->remoteVersion >= 70300)
4638 * We ignore triggers that are tied to a foreign-key constraint,
4639 * but in these versions we have to grovel through pg_constraint
4642 appendPQExpBuffer(query,
4644 "tgfoid::pg_catalog.regproc AS tgfname, "
4645 "tgtype, tgnargs, tgargs, tgenabled, "
4646 "tgisconstraint, tgconstrname, tgdeferrable, "
4647 "tgconstrrelid, tginitdeferred, tableoid, oid, "
4648 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
4649 "FROM pg_catalog.pg_trigger t "
4650 "WHERE tgrelid = '%u'::pg_catalog.oid "
4651 "AND (NOT tgisconstraint "
4653 " (SELECT 1 FROM pg_catalog.pg_depend d "
4654 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
4655 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
4656 tbinfo->dobj.catId.oid);
4658 else if (g_fout->remoteVersion >= 70100)
4660 appendPQExpBuffer(query,
4661 "SELECT tgname, tgfoid::regproc AS tgfname, "
4662 "tgtype, tgnargs, tgargs, tgenabled, "
4663 "tgisconstraint, tgconstrname, tgdeferrable, "
4664 "tgconstrrelid, tginitdeferred, tableoid, oid, "
4665 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
4666 " AS tgconstrrelname "
4668 "WHERE tgrelid = '%u'::oid",
4669 tbinfo->dobj.catId.oid);
4673 appendPQExpBuffer(query,
4674 "SELECT tgname, tgfoid::regproc AS tgfname, "
4675 "tgtype, tgnargs, tgargs, tgenabled, "
4676 "tgisconstraint, tgconstrname, tgdeferrable, "
4677 "tgconstrrelid, tginitdeferred, "
4678 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
4680 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
4681 " AS tgconstrrelname "
4683 "WHERE tgrelid = '%u'::oid",
4684 tbinfo->dobj.catId.oid);
4686 res = PQexec(g_conn, query->data);
4687 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4689 ntups = PQntuples(res);
4691 i_tableoid = PQfnumber(res, "tableoid");
4692 i_oid = PQfnumber(res, "oid");
4693 i_tgname = PQfnumber(res, "tgname");
4694 i_tgfname = PQfnumber(res, "tgfname");
4695 i_tgtype = PQfnumber(res, "tgtype");
4696 i_tgnargs = PQfnumber(res, "tgnargs");
4697 i_tgargs = PQfnumber(res, "tgargs");
4698 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
4699 i_tgconstrname = PQfnumber(res, "tgconstrname");
4700 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
4701 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
4702 i_tgenabled = PQfnumber(res, "tgenabled");
4703 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
4704 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
4705 i_tgdef = PQfnumber(res, "tgdef");
4707 tginfo = (TriggerInfo *) malloc(ntups * sizeof(TriggerInfo));
4709 for (j = 0; j < ntups; j++)
4711 tginfo[j].dobj.objType = DO_TRIGGER;
4712 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4713 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4714 AssignDumpId(&tginfo[j].dobj);
4715 tginfo[j].dobj.name = strdup(PQgetvalue(res, j, i_tgname));
4716 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
4717 tginfo[j].tgtable = tbinfo;
4718 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
4721 tginfo[j].tgdef = strdup(PQgetvalue(res, j, i_tgdef));
4723 /* remaining fields are not valid if we have tgdef */
4724 tginfo[j].tgfname = NULL;
4725 tginfo[j].tgtype = 0;
4726 tginfo[j].tgnargs = 0;
4727 tginfo[j].tgargs = NULL;
4728 tginfo[j].tgisconstraint = false;
4729 tginfo[j].tgdeferrable = false;
4730 tginfo[j].tginitdeferred = false;
4731 tginfo[j].tgconstrname = NULL;
4732 tginfo[j].tgconstrrelid = InvalidOid;
4733 tginfo[j].tgconstrrelname = NULL;
4737 tginfo[j].tgdef = NULL;
4739 tginfo[j].tgfname = strdup(PQgetvalue(res, j, i_tgfname));
4740 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
4741 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
4742 tginfo[j].tgargs = strdup(PQgetvalue(res, j, i_tgargs));
4743 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
4744 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
4745 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
4747 if (tginfo[j].tgisconstraint)
4749 tginfo[j].tgconstrname = strdup(PQgetvalue(res, j, i_tgconstrname));
4750 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
4751 if (OidIsValid(tginfo[j].tgconstrrelid))
4753 if (PQgetisnull(res, j, i_tgconstrrelname))
4755 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
4756 tginfo[j].dobj.name, tbinfo->dobj.name,
4757 tginfo[j].tgconstrrelid);
4760 tginfo[j].tgconstrrelname = strdup(PQgetvalue(res, j, i_tgconstrrelname));
4763 tginfo[j].tgconstrrelname = NULL;
4767 tginfo[j].tgconstrname = NULL;
4768 tginfo[j].tgconstrrelid = InvalidOid;
4769 tginfo[j].tgconstrrelname = NULL;
4777 destroyPQExpBuffer(query);
4782 * get basic information about every procedural language in the system
4784 * numProcLangs is set to the number of langs read in
4786 * NB: this must run after getFuncs() because we assume we can do
4790 getProcLangs(int *numProcLangs)
4795 PQExpBuffer query = createPQExpBuffer();
4796 ProcLangInfo *planginfo;
4801 int i_lanplcallfoid;
4807 /* Make sure we are in proper schema */
4808 selectSourceSchema("pg_catalog");
4810 if (g_fout->remoteVersion >= 90000)
4812 /* pg_language has a laninline column */
4813 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4814 "lanname, lanpltrusted, lanplcallfoid, "
4815 "laninline, lanvalidator, lanacl, "
4816 "(%s lanowner) AS lanowner "
4822 else if (g_fout->remoteVersion >= 80300)
4824 /* pg_language has a lanowner column */
4825 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4826 "lanname, lanpltrusted, lanplcallfoid, "
4827 "lanvalidator, lanacl, "
4828 "(%s lanowner) AS lanowner "
4834 else if (g_fout->remoteVersion >= 80100)
4836 /* Languages are owned by the bootstrap superuser, OID 10 */
4837 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
4838 "(%s '10') AS lanowner "
4844 else if (g_fout->remoteVersion >= 70400)
4846 /* Languages are owned by the bootstrap superuser, sysid 1 */
4847 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
4848 "(%s '1') AS lanowner "
4854 else if (g_fout->remoteVersion >= 70100)
4856 /* No clear notion of an owner at all before 7.4 ... */
4857 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
4863 appendPQExpBuffer(query, "SELECT "
4864 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
4865 "oid, * FROM pg_language "
4870 res = PQexec(g_conn, query->data);
4871 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4873 ntups = PQntuples(res);
4875 *numProcLangs = ntups;
4877 planginfo = (ProcLangInfo *) malloc(ntups * sizeof(ProcLangInfo));
4879 i_tableoid = PQfnumber(res, "tableoid");
4880 i_oid = PQfnumber(res, "oid");
4881 i_lanname = PQfnumber(res, "lanname");
4882 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
4883 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
4884 /* these may fail and return -1: */
4885 i_laninline = PQfnumber(res, "laninline");
4886 i_lanvalidator = PQfnumber(res, "lanvalidator");
4887 i_lanacl = PQfnumber(res, "lanacl");
4888 i_lanowner = PQfnumber(res, "lanowner");
4890 for (i = 0; i < ntups; i++)
4892 planginfo[i].dobj.objType = DO_PROCLANG;
4893 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4894 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4895 AssignDumpId(&planginfo[i].dobj);
4897 planginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_lanname));
4898 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
4899 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
4900 if (i_laninline >= 0)
4901 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
4903 planginfo[i].laninline = InvalidOid;
4904 if (i_lanvalidator >= 0)
4905 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
4907 planginfo[i].lanvalidator = InvalidOid;
4909 planginfo[i].lanacl = strdup(PQgetvalue(res, i, i_lanacl));
4911 planginfo[i].lanacl = strdup("{=U}");
4912 if (i_lanowner >= 0)
4913 planginfo[i].lanowner = strdup(PQgetvalue(res, i, i_lanowner));
4915 planginfo[i].lanowner = strdup("");
4917 if (g_fout->remoteVersion < 70300)
4920 * We need to make a dependency to ensure the function will be
4921 * dumped first. (In 7.3 and later the regular dependency
4922 * mechanism will handle this for us.)
4924 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
4927 addObjectDependency(&planginfo[i].dobj,
4928 funcInfo->dobj.dumpId);
4934 destroyPQExpBuffer(query);
4941 * get basic information about every cast in the system
4943 * numCasts is set to the number of casts read in
4946 getCasts(int *numCasts)
4951 PQExpBuffer query = createPQExpBuffer();
4961 /* Make sure we are in proper schema */
4962 selectSourceSchema("pg_catalog");
4964 if (g_fout->remoteVersion >= 80400)
4966 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4967 "castsource, casttarget, castfunc, castcontext, "
4969 "FROM pg_cast ORDER BY 3,4");
4971 else if (g_fout->remoteVersion >= 70300)
4973 appendPQExpBuffer(query, "SELECT tableoid, oid, "
4974 "castsource, casttarget, castfunc, castcontext, "
4975 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
4976 "FROM pg_cast ORDER BY 3,4");
4980 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
4981 "t1.oid AS castsource, t2.oid AS casttarget, "
4982 "p.oid AS castfunc, 'e' AS castcontext, "
4983 "'f' AS castmethod "
4984 "FROM pg_type t1, pg_type t2, pg_proc p "
4985 "WHERE p.pronargs = 1 AND "
4986 "p.proargtypes[0] = t1.oid AND "
4987 "p.prorettype = t2.oid AND p.proname = t2.typname "
4991 res = PQexec(g_conn, query->data);
4992 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4994 ntups = PQntuples(res);
4998 castinfo = (CastInfo *) malloc(ntups * sizeof(CastInfo));
5000 i_tableoid = PQfnumber(res, "tableoid");
5001 i_oid = PQfnumber(res, "oid");
5002 i_castsource = PQfnumber(res, "castsource");
5003 i_casttarget = PQfnumber(res, "casttarget");
5004 i_castfunc = PQfnumber(res, "castfunc");
5005 i_castcontext = PQfnumber(res, "castcontext");
5006 i_castmethod = PQfnumber(res, "castmethod");
5008 for (i = 0; i < ntups; i++)
5010 PQExpBufferData namebuf;
5011 TypeInfo *sTypeInfo;
5012 TypeInfo *tTypeInfo;
5014 castinfo[i].dobj.objType = DO_CAST;
5015 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5016 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5017 AssignDumpId(&castinfo[i].dobj);
5018 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5019 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5020 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5021 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5022 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5025 * Try to name cast as concatenation of typnames. This is only used
5026 * for purposes of sorting. If we fail to find either type, the name
5027 * will be an empty string.
5029 initPQExpBuffer(&namebuf);
5030 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5031 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5032 if (sTypeInfo && tTypeInfo)
5033 appendPQExpBuffer(&namebuf, "%s %s",
5034 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5035 castinfo[i].dobj.name = namebuf.data;
5037 if (OidIsValid(castinfo[i].castfunc))
5040 * We need to make a dependency to ensure the function will be
5041 * dumped first. (In 7.3 and later the regular dependency
5042 * mechanism will handle this for us.)
5046 funcInfo = findFuncByOid(castinfo[i].castfunc);
5048 addObjectDependency(&castinfo[i].dobj,
5049 funcInfo->dobj.dumpId);
5055 destroyPQExpBuffer(query);
5062 * for each interesting table, read info about its attributes
5063 * (names, types, default values, CHECK constraints, etc)
5065 * This is implemented in a very inefficient way right now, looping
5066 * through the tblinfo and doing a join per table to find the attrs and their
5067 * types. However, because we want type names and so forth to be named
5068 * relative to the schema of each table, we couldn't do it in just one
5069 * query. (Maybe one query per schema?)
5074 getTableAttrs(TableInfo *tblinfo, int numTables)
5078 PQExpBuffer q = createPQExpBuffer();
5083 int i_attstattarget;
5097 for (i = 0; i < numTables; i++)
5099 TableInfo *tbinfo = &tblinfo[i];
5101 /* Don't bother to collect info for sequences */
5102 if (tbinfo->relkind == RELKIND_SEQUENCE)
5105 /* Don't bother with uninteresting tables, either */
5106 if (!tbinfo->interesting)
5110 * Make sure we are in proper schema for this table; this allows
5111 * correct retrieval of formatted type names and default exprs
5113 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
5115 /* find all the user attributes and their types */
5118 * we must read the attribute names in attribute number order! because
5119 * we will use the attnum to index into the attnames array later. We
5120 * actually ask to order by "attrelid, attnum" because (at least up to
5121 * 7.3) the planner is not smart enough to realize it needn't re-sort
5122 * the output of an indexscan on pg_attribute_relid_attnum_index.
5125 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5128 resetPQExpBuffer(q);
5130 if (g_fout->remoteVersion >= 90000)
5132 /* attoptions is new in 9.0 */
5133 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5134 "a.attstattarget, a.attstorage, t.typstorage, "
5135 "a.attnotnull, a.atthasdef, a.attisdropped, "
5136 "a.attlen, a.attalign, a.attislocal, "
5137 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5138 "array_to_string(attoptions, ', ') AS attoptions "
5139 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5140 "ON a.atttypid = t.oid "
5141 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5142 "AND a.attnum > 0::pg_catalog.int2 "
5143 "ORDER BY a.attrelid, a.attnum",
5144 tbinfo->dobj.catId.oid);
5146 else if (g_fout->remoteVersion >= 70300)
5148 /* need left join here to not fail on dropped columns ... */
5149 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5150 "a.attstattarget, a.attstorage, t.typstorage, "
5151 "a.attnotnull, a.atthasdef, a.attisdropped, "
5152 "a.attlen, a.attalign, a.attislocal, "
5153 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5155 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5156 "ON a.atttypid = t.oid "
5157 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5158 "AND a.attnum > 0::pg_catalog.int2 "
5159 "ORDER BY a.attrelid, a.attnum",
5160 tbinfo->dobj.catId.oid);
5162 else if (g_fout->remoteVersion >= 70100)
5165 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5166 * we don't dump it because we can't tell whether it's been
5167 * explicitly set or was just a default.
5169 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5170 "-1 AS attstattarget, a.attstorage, "
5171 "t.typstorage, a.attnotnull, a.atthasdef, "
5172 "false AS attisdropped, a.attlen, "
5173 "a.attalign, false AS attislocal, "
5174 "format_type(t.oid,a.atttypmod) AS atttypname, "
5176 "FROM pg_attribute a LEFT JOIN pg_type t "
5177 "ON a.atttypid = t.oid "
5178 "WHERE a.attrelid = '%u'::oid "
5179 "AND a.attnum > 0::int2 "
5180 "ORDER BY a.attrelid, a.attnum",
5181 tbinfo->dobj.catId.oid);
5185 /* format_type not available before 7.1 */
5186 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5187 "-1 AS attstattarget, "
5188 "attstorage, attstorage AS typstorage, "
5189 "attnotnull, atthasdef, false AS attisdropped, "
5190 "attlen, attalign, "
5191 "false AS attislocal, "
5192 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5194 "FROM pg_attribute a "
5195 "WHERE attrelid = '%u'::oid "
5196 "AND attnum > 0::int2 "
5197 "ORDER BY attrelid, attnum",
5198 tbinfo->dobj.catId.oid);
5201 res = PQexec(g_conn, q->data);
5202 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5204 ntups = PQntuples(res);
5206 i_attnum = PQfnumber(res, "attnum");
5207 i_attname = PQfnumber(res, "attname");
5208 i_atttypname = PQfnumber(res, "atttypname");
5209 i_atttypmod = PQfnumber(res, "atttypmod");
5210 i_attstattarget = PQfnumber(res, "attstattarget");
5211 i_attstorage = PQfnumber(res, "attstorage");
5212 i_typstorage = PQfnumber(res, "typstorage");
5213 i_attnotnull = PQfnumber(res, "attnotnull");
5214 i_atthasdef = PQfnumber(res, "atthasdef");
5215 i_attisdropped = PQfnumber(res, "attisdropped");
5216 i_attlen = PQfnumber(res, "attlen");
5217 i_attalign = PQfnumber(res, "attalign");
5218 i_attislocal = PQfnumber(res, "attislocal");
5219 i_attoptions = PQfnumber(res, "attoptions");
5221 tbinfo->numatts = ntups;
5222 tbinfo->attnames = (char **) malloc(ntups * sizeof(char *));
5223 tbinfo->atttypnames = (char **) malloc(ntups * sizeof(char *));
5224 tbinfo->atttypmod = (int *) malloc(ntups * sizeof(int));
5225 tbinfo->attstattarget = (int *) malloc(ntups * sizeof(int));
5226 tbinfo->attstorage = (char *) malloc(ntups * sizeof(char));
5227 tbinfo->typstorage = (char *) malloc(ntups * sizeof(char));
5228 tbinfo->attisdropped = (bool *) malloc(ntups * sizeof(bool));
5229 tbinfo->attlen = (int *) malloc(ntups * sizeof(int));
5230 tbinfo->attalign = (char *) malloc(ntups * sizeof(char));
5231 tbinfo->attislocal = (bool *) malloc(ntups * sizeof(bool));
5232 tbinfo->notnull = (bool *) malloc(ntups * sizeof(bool));
5233 tbinfo->attrdefs = (AttrDefInfo **) malloc(ntups * sizeof(AttrDefInfo *));
5234 tbinfo->attoptions = (char **) malloc(ntups * sizeof(char *));
5235 tbinfo->inhAttrs = (bool *) malloc(ntups * sizeof(bool));
5236 tbinfo->inhAttrDef = (bool *) malloc(ntups * sizeof(bool));
5237 tbinfo->inhNotNull = (bool *) malloc(ntups * sizeof(bool));
5238 hasdefaults = false;
5240 for (j = 0; j < ntups; j++)
5242 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5244 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5248 tbinfo->attnames[j] = strdup(PQgetvalue(res, j, i_attname));
5249 tbinfo->atttypnames[j] = strdup(PQgetvalue(res, j, i_atttypname));
5250 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5251 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5252 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5253 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5254 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5255 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5256 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5257 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5258 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5259 tbinfo->attoptions[j] = strdup(PQgetvalue(res, j, i_attoptions));
5260 tbinfo->attrdefs[j] = NULL; /* fix below */
5261 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5263 /* these flags will be set in flagInhAttrs() */
5264 tbinfo->inhAttrs[j] = false;
5265 tbinfo->inhAttrDef[j] = false;
5266 tbinfo->inhNotNull[j] = false;
5272 * Get info about column defaults
5276 AttrDefInfo *attrdefs;
5280 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5283 resetPQExpBuffer(q);
5284 if (g_fout->remoteVersion >= 70300)
5286 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5287 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5288 "FROM pg_catalog.pg_attrdef "
5289 "WHERE adrelid = '%u'::pg_catalog.oid",
5290 tbinfo->dobj.catId.oid);
5292 else if (g_fout->remoteVersion >= 70200)
5294 /* 7.2 did not have OIDs in pg_attrdef */
5295 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5296 "pg_get_expr(adbin, adrelid) AS adsrc "
5298 "WHERE adrelid = '%u'::oid",
5299 tbinfo->dobj.catId.oid);
5301 else if (g_fout->remoteVersion >= 70100)
5303 /* no pg_get_expr, so must rely on adsrc */
5304 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5306 "WHERE adrelid = '%u'::oid",
5307 tbinfo->dobj.catId.oid);
5311 /* no pg_get_expr, no tableoid either */
5312 appendPQExpBuffer(q, "SELECT "
5313 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5314 "oid, adnum, adsrc "
5316 "WHERE adrelid = '%u'::oid",
5317 tbinfo->dobj.catId.oid);
5319 res = PQexec(g_conn, q->data);
5320 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5322 numDefaults = PQntuples(res);
5323 attrdefs = (AttrDefInfo *) malloc(numDefaults * sizeof(AttrDefInfo));
5325 for (j = 0; j < numDefaults; j++)
5329 attrdefs[j].dobj.objType = DO_ATTRDEF;
5330 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5331 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5332 AssignDumpId(&attrdefs[j].dobj);
5333 attrdefs[j].adtable = tbinfo;
5334 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
5335 attrdefs[j].adef_expr = strdup(PQgetvalue(res, j, 3));
5337 attrdefs[j].dobj.name = strdup(tbinfo->dobj.name);
5338 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5340 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5343 * Defaults on a VIEW must always be dumped as separate ALTER
5344 * TABLE commands. Defaults on regular tables are dumped as
5345 * part of the CREATE TABLE if possible. To check if it's
5346 * safe, we mark the default as needing to appear before the
5349 if (tbinfo->relkind == RELKIND_VIEW)
5351 attrdefs[j].separate = true;
5352 /* needed in case pre-7.3 DB: */
5353 addObjectDependency(&attrdefs[j].dobj,
5354 tbinfo->dobj.dumpId);
5358 attrdefs[j].separate = false;
5359 addObjectDependency(&tbinfo->dobj,
5360 attrdefs[j].dobj.dumpId);
5363 if (adnum <= 0 || adnum > ntups)
5365 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
5366 adnum, tbinfo->dobj.name);
5369 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5375 * Get info about table CHECK constraints
5377 if (tbinfo->ncheck > 0)
5379 ConstraintInfo *constrs;
5383 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5386 resetPQExpBuffer(q);
5387 if (g_fout->remoteVersion >= 80400)
5389 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5390 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5392 "FROM pg_catalog.pg_constraint "
5393 "WHERE conrelid = '%u'::pg_catalog.oid "
5394 " AND contype = 'c' "
5396 tbinfo->dobj.catId.oid);
5398 else if (g_fout->remoteVersion >= 70400)
5400 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5401 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5402 "true AS conislocal "
5403 "FROM pg_catalog.pg_constraint "
5404 "WHERE conrelid = '%u'::pg_catalog.oid "
5405 " AND contype = 'c' "
5407 tbinfo->dobj.catId.oid);
5409 else if (g_fout->remoteVersion >= 70300)
5411 /* no pg_get_constraintdef, must use consrc */
5412 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5413 "'CHECK (' || consrc || ')' AS consrc, "
5414 "true AS conislocal "
5415 "FROM pg_catalog.pg_constraint "
5416 "WHERE conrelid = '%u'::pg_catalog.oid "
5417 " AND contype = 'c' "
5419 tbinfo->dobj.catId.oid);
5421 else if (g_fout->remoteVersion >= 70200)
5423 /* 7.2 did not have OIDs in pg_relcheck */
5424 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
5425 "rcname AS conname, "
5426 "'CHECK (' || rcsrc || ')' AS consrc, "
5427 "true AS conislocal "
5429 "WHERE rcrelid = '%u'::oid "
5431 tbinfo->dobj.catId.oid);
5433 else if (g_fout->remoteVersion >= 70100)
5435 appendPQExpBuffer(q, "SELECT tableoid, oid, "
5436 "rcname AS conname, "
5437 "'CHECK (' || rcsrc || ')' AS consrc, "
5438 "true AS conislocal "
5440 "WHERE rcrelid = '%u'::oid "
5442 tbinfo->dobj.catId.oid);
5446 /* no tableoid in 7.0 */
5447 appendPQExpBuffer(q, "SELECT "
5448 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
5449 "oid, rcname AS conname, "
5450 "'CHECK (' || rcsrc || ')' AS consrc, "
5451 "true AS conislocal "
5453 "WHERE rcrelid = '%u'::oid "
5455 tbinfo->dobj.catId.oid);
5457 res = PQexec(g_conn, q->data);
5458 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5460 numConstrs = PQntuples(res);
5461 if (numConstrs != tbinfo->ncheck)
5463 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
5464 "expected %d check constraints on table \"%s\" but found %d\n",
5466 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
5467 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
5471 constrs = (ConstraintInfo *) malloc(numConstrs * sizeof(ConstraintInfo));
5472 tbinfo->checkexprs = constrs;
5474 for (j = 0; j < numConstrs; j++)
5476 constrs[j].dobj.objType = DO_CONSTRAINT;
5477 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5478 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5479 AssignDumpId(&constrs[j].dobj);
5480 constrs[j].dobj.name = strdup(PQgetvalue(res, j, 2));
5481 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
5482 constrs[j].contable = tbinfo;
5483 constrs[j].condomain = NULL;
5484 constrs[j].contype = 'c';
5485 constrs[j].condef = strdup(PQgetvalue(res, j, 3));
5486 constrs[j].confrelid = InvalidOid;
5487 constrs[j].conindex = 0;
5488 constrs[j].condeferrable = false;
5489 constrs[j].condeferred = false;
5490 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
5491 constrs[j].separate = false;
5493 constrs[j].dobj.dump = tbinfo->dobj.dump;
5496 * Mark the constraint as needing to appear before the table
5497 * --- this is so that any other dependencies of the
5498 * constraint will be emitted before we try to create the
5501 addObjectDependency(&tbinfo->dobj,
5502 constrs[j].dobj.dumpId);
5505 * If the constraint is inherited, this will be detected later
5506 * (in pre-8.4 databases). We also detect later if the
5507 * constraint must be split out from the table definition.
5514 destroyPQExpBuffer(q);
5520 * read all text search parsers in the system catalogs and return them
5521 * in the TSParserInfo* structure
5523 * numTSParsers is set to the number of parsers read in
5526 getTSParsers(int *numTSParsers)
5531 PQExpBuffer query = createPQExpBuffer();
5532 TSParserInfo *prsinfo;
5543 /* Before 8.3, there is no built-in text search support */
5544 if (g_fout->remoteVersion < 80300)
5551 * find all text search objects, including builtin ones; we filter out
5552 * system-defined objects at dump-out time.
5555 /* Make sure we are in proper schema */
5556 selectSourceSchema("pg_catalog");
5558 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
5559 "prsstart::oid, prstoken::oid, "
5560 "prsend::oid, prsheadline::oid, prslextype::oid "
5561 "FROM pg_ts_parser");
5563 res = PQexec(g_conn, query->data);
5564 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5566 ntups = PQntuples(res);
5567 *numTSParsers = ntups;
5569 prsinfo = (TSParserInfo *) malloc(ntups * sizeof(TSParserInfo));
5571 i_tableoid = PQfnumber(res, "tableoid");
5572 i_oid = PQfnumber(res, "oid");
5573 i_prsname = PQfnumber(res, "prsname");
5574 i_prsnamespace = PQfnumber(res, "prsnamespace");
5575 i_prsstart = PQfnumber(res, "prsstart");
5576 i_prstoken = PQfnumber(res, "prstoken");
5577 i_prsend = PQfnumber(res, "prsend");
5578 i_prsheadline = PQfnumber(res, "prsheadline");
5579 i_prslextype = PQfnumber(res, "prslextype");
5581 for (i = 0; i < ntups; i++)
5583 prsinfo[i].dobj.objType = DO_TSPARSER;
5584 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5585 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5586 AssignDumpId(&prsinfo[i].dobj);
5587 prsinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_prsname));
5588 prsinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_prsnamespace)),
5589 prsinfo[i].dobj.catId.oid);
5590 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
5591 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
5592 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
5593 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
5594 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
5596 /* Decide whether we want to dump it */
5597 selectDumpableObject(&(prsinfo[i].dobj));
5602 destroyPQExpBuffer(query);
5608 * getTSDictionaries:
5609 * read all text search dictionaries in the system catalogs and return them
5610 * in the TSDictInfo* structure
5612 * numTSDicts is set to the number of dictionaries read in
5615 getTSDictionaries(int *numTSDicts)
5620 PQExpBuffer query = createPQExpBuffer();
5621 TSDictInfo *dictinfo;
5625 int i_dictnamespace;
5628 int i_dictinitoption;
5630 /* Before 8.3, there is no built-in text search support */
5631 if (g_fout->remoteVersion < 80300)
5637 /* Make sure we are in proper schema */
5638 selectSourceSchema("pg_catalog");
5640 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
5641 "dictnamespace, (%s dictowner) AS rolname, "
5642 "dicttemplate, dictinitoption "
5646 res = PQexec(g_conn, query->data);
5647 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5649 ntups = PQntuples(res);
5650 *numTSDicts = ntups;
5652 dictinfo = (TSDictInfo *) malloc(ntups * sizeof(TSDictInfo));
5654 i_tableoid = PQfnumber(res, "tableoid");
5655 i_oid = PQfnumber(res, "oid");
5656 i_dictname = PQfnumber(res, "dictname");
5657 i_dictnamespace = PQfnumber(res, "dictnamespace");
5658 i_rolname = PQfnumber(res, "rolname");
5659 i_dictinitoption = PQfnumber(res, "dictinitoption");
5660 i_dicttemplate = PQfnumber(res, "dicttemplate");
5662 for (i = 0; i < ntups; i++)
5664 dictinfo[i].dobj.objType = DO_TSDICT;
5665 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5666 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5667 AssignDumpId(&dictinfo[i].dobj);
5668 dictinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_dictname));
5669 dictinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_dictnamespace)),
5670 dictinfo[i].dobj.catId.oid);
5671 dictinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5672 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
5673 if (PQgetisnull(res, i, i_dictinitoption))
5674 dictinfo[i].dictinitoption = NULL;
5676 dictinfo[i].dictinitoption = strdup(PQgetvalue(res, i, i_dictinitoption));
5678 /* Decide whether we want to dump it */
5679 selectDumpableObject(&(dictinfo[i].dobj));
5684 destroyPQExpBuffer(query);
5691 * read all text search templates in the system catalogs and return them
5692 * in the TSTemplateInfo* structure
5694 * numTSTemplates is set to the number of templates read in
5697 getTSTemplates(int *numTSTemplates)
5702 PQExpBuffer query = createPQExpBuffer();
5703 TSTemplateInfo *tmplinfo;
5707 int i_tmplnamespace;
5711 /* Before 8.3, there is no built-in text search support */
5712 if (g_fout->remoteVersion < 80300)
5714 *numTSTemplates = 0;
5718 /* Make sure we are in proper schema */
5719 selectSourceSchema("pg_catalog");
5721 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
5722 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
5723 "FROM pg_ts_template");
5725 res = PQexec(g_conn, query->data);
5726 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5728 ntups = PQntuples(res);
5729 *numTSTemplates = ntups;
5731 tmplinfo = (TSTemplateInfo *) malloc(ntups * sizeof(TSTemplateInfo));
5733 i_tableoid = PQfnumber(res, "tableoid");
5734 i_oid = PQfnumber(res, "oid");
5735 i_tmplname = PQfnumber(res, "tmplname");
5736 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
5737 i_tmplinit = PQfnumber(res, "tmplinit");
5738 i_tmpllexize = PQfnumber(res, "tmpllexize");
5740 for (i = 0; i < ntups; i++)
5742 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
5743 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5744 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5745 AssignDumpId(&tmplinfo[i].dobj);
5746 tmplinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_tmplname));
5747 tmplinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_tmplnamespace)),
5748 tmplinfo[i].dobj.catId.oid);
5749 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
5750 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
5752 /* Decide whether we want to dump it */
5753 selectDumpableObject(&(tmplinfo[i].dobj));
5758 destroyPQExpBuffer(query);
5764 * getTSConfigurations:
5765 * read all text search configurations in the system catalogs and return
5766 * them in the TSConfigInfo* structure
5768 * numTSConfigs is set to the number of configurations read in
5771 getTSConfigurations(int *numTSConfigs)
5776 PQExpBuffer query = createPQExpBuffer();
5777 TSConfigInfo *cfginfo;
5785 /* Before 8.3, there is no built-in text search support */
5786 if (g_fout->remoteVersion < 80300)
5792 /* Make sure we are in proper schema */
5793 selectSourceSchema("pg_catalog");
5795 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
5796 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
5797 "FROM pg_ts_config",
5800 res = PQexec(g_conn, query->data);
5801 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5803 ntups = PQntuples(res);
5804 *numTSConfigs = ntups;
5806 cfginfo = (TSConfigInfo *) malloc(ntups * sizeof(TSConfigInfo));
5808 i_tableoid = PQfnumber(res, "tableoid");
5809 i_oid = PQfnumber(res, "oid");
5810 i_cfgname = PQfnumber(res, "cfgname");
5811 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
5812 i_rolname = PQfnumber(res, "rolname");
5813 i_cfgparser = PQfnumber(res, "cfgparser");
5815 for (i = 0; i < ntups; i++)
5817 cfginfo[i].dobj.objType = DO_TSCONFIG;
5818 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5819 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5820 AssignDumpId(&cfginfo[i].dobj);
5821 cfginfo[i].dobj.name = strdup(PQgetvalue(res, i, i_cfgname));
5822 cfginfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_cfgnamespace)),
5823 cfginfo[i].dobj.catId.oid);
5824 cfginfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5825 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
5827 /* Decide whether we want to dump it */
5828 selectDumpableObject(&(cfginfo[i].dobj));
5833 destroyPQExpBuffer(query);
5839 * getForeignDataWrappers:
5840 * read all foreign-data wrappers in the system catalogs and return
5841 * them in the FdwInfo* structure
5843 * numForeignDataWrappers is set to the number of fdws read in
5846 getForeignDataWrappers(int *numForeignDataWrappers)
5851 PQExpBuffer query = createPQExpBuffer();
5860 /* Before 8.4, there are no foreign-data wrappers */
5861 if (g_fout->remoteVersion < 80400)
5863 *numForeignDataWrappers = 0;
5867 /* Make sure we are in proper schema */
5868 selectSourceSchema("pg_catalog");
5870 appendPQExpBuffer(query, "SELECT oid, fdwname, "
5871 "(%s fdwowner) AS rolname, fdwvalidator::pg_catalog.regproc, fdwacl,"
5872 "array_to_string(ARRAY("
5873 " SELECT option_name || ' ' || quote_literal(option_value) "
5874 " FROM pg_options_to_table(fdwoptions)), ', ') AS fdwoptions "
5875 "FROM pg_foreign_data_wrapper",
5878 res = PQexec(g_conn, query->data);
5879 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5881 ntups = PQntuples(res);
5882 *numForeignDataWrappers = ntups;
5884 fdwinfo = (FdwInfo *) malloc(ntups * sizeof(FdwInfo));
5886 i_oid = PQfnumber(res, "oid");
5887 i_fdwname = PQfnumber(res, "fdwname");
5888 i_rolname = PQfnumber(res, "rolname");
5889 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
5890 i_fdwacl = PQfnumber(res, "fdwacl");
5891 i_fdwoptions = PQfnumber(res, "fdwoptions");
5893 for (i = 0; i < ntups; i++)
5895 fdwinfo[i].dobj.objType = DO_FDW;
5896 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5897 AssignDumpId(&fdwinfo[i].dobj);
5898 fdwinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_fdwname));
5899 fdwinfo[i].dobj.namespace = NULL;
5900 fdwinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5901 fdwinfo[i].fdwvalidator = strdup(PQgetvalue(res, i, i_fdwvalidator));
5902 fdwinfo[i].fdwoptions = strdup(PQgetvalue(res, i, i_fdwoptions));
5903 fdwinfo[i].fdwacl = strdup(PQgetvalue(res, i, i_fdwacl));
5906 /* Decide whether we want to dump it */
5907 selectDumpableObject(&(fdwinfo[i].dobj));
5912 destroyPQExpBuffer(query);
5918 * getForeignServers:
5919 * read all foreign servers in the system catalogs and return
5920 * them in the ForeignServerInfo * structure
5922 * numForeignServers is set to the number of servers read in
5925 getForeignServers(int *numForeignServers)
5930 PQExpBuffer query = createPQExpBuffer();
5931 ForeignServerInfo *srvinfo;
5941 /* Before 8.4, there are no foreign servers */
5942 if (g_fout->remoteVersion < 80400)
5944 *numForeignServers = 0;
5948 /* Make sure we are in proper schema */
5949 selectSourceSchema("pg_catalog");
5951 appendPQExpBuffer(query, "SELECT oid, srvname, "
5952 "(%s srvowner) AS rolname, "
5953 "srvfdw, srvtype, srvversion, srvacl,"
5954 "array_to_string(ARRAY("
5955 " SELECT option_name || ' ' || quote_literal(option_value) "
5956 " FROM pg_options_to_table(srvoptions)), ', ') AS srvoptions "
5957 "FROM pg_foreign_server",
5960 res = PQexec(g_conn, query->data);
5961 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5963 ntups = PQntuples(res);
5964 *numForeignServers = ntups;
5966 srvinfo = (ForeignServerInfo *) malloc(ntups * sizeof(ForeignServerInfo));
5968 i_oid = PQfnumber(res, "oid");
5969 i_srvname = PQfnumber(res, "srvname");
5970 i_rolname = PQfnumber(res, "rolname");
5971 i_srvfdw = PQfnumber(res, "srvfdw");
5972 i_srvtype = PQfnumber(res, "srvtype");
5973 i_srvversion = PQfnumber(res, "srvversion");
5974 i_srvacl = PQfnumber(res, "srvacl");
5975 i_srvoptions = PQfnumber(res, "srvoptions");
5977 for (i = 0; i < ntups; i++)
5979 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
5980 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5981 AssignDumpId(&srvinfo[i].dobj);
5982 srvinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_srvname));
5983 srvinfo[i].dobj.namespace = NULL;
5984 srvinfo[i].rolname = strdup(PQgetvalue(res, i, i_rolname));
5985 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
5986 srvinfo[i].srvtype = strdup(PQgetvalue(res, i, i_srvtype));
5987 srvinfo[i].srvversion = strdup(PQgetvalue(res, i, i_srvversion));
5988 srvinfo[i].srvoptions = strdup(PQgetvalue(res, i, i_srvoptions));
5989 srvinfo[i].srvacl = strdup(PQgetvalue(res, i, i_srvacl));
5991 /* Decide whether we want to dump it */
5992 selectDumpableObject(&(srvinfo[i].dobj));
5997 destroyPQExpBuffer(query);
6004 * read all default ACL information in the system catalogs and return
6005 * them in the DefaultACLInfo structure
6007 * numDefaultACLs is set to the number of ACLs read in
6010 getDefaultACLs(int *numDefaultACLs)
6012 DefaultACLInfo *daclinfo;
6018 int i_defaclnamespace;
6019 int i_defaclobjtype;
6024 if (g_fout->remoteVersion < 90000)
6026 *numDefaultACLs = 0;
6030 query = createPQExpBuffer();
6032 /* Make sure we are in proper schema */
6033 selectSourceSchema("pg_catalog");
6035 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6036 "(%s defaclrole) AS defaclrole, "
6040 "FROM pg_default_acl",
6043 res = PQexec(g_conn, query->data);
6044 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6046 ntups = PQntuples(res);
6047 *numDefaultACLs = ntups;
6049 daclinfo = (DefaultACLInfo *) malloc(ntups * sizeof(DefaultACLInfo));
6051 i_oid = PQfnumber(res, "oid");
6052 i_tableoid = PQfnumber(res, "tableoid");
6053 i_defaclrole = PQfnumber(res, "defaclrole");
6054 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6055 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6056 i_defaclacl = PQfnumber(res, "defaclacl");
6058 for (i = 0; i < ntups; i++)
6060 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6062 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6063 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6064 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6065 AssignDumpId(&daclinfo[i].dobj);
6066 /* cheesy ... is it worth coming up with a better object name? */
6067 daclinfo[i].dobj.name = strdup(PQgetvalue(res, i, i_defaclobjtype));
6069 if (nspid != InvalidOid)
6070 daclinfo[i].dobj.namespace = findNamespace(nspid,
6071 daclinfo[i].dobj.catId.oid);
6073 daclinfo[i].dobj.namespace = NULL;
6075 daclinfo[i].defaclrole = strdup(PQgetvalue(res, i, i_defaclrole));
6076 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6077 daclinfo[i].defaclacl = strdup(PQgetvalue(res, i, i_defaclacl));
6079 /* Decide whether we want to dump it */
6080 selectDumpableDefaultACL(&(daclinfo[i]));
6085 destroyPQExpBuffer(query);
6093 * This routine is used to dump any comments associated with the
6094 * object handed to this routine. The routine takes a constant character
6095 * string for the target part of the comment-creation command, plus
6096 * the namespace and owner of the object (for labeling the ArchiveEntry),
6097 * plus catalog ID and subid which are the lookup key for pg_description,
6098 * plus the dump ID for the object (for setting a dependency).
6099 * If a matching pg_description entry is found, it is dumped.
6101 * Note: although this routine takes a dumpId for dependency purposes,
6102 * that purpose is just to mark the dependency in the emitted dump file
6103 * for possible future use by pg_restore. We do NOT use it for determining
6104 * ordering of the comment in the dump file, because this routine is called
6105 * after dependency sorting occurs. This routine should be called just after
6106 * calling ArchiveEntry() for the specified object.
6109 dumpComment(Archive *fout, const char *target,
6110 const char *namespace, const char *owner,
6111 CatalogId catalogId, int subid, DumpId dumpId)
6113 CommentItem *comments;
6116 /* Comments are schema not data ... except blob comments are data */
6117 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6128 /* Search for comments associated with catalogId, using table */
6129 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6132 /* Is there one matching the subid? */
6133 while (ncomments > 0)
6135 if (comments->objsubid == subid)
6141 /* If a comment exists, build COMMENT ON statement */
6144 PQExpBuffer query = createPQExpBuffer();
6146 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6147 appendStringLiteralAH(query, comments->descr, fout);
6148 appendPQExpBuffer(query, ";\n");
6151 * We mark comments as SECTION_NONE because they really belong in the
6152 * same section as their parent, whether that is pre-data or
6155 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6156 target, namespace, NULL, owner,
6157 false, "COMMENT", SECTION_NONE,
6158 query->data, "", NULL,
6162 destroyPQExpBuffer(query);
6167 * dumpTableComment --
6169 * As above, but dump comments for both the specified table (or view)
6173 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6174 const char *reltypename)
6176 CommentItem *comments;
6181 /* Comments are SCHEMA not data */
6185 /* Search for comments associated with relation, using table */
6186 ncomments = findComments(fout,
6187 tbinfo->dobj.catId.tableoid,
6188 tbinfo->dobj.catId.oid,
6191 /* If comments exist, build COMMENT ON statements */
6195 query = createPQExpBuffer();
6196 target = createPQExpBuffer();
6198 while (ncomments > 0)
6200 const char *descr = comments->descr;
6201 int objsubid = comments->objsubid;
6205 resetPQExpBuffer(target);
6206 appendPQExpBuffer(target, "%s %s", reltypename,
6207 fmtId(tbinfo->dobj.name));
6209 resetPQExpBuffer(query);
6210 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6211 appendStringLiteralAH(query, descr, fout);
6212 appendPQExpBuffer(query, ";\n");
6214 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6216 tbinfo->dobj.namespace->dobj.name,
6217 NULL, tbinfo->rolname,
6218 false, "COMMENT", SECTION_NONE,
6219 query->data, "", NULL,
6220 &(tbinfo->dobj.dumpId), 1,
6223 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6225 resetPQExpBuffer(target);
6226 appendPQExpBuffer(target, "COLUMN %s.",
6227 fmtId(tbinfo->dobj.name));
6228 appendPQExpBuffer(target, "%s",
6229 fmtId(tbinfo->attnames[objsubid - 1]));
6231 resetPQExpBuffer(query);
6232 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6233 appendStringLiteralAH(query, descr, fout);
6234 appendPQExpBuffer(query, ";\n");
6236 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6238 tbinfo->dobj.namespace->dobj.name,
6239 NULL, tbinfo->rolname,
6240 false, "COMMENT", SECTION_NONE,
6241 query->data, "", NULL,
6242 &(tbinfo->dobj.dumpId), 1,
6250 destroyPQExpBuffer(query);
6251 destroyPQExpBuffer(target);
6257 * Find the comment(s), if any, associated with the given object. All the
6258 * objsubid values associated with the given classoid/objoid are found with
6262 findComments(Archive *fout, Oid classoid, Oid objoid,
6263 CommentItem **items)
6265 /* static storage for table of comments */
6266 static CommentItem *comments = NULL;
6267 static int ncomments = -1;
6269 CommentItem *middle = NULL;
6274 /* Get comments if we didn't already */
6276 ncomments = collectComments(fout, &comments);
6279 * Pre-7.2, pg_description does not contain classoid, so collectComments
6280 * just stores a zero. If there's a collision on object OID, well, you
6281 * get duplicate comments.
6283 if (fout->remoteVersion < 70200)
6287 * Do binary search to find some item matching the object.
6290 high = &comments[ncomments - 1];
6293 middle = low + (high - low) / 2;
6295 if (classoid < middle->classoid)
6297 else if (classoid > middle->classoid)
6299 else if (objoid < middle->objoid)
6301 else if (objoid > middle->objoid)
6304 break; /* found a match */
6307 if (low > high) /* no matches */
6314 * Now determine how many items match the object. The search loop
6315 * invariant still holds: only items between low and high inclusive could
6319 while (middle > low)
6321 if (classoid != middle[-1].classoid ||
6322 objoid != middle[-1].objoid)
6331 while (middle <= high)
6333 if (classoid != middle->classoid ||
6334 objoid != middle->objoid)
6344 * collectComments --
6346 * Construct a table of all comments available for database objects.
6347 * We used to do per-object queries for the comments, but it's much faster
6348 * to pull them all over at once, and on most databases the memory cost
6351 * The table is sorted by classoid/objid/objsubid for speed in lookup.
6354 collectComments(Archive *fout, CommentItem **items)
6364 CommentItem *comments;
6367 * Note we do NOT change source schema here; preserve the caller's
6371 query = createPQExpBuffer();
6373 if (fout->remoteVersion >= 70300)
6375 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
6376 "FROM pg_catalog.pg_description "
6377 "ORDER BY classoid, objoid, objsubid");
6379 else if (fout->remoteVersion >= 70200)
6381 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
6382 "FROM pg_description "
6383 "ORDER BY classoid, objoid, objsubid");
6387 /* Note: this will fail to find attribute comments in pre-7.2... */
6388 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
6389 "FROM pg_description "
6393 res = PQexec(g_conn, query->data);
6394 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6396 /* Construct lookup table containing OIDs in numeric form */
6398 i_description = PQfnumber(res, "description");
6399 i_classoid = PQfnumber(res, "classoid");
6400 i_objoid = PQfnumber(res, "objoid");
6401 i_objsubid = PQfnumber(res, "objsubid");
6403 ntups = PQntuples(res);
6405 comments = (CommentItem *) malloc(ntups * sizeof(CommentItem));
6407 for (i = 0; i < ntups; i++)
6409 comments[i].descr = PQgetvalue(res, i, i_description);
6410 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
6411 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
6412 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
6415 /* Do NOT free the PGresult since we are keeping pointers into it */
6416 destroyPQExpBuffer(query);
6423 * dumpDumpableObject
6425 * This routine and its subsidiaries are responsible for creating
6426 * ArchiveEntries (TOC objects) for each object to be dumped.
6429 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
6431 switch (dobj->objType)
6434 dumpNamespace(fout, (NamespaceInfo *) dobj);
6437 dumpType(fout, (TypeInfo *) dobj);
6440 dumpShellType(fout, (ShellTypeInfo *) dobj);
6443 dumpFunc(fout, (FuncInfo *) dobj);
6446 dumpAgg(fout, (AggInfo *) dobj);
6449 dumpOpr(fout, (OprInfo *) dobj);
6452 dumpOpclass(fout, (OpclassInfo *) dobj);
6455 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
6458 dumpConversion(fout, (ConvInfo *) dobj);
6461 dumpTable(fout, (TableInfo *) dobj);
6464 dumpAttrDef(fout, (AttrDefInfo *) dobj);
6467 dumpIndex(fout, (IndxInfo *) dobj);
6470 dumpRule(fout, (RuleInfo *) dobj);
6473 dumpTrigger(fout, (TriggerInfo *) dobj);
6476 dumpConstraint(fout, (ConstraintInfo *) dobj);
6478 case DO_FK_CONSTRAINT:
6479 dumpConstraint(fout, (ConstraintInfo *) dobj);
6482 dumpProcLang(fout, (ProcLangInfo *) dobj);
6485 dumpCast(fout, (CastInfo *) dobj);
6488 dumpTableData(fout, (TableDataInfo *) dobj);
6491 /* table rowtypes and array types are never dumped separately */
6494 dumpTSParser(fout, (TSParserInfo *) dobj);
6497 dumpTSDictionary(fout, (TSDictInfo *) dobj);
6500 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
6503 dumpTSConfig(fout, (TSConfigInfo *) dobj);
6506 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
6508 case DO_FOREIGN_SERVER:
6509 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
6511 case DO_DEFAULT_ACL:
6512 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
6515 dumpBlob(fout, (BlobInfo *) dobj);
6518 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
6519 dobj->name, NULL, NULL, "",
6520 false, "BLOBS", SECTION_DATA,
6522 dobj->dependencies, dobj->nDeps,
6530 * writes out to fout the queries to recreate a user-defined namespace
6533 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
6539 /* Skip if not to be dumped */
6540 if (!nspinfo->dobj.dump || dataOnly)
6543 /* don't dump dummy namespace from pre-7.3 source */
6544 if (strlen(nspinfo->dobj.name) == 0)
6547 q = createPQExpBuffer();
6548 delq = createPQExpBuffer();
6550 qnspname = strdup(fmtId(nspinfo->dobj.name));
6552 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
6554 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
6556 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
6560 false, "SCHEMA", SECTION_PRE_DATA,
6561 q->data, delq->data, NULL,
6562 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
6565 /* Dump Schema Comments */
6566 resetPQExpBuffer(q);
6567 appendPQExpBuffer(q, "SCHEMA %s", qnspname);
6568 dumpComment(fout, q->data,
6569 NULL, nspinfo->rolname,
6570 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
6572 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
6573 qnspname, NULL, nspinfo->dobj.name, NULL,
6574 nspinfo->rolname, nspinfo->nspacl);
6578 destroyPQExpBuffer(q);
6579 destroyPQExpBuffer(delq);
6584 * writes out to fout the queries to recreate a user-defined type
6587 dumpType(Archive *fout, TypeInfo *tyinfo)
6589 /* Skip if not to be dumped */
6590 if (!tyinfo->dobj.dump || dataOnly)
6593 /* Dump out in proper style */
6594 if (tyinfo->typtype == TYPTYPE_BASE)
6595 dumpBaseType(fout, tyinfo);
6596 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
6597 dumpDomain(fout, tyinfo);
6598 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
6599 dumpCompositeType(fout, tyinfo);
6600 else if (tyinfo->typtype == TYPTYPE_ENUM)
6601 dumpEnumType(fout, tyinfo);
6606 * writes out to fout the queries to recreate a user-defined enum type
6609 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
6611 PQExpBuffer q = createPQExpBuffer();
6612 PQExpBuffer delq = createPQExpBuffer();
6613 PQExpBuffer query = createPQExpBuffer();
6620 /* Set proper schema search path so regproc references list correctly */
6621 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
6623 appendPQExpBuffer(query, "SELECT oid, enumlabel "
6624 "FROM pg_catalog.pg_enum "
6625 "WHERE enumtypid = '%u'"
6627 tyinfo->dobj.catId.oid);
6629 res = PQexec(g_conn, query->data);
6630 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6632 num = PQntuples(res);
6635 * DROP must be fully qualified in case same name appears in pg_catalog.
6636 * CASCADE shouldn't be required here as for normal types since the I/O
6637 * functions are generic and do not get dropped.
6639 appendPQExpBuffer(delq, "DROP TYPE %s.",
6640 fmtId(tyinfo->dobj.namespace->dobj.name));
6641 appendPQExpBuffer(delq, "%s;\n",
6642 fmtId(tyinfo->dobj.name));
6645 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
6647 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
6648 fmtId(tyinfo->dobj.name));
6650 if (!binary_upgrade)
6652 /* Labels with server-assigned oids */
6653 for (i = 0; i < num; i++)
6655 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
6657 appendPQExpBuffer(q, ",");
6658 appendPQExpBuffer(q, "\n ");
6659 appendStringLiteralAH(q, label, fout);
6663 appendPQExpBuffer(q, "\n);\n");
6667 /* Labels with dump-assigned (preserved) oids */
6668 for (i = 0; i < num; i++)
6670 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
6671 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
6674 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
6675 appendPQExpBuffer(q,
6676 "SELECT binary_upgrade.add_pg_enum_label('%u'::pg_catalog.oid, "
6677 "'%u'::pg_catalog.oid, ",
6678 enum_oid, tyinfo->dobj.catId.oid);
6679 appendStringLiteralAH(q, label, fout);
6680 appendPQExpBuffer(q, ");\n");
6682 appendPQExpBuffer(q, "\n");
6685 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
6687 tyinfo->dobj.namespace->dobj.name,
6689 tyinfo->rolname, false,
6690 "TYPE", SECTION_PRE_DATA,
6691 q->data, delq->data, NULL,
6692 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
6695 /* Dump Type Comments */
6696 resetPQExpBuffer(q);
6698 appendPQExpBuffer(q, "TYPE %s", fmtId(tyinfo->dobj.name));
6699 dumpComment(fout, q->data,
6700 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
6701 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
6704 destroyPQExpBuffer(q);
6705 destroyPQExpBuffer(delq);
6706 destroyPQExpBuffer(query);
6711 * writes out to fout the queries to recreate a user-defined base type
6714 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
6716 PQExpBuffer q = createPQExpBuffer();
6717 PQExpBuffer delq = createPQExpBuffer();
6718 PQExpBuffer query = createPQExpBuffer();
6737 char *typispreferred;
6743 bool typdefault_is_literal = false;
6745 /* Set proper schema search path so regproc references list correctly */
6746 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
6748 /* Fetch type-specific details */
6749 if (fout->remoteVersion >= 80400)
6751 appendPQExpBuffer(query, "SELECT typlen, "
6752 "typinput, typoutput, typreceive, typsend, "
6753 "typmodin, typmodout, typanalyze, "
6754 "typinput::pg_catalog.oid AS typinputoid, "
6755 "typoutput::pg_catalog.oid AS typoutputoid, "
6756 "typreceive::pg_catalog.oid AS typreceiveoid, "
6757 "typsend::pg_catalog.oid AS typsendoid, "
6758 "typmodin::pg_catalog.oid AS typmodinoid, "
6759 "typmodout::pg_catalog.oid AS typmodoutoid, "
6760 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
6761 "typcategory, typispreferred, "
6762 "typdelim, typbyval, typalign, typstorage, "
6763 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
6764 "FROM pg_catalog.pg_type "
6765 "WHERE oid = '%u'::pg_catalog.oid",
6766 tyinfo->dobj.catId.oid);
6768 else if (fout->remoteVersion >= 80300)
6770 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
6771 appendPQExpBuffer(query, "SELECT typlen, "
6772 "typinput, typoutput, typreceive, typsend, "
6773 "typmodin, typmodout, typanalyze, "
6774 "typinput::pg_catalog.oid AS typinputoid, "
6775 "typoutput::pg_catalog.oid AS typoutputoid, "
6776 "typreceive::pg_catalog.oid AS typreceiveoid, "
6777 "typsend::pg_catalog.oid AS typsendoid, "
6778 "typmodin::pg_catalog.oid AS typmodinoid, "
6779 "typmodout::pg_catalog.oid AS typmodoutoid, "
6780 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
6781 "'U' AS typcategory, false AS typispreferred, "
6782 "typdelim, typbyval, typalign, typstorage, "
6783 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6784 "FROM pg_catalog.pg_type "
6785 "WHERE oid = '%u'::pg_catalog.oid",
6786 tyinfo->dobj.catId.oid);
6788 else if (fout->remoteVersion >= 80000)
6790 appendPQExpBuffer(query, "SELECT typlen, "
6791 "typinput, typoutput, typreceive, typsend, "
6792 "'-' AS typmodin, '-' AS typmodout, "
6794 "typinput::pg_catalog.oid AS typinputoid, "
6795 "typoutput::pg_catalog.oid AS typoutputoid, "
6796 "typreceive::pg_catalog.oid AS typreceiveoid, "
6797 "typsend::pg_catalog.oid AS typsendoid, "
6798 "0 AS typmodinoid, 0 AS typmodoutoid, "
6799 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
6800 "'U' AS typcategory, false AS typispreferred, "
6801 "typdelim, typbyval, typalign, typstorage, "
6802 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6803 "FROM pg_catalog.pg_type "
6804 "WHERE oid = '%u'::pg_catalog.oid",
6805 tyinfo->dobj.catId.oid);
6807 else if (fout->remoteVersion >= 70400)
6809 appendPQExpBuffer(query, "SELECT typlen, "
6810 "typinput, typoutput, typreceive, typsend, "
6811 "'-' AS typmodin, '-' AS typmodout, "
6812 "'-' AS typanalyze, "
6813 "typinput::pg_catalog.oid AS typinputoid, "
6814 "typoutput::pg_catalog.oid AS typoutputoid, "
6815 "typreceive::pg_catalog.oid AS typreceiveoid, "
6816 "typsend::pg_catalog.oid AS typsendoid, "
6817 "0 AS typmodinoid, 0 AS typmodoutoid, "
6818 "0 AS typanalyzeoid, "
6819 "'U' AS typcategory, false AS typispreferred, "
6820 "typdelim, typbyval, typalign, typstorage, "
6821 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6822 "FROM pg_catalog.pg_type "
6823 "WHERE oid = '%u'::pg_catalog.oid",
6824 tyinfo->dobj.catId.oid);
6826 else if (fout->remoteVersion >= 70300)
6828 appendPQExpBuffer(query, "SELECT typlen, "
6829 "typinput, typoutput, "
6830 "'-' AS typreceive, '-' AS typsend, "
6831 "'-' AS typmodin, '-' AS typmodout, "
6832 "'-' AS typanalyze, "
6833 "typinput::pg_catalog.oid AS typinputoid, "
6834 "typoutput::pg_catalog.oid AS typoutputoid, "
6835 "0 AS typreceiveoid, 0 AS typsendoid, "
6836 "0 AS typmodinoid, 0 AS typmodoutoid, "
6837 "0 AS typanalyzeoid, "
6838 "'U' AS typcategory, false AS typispreferred, "
6839 "typdelim, typbyval, typalign, typstorage, "
6840 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
6841 "FROM pg_catalog.pg_type "
6842 "WHERE oid = '%u'::pg_catalog.oid",
6843 tyinfo->dobj.catId.oid);
6845 else if (fout->remoteVersion >= 70200)
6848 * Note: although pre-7.3 catalogs contain typreceive and typsend,
6849 * ignore them because they are not right.
6851 appendPQExpBuffer(query, "SELECT typlen, "
6852 "typinput, typoutput, "
6853 "'-' AS typreceive, '-' AS typsend, "
6854 "'-' AS typmodin, '-' AS typmodout, "
6855 "'-' AS typanalyze, "
6856 "typinput::oid AS typinputoid, "
6857 "typoutput::oid AS typoutputoid, "
6858 "0 AS typreceiveoid, 0 AS typsendoid, "
6859 "0 AS typmodinoid, 0 AS typmodoutoid, "
6860 "0 AS typanalyzeoid, "
6861 "'U' AS typcategory, false AS typispreferred, "
6862 "typdelim, typbyval, typalign, typstorage, "
6863 "NULL AS typdefaultbin, typdefault "
6865 "WHERE oid = '%u'::oid",
6866 tyinfo->dobj.catId.oid);
6868 else if (fout->remoteVersion >= 70100)
6871 * Ignore pre-7.2 typdefault; the field exists but has an unusable
6874 appendPQExpBuffer(query, "SELECT typlen, "
6875 "typinput, typoutput, "
6876 "'-' AS typreceive, '-' AS typsend, "
6877 "'-' AS typmodin, '-' AS typmodout, "
6878 "'-' AS typanalyze, "
6879 "typinput::oid AS typinputoid, "
6880 "typoutput::oid AS typoutputoid, "
6881 "0 AS typreceiveoid, 0 AS typsendoid, "
6882 "0 AS typmodinoid, 0 AS typmodoutoid, "
6883 "0 AS typanalyzeoid, "
6884 "'U' AS typcategory, false AS typispreferred, "
6885 "typdelim, typbyval, typalign, typstorage, "
6886 "NULL AS typdefaultbin, NULL AS typdefault "
6888 "WHERE oid = '%u'::oid",
6889 tyinfo->dobj.catId.oid);
6893 appendPQExpBuffer(query, "SELECT typlen, "
6894 "typinput, typoutput, "
6895 "'-' AS typreceive, '-' AS typsend, "
6896 "'-' AS typmodin, '-' AS typmodout, "
6897 "'-' AS typanalyze, "
6898 "typinput::oid AS typinputoid, "
6899 "typoutput::oid AS typoutputoid, "
6900 "0 AS typreceiveoid, 0 AS typsendoid, "
6901 "0 AS typmodinoid, 0 AS typmodoutoid, "
6902 "0 AS typanalyzeoid, "
6903 "'U' AS typcategory, false AS typispreferred, "
6904 "typdelim, typbyval, typalign, "
6905 "'p'::char AS typstorage, "
6906 "NULL AS typdefaultbin, NULL AS typdefault "
6908 "WHERE oid = '%u'::oid",
6909 tyinfo->dobj.catId.oid);
6912 res = PQexec(g_conn, query->data);
6913 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6915 /* Expecting a single result only */
6916 ntups = PQntuples(res);
6919 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
6920 "query returned %d rows instead of one: %s\n",
6922 ntups, query->data);
6926 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
6927 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
6928 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
6929 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
6930 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
6931 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
6932 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
6933 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
6934 typinputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typinputoid")));
6935 typoutputoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typoutputoid")));
6936 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
6937 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
6938 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
6939 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
6940 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
6941 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
6942 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
6943 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
6944 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
6945 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
6946 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
6947 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
6948 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
6949 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
6951 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
6952 typdefault_is_literal = true; /* it needs quotes */
6958 * DROP must be fully qualified in case same name appears in pg_catalog.
6959 * The reason we include CASCADE is that the circular dependency between
6960 * the type and its I/O functions makes it impossible to drop the type any
6963 appendPQExpBuffer(delq, "DROP TYPE %s.",
6964 fmtId(tyinfo->dobj.namespace->dobj.name));
6965 appendPQExpBuffer(delq, "%s CASCADE;\n",
6966 fmtId(tyinfo->dobj.name));
6968 /* We might already have a shell type, but setting pg_type_oid is harmless */
6970 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
6972 appendPQExpBuffer(q,
6973 "CREATE TYPE %s (\n"
6974 " INTERNALLENGTH = %s",
6975 fmtId(tyinfo->dobj.name),
6976 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
6978 if (fout->remoteVersion >= 70300)
6980 /* regproc result is correctly quoted as of 7.3 */
6981 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
6982 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
6983 if (OidIsValid(typreceiveoid))
6984 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
6985 if (OidIsValid(typsendoid))
6986 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
6987 if (OidIsValid(typmodinoid))
6988 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
6989 if (OidIsValid(typmodoutoid))
6990 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
6991 if (OidIsValid(typanalyzeoid))
6992 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
6996 /* regproc delivers an unquoted name before 7.3 */
6997 /* cannot combine these because fmtId uses static result area */
6998 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
6999 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7000 /* receive/send/typmodin/typmodout/analyze need not be printed */
7003 if (typdefault != NULL)
7005 appendPQExpBuffer(q, ",\n DEFAULT = ");
7006 if (typdefault_is_literal)
7007 appendStringLiteralAH(q, typdefault, fout);
7009 appendPQExpBufferStr(q, typdefault);
7012 if (OidIsValid(tyinfo->typelem))
7016 /* reselect schema in case changed by function dump */
7017 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7018 elemType = getFormattedTypeName(tyinfo->typelem, zeroAsOpaque);
7019 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
7023 if (strcmp(typcategory, "U") != 0)
7025 appendPQExpBuffer(q, ",\n CATEGORY = ");
7026 appendStringLiteralAH(q, typcategory, fout);
7029 if (strcmp(typispreferred, "t") == 0)
7030 appendPQExpBuffer(q, ",\n PREFERRED = true");
7032 if (typdelim && strcmp(typdelim, ",") != 0)
7034 appendPQExpBuffer(q, ",\n DELIMITER = ");
7035 appendStringLiteralAH(q, typdelim, fout);
7038 if (strcmp(typalign, "c") == 0)
7039 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
7040 else if (strcmp(typalign, "s") == 0)
7041 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
7042 else if (strcmp(typalign, "i") == 0)
7043 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
7044 else if (strcmp(typalign, "d") == 0)
7045 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
7047 if (strcmp(typstorage, "p") == 0)
7048 appendPQExpBuffer(q, ",\n STORAGE = plain");
7049 else if (strcmp(typstorage, "e") == 0)
7050 appendPQExpBuffer(q, ",\n STORAGE = external");
7051 else if (strcmp(typstorage, "x") == 0)
7052 appendPQExpBuffer(q, ",\n STORAGE = extended");
7053 else if (strcmp(typstorage, "m") == 0)
7054 appendPQExpBuffer(q, ",\n STORAGE = main");
7056 if (strcmp(typbyval, "t") == 0)
7057 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
7059 appendPQExpBuffer(q, "\n);\n");
7061 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7063 tyinfo->dobj.namespace->dobj.name,
7065 tyinfo->rolname, false,
7066 "TYPE", SECTION_PRE_DATA,
7067 q->data, delq->data, NULL,
7068 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7071 /* Dump Type Comments */
7072 resetPQExpBuffer(q);
7074 appendPQExpBuffer(q, "TYPE %s", fmtId(tyinfo->dobj.name));
7075 dumpComment(fout, q->data,
7076 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7077 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7080 destroyPQExpBuffer(q);
7081 destroyPQExpBuffer(delq);
7082 destroyPQExpBuffer(query);
7087 * writes out to fout the queries to recreate a user-defined domain
7090 dumpDomain(Archive *fout, TypeInfo *tyinfo)
7092 PQExpBuffer q = createPQExpBuffer();
7093 PQExpBuffer delq = createPQExpBuffer();
7094 PQExpBuffer query = createPQExpBuffer();
7101 bool typdefault_is_literal = false;
7103 /* Set proper schema search path so type references list correctly */
7104 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7106 /* Fetch domain specific details */
7107 /* We assume here that remoteVersion must be at least 70300 */
7108 appendPQExpBuffer(query, "SELECT typnotnull, "
7109 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
7110 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7111 "FROM pg_catalog.pg_type "
7112 "WHERE oid = '%u'::pg_catalog.oid",
7113 tyinfo->dobj.catId.oid);
7115 res = PQexec(g_conn, query->data);
7116 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7118 /* Expecting a single result only */
7119 ntups = PQntuples(res);
7122 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7123 "query returned %d rows instead of one: %s\n",
7125 ntups, query->data);
7129 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
7130 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
7131 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7132 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7133 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7135 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7136 typdefault_is_literal = true; /* it needs quotes */
7142 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7144 appendPQExpBuffer(q,
7145 "CREATE DOMAIN %s AS %s",
7146 fmtId(tyinfo->dobj.name),
7149 if (typnotnull[0] == 't')
7150 appendPQExpBuffer(q, " NOT NULL");
7152 if (typdefault != NULL)
7154 appendPQExpBuffer(q, " DEFAULT ");
7155 if (typdefault_is_literal)
7156 appendStringLiteralAH(q, typdefault, fout);
7158 appendPQExpBufferStr(q, typdefault);
7164 * Add any CHECK constraints for the domain
7166 for (i = 0; i < tyinfo->nDomChecks; i++)
7168 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
7170 if (!domcheck->separate)
7171 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
7172 fmtId(domcheck->dobj.name), domcheck->condef);
7175 appendPQExpBuffer(q, ";\n");
7178 * DROP must be fully qualified in case same name appears in pg_catalog
7180 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
7181 fmtId(tyinfo->dobj.namespace->dobj.name));
7182 appendPQExpBuffer(delq, "%s;\n",
7183 fmtId(tyinfo->dobj.name));
7185 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7187 tyinfo->dobj.namespace->dobj.name,
7189 tyinfo->rolname, false,
7190 "DOMAIN", SECTION_PRE_DATA,
7191 q->data, delq->data, NULL,
7192 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7195 /* Dump Domain Comments */
7196 resetPQExpBuffer(q);
7198 appendPQExpBuffer(q, "DOMAIN %s", fmtId(tyinfo->dobj.name));
7199 dumpComment(fout, q->data,
7200 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7201 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7203 destroyPQExpBuffer(q);
7204 destroyPQExpBuffer(delq);
7205 destroyPQExpBuffer(query);
7210 * writes out to fout the queries to recreate a user-defined stand-alone
7214 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
7216 PQExpBuffer q = createPQExpBuffer();
7217 PQExpBuffer delq = createPQExpBuffer();
7218 PQExpBuffer query = createPQExpBuffer();
7226 /* Set proper schema search path so type references list correctly */
7227 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7229 /* Fetch type specific details */
7230 /* We assume here that remoteVersion must be at least 70300 */
7232 appendPQExpBuffer(query, "SELECT a.attname, "
7233 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
7235 "FROM pg_catalog.pg_type t, pg_catalog.pg_attribute a "
7236 "WHERE t.oid = '%u'::pg_catalog.oid "
7237 "AND a.attrelid = t.typrelid "
7238 "AND NOT a.attisdropped "
7239 "ORDER BY a.attnum ",
7240 tyinfo->dobj.catId.oid);
7242 res = PQexec(g_conn, query->data);
7243 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7245 /* Expecting at least a single result */
7246 ntups = PQntuples(res);
7249 write_msg(NULL, "query returned no rows: %s\n", query->data);
7253 i_attname = PQfnumber(res, "attname");
7254 i_atttypdefn = PQfnumber(res, "atttypdefn");
7255 i_typrelid = PQfnumber(res, "typrelid");
7259 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
7261 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7262 binary_upgrade_set_relfilenodes(q, typrelid, false);
7265 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
7266 fmtId(tyinfo->dobj.name));
7268 for (i = 0; i < ntups; i++)
7273 attname = PQgetvalue(res, i, i_attname);
7274 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
7276 appendPQExpBuffer(q, "\n\t%s %s", fmtId(attname), atttypdefn);
7278 appendPQExpBuffer(q, ",");
7280 appendPQExpBuffer(q, "\n);\n");
7283 * DROP must be fully qualified in case same name appears in pg_catalog
7285 appendPQExpBuffer(delq, "DROP TYPE %s.",
7286 fmtId(tyinfo->dobj.namespace->dobj.name));
7287 appendPQExpBuffer(delq, "%s;\n",
7288 fmtId(tyinfo->dobj.name));
7290 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7292 tyinfo->dobj.namespace->dobj.name,
7294 tyinfo->rolname, false,
7295 "TYPE", SECTION_PRE_DATA,
7296 q->data, delq->data, NULL,
7297 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7301 /* Dump Type Comments */
7302 resetPQExpBuffer(q);
7304 appendPQExpBuffer(q, "TYPE %s", fmtId(tyinfo->dobj.name));
7305 dumpComment(fout, q->data,
7306 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7307 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7310 destroyPQExpBuffer(q);
7311 destroyPQExpBuffer(delq);
7312 destroyPQExpBuffer(query);
7314 /* Dump any per-column comments */
7315 dumpCompositeTypeColComments(fout, tyinfo);
7319 * dumpCompositeTypeColComments
7320 * writes out to fout the queries to recreate comments on the columns of
7321 * a user-defined stand-alone composite type
7324 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
7326 CommentItem *comments;
7337 query = createPQExpBuffer();
7339 /* We assume here that remoteVersion must be at least 70300 */
7340 appendPQExpBuffer(query,
7341 "SELECT c.tableoid, a.attname, a.attnum "
7342 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
7343 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
7344 " AND NOT a.attisdropped "
7345 "ORDER BY a.attnum ",
7348 /* Fetch column attnames */
7349 res = PQexec(g_conn, query->data);
7350 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7352 /* Expecting at least a single result */
7353 ntups = PQntuples(res);
7356 write_msg(NULL, "query returned no rows: %s\n", query->data);
7360 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
7362 /* Search for comments associated with type's pg_class OID */
7363 ncomments = findComments(fout,
7368 /* If no comments exist, we're done */
7372 destroyPQExpBuffer(query);
7376 /* Build COMMENT ON statements */
7377 target = createPQExpBuffer();
7379 i_attnum = PQfnumber(res, "attnum");
7380 i_attname = PQfnumber(res, "attname");
7381 while (ncomments > 0)
7383 const char *attname;
7386 for (i = 0; i < ntups; i++)
7388 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
7390 attname = PQgetvalue(res, i, i_attname);
7394 if (attname) /* just in case we don't find it */
7396 const char *descr = comments->descr;
7398 resetPQExpBuffer(target);
7399 appendPQExpBuffer(target, "COLUMN %s.",
7400 fmtId(tyinfo->dobj.name));
7401 appendPQExpBuffer(target, "%s",
7404 resetPQExpBuffer(query);
7405 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7406 appendStringLiteralAH(query, descr, fout);
7407 appendPQExpBuffer(query, ";\n");
7409 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7411 tyinfo->dobj.namespace->dobj.name,
7412 NULL, tyinfo->rolname,
7413 false, "COMMENT", SECTION_NONE,
7414 query->data, "", NULL,
7415 &(tyinfo->dobj.dumpId), 1,
7424 destroyPQExpBuffer(query);
7425 destroyPQExpBuffer(target);
7430 * writes out to fout the queries to create a shell type
7432 * We dump a shell definition in advance of the I/O functions for the type.
7435 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
7439 /* Skip if not to be dumped */
7440 if (!stinfo->dobj.dump || dataOnly)
7443 q = createPQExpBuffer();
7446 * Note the lack of a DROP command for the shell type; any required DROP
7447 * is driven off the base type entry, instead. This interacts with
7448 * _printTocEntry()'s use of the presence of a DROP command to decide
7449 * whether an entry needs an ALTER OWNER command. We don't want to alter
7450 * the shell type's owner immediately on creation; that should happen only
7451 * after it's filled in, otherwise the backend complains.
7455 binary_upgrade_set_type_oids_by_type_oid(q,
7456 stinfo->baseType->dobj.catId.oid);
7458 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
7459 fmtId(stinfo->dobj.name));
7461 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
7463 stinfo->dobj.namespace->dobj.name,
7465 stinfo->baseType->rolname, false,
7466 "SHELL TYPE", SECTION_PRE_DATA,
7468 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
7471 destroyPQExpBuffer(q);
7475 * Determine whether we want to dump definitions for procedural languages.
7476 * Since the languages themselves don't have schemas, we can't rely on
7477 * the normal schema-based selection mechanism. We choose to dump them
7478 * whenever neither --schema nor --table was given. (Before 8.1, we used
7479 * the dump flag of the PL's call handler function, but in 8.1 this will
7480 * probably always be false since call handlers are created in pg_catalog.)
7482 * For some backwards compatibility with the older behavior, we forcibly
7483 * dump a PL if its handler function (and validator if any) are in a
7484 * dumpable namespace. That case is not checked here.
7487 shouldDumpProcLangs(void)
7489 if (!include_everything)
7491 /* And they're schema not data */
7499 * writes out to fout the queries to recreate a user-defined
7500 * procedural language
7503 dumpProcLang(Archive *fout, ProcLangInfo *plang)
7511 FuncInfo *inlineInfo = NULL;
7512 FuncInfo *validatorInfo = NULL;
7518 * Try to find the support function(s). It is not an error if we don't
7519 * find them --- if the functions are in the pg_catalog schema, as is
7520 * standard in 8.1 and up, then we won't have loaded them. (In this case
7521 * we will emit a parameterless CREATE LANGUAGE command, which will
7522 * require PL template knowledge in the backend to reload.)
7525 funcInfo = findFuncByOid(plang->lanplcallfoid);
7526 if (funcInfo != NULL && !funcInfo->dobj.dump)
7527 funcInfo = NULL; /* treat not-dumped same as not-found */
7529 if (OidIsValid(plang->laninline))
7531 inlineInfo = findFuncByOid(plang->laninline);
7532 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
7536 if (OidIsValid(plang->lanvalidator))
7538 validatorInfo = findFuncByOid(plang->lanvalidator);
7539 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
7540 validatorInfo = NULL;
7544 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
7545 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
7548 useParams = (funcInfo != NULL &&
7549 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
7550 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
7552 if (!useParams && !shouldDumpProcLangs())
7555 defqry = createPQExpBuffer();
7556 delqry = createPQExpBuffer();
7558 qlanname = strdup(fmtId(plang->dobj.name));
7561 * If dumping a HANDLER clause, treat the language as being in the handler
7562 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
7563 * it doesn't really have a schema.
7566 lanschema = funcInfo->dobj.namespace->dobj.name;
7570 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
7575 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
7576 plang->lanpltrusted ? "TRUSTED " : "",
7578 appendPQExpBuffer(defqry, " HANDLER %s",
7579 fmtId(funcInfo->dobj.name));
7580 if (OidIsValid(plang->laninline))
7582 appendPQExpBuffer(defqry, " INLINE ");
7583 /* Cope with possibility that inline is in different schema */
7584 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
7585 appendPQExpBuffer(defqry, "%s.",
7586 fmtId(inlineInfo->dobj.namespace->dobj.name));
7587 appendPQExpBuffer(defqry, "%s",
7588 fmtId(inlineInfo->dobj.name));
7590 if (OidIsValid(plang->lanvalidator))
7592 appendPQExpBuffer(defqry, " VALIDATOR ");
7593 /* Cope with possibility that validator is in different schema */
7594 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
7595 appendPQExpBuffer(defqry, "%s.",
7596 fmtId(validatorInfo->dobj.namespace->dobj.name));
7597 appendPQExpBuffer(defqry, "%s",
7598 fmtId(validatorInfo->dobj.name));
7604 * If not dumping parameters, then use CREATE OR REPLACE so that the
7605 * command will not fail if the language is preinstalled in the target
7606 * database. We restrict the use of REPLACE to this case so as to
7607 * eliminate the risk of replacing a language with incompatible
7608 * parameter settings: this command will only succeed at all if there
7609 * is a pg_pltemplate entry, and if there is one, the existing entry
7610 * must match it too.
7612 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
7615 appendPQExpBuffer(defqry, ";\n");
7617 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
7619 lanschema, NULL, plang->lanowner,
7620 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
7621 defqry->data, delqry->data, NULL,
7622 plang->dobj.dependencies, plang->dobj.nDeps,
7625 /* Dump Proc Lang Comments */
7626 resetPQExpBuffer(defqry);
7627 appendPQExpBuffer(defqry, "LANGUAGE %s", qlanname);
7628 dumpComment(fout, defqry->data,
7630 plang->dobj.catId, 0, plang->dobj.dumpId);
7632 if (plang->lanpltrusted)
7633 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
7634 qlanname, NULL, plang->dobj.name,
7636 plang->lanowner, plang->lanacl);
7640 destroyPQExpBuffer(defqry);
7641 destroyPQExpBuffer(delqry);
7645 * format_function_arguments: generate function name and argument list
7647 * This is used when we can rely on pg_get_function_arguments to format
7648 * the argument list.
7651 format_function_arguments(FuncInfo *finfo, char *funcargs)
7655 initPQExpBuffer(&fn);
7656 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
7661 * format_function_arguments_old: generate function name and argument list
7663 * The argument type names are qualified if needed. The function name
7664 * is never qualified.
7666 * This is used only with pre-8.4 servers, so we aren't expecting to see
7667 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
7669 * Any or all of allargtypes, argmodes, argnames may be NULL.
7672 format_function_arguments_old(FuncInfo *finfo, int nallargs,
7680 initPQExpBuffer(&fn);
7681 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
7682 for (j = 0; j < nallargs; j++)
7686 const char *argmode;
7687 const char *argname;
7689 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
7690 typname = getFormattedTypeName(typid, zeroAsOpaque);
7694 switch (argmodes[j][0])
7699 case PROARGMODE_OUT:
7702 case PROARGMODE_INOUT:
7706 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
7714 argname = argnames ? argnames[j] : (char *) NULL;
7715 if (argname && argname[0] == '\0')
7718 appendPQExpBuffer(&fn, "%s%s%s%s%s",
7719 (j > 0) ? ", " : "",
7721 argname ? fmtId(argname) : "",
7726 appendPQExpBuffer(&fn, ")");
7731 * format_function_signature: generate function name and argument list
7733 * This is like format_function_arguments_old except that only a minimal
7734 * list of input argument types is generated; this is sufficient to
7735 * reference the function, but not to define it.
7737 * If honor_quotes is false then the function name is never quoted.
7738 * This is appropriate for use in TOC tags, but not in SQL commands.
7741 format_function_signature(FuncInfo *finfo, bool honor_quotes)
7746 initPQExpBuffer(&fn);
7748 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
7750 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
7751 for (j = 0; j < finfo->nargs; j++)
7755 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
7757 appendPQExpBuffer(&fn, "%s%s",
7758 (j > 0) ? ", " : "",
7762 appendPQExpBuffer(&fn, ")");
7769 * dump out one function
7772 dumpFunc(Archive *fout, FuncInfo *finfo)
7779 char *funcsig; /* identity signature */
7780 char *funcfullsig; /* full signature */
7789 char *proallargtypes;
7802 char **allargtypes = NULL;
7803 char **argmodes = NULL;
7804 char **argnames = NULL;
7805 char **configitems = NULL;
7806 int nconfigitems = 0;
7809 /* Skip if not to be dumped */
7810 if (!finfo->dobj.dump || dataOnly)
7813 query = createPQExpBuffer();
7814 q = createPQExpBuffer();
7815 delqry = createPQExpBuffer();
7816 asPart = createPQExpBuffer();
7818 /* Set proper schema search path so type references list correctly */
7819 selectSourceSchema(finfo->dobj.namespace->dobj.name);
7821 /* Fetch function-specific details */
7822 if (g_fout->remoteVersion >= 80400)
7825 * In 8.4 and up we rely on pg_get_function_arguments and
7826 * pg_get_function_result instead of examining proallargtypes etc.
7828 appendPQExpBuffer(query,
7829 "SELECT proretset, prosrc, probin, "
7830 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
7831 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
7832 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
7833 "proiswindow, provolatile, proisstrict, prosecdef, "
7834 "proconfig, procost, prorows, "
7835 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7836 "FROM pg_catalog.pg_proc "
7837 "WHERE oid = '%u'::pg_catalog.oid",
7838 finfo->dobj.catId.oid);
7840 else if (g_fout->remoteVersion >= 80300)
7842 appendPQExpBuffer(query,
7843 "SELECT proretset, prosrc, probin, "
7844 "proallargtypes, proargmodes, proargnames, "
7845 "false AS proiswindow, "
7846 "provolatile, proisstrict, prosecdef, "
7847 "proconfig, procost, prorows, "
7848 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7849 "FROM pg_catalog.pg_proc "
7850 "WHERE oid = '%u'::pg_catalog.oid",
7851 finfo->dobj.catId.oid);
7853 else if (g_fout->remoteVersion >= 80100)
7855 appendPQExpBuffer(query,
7856 "SELECT proretset, prosrc, probin, "
7857 "proallargtypes, proargmodes, proargnames, "
7858 "false AS proiswindow, "
7859 "provolatile, proisstrict, prosecdef, "
7860 "null AS proconfig, 0 AS procost, 0 AS prorows, "
7861 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7862 "FROM pg_catalog.pg_proc "
7863 "WHERE oid = '%u'::pg_catalog.oid",
7864 finfo->dobj.catId.oid);
7866 else if (g_fout->remoteVersion >= 80000)
7868 appendPQExpBuffer(query,
7869 "SELECT proretset, prosrc, probin, "
7870 "null AS proallargtypes, "
7871 "null AS proargmodes, "
7873 "false AS proiswindow, "
7874 "provolatile, proisstrict, prosecdef, "
7875 "null AS proconfig, 0 AS procost, 0 AS prorows, "
7876 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7877 "FROM pg_catalog.pg_proc "
7878 "WHERE oid = '%u'::pg_catalog.oid",
7879 finfo->dobj.catId.oid);
7881 else if (g_fout->remoteVersion >= 70300)
7883 appendPQExpBuffer(query,
7884 "SELECT proretset, prosrc, probin, "
7885 "null AS proallargtypes, "
7886 "null AS proargmodes, "
7887 "null AS proargnames, "
7888 "false AS proiswindow, "
7889 "provolatile, proisstrict, prosecdef, "
7890 "null AS proconfig, 0 AS procost, 0 AS prorows, "
7891 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
7892 "FROM pg_catalog.pg_proc "
7893 "WHERE oid = '%u'::pg_catalog.oid",
7894 finfo->dobj.catId.oid);
7896 else if (g_fout->remoteVersion >= 70100)
7898 appendPQExpBuffer(query,
7899 "SELECT proretset, prosrc, probin, "
7900 "null AS proallargtypes, "
7901 "null AS proargmodes, "
7902 "null AS proargnames, "
7903 "false AS proiswindow, "
7904 "case when proiscachable then 'i' else 'v' end AS provolatile, "
7906 "false AS prosecdef, "
7907 "null AS proconfig, 0 AS procost, 0 AS prorows, "
7908 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
7910 "WHERE oid = '%u'::oid",
7911 finfo->dobj.catId.oid);
7915 appendPQExpBuffer(query,
7916 "SELECT proretset, prosrc, probin, "
7917 "null AS proallargtypes, "
7918 "null AS proargmodes, "
7919 "null AS proargnames, "
7920 "false AS proiswindow, "
7921 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
7922 "false AS proisstrict, "
7923 "false AS prosecdef, "
7924 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
7925 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
7927 "WHERE oid = '%u'::oid",
7928 finfo->dobj.catId.oid);
7931 res = PQexec(g_conn, query->data);
7932 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7934 /* Expecting a single result only */
7935 ntups = PQntuples(res);
7938 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7939 "query returned %d rows instead of one: %s\n",
7941 ntups, query->data);
7945 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
7946 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
7947 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
7948 if (g_fout->remoteVersion >= 80400)
7950 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
7951 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
7952 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
7953 proallargtypes = proargmodes = proargnames = NULL;
7957 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
7958 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
7959 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
7960 funcargs = funciargs = funcresult = NULL;
7962 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
7963 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
7964 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
7965 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
7966 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
7967 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
7968 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
7969 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
7972 * See backend/commands/functioncmds.c for details of how the 'AS' clause
7973 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
7974 * versions would set it to "-". There are no known cases in which prosrc
7975 * is unused, so the tests below for "-" are probably useless.
7977 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
7979 appendPQExpBuffer(asPart, "AS ");
7980 appendStringLiteralAH(asPart, probin, fout);
7981 if (strcmp(prosrc, "-") != 0)
7983 appendPQExpBuffer(asPart, ", ");
7986 * where we have bin, use dollar quoting if allowed and src
7987 * contains quote or backslash; else use regular quoting.
7989 if (disable_dollar_quoting ||
7990 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
7991 appendStringLiteralAH(asPart, prosrc, fout);
7993 appendStringLiteralDQ(asPart, prosrc, NULL);
7998 if (strcmp(prosrc, "-") != 0)
8000 appendPQExpBuffer(asPart, "AS ");
8001 /* with no bin, dollar quote src unconditionally if allowed */
8002 if (disable_dollar_quoting)
8003 appendStringLiteralAH(asPart, prosrc, fout);
8005 appendStringLiteralDQ(asPart, prosrc, NULL);
8009 nallargs = finfo->nargs; /* unless we learn different from allargs */
8011 if (proallargtypes && *proallargtypes)
8015 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
8016 nitems < finfo->nargs)
8018 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
8027 if (proargmodes && *proargmodes)
8031 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
8034 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
8041 if (proargnames && *proargnames)
8045 if (!parsePGArray(proargnames, &argnames, &nitems) ||
8048 write_msg(NULL, "WARNING: could not parse proargnames array\n");
8055 if (proconfig && *proconfig)
8057 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
8059 write_msg(NULL, "WARNING: could not parse proconfig array\n");
8069 /* 8.4 or later; we rely on server-side code for most of the work */
8070 funcfullsig = format_function_arguments(finfo, funcargs);
8071 funcsig = format_function_arguments(finfo, funciargs);
8075 /* pre-8.4, do it ourselves */
8076 funcsig = format_function_arguments_old(finfo, nallargs, allargtypes,
8077 argmodes, argnames);
8078 funcfullsig = funcsig;
8081 funcsig_tag = format_function_signature(finfo, false);
8084 * DROP must be fully qualified in case same name appears in pg_catalog
8086 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
8087 fmtId(finfo->dobj.namespace->dobj.name),
8090 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
8092 appendPQExpBuffer(q, "RETURNS %s", funcresult);
8095 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
8096 appendPQExpBuffer(q, "RETURNS %s%s",
8097 (proretset[0] == 't') ? "SETOF " : "",
8102 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
8104 if (proiswindow[0] == 't')
8105 appendPQExpBuffer(q, " WINDOW");
8107 if (provolatile[0] != PROVOLATILE_VOLATILE)
8109 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
8110 appendPQExpBuffer(q, " IMMUTABLE");
8111 else if (provolatile[0] == PROVOLATILE_STABLE)
8112 appendPQExpBuffer(q, " STABLE");
8113 else if (provolatile[0] != PROVOLATILE_VOLATILE)
8115 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
8121 if (proisstrict[0] == 't')
8122 appendPQExpBuffer(q, " STRICT");
8124 if (prosecdef[0] == 't')
8125 appendPQExpBuffer(q, " SECURITY DEFINER");
8128 * COST and ROWS are emitted only if present and not default, so as not to
8129 * break backwards-compatibility of the dump without need. Keep this code
8130 * in sync with the defaults in functioncmds.c.
8132 if (strcmp(procost, "0") != 0)
8134 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
8136 /* default cost is 1 */
8137 if (strcmp(procost, "1") != 0)
8138 appendPQExpBuffer(q, " COST %s", procost);
8142 /* default cost is 100 */
8143 if (strcmp(procost, "100") != 0)
8144 appendPQExpBuffer(q, " COST %s", procost);
8147 if (proretset[0] == 't' &&
8148 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
8149 appendPQExpBuffer(q, " ROWS %s", prorows);
8151 for (i = 0; i < nconfigitems; i++)
8153 /* we feel free to scribble on configitems[] here */
8154 char *configitem = configitems[i];
8157 pos = strchr(configitem, '=');
8161 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
8164 * Some GUC variable names are 'LIST' type and hence must not be
8167 if (pg_strcasecmp(configitem, "DateStyle") == 0
8168 || pg_strcasecmp(configitem, "search_path") == 0)
8169 appendPQExpBuffer(q, "%s", pos);
8171 appendStringLiteralAH(q, pos, fout);
8174 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
8176 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
8178 finfo->dobj.namespace->dobj.name,
8180 finfo->rolname, false,
8181 "FUNCTION", SECTION_PRE_DATA,
8182 q->data, delqry->data, NULL,
8183 finfo->dobj.dependencies, finfo->dobj.nDeps,
8186 /* Dump Function Comments */
8187 resetPQExpBuffer(q);
8188 appendPQExpBuffer(q, "FUNCTION %s", funcsig);
8189 dumpComment(fout, q->data,
8190 finfo->dobj.namespace->dobj.name, finfo->rolname,
8191 finfo->dobj.catId, 0, finfo->dobj.dumpId);
8193 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
8194 funcsig, NULL, funcsig_tag,
8195 finfo->dobj.namespace->dobj.name,
8196 finfo->rolname, finfo->proacl);
8200 destroyPQExpBuffer(query);
8201 destroyPQExpBuffer(q);
8202 destroyPQExpBuffer(delqry);
8203 destroyPQExpBuffer(asPart);
8218 * Dump a user-defined cast
8221 dumpCast(Archive *fout, CastInfo *cast)
8225 PQExpBuffer castsig;
8226 FuncInfo *funcInfo = NULL;
8227 TypeInfo *sourceInfo;
8228 TypeInfo *targetInfo;
8233 if (OidIsValid(cast->castfunc))
8235 funcInfo = findFuncByOid(cast->castfunc);
8236 if (funcInfo == NULL)
8241 * As per discussion we dump casts if one or more of the underlying
8242 * objects (the conversion function and the two data types) are not
8243 * builtin AND if all of the non-builtin objects are included in the dump.
8244 * Builtin meaning, the namespace name does not start with "pg_".
8246 sourceInfo = findTypeByOid(cast->castsource);
8247 targetInfo = findTypeByOid(cast->casttarget);
8249 if (sourceInfo == NULL || targetInfo == NULL)
8253 * Skip this cast if all objects are from pg_
8255 if ((funcInfo == NULL ||
8256 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
8257 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
8258 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
8262 * Skip cast if function isn't from pg_ and is not to be dumped.
8265 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
8266 !funcInfo->dobj.dump)
8270 * Same for the source type
8272 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
8273 !sourceInfo->dobj.dump)
8277 * and the target type.
8279 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
8280 !targetInfo->dobj.dump)
8283 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
8284 selectSourceSchema("pg_catalog");
8286 defqry = createPQExpBuffer();
8287 delqry = createPQExpBuffer();
8288 castsig = createPQExpBuffer();
8290 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
8291 getFormattedTypeName(cast->castsource, zeroAsNone),
8292 getFormattedTypeName(cast->casttarget, zeroAsNone));
8294 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
8295 getFormattedTypeName(cast->castsource, zeroAsNone),
8296 getFormattedTypeName(cast->casttarget, zeroAsNone));
8298 switch (cast->castmethod)
8300 case COERCION_METHOD_BINARY:
8301 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
8303 case COERCION_METHOD_INOUT:
8304 appendPQExpBuffer(defqry, "WITH INOUT");
8306 case COERCION_METHOD_FUNCTION:
8309 * Always qualify the function name, in case it is not in
8310 * pg_catalog schema (format_function_signature won't qualify it).
8312 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
8313 fmtId(funcInfo->dobj.namespace->dobj.name));
8314 appendPQExpBuffer(defqry, "%s",
8315 format_function_signature(funcInfo, true));
8318 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
8321 if (cast->castcontext == 'a')
8322 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
8323 else if (cast->castcontext == 'i')
8324 appendPQExpBuffer(defqry, " AS IMPLICIT");
8325 appendPQExpBuffer(defqry, ";\n");
8327 appendPQExpBuffer(castsig, "CAST (%s AS %s)",
8328 getFormattedTypeName(cast->castsource, zeroAsNone),
8329 getFormattedTypeName(cast->casttarget, zeroAsNone));
8331 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
8333 "pg_catalog", NULL, "",
8334 false, "CAST", SECTION_PRE_DATA,
8335 defqry->data, delqry->data, NULL,
8336 cast->dobj.dependencies, cast->dobj.nDeps,
8339 /* Dump Cast Comments */
8340 resetPQExpBuffer(defqry);
8341 appendPQExpBuffer(defqry, "CAST (%s AS %s)",
8342 getFormattedTypeName(cast->castsource, zeroAsNone),
8343 getFormattedTypeName(cast->casttarget, zeroAsNone));
8344 dumpComment(fout, defqry->data,
8346 cast->dobj.catId, 0, cast->dobj.dumpId);
8348 destroyPQExpBuffer(defqry);
8349 destroyPQExpBuffer(delqry);
8350 destroyPQExpBuffer(castsig);
8355 * write out a single operator definition
8358 dumpOpr(Archive *fout, OprInfo *oprinfo)
8364 PQExpBuffer details;
8389 /* Skip if not to be dumped */
8390 if (!oprinfo->dobj.dump || dataOnly)
8394 * some operators are invalid because they were the result of user
8395 * defining operators before commutators exist
8397 if (!OidIsValid(oprinfo->oprcode))
8400 query = createPQExpBuffer();
8401 q = createPQExpBuffer();
8402 delq = createPQExpBuffer();
8403 oprid = createPQExpBuffer();
8404 details = createPQExpBuffer();
8406 /* Make sure we are in proper schema so regoperator works correctly */
8407 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
8409 if (g_fout->remoteVersion >= 80300)
8411 appendPQExpBuffer(query, "SELECT oprkind, "
8412 "oprcode::pg_catalog.regprocedure, "
8413 "oprleft::pg_catalog.regtype, "
8414 "oprright::pg_catalog.regtype, "
8415 "oprcom::pg_catalog.regoperator, "
8416 "oprnegate::pg_catalog.regoperator, "
8417 "oprrest::pg_catalog.regprocedure, "
8418 "oprjoin::pg_catalog.regprocedure, "
8419 "oprcanmerge, oprcanhash "
8420 "FROM pg_catalog.pg_operator "
8421 "WHERE oid = '%u'::pg_catalog.oid",
8422 oprinfo->dobj.catId.oid);
8424 else if (g_fout->remoteVersion >= 70300)
8426 appendPQExpBuffer(query, "SELECT oprkind, "
8427 "oprcode::pg_catalog.regprocedure, "
8428 "oprleft::pg_catalog.regtype, "
8429 "oprright::pg_catalog.regtype, "
8430 "oprcom::pg_catalog.regoperator, "
8431 "oprnegate::pg_catalog.regoperator, "
8432 "oprrest::pg_catalog.regprocedure, "
8433 "oprjoin::pg_catalog.regprocedure, "
8434 "(oprlsortop != 0) AS oprcanmerge, "
8436 "FROM pg_catalog.pg_operator "
8437 "WHERE oid = '%u'::pg_catalog.oid",
8438 oprinfo->dobj.catId.oid);
8440 else if (g_fout->remoteVersion >= 70100)
8442 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
8443 "CASE WHEN oprleft = 0 THEN '-' "
8444 "ELSE format_type(oprleft, NULL) END AS oprleft, "
8445 "CASE WHEN oprright = 0 THEN '-' "
8446 "ELSE format_type(oprright, NULL) END AS oprright, "
8447 "oprcom, oprnegate, oprrest, oprjoin, "
8448 "(oprlsortop != 0) AS oprcanmerge, "
8451 "WHERE oid = '%u'::oid",
8452 oprinfo->dobj.catId.oid);
8456 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
8457 "CASE WHEN oprleft = 0 THEN '-'::name "
8458 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
8459 "CASE WHEN oprright = 0 THEN '-'::name "
8460 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
8461 "oprcom, oprnegate, oprrest, oprjoin, "
8462 "(oprlsortop != 0) AS oprcanmerge, "
8465 "WHERE oid = '%u'::oid",
8466 oprinfo->dobj.catId.oid);
8469 res = PQexec(g_conn, query->data);
8470 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8472 /* Expecting a single result only */
8473 ntups = PQntuples(res);
8476 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8477 "query returned %d rows instead of one: %s\n",
8479 ntups, query->data);
8483 i_oprkind = PQfnumber(res, "oprkind");
8484 i_oprcode = PQfnumber(res, "oprcode");
8485 i_oprleft = PQfnumber(res, "oprleft");
8486 i_oprright = PQfnumber(res, "oprright");
8487 i_oprcom = PQfnumber(res, "oprcom");
8488 i_oprnegate = PQfnumber(res, "oprnegate");
8489 i_oprrest = PQfnumber(res, "oprrest");
8490 i_oprjoin = PQfnumber(res, "oprjoin");
8491 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
8492 i_oprcanhash = PQfnumber(res, "oprcanhash");
8494 oprkind = PQgetvalue(res, 0, i_oprkind);
8495 oprcode = PQgetvalue(res, 0, i_oprcode);
8496 oprleft = PQgetvalue(res, 0, i_oprleft);
8497 oprright = PQgetvalue(res, 0, i_oprright);
8498 oprcom = PQgetvalue(res, 0, i_oprcom);
8499 oprnegate = PQgetvalue(res, 0, i_oprnegate);
8500 oprrest = PQgetvalue(res, 0, i_oprrest);
8501 oprjoin = PQgetvalue(res, 0, i_oprjoin);
8502 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
8503 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
8505 appendPQExpBuffer(details, " PROCEDURE = %s",
8506 convertRegProcReference(oprcode));
8508 appendPQExpBuffer(oprid, "%s (",
8509 oprinfo->dobj.name);
8512 * right unary means there's a left arg and left unary means there's a
8515 if (strcmp(oprkind, "r") == 0 ||
8516 strcmp(oprkind, "b") == 0)
8518 if (g_fout->remoteVersion >= 70100)
8521 name = fmtId(oprleft);
8522 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
8523 appendPQExpBuffer(oprid, "%s", name);
8526 appendPQExpBuffer(oprid, "NONE");
8528 if (strcmp(oprkind, "l") == 0 ||
8529 strcmp(oprkind, "b") == 0)
8531 if (g_fout->remoteVersion >= 70100)
8534 name = fmtId(oprright);
8535 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
8536 appendPQExpBuffer(oprid, ", %s)", name);
8539 appendPQExpBuffer(oprid, ", NONE)");
8541 name = convertOperatorReference(oprcom);
8543 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
8545 name = convertOperatorReference(oprnegate);
8547 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
8549 if (strcmp(oprcanmerge, "t") == 0)
8550 appendPQExpBuffer(details, ",\n MERGES");
8552 if (strcmp(oprcanhash, "t") == 0)
8553 appendPQExpBuffer(details, ",\n HASHES");
8555 name = convertRegProcReference(oprrest);
8557 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
8559 name = convertRegProcReference(oprjoin);
8561 appendPQExpBuffer(details, ",\n JOIN = %s", name);
8564 * DROP must be fully qualified in case same name appears in pg_catalog
8566 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
8567 fmtId(oprinfo->dobj.namespace->dobj.name),
8570 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
8571 oprinfo->dobj.name, details->data);
8573 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
8575 oprinfo->dobj.namespace->dobj.name,
8578 false, "OPERATOR", SECTION_PRE_DATA,
8579 q->data, delq->data, NULL,
8580 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
8583 /* Dump Operator Comments */
8584 resetPQExpBuffer(q);
8585 appendPQExpBuffer(q, "OPERATOR %s", oprid->data);
8586 dumpComment(fout, q->data,
8587 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
8588 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
8592 destroyPQExpBuffer(query);
8593 destroyPQExpBuffer(q);
8594 destroyPQExpBuffer(delq);
8595 destroyPQExpBuffer(oprid);
8596 destroyPQExpBuffer(details);
8600 * Convert a function reference obtained from pg_operator
8602 * Returns what to print, or NULL if function references is InvalidOid
8604 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
8605 * argument-types part. In prior versions, the input is a REGPROC display.
8608 convertRegProcReference(const char *proc)
8610 /* In all cases "-" means a null reference */
8611 if (strcmp(proc, "-") == 0)
8614 if (g_fout->remoteVersion >= 70300)
8620 name = strdup(proc);
8621 /* find non-double-quoted left paren */
8623 for (paren = name; *paren; paren++)
8625 if (*paren == '(' && !inquote)
8636 /* REGPROC before 7.3 does not quote its result */
8641 * Convert an operator cross-reference obtained from pg_operator
8643 * Returns what to print, or NULL to print nothing
8645 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
8646 * argument-types part, and add OPERATOR() decoration if the name is
8647 * schema-qualified. In older versions, the input is just a numeric OID,
8648 * which we search our operator list for.
8651 convertOperatorReference(const char *opr)
8655 /* In all cases "0" means a null reference */
8656 if (strcmp(opr, "0") == 0)
8659 if (g_fout->remoteVersion >= 70300)
8668 /* find non-double-quoted left paren, and check for non-quoted dot */
8671 for (ptr = name; *ptr; ptr++)
8675 else if (*ptr == '.' && !inquote)
8677 else if (*ptr == '(' && !inquote)
8683 /* If not schema-qualified, don't need to add OPERATOR() */
8686 oname = malloc(strlen(name) + 11);
8687 sprintf(oname, "OPERATOR(%s)", name);
8692 oprInfo = findOprByOid(atooid(opr));
8693 if (oprInfo == NULL)
8695 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
8699 return oprInfo->dobj.name;
8703 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
8705 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
8706 * argument lists of these functions are predetermined. Note that the
8707 * caller should ensure we are in the proper schema, because the results
8708 * are search path dependent!
8711 convertTSFunction(Oid funcOid)
8718 snprintf(query, sizeof(query),
8719 "SELECT '%u'::pg_catalog.regproc", funcOid);
8720 res = PQexec(g_conn, query);
8721 check_sql_result(res, g_conn, query, PGRES_TUPLES_OK);
8723 ntups = PQntuples(res);
8726 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8727 "query returned %d rows instead of one: %s\n",
8733 result = strdup(PQgetvalue(res, 0, 0));
8743 * write out a single operator class definition
8746 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
8778 /* Skip if not to be dumped */
8779 if (!opcinfo->dobj.dump || dataOnly)
8783 * XXX currently we do not implement dumping of operator classes from
8784 * pre-7.3 databases. This could be done but it seems not worth the
8787 if (g_fout->remoteVersion < 70300)
8790 query = createPQExpBuffer();
8791 q = createPQExpBuffer();
8792 delq = createPQExpBuffer();
8794 /* Make sure we are in proper schema so regoperator works correctly */
8795 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
8797 /* Get additional fields from the pg_opclass row */
8798 if (g_fout->remoteVersion >= 80300)
8800 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
8801 "opckeytype::pg_catalog.regtype, "
8803 "opfname AS opcfamily, "
8804 "nspname AS opcfamilynsp, "
8805 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
8806 "FROM pg_catalog.pg_opclass c "
8807 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
8808 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
8809 "WHERE c.oid = '%u'::pg_catalog.oid",
8810 opcinfo->dobj.catId.oid);
8814 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
8815 "opckeytype::pg_catalog.regtype, "
8817 "NULL AS opcfamily, "
8818 "NULL AS opcfamilynsp, "
8819 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
8820 "FROM pg_catalog.pg_opclass "
8821 "WHERE oid = '%u'::pg_catalog.oid",
8822 opcinfo->dobj.catId.oid);
8825 res = PQexec(g_conn, query->data);
8826 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8828 /* Expecting a single result only */
8829 ntups = PQntuples(res);
8832 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8833 "query returned %d rows instead of one: %s\n",
8835 ntups, query->data);
8839 i_opcintype = PQfnumber(res, "opcintype");
8840 i_opckeytype = PQfnumber(res, "opckeytype");
8841 i_opcdefault = PQfnumber(res, "opcdefault");
8842 i_opcfamily = PQfnumber(res, "opcfamily");
8843 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
8844 i_amname = PQfnumber(res, "amname");
8846 opcintype = PQgetvalue(res, 0, i_opcintype);
8847 opckeytype = PQgetvalue(res, 0, i_opckeytype);
8848 opcdefault = PQgetvalue(res, 0, i_opcdefault);
8849 opcfamily = PQgetvalue(res, 0, i_opcfamily);
8850 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
8851 /* amname will still be needed after we PQclear res */
8852 amname = strdup(PQgetvalue(res, 0, i_amname));
8855 * DROP must be fully qualified in case same name appears in pg_catalog
8857 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
8858 fmtId(opcinfo->dobj.namespace->dobj.name));
8859 appendPQExpBuffer(delq, ".%s",
8860 fmtId(opcinfo->dobj.name));
8861 appendPQExpBuffer(delq, " USING %s;\n",
8864 /* Build the fixed portion of the CREATE command */
8865 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
8866 fmtId(opcinfo->dobj.name));
8867 if (strcmp(opcdefault, "t") == 0)
8868 appendPQExpBuffer(q, "DEFAULT ");
8869 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
8872 if (strlen(opcfamily) > 0 &&
8873 (strcmp(opcfamily, opcinfo->dobj.name) != 0 ||
8874 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
8876 appendPQExpBuffer(q, " FAMILY ");
8877 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
8878 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
8879 appendPQExpBuffer(q, "%s", fmtId(opcfamily));
8881 appendPQExpBuffer(q, " AS\n ");
8885 if (strcmp(opckeytype, "-") != 0)
8887 appendPQExpBuffer(q, "STORAGE %s",
8895 * Now fetch and print the OPERATOR entries (pg_amop rows).
8897 resetPQExpBuffer(query);
8899 if (g_fout->remoteVersion >= 80400)
8902 * Print only those opfamily members that are tied to the opclass by
8903 * pg_depend entries.
8905 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping
8906 * an older server's opclass in which it is used. This is to avoid
8907 * hard-to-detect breakage if a newer pg_dump is used to dump from an
8908 * older server and then reload into that old version. This can go
8909 * away once 8.3 is so old as to not be of interest to anyone.
8911 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
8912 "amopopr::pg_catalog.regoperator "
8913 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
8914 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
8915 "AND refobjid = '%u'::pg_catalog.oid "
8916 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
8917 "AND objid = ao.oid "
8918 "ORDER BY amopstrategy",
8919 opcinfo->dobj.catId.oid);
8921 else if (g_fout->remoteVersion >= 80300)
8924 * Print only those opfamily members that are tied to the opclass by
8925 * pg_depend entries.
8927 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
8928 "amopopr::pg_catalog.regoperator "
8929 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
8930 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
8931 "AND refobjid = '%u'::pg_catalog.oid "
8932 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
8933 "AND objid = ao.oid "
8934 "ORDER BY amopstrategy",
8935 opcinfo->dobj.catId.oid);
8939 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
8940 "amopopr::pg_catalog.regoperator "
8941 "FROM pg_catalog.pg_amop "
8942 "WHERE amopclaid = '%u'::pg_catalog.oid "
8943 "ORDER BY amopstrategy",
8944 opcinfo->dobj.catId.oid);
8947 res = PQexec(g_conn, query->data);
8948 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8950 ntups = PQntuples(res);
8952 i_amopstrategy = PQfnumber(res, "amopstrategy");
8953 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
8954 i_amopopr = PQfnumber(res, "amopopr");
8956 for (i = 0; i < ntups; i++)
8958 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
8959 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
8960 amopopr = PQgetvalue(res, i, i_amopopr);
8963 appendPQExpBuffer(q, " ,\n ");
8965 appendPQExpBuffer(q, "OPERATOR %s %s",
8966 amopstrategy, amopopr);
8967 if (strcmp(amopreqcheck, "t") == 0)
8968 appendPQExpBuffer(q, " RECHECK");
8976 * Now fetch and print the FUNCTION entries (pg_amproc rows).
8978 resetPQExpBuffer(query);
8980 if (g_fout->remoteVersion >= 80300)
8983 * Print only those opfamily members that are tied to the opclass by
8984 * pg_depend entries.
8986 appendPQExpBuffer(query, "SELECT amprocnum, "
8987 "amproc::pg_catalog.regprocedure "
8988 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
8989 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
8990 "AND refobjid = '%u'::pg_catalog.oid "
8991 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
8992 "AND objid = ap.oid "
8993 "ORDER BY amprocnum",
8994 opcinfo->dobj.catId.oid);
8998 appendPQExpBuffer(query, "SELECT amprocnum, "
8999 "amproc::pg_catalog.regprocedure "
9000 "FROM pg_catalog.pg_amproc "
9001 "WHERE amopclaid = '%u'::pg_catalog.oid "
9002 "ORDER BY amprocnum",
9003 opcinfo->dobj.catId.oid);
9006 res = PQexec(g_conn, query->data);
9007 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9009 ntups = PQntuples(res);
9011 i_amprocnum = PQfnumber(res, "amprocnum");
9012 i_amproc = PQfnumber(res, "amproc");
9014 for (i = 0; i < ntups; i++)
9016 amprocnum = PQgetvalue(res, i, i_amprocnum);
9017 amproc = PQgetvalue(res, i, i_amproc);
9020 appendPQExpBuffer(q, " ,\n ");
9022 appendPQExpBuffer(q, "FUNCTION %s %s",
9030 appendPQExpBuffer(q, ";\n");
9032 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
9034 opcinfo->dobj.namespace->dobj.name,
9037 false, "OPERATOR CLASS", SECTION_PRE_DATA,
9038 q->data, delq->data, NULL,
9039 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
9042 /* Dump Operator Class Comments */
9043 resetPQExpBuffer(q);
9044 appendPQExpBuffer(q, "OPERATOR CLASS %s",
9045 fmtId(opcinfo->dobj.name));
9046 appendPQExpBuffer(q, " USING %s",
9048 dumpComment(fout, q->data,
9049 NULL, opcinfo->rolname,
9050 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
9053 destroyPQExpBuffer(query);
9054 destroyPQExpBuffer(q);
9055 destroyPQExpBuffer(delq);
9060 * write out a single operator family definition
9063 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
9070 PGresult *res_procs;
9078 int i_amproclefttype;
9079 int i_amprocrighttype;
9086 char *amproclefttype;
9087 char *amprocrighttype;
9091 /* Skip if not to be dumped */
9092 if (!opfinfo->dobj.dump || dataOnly)
9096 * We want to dump the opfamily only if (1) it contains "loose" operators
9097 * or functions, or (2) it contains an opclass with a different name or
9098 * owner. Otherwise it's sufficient to let it be created during creation
9099 * of the contained opclass, and not dumping it improves portability of
9100 * the dump. Since we have to fetch the loose operators/funcs anyway, do
9104 query = createPQExpBuffer();
9105 q = createPQExpBuffer();
9106 delq = createPQExpBuffer();
9108 /* Make sure we are in proper schema so regoperator works correctly */
9109 selectSourceSchema(opfinfo->dobj.namespace->dobj.name);
9112 * Fetch only those opfamily members that are tied directly to the
9113 * opfamily by pg_depend entries.
9115 if (g_fout->remoteVersion >= 80400)
9118 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping
9119 * an older server's opclass in which it is used. This is to avoid
9120 * hard-to-detect breakage if a newer pg_dump is used to dump from an
9121 * older server and then reload into that old version. This can go
9122 * away once 8.3 is so old as to not be of interest to anyone.
9124 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
9125 "amopopr::pg_catalog.regoperator "
9126 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
9127 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9128 "AND refobjid = '%u'::pg_catalog.oid "
9129 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
9130 "AND objid = ao.oid "
9131 "ORDER BY amopstrategy",
9132 opfinfo->dobj.catId.oid);
9136 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
9137 "amopopr::pg_catalog.regoperator "
9138 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
9139 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9140 "AND refobjid = '%u'::pg_catalog.oid "
9141 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
9142 "AND objid = ao.oid "
9143 "ORDER BY amopstrategy",
9144 opfinfo->dobj.catId.oid);
9147 res_ops = PQexec(g_conn, query->data);
9148 check_sql_result(res_ops, g_conn, query->data, PGRES_TUPLES_OK);
9150 resetPQExpBuffer(query);
9152 appendPQExpBuffer(query, "SELECT amprocnum, "
9153 "amproc::pg_catalog.regprocedure, "
9154 "amproclefttype::pg_catalog.regtype, "
9155 "amprocrighttype::pg_catalog.regtype "
9156 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
9157 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9158 "AND refobjid = '%u'::pg_catalog.oid "
9159 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
9160 "AND objid = ap.oid "
9161 "ORDER BY amprocnum",
9162 opfinfo->dobj.catId.oid);
9164 res_procs = PQexec(g_conn, query->data);
9165 check_sql_result(res_procs, g_conn, query->data, PGRES_TUPLES_OK);
9167 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
9169 /* No loose members, so check contained opclasses */
9170 resetPQExpBuffer(query);
9172 appendPQExpBuffer(query, "SELECT 1 "
9173 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
9174 "WHERE f.oid = '%u'::pg_catalog.oid "
9175 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
9176 "AND refobjid = f.oid "
9177 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
9178 "AND objid = c.oid "
9179 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
9181 opfinfo->dobj.catId.oid);
9183 res = PQexec(g_conn, query->data);
9184 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9186 if (PQntuples(res) == 0)
9188 /* no need to dump it, so bail out */
9192 destroyPQExpBuffer(query);
9193 destroyPQExpBuffer(q);
9194 destroyPQExpBuffer(delq);
9201 /* Get additional fields from the pg_opfamily row */
9202 resetPQExpBuffer(query);
9204 appendPQExpBuffer(query, "SELECT "
9205 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
9206 "FROM pg_catalog.pg_opfamily "
9207 "WHERE oid = '%u'::pg_catalog.oid",
9208 opfinfo->dobj.catId.oid);
9210 res = PQexec(g_conn, query->data);
9211 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9213 /* Expecting a single result only */
9214 ntups = PQntuples(res);
9217 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9218 "query returned %d rows instead of one: %s\n",
9220 ntups, query->data);
9224 i_amname = PQfnumber(res, "amname");
9226 /* amname will still be needed after we PQclear res */
9227 amname = strdup(PQgetvalue(res, 0, i_amname));
9230 * DROP must be fully qualified in case same name appears in pg_catalog
9232 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
9233 fmtId(opfinfo->dobj.namespace->dobj.name));
9234 appendPQExpBuffer(delq, ".%s",
9235 fmtId(opfinfo->dobj.name));
9236 appendPQExpBuffer(delq, " USING %s;\n",
9239 /* Build the fixed portion of the CREATE command */
9240 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
9241 fmtId(opfinfo->dobj.name));
9242 appendPQExpBuffer(q, " USING %s;\n",
9247 /* Do we need an ALTER to add loose members? */
9248 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
9250 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
9251 fmtId(opfinfo->dobj.name));
9252 appendPQExpBuffer(q, " USING %s ADD\n ",
9258 * Now fetch and print the OPERATOR entries (pg_amop rows).
9260 ntups = PQntuples(res_ops);
9262 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
9263 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
9264 i_amopopr = PQfnumber(res_ops, "amopopr");
9266 for (i = 0; i < ntups; i++)
9268 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
9269 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
9270 amopopr = PQgetvalue(res_ops, i, i_amopopr);
9273 appendPQExpBuffer(q, " ,\n ");
9275 appendPQExpBuffer(q, "OPERATOR %s %s",
9276 amopstrategy, amopopr);
9277 if (strcmp(amopreqcheck, "t") == 0)
9278 appendPQExpBuffer(q, " RECHECK");
9284 * Now fetch and print the FUNCTION entries (pg_amproc rows).
9286 ntups = PQntuples(res_procs);
9288 i_amprocnum = PQfnumber(res_procs, "amprocnum");
9289 i_amproc = PQfnumber(res_procs, "amproc");
9290 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
9291 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
9293 for (i = 0; i < ntups; i++)
9295 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
9296 amproc = PQgetvalue(res_procs, i, i_amproc);
9297 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
9298 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
9301 appendPQExpBuffer(q, " ,\n ");
9303 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
9304 amprocnum, amproclefttype, amprocrighttype,
9310 appendPQExpBuffer(q, ";\n");
9313 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
9315 opfinfo->dobj.namespace->dobj.name,
9318 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
9319 q->data, delq->data, NULL,
9320 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
9323 /* Dump Operator Family Comments */
9324 resetPQExpBuffer(q);
9325 appendPQExpBuffer(q, "OPERATOR FAMILY %s",
9326 fmtId(opfinfo->dobj.name));
9327 appendPQExpBuffer(q, " USING %s",
9329 dumpComment(fout, q->data,
9330 NULL, opfinfo->rolname,
9331 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
9336 destroyPQExpBuffer(query);
9337 destroyPQExpBuffer(q);
9338 destroyPQExpBuffer(delq);
9343 * write out a single conversion definition
9346 dumpConversion(Archive *fout, ConvInfo *convinfo)
9351 PQExpBuffer details;
9355 int i_conforencoding;
9356 int i_contoencoding;
9359 const char *conname;
9360 const char *conforencoding;
9361 const char *contoencoding;
9362 const char *conproc;
9365 /* Skip if not to be dumped */
9366 if (!convinfo->dobj.dump || dataOnly)
9369 query = createPQExpBuffer();
9370 q = createPQExpBuffer();
9371 delq = createPQExpBuffer();
9372 details = createPQExpBuffer();
9374 /* Make sure we are in proper schema */
9375 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
9377 /* Get conversion-specific details */
9378 appendPQExpBuffer(query, "SELECT conname, "
9379 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
9380 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
9381 "conproc, condefault "
9382 "FROM pg_catalog.pg_conversion c "
9383 "WHERE c.oid = '%u'::pg_catalog.oid",
9384 convinfo->dobj.catId.oid);
9386 res = PQexec(g_conn, query->data);
9387 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9389 /* Expecting a single result only */
9390 ntups = PQntuples(res);
9393 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9394 "query returned %d rows instead of one: %s\n",
9396 ntups, query->data);
9400 i_conname = PQfnumber(res, "conname");
9401 i_conforencoding = PQfnumber(res, "conforencoding");
9402 i_contoencoding = PQfnumber(res, "contoencoding");
9403 i_conproc = PQfnumber(res, "conproc");
9404 i_condefault = PQfnumber(res, "condefault");
9406 conname = PQgetvalue(res, 0, i_conname);
9407 conforencoding = PQgetvalue(res, 0, i_conforencoding);
9408 contoencoding = PQgetvalue(res, 0, i_contoencoding);
9409 conproc = PQgetvalue(res, 0, i_conproc);
9410 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
9413 * DROP must be fully qualified in case same name appears in pg_catalog
9415 appendPQExpBuffer(delq, "DROP CONVERSION %s",
9416 fmtId(convinfo->dobj.namespace->dobj.name));
9417 appendPQExpBuffer(delq, ".%s;\n",
9418 fmtId(convinfo->dobj.name));
9420 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
9421 (condefault) ? "DEFAULT " : "",
9422 fmtId(convinfo->dobj.name));
9423 appendStringLiteralAH(q, conforencoding, fout);
9424 appendPQExpBuffer(q, " TO ");
9425 appendStringLiteralAH(q, contoencoding, fout);
9426 /* regproc is automatically quoted in 7.3 and above */
9427 appendPQExpBuffer(q, " FROM %s;\n", conproc);
9429 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
9430 convinfo->dobj.name,
9431 convinfo->dobj.namespace->dobj.name,
9434 false, "CONVERSION", SECTION_PRE_DATA,
9435 q->data, delq->data, NULL,
9436 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
9439 /* Dump Conversion Comments */
9440 resetPQExpBuffer(q);
9441 appendPQExpBuffer(q, "CONVERSION %s", fmtId(convinfo->dobj.name));
9442 dumpComment(fout, q->data,
9443 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
9444 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
9448 destroyPQExpBuffer(query);
9449 destroyPQExpBuffer(q);
9450 destroyPQExpBuffer(delq);
9451 destroyPQExpBuffer(details);
9455 * format_aggregate_signature: generate aggregate name and argument list
9457 * The argument type names are qualified if needed. The aggregate name
9458 * is never qualified.
9461 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
9463 PQExpBufferData buf;
9466 initPQExpBuffer(&buf);
9468 appendPQExpBuffer(&buf, "%s",
9469 fmtId(agginfo->aggfn.dobj.name));
9471 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
9473 if (agginfo->aggfn.nargs == 0)
9474 appendPQExpBuffer(&buf, "(*)");
9477 appendPQExpBuffer(&buf, "(");
9478 for (j = 0; j < agginfo->aggfn.nargs; j++)
9482 typname = getFormattedTypeName(agginfo->aggfn.argtypes[j], zeroAsOpaque);
9484 appendPQExpBuffer(&buf, "%s%s",
9485 (j > 0) ? ", " : "",
9489 appendPQExpBuffer(&buf, ")");
9496 * write out a single aggregate definition
9499 dumpAgg(Archive *fout, AggInfo *agginfo)
9504 PQExpBuffer details;
9515 const char *aggtransfn;
9516 const char *aggfinalfn;
9517 const char *aggsortop;
9518 const char *aggtranstype;
9519 const char *agginitval;
9522 /* Skip if not to be dumped */
9523 if (!agginfo->aggfn.dobj.dump || dataOnly)
9526 query = createPQExpBuffer();
9527 q = createPQExpBuffer();
9528 delq = createPQExpBuffer();
9529 details = createPQExpBuffer();
9531 /* Make sure we are in proper schema */
9532 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
9534 /* Get aggregate-specific details */
9535 if (g_fout->remoteVersion >= 80100)
9537 appendPQExpBuffer(query, "SELECT aggtransfn, "
9538 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
9539 "aggsortop::pg_catalog.regoperator, "
9541 "'t'::boolean AS convertok "
9542 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
9543 "WHERE a.aggfnoid = p.oid "
9544 "AND p.oid = '%u'::pg_catalog.oid",
9545 agginfo->aggfn.dobj.catId.oid);
9547 else if (g_fout->remoteVersion >= 70300)
9549 appendPQExpBuffer(query, "SELECT aggtransfn, "
9550 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
9553 "'t'::boolean AS convertok "
9554 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
9555 "WHERE a.aggfnoid = p.oid "
9556 "AND p.oid = '%u'::pg_catalog.oid",
9557 agginfo->aggfn.dobj.catId.oid);
9559 else if (g_fout->remoteVersion >= 70100)
9561 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
9562 "format_type(aggtranstype, NULL) AS aggtranstype, "
9565 "'t'::boolean AS convertok "
9566 "FROM pg_aggregate "
9567 "WHERE oid = '%u'::oid",
9568 agginfo->aggfn.dobj.catId.oid);
9572 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
9574 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
9576 "agginitval1 AS agginitval, "
9577 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
9578 "FROM pg_aggregate "
9579 "WHERE oid = '%u'::oid",
9580 agginfo->aggfn.dobj.catId.oid);
9583 res = PQexec(g_conn, query->data);
9584 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9586 /* Expecting a single result only */
9587 ntups = PQntuples(res);
9590 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9591 "query returned %d rows instead of one: %s\n",
9593 ntups, query->data);
9597 i_aggtransfn = PQfnumber(res, "aggtransfn");
9598 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
9599 i_aggsortop = PQfnumber(res, "aggsortop");
9600 i_aggtranstype = PQfnumber(res, "aggtranstype");
9601 i_agginitval = PQfnumber(res, "agginitval");
9602 i_convertok = PQfnumber(res, "convertok");
9604 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
9605 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
9606 aggsortop = PQgetvalue(res, 0, i_aggsortop);
9607 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
9608 agginitval = PQgetvalue(res, 0, i_agginitval);
9609 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
9611 aggsig = format_aggregate_signature(agginfo, fout, true);
9612 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
9616 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
9621 if (g_fout->remoteVersion >= 70300)
9623 /* If using 7.3's regproc or regtype, data is already quoted */
9624 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
9628 else if (g_fout->remoteVersion >= 70100)
9630 /* format_type quotes, regproc does not */
9631 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
9637 /* need quotes all around */
9638 appendPQExpBuffer(details, " SFUNC = %s,\n",
9640 appendPQExpBuffer(details, " STYPE = %s",
9641 fmtId(aggtranstype));
9644 if (!PQgetisnull(res, 0, i_agginitval))
9646 appendPQExpBuffer(details, ",\n INITCOND = ");
9647 appendStringLiteralAH(details, agginitval, fout);
9650 if (strcmp(aggfinalfn, "-") != 0)
9652 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
9656 aggsortop = convertOperatorReference(aggsortop);
9659 appendPQExpBuffer(details, ",\n SORTOP = %s",
9664 * DROP must be fully qualified in case same name appears in pg_catalog
9666 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
9667 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
9670 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
9671 aggsig, details->data);
9673 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
9675 agginfo->aggfn.dobj.namespace->dobj.name,
9677 agginfo->aggfn.rolname,
9678 false, "AGGREGATE", SECTION_PRE_DATA,
9679 q->data, delq->data, NULL,
9680 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
9683 /* Dump Aggregate Comments */
9684 resetPQExpBuffer(q);
9685 appendPQExpBuffer(q, "AGGREGATE %s", aggsig);
9686 dumpComment(fout, q->data,
9687 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
9688 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
9691 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
9692 * command look like a function's GRANT; in particular this affects the
9693 * syntax for zero-argument aggregates.
9698 aggsig = format_function_signature(&agginfo->aggfn, true);
9699 aggsig_tag = format_function_signature(&agginfo->aggfn, false);
9701 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
9703 aggsig, NULL, aggsig_tag,
9704 agginfo->aggfn.dobj.namespace->dobj.name,
9705 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
9712 destroyPQExpBuffer(query);
9713 destroyPQExpBuffer(q);
9714 destroyPQExpBuffer(delq);
9715 destroyPQExpBuffer(details);
9720 * write out a single text search parser
9723 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
9728 /* Skip if not to be dumped */
9729 if (!prsinfo->dobj.dump || dataOnly)
9732 q = createPQExpBuffer();
9733 delq = createPQExpBuffer();
9735 /* Make sure we are in proper schema */
9736 selectSourceSchema(prsinfo->dobj.namespace->dobj.name);
9738 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
9739 fmtId(prsinfo->dobj.name));
9741 appendPQExpBuffer(q, " START = %s,\n",
9742 convertTSFunction(prsinfo->prsstart));
9743 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
9744 convertTSFunction(prsinfo->prstoken));
9745 appendPQExpBuffer(q, " END = %s,\n",
9746 convertTSFunction(prsinfo->prsend));
9747 if (prsinfo->prsheadline != InvalidOid)
9748 appendPQExpBuffer(q, " HEADLINE = %s,\n",
9749 convertTSFunction(prsinfo->prsheadline));
9750 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
9751 convertTSFunction(prsinfo->prslextype));
9754 * DROP must be fully qualified in case same name appears in pg_catalog
9756 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
9757 fmtId(prsinfo->dobj.namespace->dobj.name));
9758 appendPQExpBuffer(delq, ".%s;\n",
9759 fmtId(prsinfo->dobj.name));
9761 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
9763 prsinfo->dobj.namespace->dobj.name,
9766 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
9767 q->data, delq->data, NULL,
9768 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
9771 /* Dump Parser Comments */
9772 resetPQExpBuffer(q);
9773 appendPQExpBuffer(q, "TEXT SEARCH PARSER %s",
9774 fmtId(prsinfo->dobj.name));
9775 dumpComment(fout, q->data,
9777 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
9779 destroyPQExpBuffer(q);
9780 destroyPQExpBuffer(delq);
9785 * write out a single text search dictionary
9788 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
9798 /* Skip if not to be dumped */
9799 if (!dictinfo->dobj.dump || dataOnly)
9802 q = createPQExpBuffer();
9803 delq = createPQExpBuffer();
9804 query = createPQExpBuffer();
9806 /* Fetch name and namespace of the dictionary's template */
9807 selectSourceSchema("pg_catalog");
9808 appendPQExpBuffer(query, "SELECT nspname, tmplname "
9809 "FROM pg_ts_template p, pg_namespace n "
9810 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
9811 dictinfo->dicttemplate);
9812 res = PQexec(g_conn, query->data);
9813 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9814 ntups = PQntuples(res);
9817 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9818 "query returned %d rows instead of one: %s\n",
9820 ntups, query->data);
9823 nspname = PQgetvalue(res, 0, 0);
9824 tmplname = PQgetvalue(res, 0, 1);
9826 /* Make sure we are in proper schema */
9827 selectSourceSchema(dictinfo->dobj.namespace->dobj.name);
9829 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
9830 fmtId(dictinfo->dobj.name));
9832 appendPQExpBuffer(q, " TEMPLATE = ");
9833 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
9834 appendPQExpBuffer(q, "%s.", fmtId(nspname));
9835 appendPQExpBuffer(q, "%s", fmtId(tmplname));
9839 /* the dictinitoption can be dumped straight into the command */
9840 if (dictinfo->dictinitoption)
9841 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
9843 appendPQExpBuffer(q, " );\n");
9846 * DROP must be fully qualified in case same name appears in pg_catalog
9848 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
9849 fmtId(dictinfo->dobj.namespace->dobj.name));
9850 appendPQExpBuffer(delq, ".%s;\n",
9851 fmtId(dictinfo->dobj.name));
9853 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
9854 dictinfo->dobj.name,
9855 dictinfo->dobj.namespace->dobj.name,
9858 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
9859 q->data, delq->data, NULL,
9860 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
9863 /* Dump Dictionary Comments */
9864 resetPQExpBuffer(q);
9865 appendPQExpBuffer(q, "TEXT SEARCH DICTIONARY %s",
9866 fmtId(dictinfo->dobj.name));
9867 dumpComment(fout, q->data,
9868 NULL, dictinfo->rolname,
9869 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
9871 destroyPQExpBuffer(q);
9872 destroyPQExpBuffer(delq);
9873 destroyPQExpBuffer(query);
9878 * write out a single text search template
9881 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
9886 /* Skip if not to be dumped */
9887 if (!tmplinfo->dobj.dump || dataOnly)
9890 q = createPQExpBuffer();
9891 delq = createPQExpBuffer();
9893 /* Make sure we are in proper schema */
9894 selectSourceSchema(tmplinfo->dobj.namespace->dobj.name);
9896 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
9897 fmtId(tmplinfo->dobj.name));
9899 if (tmplinfo->tmplinit != InvalidOid)
9900 appendPQExpBuffer(q, " INIT = %s,\n",
9901 convertTSFunction(tmplinfo->tmplinit));
9902 appendPQExpBuffer(q, " LEXIZE = %s );\n",
9903 convertTSFunction(tmplinfo->tmpllexize));
9906 * DROP must be fully qualified in case same name appears in pg_catalog
9908 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
9909 fmtId(tmplinfo->dobj.namespace->dobj.name));
9910 appendPQExpBuffer(delq, ".%s;\n",
9911 fmtId(tmplinfo->dobj.name));
9913 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
9914 tmplinfo->dobj.name,
9915 tmplinfo->dobj.namespace->dobj.name,
9918 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
9919 q->data, delq->data, NULL,
9920 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
9923 /* Dump Template Comments */
9924 resetPQExpBuffer(q);
9925 appendPQExpBuffer(q, "TEXT SEARCH TEMPLATE %s",
9926 fmtId(tmplinfo->dobj.name));
9927 dumpComment(fout, q->data,
9929 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
9931 destroyPQExpBuffer(q);
9932 destroyPQExpBuffer(delq);
9937 * write out a single text search configuration
9940 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
9953 /* Skip if not to be dumped */
9954 if (!cfginfo->dobj.dump || dataOnly)
9957 q = createPQExpBuffer();
9958 delq = createPQExpBuffer();
9959 query = createPQExpBuffer();
9961 /* Fetch name and namespace of the config's parser */
9962 selectSourceSchema("pg_catalog");
9963 appendPQExpBuffer(query, "SELECT nspname, prsname "
9964 "FROM pg_ts_parser p, pg_namespace n "
9965 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
9966 cfginfo->cfgparser);
9967 res = PQexec(g_conn, query->data);
9968 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9969 ntups = PQntuples(res);
9972 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9973 "query returned %d rows instead of one: %s\n",
9975 ntups, query->data);
9978 nspname = PQgetvalue(res, 0, 0);
9979 prsname = PQgetvalue(res, 0, 1);
9981 /* Make sure we are in proper schema */
9982 selectSourceSchema(cfginfo->dobj.namespace->dobj.name);
9984 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
9985 fmtId(cfginfo->dobj.name));
9987 appendPQExpBuffer(q, " PARSER = ");
9988 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
9989 appendPQExpBuffer(q, "%s.", fmtId(nspname));
9990 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
9994 resetPQExpBuffer(query);
9995 appendPQExpBuffer(query,
9997 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
9998 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
9999 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
10000 "FROM pg_catalog.pg_ts_config_map AS m \n"
10001 "WHERE m.mapcfg = '%u' \n"
10002 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
10003 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
10005 res = PQexec(g_conn, query->data);
10006 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10007 ntups = PQntuples(res);
10009 i_tokenname = PQfnumber(res, "tokenname");
10010 i_dictname = PQfnumber(res, "dictname");
10012 for (i = 0; i < ntups; i++)
10014 char *tokenname = PQgetvalue(res, i, i_tokenname);
10015 char *dictname = PQgetvalue(res, i, i_dictname);
10018 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
10020 /* starting a new token type, so start a new command */
10022 appendPQExpBuffer(q, ";\n");
10023 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
10024 fmtId(cfginfo->dobj.name));
10025 /* tokenname needs quoting, dictname does NOT */
10026 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
10027 fmtId(tokenname), dictname);
10030 appendPQExpBuffer(q, ", %s", dictname);
10034 appendPQExpBuffer(q, ";\n");
10039 * DROP must be fully qualified in case same name appears in pg_catalog
10041 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
10042 fmtId(cfginfo->dobj.namespace->dobj.name));
10043 appendPQExpBuffer(delq, ".%s;\n",
10044 fmtId(cfginfo->dobj.name));
10046 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
10047 cfginfo->dobj.name,
10048 cfginfo->dobj.namespace->dobj.name,
10051 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
10052 q->data, delq->data, NULL,
10053 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
10056 /* Dump Configuration Comments */
10057 resetPQExpBuffer(q);
10058 appendPQExpBuffer(q, "TEXT SEARCH CONFIGURATION %s",
10059 fmtId(cfginfo->dobj.name));
10060 dumpComment(fout, q->data,
10061 NULL, cfginfo->rolname,
10062 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
10064 destroyPQExpBuffer(q);
10065 destroyPQExpBuffer(delq);
10066 destroyPQExpBuffer(query);
10070 * dumpForeignDataWrapper
10071 * write out a single foreign-data wrapper definition
10074 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
10080 /* Skip if not to be dumped */
10081 if (!fdwinfo->dobj.dump || dataOnly)
10084 q = createPQExpBuffer();
10085 delq = createPQExpBuffer();
10087 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
10088 fmtId(fdwinfo->dobj.name));
10090 if (fdwinfo->fdwvalidator && strcmp(fdwinfo->fdwvalidator, "-") != 0)
10091 appendPQExpBuffer(q, " VALIDATOR %s",
10092 fdwinfo->fdwvalidator);
10094 if (fdwinfo->fdwoptions && strlen(fdwinfo->fdwoptions) > 0)
10095 appendPQExpBuffer(q, " OPTIONS (%s)", fdwinfo->fdwoptions);
10097 appendPQExpBuffer(q, ";\n");
10099 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
10100 fmtId(fdwinfo->dobj.name));
10102 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
10103 fdwinfo->dobj.name,
10107 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
10108 q->data, delq->data, NULL,
10109 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
10112 /* Handle the ACL */
10113 namecopy = strdup(fmtId(fdwinfo->dobj.name));
10114 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
10115 "FOREIGN DATA WRAPPER",
10116 namecopy, NULL, fdwinfo->dobj.name,
10117 NULL, fdwinfo->rolname,
10121 destroyPQExpBuffer(q);
10122 destroyPQExpBuffer(delq);
10126 * dumpForeignServer
10127 * write out a foreign server definition
10130 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
10140 /* Skip if not to be dumped */
10141 if (!srvinfo->dobj.dump || dataOnly)
10144 q = createPQExpBuffer();
10145 delq = createPQExpBuffer();
10146 query = createPQExpBuffer();
10148 /* look up the foreign-data wrapper */
10149 selectSourceSchema("pg_catalog");
10150 appendPQExpBuffer(query, "SELECT fdwname "
10151 "FROM pg_foreign_data_wrapper w "
10152 "WHERE w.oid = '%u'",
10154 res = PQexec(g_conn, query->data);
10155 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10156 ntups = PQntuples(res);
10159 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10160 "query returned %d rows instead of one: %s\n",
10162 ntups, query->data);
10165 fdwname = PQgetvalue(res, 0, 0);
10167 appendPQExpBuffer(q, "CREATE SERVER %s", fmtId(srvinfo->dobj.name));
10168 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
10170 appendPQExpBuffer(q, " TYPE ");
10171 appendStringLiteralAH(q, srvinfo->srvtype, fout);
10173 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
10175 appendPQExpBuffer(q, " VERSION ");
10176 appendStringLiteralAH(q, srvinfo->srvversion, fout);
10179 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
10180 appendPQExpBuffer(q, "%s", fmtId(fdwname));
10182 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
10183 appendPQExpBuffer(q, " OPTIONS (%s)", srvinfo->srvoptions);
10185 appendPQExpBuffer(q, ";\n");
10187 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
10188 fmtId(srvinfo->dobj.name));
10190 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
10191 srvinfo->dobj.name,
10195 false, "SERVER", SECTION_PRE_DATA,
10196 q->data, delq->data, NULL,
10197 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
10200 /* Handle the ACL */
10201 namecopy = strdup(fmtId(srvinfo->dobj.name));
10202 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
10204 namecopy, NULL, srvinfo->dobj.name,
10205 NULL, srvinfo->rolname,
10209 /* Dump user mappings */
10210 dumpUserMappings(fout,
10211 srvinfo->dobj.name, NULL,
10213 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
10215 destroyPQExpBuffer(q);
10216 destroyPQExpBuffer(delq);
10222 * This routine is used to dump any user mappings associated with the
10223 * server handed to this routine. Should be called after ArchiveEntry()
10227 dumpUserMappings(Archive *fout,
10228 const char *servername, const char *namespace,
10230 CatalogId catalogId, DumpId dumpId)
10242 q = createPQExpBuffer();
10243 tag = createPQExpBuffer();
10244 delq = createPQExpBuffer();
10245 query = createPQExpBuffer();
10248 * We read from the publicly accessible view pg_user_mappings, so as not
10249 * to fail if run by a non-superuser. Note that the view will show
10250 * umoptions as null if the user hasn't got privileges for the associated
10251 * server; this means that pg_dump will dump such a mapping, but with no
10252 * OPTIONS clause. A possible alternative is to skip such mappings
10253 * altogether, but it's not clear that that's an improvement.
10255 selectSourceSchema("pg_catalog");
10257 appendPQExpBuffer(query,
10259 "array_to_string(ARRAY(SELECT option_name || ' ' || quote_literal(option_value) FROM pg_options_to_table(umoptions)), ', ') AS umoptions\n"
10260 "FROM pg_user_mappings "
10261 "WHERE srvid = %u",
10264 res = PQexec(g_conn, query->data);
10265 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10267 ntups = PQntuples(res);
10268 i_usename = PQfnumber(res, "usename");
10269 i_umoptions = PQfnumber(res, "umoptions");
10271 for (i = 0; i < ntups; i++)
10276 usename = PQgetvalue(res, i, i_usename);
10277 umoptions = PQgetvalue(res, i, i_umoptions);
10279 resetPQExpBuffer(q);
10280 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
10281 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
10283 if (umoptions && strlen(umoptions) > 0)
10284 appendPQExpBuffer(q, " OPTIONS (%s)", umoptions);
10286 appendPQExpBuffer(q, ";\n");
10288 resetPQExpBuffer(delq);
10289 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
10290 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
10292 resetPQExpBuffer(tag);
10293 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
10294 usename, servername);
10296 ArchiveEntry(fout, nilCatalogId, createDumpId(),
10301 "USER MAPPING", SECTION_PRE_DATA,
10302 q->data, delq->data, NULL,
10309 destroyPQExpBuffer(query);
10310 destroyPQExpBuffer(delq);
10311 destroyPQExpBuffer(q);
10315 * Write out default privileges information
10318 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
10324 /* Skip if not to be dumped */
10325 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
10328 q = createPQExpBuffer();
10329 tag = createPQExpBuffer();
10331 switch (daclinfo->defaclobjtype)
10333 case DEFACLOBJ_RELATION:
10336 case DEFACLOBJ_SEQUENCE:
10337 type = "SEQUENCES";
10339 case DEFACLOBJ_FUNCTION:
10340 type = "FUNCTIONS";
10343 /* shouldn't get here */
10344 write_msg(NULL, "unknown object type (%d) in default privileges\n",
10345 (int) daclinfo->defaclobjtype);
10347 type = ""; /* keep compiler quiet */
10350 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
10352 /* build the actual command(s) for this tuple */
10353 if (!buildDefaultACLCommands(type,
10354 daclinfo->dobj.namespace != NULL ?
10355 daclinfo->dobj.namespace->dobj.name : NULL,
10356 daclinfo->defaclacl,
10357 daclinfo->defaclrole,
10358 fout->remoteVersion,
10361 write_msg(NULL, "could not parse default ACL list (%s)\n",
10362 daclinfo->defaclacl);
10366 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
10368 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
10370 daclinfo->defaclrole,
10371 false, "DEFAULT ACL", SECTION_NONE,
10373 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
10376 destroyPQExpBuffer(tag);
10377 destroyPQExpBuffer(q);
10381 * Write out grant/revoke information
10383 * 'objCatId' is the catalog ID of the underlying object.
10384 * 'objDumpId' is the dump ID of the underlying object.
10385 * 'type' must be one of
10386 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
10387 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
10388 * 'name' is the formatted name of the object. Must be quoted etc. already.
10389 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
10390 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
10391 * 'nspname' is the namespace the object is in (NULL if none).
10392 * 'owner' is the owner, NULL if there is no owner (for languages).
10393 * 'acls' is the string read out of the fooacl system catalog field;
10394 * it will be parsed here.
10398 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
10399 const char *type, const char *name, const char *subname,
10400 const char *tag, const char *nspname, const char *owner,
10405 /* Do nothing if ACL dump is not enabled */
10409 /* --data-only skips ACLs *except* BLOB ACLs */
10410 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
10413 sql = createPQExpBuffer();
10415 if (!buildACLCommands(name, subname, type, acls, owner,
10416 "", fout->remoteVersion, sql))
10418 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
10424 ArchiveEntry(fout, nilCatalogId, createDumpId(),
10427 owner ? owner : "",
10428 false, "ACL", SECTION_NONE,
10429 sql->data, "", NULL,
10433 destroyPQExpBuffer(sql);
10438 * write out to fout the declarations (not data) of a user-defined table
10441 dumpTable(Archive *fout, TableInfo *tbinfo)
10443 if (tbinfo->dobj.dump)
10447 if (tbinfo->relkind == RELKIND_SEQUENCE)
10448 dumpSequence(fout, tbinfo);
10449 else if (!dataOnly)
10450 dumpTableSchema(fout, tbinfo);
10452 /* Handle the ACL here */
10453 namecopy = strdup(fmtId(tbinfo->dobj.name));
10454 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
10455 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE",
10456 namecopy, NULL, tbinfo->dobj.name,
10457 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
10461 * Handle column ACLs, if any. Note: we pull these with a separate
10462 * query rather than trying to fetch them during getTableAttrs, so
10463 * that we won't miss ACLs on system columns.
10465 if (g_fout->remoteVersion >= 80400)
10467 PQExpBuffer query = createPQExpBuffer();
10471 appendPQExpBuffer(query,
10472 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
10473 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
10475 tbinfo->dobj.catId.oid);
10476 res = PQexec(g_conn, query->data);
10477 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10479 for (i = 0; i < PQntuples(res); i++)
10481 char *attname = PQgetvalue(res, i, 0);
10482 char *attacl = PQgetvalue(res, i, 1);
10486 attnamecopy = strdup(fmtId(attname));
10487 acltag = malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
10488 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
10489 /* Column's GRANT type is always TABLE */
10490 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
10491 namecopy, attnamecopy, acltag,
10492 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
10498 destroyPQExpBuffer(query);
10507 * write the declaration (not data) of one user-defined table or view
10510 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
10512 PQExpBuffer query = createPQExpBuffer();
10513 PQExpBuffer q = createPQExpBuffer();
10514 PQExpBuffer delq = createPQExpBuffer();
10517 TableInfo **parents;
10518 int actual_atts; /* number of attrs in this CREATE statment */
10523 bool toast_set = false;
10525 /* Make sure we are in proper schema */
10526 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
10528 if (binary_upgrade)
10529 toast_set = binary_upgrade_set_type_oids_by_rel_oid(q,
10530 tbinfo->dobj.catId.oid);
10532 /* Is it a table or a view? */
10533 if (tbinfo->relkind == RELKIND_VIEW)
10537 reltypename = "VIEW";
10539 /* Fetch the view definition */
10540 if (g_fout->remoteVersion >= 70300)
10542 /* Beginning in 7.3, viewname is not unique; rely on OID */
10543 appendPQExpBuffer(query,
10544 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
10545 tbinfo->dobj.catId.oid);
10549 appendPQExpBuffer(query, "SELECT definition AS viewdef "
10550 "FROM pg_views WHERE viewname = ");
10551 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
10552 appendPQExpBuffer(query, ";");
10555 res = PQexec(g_conn, query->data);
10556 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10558 if (PQntuples(res) != 1)
10560 if (PQntuples(res) < 1)
10561 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
10562 tbinfo->dobj.name);
10564 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
10565 tbinfo->dobj.name);
10569 viewdef = PQgetvalue(res, 0, 0);
10571 if (strlen(viewdef) == 0)
10573 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
10574 tbinfo->dobj.name);
10579 * DROP must be fully qualified in case same name appears in
10582 appendPQExpBuffer(delq, "DROP VIEW %s.",
10583 fmtId(tbinfo->dobj.namespace->dobj.name));
10584 appendPQExpBuffer(delq, "%s;\n",
10585 fmtId(tbinfo->dobj.name));
10587 if (binary_upgrade)
10588 binary_upgrade_set_relfilenodes(q, tbinfo->dobj.catId.oid, false);
10590 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
10591 fmtId(tbinfo->dobj.name), viewdef);
10597 reltypename = "TABLE";
10598 numParents = tbinfo->numParents;
10599 parents = tbinfo->parents;
10602 * DROP must be fully qualified in case same name appears in
10605 appendPQExpBuffer(delq, "DROP TABLE %s.",
10606 fmtId(tbinfo->dobj.namespace->dobj.name));
10607 appendPQExpBuffer(delq, "%s;\n",
10608 fmtId(tbinfo->dobj.name));
10610 if (binary_upgrade)
10611 binary_upgrade_set_relfilenodes(q, tbinfo->dobj.catId.oid, false);
10613 appendPQExpBuffer(q, "CREATE TABLE %s",
10614 fmtId(tbinfo->dobj.name));
10615 if (tbinfo->reloftype)
10616 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
10618 for (j = 0; j < tbinfo->numatts; j++)
10621 * Normally, dump if it's one of the table's own attrs, and not
10622 * dropped. But for binary upgrade, dump all the columns.
10624 if ((!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j]) ||
10628 * Default value --- suppress if inherited (except in
10629 * binary-upgrade case, where we're not doing normal
10630 * inheritance) or if it's to be printed separately.
10632 bool has_default = (tbinfo->attrdefs[j] != NULL
10633 && (!tbinfo->inhAttrDef[j] || binary_upgrade)
10634 && !tbinfo->attrdefs[j]->separate);
10637 * Not Null constraint --- suppress if inherited, except in
10638 * binary-upgrade case.
10640 bool has_notnull = (tbinfo->notnull[j]
10641 && (!tbinfo->inhNotNull[j] || binary_upgrade));
10643 if (tbinfo->reloftype && !has_default && !has_notnull)
10646 /* Format properly if not first attr */
10647 if (actual_atts == 0)
10648 appendPQExpBuffer(q, " (");
10650 appendPQExpBuffer(q, ",");
10651 appendPQExpBuffer(q, "\n ");
10654 /* Attribute name */
10655 appendPQExpBuffer(q, "%s ",
10656 fmtId(tbinfo->attnames[j]));
10658 if (tbinfo->attisdropped[j])
10661 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
10662 * so we will not have gotten a valid type name; insert
10663 * INTEGER as a stopgap. We'll clean things up later.
10665 appendPQExpBuffer(q, "INTEGER /* dummy */");
10666 /* Skip all the rest, too */
10670 /* Attribute type */
10671 if (tbinfo->reloftype)
10673 appendPQExpBuffer(q, "WITH OPTIONS");
10675 else if (g_fout->remoteVersion >= 70100)
10677 appendPQExpBuffer(q, "%s",
10678 tbinfo->atttypnames[j]);
10682 /* If no format_type, fake it */
10683 appendPQExpBuffer(q, "%s",
10684 myFormatType(tbinfo->atttypnames[j],
10685 tbinfo->atttypmod[j]));
10689 appendPQExpBuffer(q, " DEFAULT %s",
10690 tbinfo->attrdefs[j]->adef_expr);
10693 appendPQExpBuffer(q, " NOT NULL");
10698 * Add non-inherited CHECK constraints, if any.
10700 for (j = 0; j < tbinfo->ncheck; j++)
10702 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
10704 if (constr->separate || !constr->conislocal)
10707 if (actual_atts == 0)
10708 appendPQExpBuffer(q, " (\n ");
10710 appendPQExpBuffer(q, ",\n ");
10712 appendPQExpBuffer(q, "CONSTRAINT %s ",
10713 fmtId(constr->dobj.name));
10714 appendPQExpBuffer(q, "%s", constr->condef);
10720 appendPQExpBuffer(q, "\n)");
10721 else if (!tbinfo->reloftype)
10724 * We must have a parenthesized attribute list, even though empty,
10725 * when not using the OF TYPE syntax.
10727 appendPQExpBuffer(q, " (\n)");
10730 if (numParents > 0 && !binary_upgrade)
10732 appendPQExpBuffer(q, "\nINHERITS (");
10733 for (k = 0; k < numParents; k++)
10735 TableInfo *parentRel = parents[k];
10738 appendPQExpBuffer(q, ", ");
10739 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
10740 appendPQExpBuffer(q, "%s.",
10741 fmtId(parentRel->dobj.namespace->dobj.name));
10742 appendPQExpBuffer(q, "%s",
10743 fmtId(parentRel->dobj.name));
10745 appendPQExpBuffer(q, ")");
10748 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
10749 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
10751 bool addcomma = false;
10753 appendPQExpBuffer(q, "\nWITH (");
10754 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
10757 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
10759 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
10761 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
10762 tbinfo->toast_reloptions);
10764 appendPQExpBuffer(q, ")");
10767 appendPQExpBuffer(q, ";\n");
10770 * To create binary-compatible heap files, we have to ensure the same
10771 * physical column order, including dropped columns, as in the
10772 * original. Therefore, we create dropped columns above and drop them
10773 * here, also updating their attlen/attalign values so that the
10774 * dropped column can be skipped properly. (We do not bother with
10775 * restoring the original attbyval setting.) Also, inheritance
10776 * relationships are set up by doing ALTER INHERIT rather than using
10777 * an INHERITS clause --- the latter would possibly mess up the column
10778 * order. That also means we have to take care about setting
10779 * attislocal correctly, plus fix up any inherited CHECK constraints.
10781 if (binary_upgrade)
10783 for (j = 0; j < tbinfo->numatts; j++)
10785 if (tbinfo->attisdropped[j])
10787 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
10788 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
10789 "SET attlen = %d, "
10790 "attalign = '%c', attbyval = false\n"
10791 "WHERE attname = ",
10793 tbinfo->attalign[j]);
10794 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
10795 appendPQExpBuffer(q, "\n AND attrelid = ");
10796 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10797 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10799 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10800 fmtId(tbinfo->dobj.name));
10801 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
10802 fmtId(tbinfo->attnames[j]));
10804 else if (!tbinfo->attislocal[j])
10806 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
10807 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
10808 "SET attislocal = false\n"
10809 "WHERE attname = ");
10810 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
10811 appendPQExpBuffer(q, "\n AND attrelid = ");
10812 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10813 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10817 for (k = 0; k < tbinfo->ncheck; k++)
10819 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
10821 if (constr->separate || constr->conislocal)
10824 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
10825 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10826 fmtId(tbinfo->dobj.name));
10827 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
10828 fmtId(constr->dobj.name));
10829 appendPQExpBuffer(q, "%s;\n", constr->condef);
10830 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
10831 "SET conislocal = false\n"
10832 "WHERE contype = 'c' AND conname = ");
10833 appendStringLiteralAH(q, constr->dobj.name, fout);
10834 appendPQExpBuffer(q, "\n AND conrelid = ");
10835 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10836 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10839 if (numParents > 0)
10841 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
10842 for (k = 0; k < numParents; k++)
10844 TableInfo *parentRel = parents[k];
10846 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
10847 fmtId(tbinfo->dobj.name));
10848 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
10849 appendPQExpBuffer(q, "%s.",
10850 fmtId(parentRel->dobj.namespace->dobj.name));
10851 appendPQExpBuffer(q, "%s;\n",
10852 fmtId(parentRel->dobj.name));
10856 appendPQExpBuffer(q, "\n-- For binary upgrade, set relfrozenxid.\n");
10857 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
10858 "SET relfrozenxid = '%u'\n"
10860 tbinfo->frozenxid);
10861 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
10862 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
10865 /* Loop dumping statistics and storage statements */
10866 for (j = 0; j < tbinfo->numatts; j++)
10869 * Dump per-column statistics information. We only issue an ALTER
10870 * TABLE statement if the attstattarget entry for this column is
10871 * non-negative (i.e. it's not the default value)
10873 if (tbinfo->attstattarget[j] >= 0 &&
10874 !tbinfo->attisdropped[j])
10876 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10877 fmtId(tbinfo->dobj.name));
10878 appendPQExpBuffer(q, "ALTER COLUMN %s ",
10879 fmtId(tbinfo->attnames[j]));
10880 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
10881 tbinfo->attstattarget[j]);
10885 * Dump per-column storage information. The statement is only
10886 * dumped if the storage has been changed from the type's default.
10888 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
10890 switch (tbinfo->attstorage[j])
10896 storage = "EXTERNAL";
10902 storage = "EXTENDED";
10909 * Only dump the statement if it's a storage type we recognize
10911 if (storage != NULL)
10913 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10914 fmtId(tbinfo->dobj.name));
10915 appendPQExpBuffer(q, "ALTER COLUMN %s ",
10916 fmtId(tbinfo->attnames[j]));
10917 appendPQExpBuffer(q, "SET STORAGE %s;\n",
10923 * Dump per-column attributes.
10925 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
10927 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
10928 fmtId(tbinfo->dobj.name));
10929 appendPQExpBuffer(q, "ALTER COLUMN %s ",
10930 fmtId(tbinfo->attnames[j]));
10931 appendPQExpBuffer(q, "SET (%s);\n",
10932 tbinfo->attoptions[j]);
10937 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
10939 tbinfo->dobj.namespace->dobj.name,
10940 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
10942 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
10943 reltypename, SECTION_PRE_DATA,
10944 q->data, delq->data, NULL,
10945 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
10949 /* Dump Table Comments */
10950 dumpTableComment(fout, tbinfo, reltypename);
10952 /* Dump comments on inlined table constraints */
10953 for (j = 0; j < tbinfo->ncheck; j++)
10955 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
10957 if (constr->separate || !constr->conislocal)
10960 dumpTableConstraintComment(fout, constr);
10963 destroyPQExpBuffer(query);
10964 destroyPQExpBuffer(q);
10965 destroyPQExpBuffer(delq);
10969 * dumpAttrDef --- dump an attribute's default-value declaration
10972 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
10974 TableInfo *tbinfo = adinfo->adtable;
10975 int adnum = adinfo->adnum;
10979 /* Only print it if "separate" mode is selected */
10980 if (!tbinfo->dobj.dump || !adinfo->separate || dataOnly)
10983 /* Don't print inherited defaults, either, except for binary upgrade */
10984 if (tbinfo->inhAttrDef[adnum - 1] && !binary_upgrade)
10987 q = createPQExpBuffer();
10988 delq = createPQExpBuffer();
10990 appendPQExpBuffer(q, "ALTER TABLE %s ",
10991 fmtId(tbinfo->dobj.name));
10992 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
10993 fmtId(tbinfo->attnames[adnum - 1]),
10994 adinfo->adef_expr);
10997 * DROP must be fully qualified in case same name appears in pg_catalog
10999 appendPQExpBuffer(delq, "ALTER TABLE %s.",
11000 fmtId(tbinfo->dobj.namespace->dobj.name));
11001 appendPQExpBuffer(delq, "%s ",
11002 fmtId(tbinfo->dobj.name));
11003 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
11004 fmtId(tbinfo->attnames[adnum - 1]));
11006 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
11007 tbinfo->attnames[adnum - 1],
11008 tbinfo->dobj.namespace->dobj.name,
11011 false, "DEFAULT", SECTION_PRE_DATA,
11012 q->data, delq->data, NULL,
11013 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
11016 destroyPQExpBuffer(q);
11017 destroyPQExpBuffer(delq);
11021 * getAttrName: extract the correct name for an attribute
11023 * The array tblInfo->attnames[] only provides names of user attributes;
11024 * if a system attribute number is supplied, we have to fake it.
11025 * We also do a little bit of bounds checking for safety's sake.
11027 static const char *
11028 getAttrName(int attrnum, TableInfo *tblInfo)
11030 if (attrnum > 0 && attrnum <= tblInfo->numatts)
11031 return tblInfo->attnames[attrnum - 1];
11034 case SelfItemPointerAttributeNumber:
11036 case ObjectIdAttributeNumber:
11038 case MinTransactionIdAttributeNumber:
11040 case MinCommandIdAttributeNumber:
11042 case MaxTransactionIdAttributeNumber:
11044 case MaxCommandIdAttributeNumber:
11046 case TableOidAttributeNumber:
11049 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
11050 attrnum, tblInfo->dobj.name);
11052 return NULL; /* keep compiler quiet */
11057 * write out to fout a user-defined index
11060 dumpIndex(Archive *fout, IndxInfo *indxinfo)
11062 TableInfo *tbinfo = indxinfo->indextable;
11069 q = createPQExpBuffer();
11070 delq = createPQExpBuffer();
11073 * If there's an associated constraint, don't dump the index per se, but
11074 * do dump any comment for it. (This is safe because dependency ordering
11075 * will have ensured the constraint is emitted first.)
11077 if (indxinfo->indexconstraint == 0)
11079 if (binary_upgrade)
11080 binary_upgrade_set_relfilenodes(q, indxinfo->dobj.catId.oid, true);
11082 /* Plain secondary index */
11083 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
11085 /* If the index is clustered, we need to record that. */
11086 if (indxinfo->indisclustered)
11088 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
11089 fmtId(tbinfo->dobj.name));
11090 appendPQExpBuffer(q, " ON %s;\n",
11091 fmtId(indxinfo->dobj.name));
11095 * DROP must be fully qualified in case same name appears in
11098 appendPQExpBuffer(delq, "DROP INDEX %s.",
11099 fmtId(tbinfo->dobj.namespace->dobj.name));
11100 appendPQExpBuffer(delq, "%s;\n",
11101 fmtId(indxinfo->dobj.name));
11103 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
11104 indxinfo->dobj.name,
11105 tbinfo->dobj.namespace->dobj.name,
11106 indxinfo->tablespace,
11107 tbinfo->rolname, false,
11108 "INDEX", SECTION_POST_DATA,
11109 q->data, delq->data, NULL,
11110 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
11114 /* Dump Index Comments */
11115 resetPQExpBuffer(q);
11116 appendPQExpBuffer(q, "INDEX %s",
11117 fmtId(indxinfo->dobj.name));
11118 dumpComment(fout, q->data,
11119 tbinfo->dobj.namespace->dobj.name,
11121 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
11123 destroyPQExpBuffer(q);
11124 destroyPQExpBuffer(delq);
11129 * write out to fout a user-defined constraint
11132 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
11134 TableInfo *tbinfo = coninfo->contable;
11138 /* Skip if not to be dumped */
11139 if (!coninfo->dobj.dump || dataOnly)
11142 q = createPQExpBuffer();
11143 delq = createPQExpBuffer();
11145 if (coninfo->contype == 'p' ||
11146 coninfo->contype == 'u' ||
11147 coninfo->contype == 'x')
11149 /* Index-related constraint */
11150 IndxInfo *indxinfo;
11153 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
11155 if (indxinfo == NULL)
11157 write_msg(NULL, "missing index for constraint \"%s\"\n",
11158 coninfo->dobj.name);
11162 if (binary_upgrade && !coninfo->condef)
11163 binary_upgrade_set_relfilenodes(q, indxinfo->dobj.catId.oid, true);
11165 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
11166 fmtId(tbinfo->dobj.name));
11167 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
11168 fmtId(coninfo->dobj.name));
11170 if (coninfo->condef)
11172 /* pg_get_constraintdef should have provided everything */
11173 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
11177 appendPQExpBuffer(q, "%s (",
11178 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
11179 for (k = 0; k < indxinfo->indnkeys; k++)
11181 int indkey = (int) indxinfo->indkeys[k];
11182 const char *attname;
11184 if (indkey == InvalidAttrNumber)
11186 attname = getAttrName(indkey, tbinfo);
11188 appendPQExpBuffer(q, "%s%s",
11189 (k == 0) ? "" : ", ",
11193 appendPQExpBuffer(q, ")");
11195 if (indxinfo->options && strlen(indxinfo->options) > 0)
11196 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
11198 if (coninfo->condeferrable)
11200 appendPQExpBuffer(q, " DEFERRABLE");
11201 if (coninfo->condeferred)
11202 appendPQExpBuffer(q, " INITIALLY DEFERRED");
11205 appendPQExpBuffer(q, ";\n");
11208 /* If the index is clustered, we need to record that. */
11209 if (indxinfo->indisclustered)
11211 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
11212 fmtId(tbinfo->dobj.name));
11213 appendPQExpBuffer(q, " ON %s;\n",
11214 fmtId(indxinfo->dobj.name));
11218 * DROP must be fully qualified in case same name appears in
11221 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
11222 fmtId(tbinfo->dobj.namespace->dobj.name));
11223 appendPQExpBuffer(delq, "%s ",
11224 fmtId(tbinfo->dobj.name));
11225 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11226 fmtId(coninfo->dobj.name));
11228 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11229 coninfo->dobj.name,
11230 tbinfo->dobj.namespace->dobj.name,
11231 indxinfo->tablespace,
11232 tbinfo->rolname, false,
11233 "CONSTRAINT", SECTION_POST_DATA,
11234 q->data, delq->data, NULL,
11235 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11238 else if (coninfo->contype == 'f')
11241 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
11242 * current table data is not processed
11244 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
11245 fmtId(tbinfo->dobj.name));
11246 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
11247 fmtId(coninfo->dobj.name),
11251 * DROP must be fully qualified in case same name appears in
11254 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
11255 fmtId(tbinfo->dobj.namespace->dobj.name));
11256 appendPQExpBuffer(delq, "%s ",
11257 fmtId(tbinfo->dobj.name));
11258 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11259 fmtId(coninfo->dobj.name));
11261 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11262 coninfo->dobj.name,
11263 tbinfo->dobj.namespace->dobj.name,
11265 tbinfo->rolname, false,
11266 "FK CONSTRAINT", SECTION_POST_DATA,
11267 q->data, delq->data, NULL,
11268 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11271 else if (coninfo->contype == 'c' && tbinfo)
11273 /* CHECK constraint on a table */
11275 /* Ignore if not to be dumped separately */
11276 if (coninfo->separate)
11278 /* not ONLY since we want it to propagate to children */
11279 appendPQExpBuffer(q, "ALTER TABLE %s\n",
11280 fmtId(tbinfo->dobj.name));
11281 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
11282 fmtId(coninfo->dobj.name),
11286 * DROP must be fully qualified in case same name appears in
11289 appendPQExpBuffer(delq, "ALTER TABLE %s.",
11290 fmtId(tbinfo->dobj.namespace->dobj.name));
11291 appendPQExpBuffer(delq, "%s ",
11292 fmtId(tbinfo->dobj.name));
11293 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11294 fmtId(coninfo->dobj.name));
11296 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11297 coninfo->dobj.name,
11298 tbinfo->dobj.namespace->dobj.name,
11300 tbinfo->rolname, false,
11301 "CHECK CONSTRAINT", SECTION_POST_DATA,
11302 q->data, delq->data, NULL,
11303 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11307 else if (coninfo->contype == 'c' && tbinfo == NULL)
11309 /* CHECK constraint on a domain */
11310 TypeInfo *tyinfo = coninfo->condomain;
11312 /* Ignore if not to be dumped separately */
11313 if (coninfo->separate)
11315 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
11316 fmtId(tyinfo->dobj.name));
11317 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
11318 fmtId(coninfo->dobj.name),
11322 * DROP must be fully qualified in case same name appears in
11325 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
11326 fmtId(tyinfo->dobj.namespace->dobj.name));
11327 appendPQExpBuffer(delq, "%s ",
11328 fmtId(tyinfo->dobj.name));
11329 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
11330 fmtId(coninfo->dobj.name));
11332 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
11333 coninfo->dobj.name,
11334 tyinfo->dobj.namespace->dobj.name,
11336 tyinfo->rolname, false,
11337 "CHECK CONSTRAINT", SECTION_POST_DATA,
11338 q->data, delq->data, NULL,
11339 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
11345 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
11349 /* Dump Constraint Comments --- only works for table constraints */
11350 if (tbinfo && coninfo->separate)
11351 dumpTableConstraintComment(fout, coninfo);
11353 destroyPQExpBuffer(q);
11354 destroyPQExpBuffer(delq);
11358 * dumpTableConstraintComment --- dump a constraint's comment if any
11360 * This is split out because we need the function in two different places
11361 * depending on whether the constraint is dumped as part of CREATE TABLE
11362 * or as a separate ALTER command.
11365 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
11367 TableInfo *tbinfo = coninfo->contable;
11368 PQExpBuffer q = createPQExpBuffer();
11370 appendPQExpBuffer(q, "CONSTRAINT %s ",
11371 fmtId(coninfo->dobj.name));
11372 appendPQExpBuffer(q, "ON %s",
11373 fmtId(tbinfo->dobj.name));
11374 dumpComment(fout, q->data,
11375 tbinfo->dobj.namespace->dobj.name,
11377 coninfo->dobj.catId, 0,
11378 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
11380 destroyPQExpBuffer(q);
11384 * findLastBuiltInOid -
11385 * find the last built in oid
11387 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
11388 * pg_database entry for the current database
11391 findLastBuiltinOid_V71(const char *dbname)
11396 PQExpBuffer query = createPQExpBuffer();
11398 resetPQExpBuffer(query);
11399 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
11400 appendStringLiteralAH(query, dbname, g_fout);
11402 res = PQexec(g_conn, query->data);
11403 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11405 ntups = PQntuples(res);
11408 write_msg(NULL, "missing pg_database entry for this database\n");
11413 write_msg(NULL, "found more than one pg_database entry for this database\n");
11416 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
11418 destroyPQExpBuffer(query);
11423 * findLastBuiltInOid -
11424 * find the last built in oid
11426 * For 7.0, we do this by assuming that the last thing that initdb does is to
11427 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
11428 * initdb won't be changing anymore, it'll do.
11431 findLastBuiltinOid_V70(void)
11437 res = PQexec(g_conn,
11438 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
11439 check_sql_result(res, g_conn,
11440 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
11442 ntups = PQntuples(res);
11445 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
11450 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
11453 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
11459 dumpSequence(Archive *fout, TableInfo *tbinfo)
11472 PQExpBuffer query = createPQExpBuffer();
11473 PQExpBuffer delqry = createPQExpBuffer();
11475 /* Make sure we are in proper schema */
11476 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
11478 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
11479 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
11481 if (g_fout->remoteVersion >= 80400)
11483 appendPQExpBuffer(query,
11484 "SELECT sequence_name, "
11485 "start_value, last_value, increment_by, "
11486 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
11487 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
11489 "END AS max_value, "
11490 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
11491 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
11493 "END AS min_value, "
11494 "cache_value, is_cycled, is_called from %s",
11496 fmtId(tbinfo->dobj.name));
11500 appendPQExpBuffer(query,
11501 "SELECT sequence_name, "
11502 "0 AS start_value, last_value, increment_by, "
11503 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
11504 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
11506 "END AS max_value, "
11507 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
11508 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
11510 "END AS min_value, "
11511 "cache_value, is_cycled, is_called from %s",
11513 fmtId(tbinfo->dobj.name));
11516 res = PQexec(g_conn, query->data);
11517 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11519 if (PQntuples(res) != 1)
11521 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
11522 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
11524 tbinfo->dobj.name, PQntuples(res));
11528 /* Disable this check: it fails if sequence has been renamed */
11530 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
11532 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
11533 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
11538 startv = PQgetvalue(res, 0, 1);
11539 last = PQgetvalue(res, 0, 2);
11540 incby = PQgetvalue(res, 0, 3);
11541 if (!PQgetisnull(res, 0, 4))
11542 maxv = PQgetvalue(res, 0, 4);
11543 if (!PQgetisnull(res, 0, 5))
11544 minv = PQgetvalue(res, 0, 5);
11545 cache = PQgetvalue(res, 0, 6);
11546 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
11547 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
11550 * The logic we use for restoring sequences is as follows:
11552 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
11553 * last_val for start if called is false, else use min_val for start_val).
11554 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
11555 * BY command for it.
11557 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
11561 resetPQExpBuffer(delqry);
11564 * DROP must be fully qualified in case same name appears in
11567 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
11568 fmtId(tbinfo->dobj.namespace->dobj.name));
11569 appendPQExpBuffer(delqry, "%s;\n",
11570 fmtId(tbinfo->dobj.name));
11572 resetPQExpBuffer(query);
11574 if (binary_upgrade)
11576 binary_upgrade_set_relfilenodes(query, tbinfo->dobj.catId.oid, false);
11577 binary_upgrade_set_type_oids_by_rel_oid(query, tbinfo->dobj.catId.oid);
11580 appendPQExpBuffer(query,
11581 "CREATE SEQUENCE %s\n",
11582 fmtId(tbinfo->dobj.name));
11584 if (g_fout->remoteVersion >= 80400)
11585 appendPQExpBuffer(query, " START WITH %s\n", startv);
11589 * Versions before 8.4 did not remember the true start value. If
11590 * is_called is false then the sequence has never been incremented
11591 * so we can use last_val. Otherwise punt and let it default.
11594 appendPQExpBuffer(query, " START WITH %s\n", last);
11597 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
11600 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
11602 appendPQExpBuffer(query, " NO MINVALUE\n");
11605 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
11607 appendPQExpBuffer(query, " NO MAXVALUE\n");
11609 appendPQExpBuffer(query,
11611 cache, (cycled ? "\n CYCLE" : ""));
11613 appendPQExpBuffer(query, ";\n");
11615 /* binary_upgrade: no need to clear TOAST table oid */
11617 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
11619 tbinfo->dobj.namespace->dobj.name,
11622 false, "SEQUENCE", SECTION_PRE_DATA,
11623 query->data, delqry->data, NULL,
11624 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
11628 * If the sequence is owned by a table column, emit the ALTER for it
11629 * as a separate TOC entry immediately following the sequence's own
11630 * entry. It's OK to do this rather than using full sorting logic,
11631 * because the dependency that tells us it's owned will have forced
11632 * the table to be created first. We can't just include the ALTER in
11633 * the TOC entry because it will fail if we haven't reassigned the
11634 * sequence owner to match the table's owner.
11636 * We need not schema-qualify the table reference because both
11637 * sequence and table must be in the same schema.
11639 if (OidIsValid(tbinfo->owning_tab))
11641 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
11643 if (owning_tab && owning_tab->dobj.dump)
11645 resetPQExpBuffer(query);
11646 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
11647 fmtId(tbinfo->dobj.name));
11648 appendPQExpBuffer(query, " OWNED BY %s",
11649 fmtId(owning_tab->dobj.name));
11650 appendPQExpBuffer(query, ".%s;\n",
11651 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
11653 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11655 tbinfo->dobj.namespace->dobj.name,
11658 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
11659 query->data, "", NULL,
11660 &(tbinfo->dobj.dumpId), 1,
11665 /* Dump Sequence Comments */
11666 resetPQExpBuffer(query);
11667 appendPQExpBuffer(query, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
11668 dumpComment(fout, query->data,
11669 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
11670 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
11675 resetPQExpBuffer(query);
11676 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
11677 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
11678 appendPQExpBuffer(query, ", %s, %s);\n",
11679 last, (called ? "true" : "false"));
11681 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11683 tbinfo->dobj.namespace->dobj.name,
11686 false, "SEQUENCE SET", SECTION_PRE_DATA,
11687 query->data, "", NULL,
11688 &(tbinfo->dobj.dumpId), 1,
11694 destroyPQExpBuffer(query);
11695 destroyPQExpBuffer(delqry);
11699 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
11701 TableInfo *tbinfo = tginfo->tgtable;
11703 PQExpBuffer delqry;
11712 query = createPQExpBuffer();
11713 delqry = createPQExpBuffer();
11716 * DROP must be fully qualified in case same name appears in pg_catalog
11718 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
11719 fmtId(tginfo->dobj.name));
11720 appendPQExpBuffer(delqry, "ON %s.",
11721 fmtId(tbinfo->dobj.namespace->dobj.name));
11722 appendPQExpBuffer(delqry, "%s;\n",
11723 fmtId(tbinfo->dobj.name));
11727 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
11731 if (tginfo->tgisconstraint)
11733 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
11734 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
11738 appendPQExpBuffer(query, "CREATE TRIGGER ");
11739 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
11741 appendPQExpBuffer(query, "\n ");
11745 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
11746 appendPQExpBuffer(query, "BEFORE");
11748 appendPQExpBuffer(query, "AFTER");
11749 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
11751 appendPQExpBuffer(query, " INSERT");
11754 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
11757 appendPQExpBuffer(query, " OR DELETE");
11759 appendPQExpBuffer(query, " DELETE");
11762 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
11765 appendPQExpBuffer(query, " OR UPDATE");
11767 appendPQExpBuffer(query, " UPDATE");
11770 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
11773 appendPQExpBuffer(query, " OR TRUNCATE");
11775 appendPQExpBuffer(query, " TRUNCATE");
11778 appendPQExpBuffer(query, " ON %s\n",
11779 fmtId(tbinfo->dobj.name));
11781 if (tginfo->tgisconstraint)
11783 if (OidIsValid(tginfo->tgconstrrelid))
11785 /* If we are using regclass, name is already quoted */
11786 if (g_fout->remoteVersion >= 70300)
11787 appendPQExpBuffer(query, " FROM %s\n ",
11788 tginfo->tgconstrrelname);
11790 appendPQExpBuffer(query, " FROM %s\n ",
11791 fmtId(tginfo->tgconstrrelname));
11793 if (!tginfo->tgdeferrable)
11794 appendPQExpBuffer(query, "NOT ");
11795 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
11796 if (tginfo->tginitdeferred)
11797 appendPQExpBuffer(query, "DEFERRED\n");
11799 appendPQExpBuffer(query, "IMMEDIATE\n");
11802 if (TRIGGER_FOR_ROW(tginfo->tgtype))
11803 appendPQExpBuffer(query, " FOR EACH ROW\n ");
11805 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
11807 /* In 7.3, result of regproc is already quoted */
11808 if (g_fout->remoteVersion >= 70300)
11809 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
11812 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
11813 fmtId(tginfo->tgfname));
11815 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
11818 for (findx = 0; findx < tginfo->tgnargs; findx++)
11820 /* find the embedded null that terminates this trigger argument */
11821 size_t tlen = strlen(p);
11823 if (p + tlen >= tgargs + lentgargs)
11825 /* hm, not found before end of bytea value... */
11826 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
11829 tbinfo->dobj.name);
11834 appendPQExpBuffer(query, ", ");
11835 appendStringLiteralAH(query, p, fout);
11839 appendPQExpBuffer(query, ");\n");
11842 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
11844 appendPQExpBuffer(query, "\nALTER TABLE %s ",
11845 fmtId(tbinfo->dobj.name));
11846 switch (tginfo->tgenabled)
11850 appendPQExpBuffer(query, "DISABLE");
11853 appendPQExpBuffer(query, "ENABLE ALWAYS");
11856 appendPQExpBuffer(query, "ENABLE REPLICA");
11859 appendPQExpBuffer(query, "ENABLE");
11862 appendPQExpBuffer(query, " TRIGGER %s;\n",
11863 fmtId(tginfo->dobj.name));
11866 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
11868 tbinfo->dobj.namespace->dobj.name,
11870 tbinfo->rolname, false,
11871 "TRIGGER", SECTION_POST_DATA,
11872 query->data, delqry->data, NULL,
11873 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
11876 resetPQExpBuffer(query);
11877 appendPQExpBuffer(query, "TRIGGER %s ",
11878 fmtId(tginfo->dobj.name));
11879 appendPQExpBuffer(query, "ON %s",
11880 fmtId(tbinfo->dobj.name));
11882 dumpComment(fout, query->data,
11883 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
11884 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
11886 destroyPQExpBuffer(query);
11887 destroyPQExpBuffer(delqry);
11895 dumpRule(Archive *fout, RuleInfo *rinfo)
11897 TableInfo *tbinfo = rinfo->ruletable;
11900 PQExpBuffer delcmd;
11903 /* Skip if not to be dumped */
11904 if (!rinfo->dobj.dump || dataOnly)
11908 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
11909 * we do not want to dump it as a separate object.
11911 if (!rinfo->separate)
11915 * Make sure we are in proper schema.
11917 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
11919 query = createPQExpBuffer();
11920 cmd = createPQExpBuffer();
11921 delcmd = createPQExpBuffer();
11923 if (g_fout->remoteVersion >= 70300)
11925 appendPQExpBuffer(query,
11926 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
11927 rinfo->dobj.catId.oid);
11931 /* Rule name was unique before 7.3 ... */
11932 appendPQExpBuffer(query,
11933 "SELECT pg_get_ruledef('%s') AS definition",
11937 res = PQexec(g_conn, query->data);
11938 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11940 if (PQntuples(res) != 1)
11942 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
11943 rinfo->dobj.name, tbinfo->dobj.name);
11947 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
11950 * Add the command to alter the rules replication firing semantics if it
11951 * differs from the default.
11953 if (rinfo->ev_enabled != 'O')
11955 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
11956 fmtId(tbinfo->dobj.namespace->dobj.name));
11957 appendPQExpBuffer(cmd, "%s ",
11958 fmtId(tbinfo->dobj.name));
11959 switch (rinfo->ev_enabled)
11962 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
11963 fmtId(rinfo->dobj.name));
11966 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
11967 fmtId(rinfo->dobj.name));
11970 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
11971 fmtId(rinfo->dobj.name));
11977 * DROP must be fully qualified in case same name appears in pg_catalog
11979 appendPQExpBuffer(delcmd, "DROP RULE %s ",
11980 fmtId(rinfo->dobj.name));
11981 appendPQExpBuffer(delcmd, "ON %s.",
11982 fmtId(tbinfo->dobj.namespace->dobj.name));
11983 appendPQExpBuffer(delcmd, "%s;\n",
11984 fmtId(tbinfo->dobj.name));
11986 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
11988 tbinfo->dobj.namespace->dobj.name,
11990 tbinfo->rolname, false,
11991 "RULE", SECTION_POST_DATA,
11992 cmd->data, delcmd->data, NULL,
11993 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
11996 /* Dump rule comments */
11997 resetPQExpBuffer(query);
11998 appendPQExpBuffer(query, "RULE %s",
11999 fmtId(rinfo->dobj.name));
12000 appendPQExpBuffer(query, " ON %s",
12001 fmtId(tbinfo->dobj.name));
12002 dumpComment(fout, query->data,
12003 tbinfo->dobj.namespace->dobj.name,
12005 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
12009 destroyPQExpBuffer(query);
12010 destroyPQExpBuffer(cmd);
12011 destroyPQExpBuffer(delcmd);
12015 * getDependencies --- obtain available dependency data
12018 getDependencies(void)
12029 DumpableObject *dobj,
12032 /* No dependency info available before 7.3 */
12033 if (g_fout->remoteVersion < 70300)
12037 write_msg(NULL, "reading dependency data\n");
12039 /* Make sure we are in proper schema */
12040 selectSourceSchema("pg_catalog");
12042 query = createPQExpBuffer();
12044 appendPQExpBuffer(query, "SELECT "
12045 "classid, objid, refclassid, refobjid, deptype "
12047 "WHERE deptype != 'p' "
12050 res = PQexec(g_conn, query->data);
12051 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12053 ntups = PQntuples(res);
12055 i_classid = PQfnumber(res, "classid");
12056 i_objid = PQfnumber(res, "objid");
12057 i_refclassid = PQfnumber(res, "refclassid");
12058 i_refobjid = PQfnumber(res, "refobjid");
12059 i_deptype = PQfnumber(res, "deptype");
12062 * Since we ordered the SELECT by referencing ID, we can expect that
12063 * multiple entries for the same object will appear together; this saves
12068 for (i = 0; i < ntups; i++)
12071 CatalogId refobjId;
12074 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
12075 objId.oid = atooid(PQgetvalue(res, i, i_objid));
12076 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
12077 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
12078 deptype = *(PQgetvalue(res, i, i_deptype));
12080 if (dobj == NULL ||
12081 dobj->catId.tableoid != objId.tableoid ||
12082 dobj->catId.oid != objId.oid)
12083 dobj = findObjectByCatalogId(objId);
12086 * Failure to find objects mentioned in pg_depend is not unexpected,
12087 * since for example we don't collect info about TOAST tables.
12092 fprintf(stderr, "no referencing object %u %u\n",
12093 objId.tableoid, objId.oid);
12098 refdobj = findObjectByCatalogId(refobjId);
12100 if (refdobj == NULL)
12103 fprintf(stderr, "no referenced object %u %u\n",
12104 refobjId.tableoid, refobjId.oid);
12110 * Ordinarily, table rowtypes have implicit dependencies on their
12111 * tables. However, for a composite type the implicit dependency goes
12112 * the other way in pg_depend; which is the right thing for DROP but
12113 * it doesn't produce the dependency ordering we need. So in that one
12114 * case, we reverse the direction of the dependency.
12116 if (deptype == 'i' &&
12117 dobj->objType == DO_TABLE &&
12118 refdobj->objType == DO_TYPE)
12119 addObjectDependency(refdobj, dobj->dumpId);
12122 addObjectDependency(dobj, refdobj->dumpId);
12127 destroyPQExpBuffer(query);
12132 * selectSourceSchema - make the specified schema the active search path
12133 * in the source database.
12135 * NB: pg_catalog is explicitly searched after the specified schema;
12136 * so user names are only qualified if they are cross-schema references,
12137 * and system names are only qualified if they conflict with a user name
12138 * in the current schema.
12140 * Whenever the selected schema is not pg_catalog, be careful to qualify
12141 * references to system catalogs and types in our emitted commands!
12144 selectSourceSchema(const char *schemaName)
12146 static char *curSchemaName = NULL;
12149 /* Not relevant if fetching from pre-7.3 DB */
12150 if (g_fout->remoteVersion < 70300)
12152 /* Ignore null schema names */
12153 if (schemaName == NULL || *schemaName == '\0')
12155 /* Optimize away repeated selection of same schema */
12156 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
12159 query = createPQExpBuffer();
12160 appendPQExpBuffer(query, "SET search_path = %s",
12161 fmtId(schemaName));
12162 if (strcmp(schemaName, "pg_catalog") != 0)
12163 appendPQExpBuffer(query, ", pg_catalog");
12165 do_sql_command(g_conn, query->data);
12167 destroyPQExpBuffer(query);
12169 free(curSchemaName);
12170 curSchemaName = strdup(schemaName);
12174 * getFormattedTypeName - retrieve a nicely-formatted type name for the
12177 * NB: in 7.3 and up the result may depend on the currently-selected
12178 * schema; this is why we don't try to cache the names.
12181 getFormattedTypeName(Oid oid, OidOptions opts)
12190 if ((opts & zeroAsOpaque) != 0)
12191 return strdup(g_opaque_type);
12192 else if ((opts & zeroAsAny) != 0)
12193 return strdup("'any'");
12194 else if ((opts & zeroAsStar) != 0)
12195 return strdup("*");
12196 else if ((opts & zeroAsNone) != 0)
12197 return strdup("NONE");
12200 query = createPQExpBuffer();
12201 if (g_fout->remoteVersion >= 70300)
12203 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
12206 else if (g_fout->remoteVersion >= 70100)
12208 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
12213 appendPQExpBuffer(query, "SELECT typname "
12215 "WHERE oid = '%u'::oid",
12219 res = PQexec(g_conn, query->data);
12220 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12222 /* Expecting a single result only */
12223 ntups = PQntuples(res);
12226 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
12227 "query returned %d rows instead of one: %s\n",
12229 ntups, query->data);
12233 if (g_fout->remoteVersion >= 70100)
12235 /* already quoted */
12236 result = strdup(PQgetvalue(res, 0, 0));
12240 /* may need to quote it */
12241 result = strdup(fmtId(PQgetvalue(res, 0, 0)));
12245 destroyPQExpBuffer(query);
12251 * myFormatType --- local implementation of format_type for use with 7.0.
12254 myFormatType(const char *typname, int32 typmod)
12257 bool isarray = false;
12258 PQExpBuffer buf = createPQExpBuffer();
12260 /* Handle array types */
12261 if (typname[0] == '_')
12267 /* Show lengths on bpchar and varchar */
12268 if (!strcmp(typname, "bpchar"))
12270 int len = (typmod - VARHDRSZ);
12272 appendPQExpBuffer(buf, "character");
12274 appendPQExpBuffer(buf, "(%d)",
12275 typmod - VARHDRSZ);
12277 else if (!strcmp(typname, "varchar"))
12279 appendPQExpBuffer(buf, "character varying");
12281 appendPQExpBuffer(buf, "(%d)",
12282 typmod - VARHDRSZ);
12284 else if (!strcmp(typname, "numeric"))
12286 appendPQExpBuffer(buf, "numeric");
12293 tmp_typmod = typmod - VARHDRSZ;
12294 precision = (tmp_typmod >> 16) & 0xffff;
12295 scale = tmp_typmod & 0xffff;
12296 appendPQExpBuffer(buf, "(%d,%d)",
12302 * char is an internal single-byte data type; Let's make sure we force it
12303 * through with quotes. - thomas 1998-12-13
12305 else if (strcmp(typname, "char") == 0)
12306 appendPQExpBuffer(buf, "\"char\"");
12308 appendPQExpBuffer(buf, "%s", fmtId(typname));
12310 /* Append array qualifier for array types */
12312 appendPQExpBuffer(buf, "[]");
12314 result = strdup(buf->data);
12315 destroyPQExpBuffer(buf);
12321 * fmtQualifiedId - convert a qualified name to the proper format for
12322 * the source database.
12324 * Like fmtId, use the result before calling again.
12326 static const char *
12327 fmtQualifiedId(const char *schema, const char *id)
12329 static PQExpBuffer id_return = NULL;
12331 if (id_return) /* first time through? */
12332 resetPQExpBuffer(id_return);
12334 id_return = createPQExpBuffer();
12336 /* Suppress schema name if fetching from pre-7.3 DB */
12337 if (g_fout->remoteVersion >= 70300 && schema && *schema)
12339 appendPQExpBuffer(id_return, "%s.",
12342 appendPQExpBuffer(id_return, "%s",
12345 return id_return->data;
12349 * Return a column list clause for the given relation.
12351 * Special case: if there are no undropped columns in the relation, return
12352 * "", not an invalid "()" column list.
12354 static const char *
12355 fmtCopyColumnList(const TableInfo *ti)
12357 static PQExpBuffer q = NULL;
12358 int numatts = ti->numatts;
12359 char **attnames = ti->attnames;
12360 bool *attisdropped = ti->attisdropped;
12364 if (q) /* first time through? */
12365 resetPQExpBuffer(q);
12367 q = createPQExpBuffer();
12369 appendPQExpBuffer(q, "(");
12371 for (i = 0; i < numatts; i++)
12373 if (attisdropped[i])
12376 appendPQExpBuffer(q, ", ");
12377 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
12382 return ""; /* no undropped columns */
12384 appendPQExpBuffer(q, ")");
12389 * Convenience subroutine to execute a SQL command and check for
12390 * COMMAND_OK status.
12393 do_sql_command(PGconn *conn, const char *query)
12397 res = PQexec(conn, query);
12398 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
12403 * Convenience subroutine to verify a SQL command succeeded,
12404 * and exit with a useful error message if not.
12407 check_sql_result(PGresult *res, PGconn *conn, const char *query,
12408 ExecStatusType expected)
12412 if (res && PQresultStatus(res) == expected)
12415 write_msg(NULL, "SQL command failed\n");
12417 err = PQresultErrorMessage(res);
12419 err = PQerrorMessage(conn);
12420 write_msg(NULL, "Error message from server: %s", err);
12421 write_msg(NULL, "The command was: %s\n", query);