1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2012, 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 transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to run on
18 * SnapshotNow time, ie they look at the currently committed state. So
19 * it is possible to get 'cache lookup failed' error if someone
20 * performs DDL changes while a dump is happening. The window for this
21 * sort of thing is from the acquisition of the transaction snapshot to
22 * getSchemaData() (when pg_dump acquires AccessShareLock on every
23 * table it intends to dump). It isn't very large, but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
33 #include "postgres_fe.h"
44 #include "getopt_long.h"
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_largeobject.h"
53 #include "catalog/pg_largeobject_metadata.h"
54 #include "catalog/pg_proc.h"
55 #include "catalog/pg_trigger.h"
56 #include "catalog/pg_type.h"
57 #include "libpq/libpq-fs.h"
59 #include "pg_backup_archiver.h"
61 #include "dumputils.h"
70 const char *descr; /* comment for an object */
71 Oid classoid; /* object class (catalog OID) */
72 Oid objoid; /* object OID */
73 int objsubid; /* subobject (table column #) */
78 const char *provider; /* label provider of this security label */
79 const char *label; /* security label for an object */
80 Oid classoid; /* object class (catalog OID) */
81 Oid objoid; /* object OID */
82 int objsubid; /* subobject (table column #) */
86 bool g_verbose; /* User wants verbose narration of our
88 Archive *g_fout; /* the script file */
89 PGconn *g_conn; /* the database connection */
91 /* various user-settable parameters */
94 int dumpSections; /* bitmask of chosen sections */
96 const char *lockWaitTimeout;
98 /* subquery used to convert user ID (eg, datdba) to user name */
99 static const char *username_subquery;
101 /* obsolete as of 7.3: */
102 static Oid g_last_builtin_oid; /* value of the last builtin oid */
105 * Object inclusion/exclusion lists
107 * The string lists record the patterns given by command-line switches,
108 * which we then convert to lists of OIDs of matching objects.
110 static SimpleStringList schema_include_patterns = {NULL, NULL};
111 static SimpleOidList schema_include_oids = {NULL, NULL};
112 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
113 static SimpleOidList schema_exclude_oids = {NULL, NULL};
115 static SimpleStringList table_include_patterns = {NULL, NULL};
116 static SimpleOidList table_include_oids = {NULL, NULL};
117 static SimpleStringList table_exclude_patterns = {NULL, NULL};
118 static SimpleOidList table_exclude_oids = {NULL, NULL};
119 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
120 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
122 /* default, if no "inclusion" switches appear, is to dump everything */
123 static bool include_everything = true;
125 char g_opaque_type[10]; /* name for the opaque type */
127 /* placeholders for the delimiters for comments */
128 char g_comment_start[10];
129 char g_comment_end[10];
131 static const CatalogId nilCatalogId = {0, 0};
133 /* these are to avoid passing around info for findNamespace() */
134 static NamespaceInfo *g_namespaces;
135 static int g_numNamespaces;
137 /* flags for various command-line long options */
138 static int binary_upgrade = 0;
139 static int disable_dollar_quoting = 0;
140 static int dump_inserts = 0;
141 static int column_inserts = 0;
142 static int no_security_labels = 0;
143 static int no_unlogged_table_data = 0;
144 static int serializable_deferrable = 0;
147 static void help(const char *progname);
148 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
149 static void expand_schema_name_patterns(SimpleStringList *patterns,
150 SimpleOidList *oids);
151 static void expand_table_name_patterns(SimpleStringList *patterns,
152 SimpleOidList *oids);
153 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
154 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
155 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
156 static void dumpComment(Archive *fout, const char *target,
157 const char *namespace, const char *owner,
158 CatalogId catalogId, int subid, DumpId dumpId);
159 static int findComments(Archive *fout, Oid classoid, Oid objoid,
160 CommentItem **items);
161 static int collectComments(Archive *fout, CommentItem **items);
162 static void dumpSecLabel(Archive *fout, const char *target,
163 const char *namespace, const char *owner,
164 CatalogId catalogId, int subid, DumpId dumpId);
165 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
166 SecLabelItem **items);
167 static int collectSecLabels(Archive *fout, SecLabelItem **items);
168 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
169 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
170 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
171 static void dumpType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
178 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
179 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
180 static void dumpFunc(Archive *fout, FuncInfo *finfo);
181 static void dumpCast(Archive *fout, CastInfo *cast);
182 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
183 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
184 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
185 static void dumpCollation(Archive *fout, CollInfo *convinfo);
186 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
187 static void dumpRule(Archive *fout, RuleInfo *rinfo);
188 static void dumpAgg(Archive *fout, AggInfo *agginfo);
189 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
190 static void dumpTable(Archive *fout, TableInfo *tbinfo);
191 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
192 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
193 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
194 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
195 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
196 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
197 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
198 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
199 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
200 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
201 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
202 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
203 static void dumpUserMappings(Archive *fout,
204 const char *servername, const char *namespace,
205 const char *owner, CatalogId catalogId, DumpId dumpId);
206 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
208 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
209 const char *type, const char *name, const char *subname,
210 const char *tag, const char *nspname, const char *owner,
213 static void getDependencies(void);
214 static void getDomainConstraints(TypeInfo *tyinfo);
215 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
216 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
217 static void getTableDataFKConstraints(void);
218 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
219 static char *format_function_arguments_old(FuncInfo *finfo, int nallargs,
223 static char *format_function_signature(FuncInfo *finfo, bool honor_quotes);
224 static const char *convertRegProcReference(const char *proc);
225 static const char *convertOperatorReference(const char *opr);
226 static const char *convertTSFunction(Oid funcOid);
227 static Oid findLastBuiltinOid_V71(const char *);
228 static Oid findLastBuiltinOid_V70(void);
229 static void selectSourceSchema(const char *schemaName);
230 static char *getFormattedTypeName(Oid oid, OidOptions opts);
231 static char *myFormatType(const char *typname, int32 typmod);
232 static const char *fmtQualifiedId(const char *schema, const char *id);
233 static void getBlobs(Archive *AH);
234 static void dumpBlob(Archive *AH, BlobInfo *binfo);
235 static int dumpBlobs(Archive *AH, void *arg);
236 static void dumpDatabase(Archive *AH);
237 static void dumpEncoding(Archive *AH);
238 static void dumpStdStrings(Archive *AH);
239 static void binary_upgrade_set_type_oids_by_type_oid(
240 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
241 static bool binary_upgrade_set_type_oids_by_rel_oid(
242 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
243 static void binary_upgrade_set_pg_class_oids(PQExpBuffer upgrade_buffer,
244 Oid pg_class_oid, bool is_index);
245 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
246 DumpableObject *dobj,
247 const char *objlabel);
248 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
249 static const char *fmtCopyColumnList(const TableInfo *ti);
250 static void do_sql_command(PGconn *conn, const char *query);
251 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
252 ExecStatusType expected);
255 main(int argc, char **argv)
258 const char *filename = NULL;
259 const char *format = "p";
260 const char *dbname = NULL;
261 const char *pghost = NULL;
262 const char *pgport = NULL;
263 const char *username = NULL;
264 const char *dumpencoding = NULL;
265 const char *std_strings;
269 DumpableObject **dobjs;
272 enum trivalue prompt_password = TRI_DEFAULT;
273 int compressLevel = -1;
276 int outputCreateDB = 0;
277 bool outputBlobs = false;
278 int outputNoOwner = 0;
279 char *outputSuperuser = NULL;
280 char *use_role = NULL;
283 RestoreOptions *ropt;
284 ArchiveFormat archiveFormat = archUnknown;
285 ArchiveMode archiveMode;
287 static int disable_triggers = 0;
288 static int outputNoTablespaces = 0;
289 static int use_setsessauth = 0;
291 static struct option long_options[] = {
292 {"data-only", no_argument, NULL, 'a'},
293 {"blobs", no_argument, NULL, 'b'},
294 {"clean", no_argument, NULL, 'c'},
295 {"create", no_argument, NULL, 'C'},
296 {"file", required_argument, NULL, 'f'},
297 {"format", required_argument, NULL, 'F'},
298 {"host", required_argument, NULL, 'h'},
299 {"ignore-version", no_argument, NULL, 'i'},
300 {"no-reconnect", no_argument, NULL, 'R'},
301 {"oids", no_argument, NULL, 'o'},
302 {"no-owner", no_argument, NULL, 'O'},
303 {"port", required_argument, NULL, 'p'},
304 {"schema", required_argument, NULL, 'n'},
305 {"exclude-schema", required_argument, NULL, 'N'},
306 {"schema-only", no_argument, NULL, 's'},
307 {"superuser", required_argument, NULL, 'S'},
308 {"table", required_argument, NULL, 't'},
309 {"exclude-table", required_argument, NULL, 'T'},
310 {"no-password", no_argument, NULL, 'w'},
311 {"password", no_argument, NULL, 'W'},
312 {"username", required_argument, NULL, 'U'},
313 {"verbose", no_argument, NULL, 'v'},
314 {"no-privileges", no_argument, NULL, 'x'},
315 {"no-acl", no_argument, NULL, 'x'},
316 {"compress", required_argument, NULL, 'Z'},
317 {"encoding", required_argument, NULL, 'E'},
318 {"help", no_argument, NULL, '?'},
319 {"version", no_argument, NULL, 'V'},
322 * the following options don't have an equivalent short option letter
324 {"attribute-inserts", no_argument, &column_inserts, 1},
325 {"binary-upgrade", no_argument, &binary_upgrade, 1},
326 {"column-inserts", no_argument, &column_inserts, 1},
327 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
328 {"disable-triggers", no_argument, &disable_triggers, 1},
329 {"exclude-table-data", required_argument, NULL, 4},
330 {"inserts", no_argument, &dump_inserts, 1},
331 {"lock-wait-timeout", required_argument, NULL, 2},
332 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
333 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
334 {"role", required_argument, NULL, 3},
335 {"section", required_argument, NULL, 5},
336 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
337 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
338 {"no-security-labels", no_argument, &no_security_labels, 1},
339 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
344 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
348 strcpy(g_comment_start, "-- ");
349 g_comment_end[0] = '\0';
350 strcpy(g_opaque_type, "opaque");
352 dataOnly = schemaOnly = false;
353 dumpSections = DUMP_UNSECTIONED;
354 lockWaitTimeout = NULL;
356 progname = get_progname(argv[0]);
358 /* Set default options based on progname */
359 if (strcmp(progname, "pg_backup") == 0)
364 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
369 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
371 puts("pg_dump (PostgreSQL) " PG_VERSION);
376 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
377 long_options, &optindex)) != -1)
381 case 'a': /* Dump data only */
385 case 'b': /* Dump blobs */
389 case 'c': /* clean (i.e., drop) schema prior to create */
393 case 'C': /* Create DB */
397 case 'E': /* Dump encoding */
398 dumpencoding = optarg;
409 case 'h': /* server host */
414 /* ignored, deprecated option */
417 case 'n': /* include schema(s) */
418 simple_string_list_append(&schema_include_patterns, optarg);
419 include_everything = false;
422 case 'N': /* exclude schema(s) */
423 simple_string_list_append(&schema_exclude_patterns, optarg);
426 case 'o': /* Dump oids */
430 case 'O': /* Don't reconnect to match owner */
434 case 'p': /* server port */
439 /* no-op, still accepted for backwards compatibility */
442 case 's': /* dump schema only */
446 case 'S': /* Username for superuser in plain text output */
447 outputSuperuser = pg_strdup(optarg);
450 case 't': /* include table(s) */
451 simple_string_list_append(&table_include_patterns, optarg);
452 include_everything = false;
455 case 'T': /* exclude table(s) */
456 simple_string_list_append(&table_exclude_patterns, optarg);
463 case 'v': /* verbose */
468 prompt_password = TRI_NO;
472 prompt_password = TRI_YES;
475 case 'x': /* skip ACL dump */
479 case 'Z': /* Compression Level */
480 compressLevel = atoi(optarg);
484 /* This covers the long options. */
487 case 2: /* lock-wait-timeout */
488 lockWaitTimeout = optarg;
491 case 3: /* SET ROLE */
495 case 4: /* exclude table(s) data */
496 simple_string_list_append(&tabledata_exclude_patterns, optarg);
499 case 5: /* section */
500 set_section(optarg, &dumpSections);
504 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
509 /* Get database name from command line */
511 dbname = argv[optind++];
513 /* Complain if any arguments remain */
516 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
517 progname, argv[optind]);
518 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
523 /* --column-inserts implies --inserts */
527 if (dataOnly && schemaOnly)
529 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
533 if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
535 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
540 dumpSections = DUMP_DATA;
542 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
543 else if ( dumpSections != DUMP_UNSECTIONED)
545 dataOnly = dumpSections == DUMP_DATA;
546 schemaOnly = !(dumpSections & DUMP_DATA);
549 if (dataOnly && outputClean)
551 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
555 if (dump_inserts && oids)
557 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
558 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
562 /* Identify archive format to emit */
563 archiveFormat = parseArchiveFormat(format, &archiveMode);
565 /* archiveFormat specific setup */
566 if (archiveFormat == archNull)
569 /* Custom and directory formats are compressed by default, others not */
570 if (compressLevel == -1)
572 if (archiveFormat == archCustom || archiveFormat == archDirectory)
573 compressLevel = Z_DEFAULT_COMPRESSION;
578 /* Open the output file */
579 g_fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
583 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
587 /* Let the archiver know how noisy to be */
588 g_fout->verbose = g_verbose;
590 my_version = parse_version(PG_VERSION);
593 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
598 * We allow the server to be back to 7.0, and up to any minor release of
599 * our own major version. (See also version check in pg_dumpall.c.)
601 g_fout->minRemoteVersion = 70000;
602 g_fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
605 * Open the database using the Archiver, so it knows about it. Errors mean
608 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
609 username, prompt_password);
611 /* Set the client encoding if requested */
614 if (PQsetClientEncoding(g_conn, dumpencoding) < 0)
616 write_msg(NULL, "invalid client encoding \"%s\" specified\n",
623 * Get the active encoding and the standard_conforming_strings setting, so
624 * we know how to escape strings.
626 g_fout->encoding = PQclientEncoding(g_conn);
628 std_strings = PQparameterStatus(g_conn, "standard_conforming_strings");
629 g_fout->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
631 /* Set the role if requested */
632 if (use_role && g_fout->remoteVersion >= 80100)
634 PQExpBuffer query = createPQExpBuffer();
636 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
637 do_sql_command(g_conn, query->data);
638 destroyPQExpBuffer(query);
641 /* Set the datestyle to ISO to ensure the dump's portability */
642 do_sql_command(g_conn, "SET DATESTYLE = ISO");
644 /* Likewise, avoid using sql_standard intervalstyle */
645 if (g_fout->remoteVersion >= 80400)
646 do_sql_command(g_conn, "SET INTERVALSTYLE = POSTGRES");
649 * If supported, set extra_float_digits so that we can dump float data
650 * exactly (given correctly implemented float I/O code, anyway)
652 if (g_fout->remoteVersion >= 90000)
653 do_sql_command(g_conn, "SET extra_float_digits TO 3");
654 else if (g_fout->remoteVersion >= 70400)
655 do_sql_command(g_conn, "SET extra_float_digits TO 2");
658 * If synchronized scanning is supported, disable it, to prevent
659 * unpredictable changes in row ordering across a dump and reload.
661 if (g_fout->remoteVersion >= 80300)
662 do_sql_command(g_conn, "SET synchronize_seqscans TO off");
665 * Disable timeouts if supported.
667 if (g_fout->remoteVersion >= 70300)
668 do_sql_command(g_conn, "SET statement_timeout = 0");
671 * Quote all identifiers, if requested.
673 if (quote_all_identifiers && g_fout->remoteVersion >= 90100)
674 do_sql_command(g_conn, "SET quote_all_identifiers = true");
677 * Disable security label support if server version < v9.1.x (prevents
678 * access to nonexistent pg_seclabel catalog)
680 if (g_fout->remoteVersion < 90100)
681 no_security_labels = 1;
684 * Start transaction-snapshot mode transaction to dump consistent data.
686 do_sql_command(g_conn, "BEGIN");
687 if (g_fout->remoteVersion >= 90100)
689 if (serializable_deferrable)
690 do_sql_command(g_conn,
691 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, "
692 "READ ONLY, DEFERRABLE");
694 do_sql_command(g_conn,
695 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
698 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
700 /* Select the appropriate subquery to convert user IDs to names */
701 if (g_fout->remoteVersion >= 80100)
702 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
703 else if (g_fout->remoteVersion >= 70300)
704 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
706 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
708 /* Find the last built-in OID, if needed */
709 if (g_fout->remoteVersion < 70300)
711 if (g_fout->remoteVersion >= 70100)
712 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
714 g_last_builtin_oid = findLastBuiltinOid_V70();
716 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
719 /* Expand schema selection patterns into OID lists */
720 if (schema_include_patterns.head != NULL)
722 expand_schema_name_patterns(&schema_include_patterns,
723 &schema_include_oids);
724 if (schema_include_oids.head == NULL)
726 write_msg(NULL, "No matching schemas were found\n");
730 expand_schema_name_patterns(&schema_exclude_patterns,
731 &schema_exclude_oids);
732 /* non-matching exclusion patterns aren't an error */
734 /* Expand table selection patterns into OID lists */
735 if (table_include_patterns.head != NULL)
737 expand_table_name_patterns(&table_include_patterns,
738 &table_include_oids);
739 if (table_include_oids.head == NULL)
741 write_msg(NULL, "No matching tables were found\n");
745 expand_table_name_patterns(&table_exclude_patterns,
746 &table_exclude_oids);
748 expand_table_name_patterns(&tabledata_exclude_patterns,
749 &tabledata_exclude_oids);
751 /* non-matching exclusion patterns aren't an error */
754 * Dumping blobs is now default unless we saw an inclusion switch or -s
755 * ... but even if we did see one of these, -b turns it back on.
757 if (include_everything && !schemaOnly)
761 * Now scan the database and create DumpableObject structs for all the
762 * objects we intend to dump.
764 tblinfo = getSchemaData(&numTables);
766 if (g_fout->remoteVersion < 80400)
767 guessConstraintInheritance(tblinfo, numTables);
771 getTableData(tblinfo, numTables, oids);
773 getTableDataFKConstraints();
780 * Collect dependency data to assist in ordering the objects.
785 * Sort the objects into a safe dump order (no forward references).
787 * In 7.3 or later, we can rely on dependency information to help us
788 * determine a safe order, so the initial sort is mostly for cosmetic
789 * purposes: we sort by name to ensure that logically identical schemas
790 * will dump identically. Before 7.3 we don't have dependencies and we
791 * use OID ordering as an (unreliable) guide to creation order.
793 getDumpableObjects(&dobjs, &numObjs);
795 if (g_fout->remoteVersion >= 70300)
796 sortDumpableObjectsByTypeName(dobjs, numObjs);
798 sortDumpableObjectsByTypeOid(dobjs, numObjs);
800 sortDumpableObjects(dobjs, numObjs);
803 * Create archive TOC entries for all the objects to be dumped, in a safe
807 /* First the special ENCODING and STDSTRINGS entries. */
808 dumpEncoding(g_fout);
809 dumpStdStrings(g_fout);
811 /* The database item is always next, unless we don't want it at all */
812 if (include_everything && !dataOnly)
813 dumpDatabase(g_fout);
815 /* Now the rearrangeable objects. */
816 for (i = 0; i < numObjs; i++)
817 dumpDumpableObject(g_fout, dobjs[i]);
820 * And finally we can do the actual output.
824 ropt = NewRestoreOptions();
825 ropt->filename = (char *) filename;
826 ropt->dropSchema = outputClean;
827 ropt->aclsSkip = aclsSkip;
828 ropt->superuser = outputSuperuser;
829 ropt->createDB = outputCreateDB;
830 ropt->noOwner = outputNoOwner;
831 ropt->noTablespace = outputNoTablespaces;
832 ropt->disable_triggers = disable_triggers;
833 ropt->use_setsessauth = use_setsessauth;
834 ropt->dataOnly = dataOnly;
836 if (compressLevel == -1)
837 ropt->compression = 0;
839 ropt->compression = compressLevel;
841 ropt->suppressDumpWarnings = true; /* We've already shown them */
843 RestoreArchive(g_fout, ropt);
846 CloseArchive(g_fout);
855 help(const char *progname)
857 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
858 printf(_("Usage:\n"));
859 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
861 printf(_("\nGeneral options:\n"));
862 printf(_(" -f, --file=FILENAME output file or directory name\n"));
863 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
864 " plain text (default))\n"));
865 printf(_(" -v, --verbose verbose mode\n"));
866 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
867 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
868 printf(_(" --help show this help, then exit\n"));
869 printf(_(" --version output version information, then exit\n"));
871 printf(_("\nOptions controlling the output content:\n"));
872 printf(_(" -a, --data-only dump only the data, not the schema\n"));
873 printf(_(" -b, --blobs include large objects in dump\n"));
874 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
875 printf(_(" -C, --create include commands to create database in dump\n"));
876 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
877 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
878 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
879 printf(_(" -o, --oids include OIDs in dump\n"));
880 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
881 " plain-text format\n"));
882 printf(_(" -s, --schema-only dump only the schema, no data\n"));
883 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
884 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
885 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
886 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
887 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
888 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
889 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
890 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
891 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
892 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
893 printf(_(" --no-security-labels do not dump security label assignments\n"));
894 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
895 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
896 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
897 printf(_(" --section=SECTION dump named section (pre-data, data or post-data)\n"));
898 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
899 printf(_(" --use-set-session-authorization\n"
900 " use SET SESSION AUTHORIZATION commands instead of\n"
901 " ALTER OWNER commands to set ownership\n"));
903 printf(_("\nConnection options:\n"));
904 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
905 printf(_(" -p, --port=PORT database server port number\n"));
906 printf(_(" -U, --username=NAME connect as specified database user\n"));
907 printf(_(" -w, --no-password never prompt for password\n"));
908 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
909 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
911 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
912 "variable value is used.\n\n"));
913 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
921 write_msg(NULL, "*** aborted because of error\n");
926 parseArchiveFormat(const char *format, ArchiveMode *mode)
928 ArchiveFormat archiveFormat;
930 *mode = archModeWrite;
932 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
934 /* This is used by pg_dumpall, and is not documented */
935 archiveFormat = archNull;
936 *mode = archModeAppend;
938 else if (pg_strcasecmp(format, "c") == 0)
939 archiveFormat = archCustom;
940 else if (pg_strcasecmp(format, "custom") == 0)
941 archiveFormat = archCustom;
942 else if (pg_strcasecmp(format, "d") == 0)
943 archiveFormat = archDirectory;
944 else if (pg_strcasecmp(format, "directory") == 0)
945 archiveFormat = archDirectory;
946 else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
949 * Dump files into the current directory; for demonstration only, not
952 archiveFormat = archFiles;
953 else if (pg_strcasecmp(format, "p") == 0)
954 archiveFormat = archNull;
955 else if (pg_strcasecmp(format, "plain") == 0)
956 archiveFormat = archNull;
957 else if (pg_strcasecmp(format, "t") == 0)
958 archiveFormat = archTar;
959 else if (pg_strcasecmp(format, "tar") == 0)
960 archiveFormat = archTar;
963 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
966 return archiveFormat;
970 * Find the OIDs of all schemas matching the given list of patterns,
971 * and append them to the given OID list.
974 expand_schema_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
978 SimpleStringListCell *cell;
981 if (patterns->head == NULL)
982 return; /* nothing to do */
984 if (g_fout->remoteVersion < 70300)
986 write_msg(NULL, "server version must be at least 7.3 to use schema selection switches\n");
990 query = createPQExpBuffer();
993 * We use UNION ALL rather than UNION; this might sometimes result in
994 * duplicate entries in the OID list, but we don't care.
997 for (cell = patterns->head; cell; cell = cell->next)
999 if (cell != patterns->head)
1000 appendPQExpBuffer(query, "UNION ALL\n");
1001 appendPQExpBuffer(query,
1002 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1003 processSQLNamePattern(g_conn, query, cell->val, false, false,
1004 NULL, "n.nspname", NULL,
1008 res = PQexec(g_conn, query->data);
1009 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1011 for (i = 0; i < PQntuples(res); i++)
1013 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1017 destroyPQExpBuffer(query);
1021 * Find the OIDs of all tables matching the given list of patterns,
1022 * and append them to the given OID list.
1025 expand_table_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
1029 SimpleStringListCell *cell;
1032 if (patterns->head == NULL)
1033 return; /* nothing to do */
1035 query = createPQExpBuffer();
1038 * We use UNION ALL rather than UNION; this might sometimes result in
1039 * duplicate entries in the OID list, but we don't care.
1042 for (cell = patterns->head; cell; cell = cell->next)
1044 if (cell != patterns->head)
1045 appendPQExpBuffer(query, "UNION ALL\n");
1046 appendPQExpBuffer(query,
1048 "\nFROM pg_catalog.pg_class c"
1049 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1050 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1051 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1052 RELKIND_FOREIGN_TABLE);
1053 processSQLNamePattern(g_conn, query, cell->val, true, false,
1054 "n.nspname", "c.relname", NULL,
1055 "pg_catalog.pg_table_is_visible(c.oid)");
1058 res = PQexec(g_conn, query->data);
1059 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1061 for (i = 0; i < PQntuples(res); i++)
1063 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1067 destroyPQExpBuffer(query);
1071 * selectDumpableNamespace: policy-setting subroutine
1072 * Mark a namespace as to be dumped or not
1075 selectDumpableNamespace(NamespaceInfo *nsinfo)
1078 * If specific tables are being dumped, do not dump any complete
1079 * namespaces. If specific namespaces are being dumped, dump just those
1080 * namespaces. Otherwise, dump all non-system namespaces.
1082 if (table_include_oids.head != NULL)
1083 nsinfo->dobj.dump = false;
1084 else if (schema_include_oids.head != NULL)
1085 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1086 nsinfo->dobj.catId.oid);
1087 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1088 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1089 nsinfo->dobj.dump = false;
1091 nsinfo->dobj.dump = true;
1094 * In any case, a namespace can be excluded by an exclusion switch
1096 if (nsinfo->dobj.dump &&
1097 simple_oid_list_member(&schema_exclude_oids,
1098 nsinfo->dobj.catId.oid))
1099 nsinfo->dobj.dump = false;
1103 * selectDumpableTable: policy-setting subroutine
1104 * Mark a table as to be dumped or not
1107 selectDumpableTable(TableInfo *tbinfo)
1110 * If specific tables are being dumped, dump just those tables; else, dump
1111 * according to the parent namespace's dump flag.
1113 if (table_include_oids.head != NULL)
1114 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1115 tbinfo->dobj.catId.oid);
1117 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1120 * In any case, a table can be excluded by an exclusion switch
1122 if (tbinfo->dobj.dump &&
1123 simple_oid_list_member(&table_exclude_oids,
1124 tbinfo->dobj.catId.oid))
1125 tbinfo->dobj.dump = false;
1127 /* If table is to be dumped, check that the data is not excluded */
1128 if (tbinfo->dobj.dump && !
1129 simple_oid_list_member(&tabledata_exclude_oids,
1130 tbinfo->dobj.catId.oid))
1131 tbinfo->dobj.dumpdata = true;
1133 tbinfo->dobj.dumpdata = false;
1138 * selectDumpableType: policy-setting subroutine
1139 * Mark a type as to be dumped or not
1141 * If it's a table's rowtype or an autogenerated array type, we also apply a
1142 * special type code to facilitate sorting into the desired order. (We don't
1143 * want to consider those to be ordinary types because that would bring tables
1144 * up into the datatype part of the dump order.) We still set the object's
1145 * dump flag; that's not going to cause the dummy type to be dumped, but we
1146 * need it so that casts involving such types will be dumped correctly -- see
1147 * dumpCast. This means the flag should be set the same as for the underlying
1148 * object (the table or base type).
1151 selectDumpableType(TypeInfo *tyinfo)
1153 /* skip complex types, except for standalone composite types */
1154 if (OidIsValid(tyinfo->typrelid) &&
1155 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1157 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1159 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1160 if (tytable != NULL)
1161 tyinfo->dobj.dump = tytable->dobj.dump;
1163 tyinfo->dobj.dump = false;
1167 /* skip auto-generated array types */
1168 if (tyinfo->isArray)
1170 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1172 * Fall through to set the dump flag; we assume that the subsequent
1173 * rules will do the same thing as they would for the array's base
1174 * type. (We cannot reliably look up the base type here, since
1175 * getTypes may not have processed it yet.)
1179 /* dump only types in dumpable namespaces */
1180 if (!tyinfo->dobj.namespace->dobj.dump)
1181 tyinfo->dobj.dump = false;
1183 /* skip undefined placeholder types */
1184 else if (!tyinfo->isDefined)
1185 tyinfo->dobj.dump = false;
1188 tyinfo->dobj.dump = true;
1192 * selectDumpableDefaultACL: policy-setting subroutine
1193 * Mark a default ACL as to be dumped or not
1195 * For per-schema default ACLs, dump if the schema is to be dumped.
1196 * Otherwise dump if we are dumping "everything". Note that dataOnly
1197 * and aclsSkip are checked separately.
1200 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1202 if (dinfo->dobj.namespace)
1203 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1205 dinfo->dobj.dump = include_everything;
1209 * selectDumpableExtension: policy-setting subroutine
1210 * Mark an extension as to be dumped or not
1212 * Normally, we dump all extensions, or none of them if include_everything
1213 * is false (i.e., a --schema or --table switch was given). However, in
1214 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1215 * assume those will already be installed in the target database. We identify
1216 * such extensions by their having OIDs in the range reserved for initdb.
1219 selectDumpableExtension(ExtensionInfo *extinfo)
1221 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1222 extinfo->dobj.dump = false;
1224 extinfo->dobj.dump = include_everything;
1228 * selectDumpableObject: policy-setting subroutine
1229 * Mark a generic dumpable object as to be dumped or not
1231 * Use this only for object types without a special-case routine above.
1234 selectDumpableObject(DumpableObject *dobj)
1237 * Default policy is to dump if parent namespace is dumpable, or always
1238 * for non-namespace-associated items.
1240 if (dobj->namespace)
1241 dobj->dump = dobj->namespace->dobj.dump;
1247 * Dump a table's contents for loading using the COPY command
1248 * - this routine is called by the Archiver when it wants the table
1253 dumpTableData_copy(Archive *fout, void *dcontext)
1255 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1256 TableInfo *tbinfo = tdinfo->tdtable;
1257 const char *classname = tbinfo->dobj.name;
1258 const bool hasoids = tbinfo->hasoids;
1259 const bool oids = tdinfo->oids;
1260 PQExpBuffer q = createPQExpBuffer();
1264 const char *column_list;
1267 write_msg(NULL, "dumping contents of table %s\n", classname);
1270 * Make sure we are in proper schema. We will qualify the table name
1271 * below anyway (in case its name conflicts with a pg_catalog table); but
1272 * this ensures reproducible results in case the table contains regproc,
1273 * regclass, etc columns.
1275 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1278 * If possible, specify the column list explicitly so that we have no
1279 * possibility of retrieving data in the wrong column order. (The default
1280 * column ordering of COPY will not be what we want in certain corner
1281 * cases involving ADD COLUMN and inheritance.)
1283 if (g_fout->remoteVersion >= 70300)
1284 column_list = fmtCopyColumnList(tbinfo);
1286 column_list = ""; /* can't select columns in COPY */
1288 if (oids && hasoids)
1290 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1291 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1295 else if (tdinfo->filtercond)
1297 /* Note: this syntax is only supported in 8.2 and up */
1298 appendPQExpBufferStr(q, "COPY (SELECT ");
1299 /* klugery to get rid of parens in column list */
1300 if (strlen(column_list) > 2)
1302 appendPQExpBufferStr(q, column_list + 1);
1303 q->data[q->len - 1] = ' ';
1306 appendPQExpBufferStr(q, "* ");
1307 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1308 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1310 tdinfo->filtercond);
1314 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1315 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1319 res = PQexec(g_conn, q->data);
1320 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
1325 ret = PQgetCopyData(g_conn, ©buf, 0);
1328 break; /* done or error */
1332 WriteData(fout, copybuf, ret);
1339 * There was considerable discussion in late July, 2000 regarding
1340 * slowing down pg_dump when backing up large tables. Users with both
1341 * slow & fast (multi-processor) machines experienced performance
1342 * degradation when doing a backup.
1344 * Initial attempts based on sleeping for a number of ms for each ms
1345 * of work were deemed too complex, then a simple 'sleep in each loop'
1346 * implementation was suggested. The latter failed because the loop
1347 * was too tight. Finally, the following was implemented:
1349 * If throttle is non-zero, then
1350 * See how long since the last sleep.
1351 * Work out how long to sleep (based on ratio).
1352 * If sleep is more than 100ms, then
1358 * where the throttle value was the number of ms to sleep per ms of
1359 * work. The calculation was done in each loop.
1361 * Most of the hard work is done in the backend, and this solution
1362 * still did not work particularly well: on slow machines, the ratio
1363 * was 50:1, and on medium paced machines, 1:1, and on fast
1364 * multi-processor machines, it had little or no effect, for reasons
1365 * that were unclear.
1367 * Further discussion ensued, and the proposal was dropped.
1369 * For those people who want this feature, it can be implemented using
1370 * gettimeofday in each loop, calculating the time since last sleep,
1371 * multiplying that by the sleep ratio, then if the result is more
1372 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1373 * function to sleep for a subsecond period ie.
1375 * select(0, NULL, NULL, NULL, &tvi);
1377 * This will return after the interval specified in the structure tvi.
1378 * Finally, call gettimeofday again to save the 'last sleep time'.
1382 archprintf(fout, "\\.\n\n\n");
1386 /* copy data transfer failed */
1387 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1388 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1389 write_msg(NULL, "The command was: %s\n", q->data);
1393 /* Check command status and return to normal libpq state */
1394 res = PQgetResult(g_conn);
1395 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1398 destroyPQExpBuffer(q);
1403 dumpTableData_insert(Archive *fout, void *dcontext)
1405 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1406 TableInfo *tbinfo = tdinfo->tdtable;
1407 const char *classname = tbinfo->dobj.name;
1408 PQExpBuffer q = createPQExpBuffer();
1415 * Make sure we are in proper schema. We will qualify the table name
1416 * below anyway (in case its name conflicts with a pg_catalog table); but
1417 * this ensures reproducible results in case the table contains regproc,
1418 * regclass, etc columns.
1420 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1422 if (fout->remoteVersion >= 70100)
1424 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1425 "SELECT * FROM ONLY %s",
1426 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1431 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1433 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1436 if (tdinfo->filtercond)
1437 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1439 res = PQexec(g_conn, q->data);
1440 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1446 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
1447 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
1449 nfields = PQnfields(res);
1450 for (tuple = 0; tuple < PQntuples(res); tuple++)
1452 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1455 /* corner case for zero-column table */
1456 archprintf(fout, "DEFAULT VALUES;\n");
1461 resetPQExpBuffer(q);
1462 appendPQExpBuffer(q, "(");
1463 for (field = 0; field < nfields; field++)
1466 appendPQExpBuffer(q, ", ");
1467 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1469 appendPQExpBuffer(q, ") ");
1470 archputs(q->data, fout);
1472 archprintf(fout, "VALUES (");
1473 for (field = 0; field < nfields; field++)
1476 archprintf(fout, ", ");
1477 if (PQgetisnull(res, tuple, field))
1479 archprintf(fout, "NULL");
1483 /* XXX This code is partially duplicated in ruleutils.c */
1484 switch (PQftype(res, field))
1495 * These types are printed without quotes unless
1496 * they contain values that aren't accepted by the
1497 * scanner unquoted (e.g., 'NaN'). Note that
1498 * strtod() and friends might accept NaN, so we
1499 * can't use that to test.
1501 * In reality we only need to defend against
1502 * infinity and NaN, so we need not get too crazy
1503 * about pattern matching here.
1505 const char *s = PQgetvalue(res, tuple, field);
1507 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1508 archprintf(fout, "%s", s);
1510 archprintf(fout, "'%s'", s);
1516 archprintf(fout, "B'%s'",
1517 PQgetvalue(res, tuple, field));
1521 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1522 archprintf(fout, "true");
1524 archprintf(fout, "false");
1528 /* All other types are printed as string literals. */
1529 resetPQExpBuffer(q);
1530 appendStringLiteralAH(q,
1531 PQgetvalue(res, tuple, field),
1533 archputs(q->data, fout);
1537 archprintf(fout, ");\n");
1539 } while (PQntuples(res) > 0);
1543 archprintf(fout, "\n\n");
1545 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1547 destroyPQExpBuffer(q);
1554 * dump the contents of a single table
1556 * Actually, this just makes an ArchiveEntry for the table contents.
1559 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1561 TableInfo *tbinfo = tdinfo->tdtable;
1562 PQExpBuffer copyBuf = createPQExpBuffer();
1563 DataDumperPtr dumpFn;
1566 /* don't do anything if the data isn't wanted */
1567 if (!tbinfo->dobj.dumpdata)
1572 /* Dump/restore using COPY */
1573 dumpFn = dumpTableData_copy;
1574 /* must use 2 steps here 'cause fmtId is nonreentrant */
1575 appendPQExpBuffer(copyBuf, "COPY %s ",
1576 fmtId(tbinfo->dobj.name));
1577 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1578 fmtCopyColumnList(tbinfo),
1579 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1580 copyStmt = copyBuf->data;
1584 /* Restore using INSERT */
1585 dumpFn = dumpTableData_insert;
1589 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1590 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1591 NULL, tbinfo->rolname,
1592 false, "TABLE DATA", SECTION_DATA,
1594 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1597 destroyPQExpBuffer(copyBuf);
1602 * set up dumpable objects representing the contents of tables
1605 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1609 for (i = 0; i < numTables; i++)
1611 /* Skip VIEWs (no data to dump) */
1612 if (tblinfo[i].relkind == RELKIND_VIEW)
1614 /* Skip SEQUENCEs (handled elsewhere) */
1615 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1617 /* Skip FOREIGN TABLEs (no data to dump) */
1618 if (tblinfo[i].relkind == RELKIND_FOREIGN_TABLE)
1620 /* Skip unlogged tables if so requested */
1621 if (tblinfo[i].relpersistence == RELPERSISTENCE_UNLOGGED
1622 && no_unlogged_table_data)
1625 if (tblinfo[i].dobj.dump && tblinfo[i].dataObj == NULL)
1626 makeTableDataInfo(&(tblinfo[i]), oids);
1631 * Make a dumpable object for the data of this specific table
1634 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1636 TableDataInfo *tdinfo;
1638 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1640 tdinfo->dobj.objType = DO_TABLE_DATA;
1643 * Note: use tableoid 0 so that this object won't be mistaken for
1644 * something that pg_depend entries apply to.
1646 tdinfo->dobj.catId.tableoid = 0;
1647 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1648 AssignDumpId(&tdinfo->dobj);
1649 tdinfo->dobj.name = tbinfo->dobj.name;
1650 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1651 tdinfo->tdtable = tbinfo;
1652 tdinfo->oids = oids;
1653 tdinfo->filtercond = NULL; /* might get set later */
1654 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1656 tbinfo->dataObj = tdinfo;
1660 * getTableDataFKConstraints -
1661 * add dump-order dependencies reflecting foreign key constraints
1663 * This code is executed only in a data-only dump --- in schema+data dumps
1664 * we handle foreign key issues by not creating the FK constraints until
1665 * after the data is loaded. In a data-only dump, however, we want to
1666 * order the table data objects in such a way that a table's referenced
1667 * tables are restored first. (In the presence of circular references or
1668 * self-references this may be impossible; we'll detect and complain about
1669 * that during the dependency sorting step.)
1672 getTableDataFKConstraints(void)
1674 DumpableObject **dobjs;
1678 /* Search through all the dumpable objects for FK constraints */
1679 getDumpableObjects(&dobjs, &numObjs);
1680 for (i = 0; i < numObjs; i++)
1682 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1684 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1687 /* Not interesting unless both tables are to be dumped */
1688 if (cinfo->contable == NULL ||
1689 cinfo->contable->dataObj == NULL)
1691 ftable = findTableByOid(cinfo->confrelid);
1692 if (ftable == NULL ||
1693 ftable->dataObj == NULL)
1697 * Okay, make referencing table's TABLE_DATA object depend on the
1698 * referenced table's TABLE_DATA object.
1700 addObjectDependency(&cinfo->contable->dataObj->dobj,
1701 ftable->dataObj->dobj.dumpId);
1709 * guessConstraintInheritance:
1710 * In pre-8.4 databases, we can't tell for certain which constraints
1711 * are inherited. We assume a CHECK constraint is inherited if its name
1712 * matches the name of any constraint in the parent. Originally this code
1713 * tried to compare the expression texts, but that can fail for various
1714 * reasons --- for example, if the parent and child tables are in different
1715 * schemas, reverse-listing of function calls may produce different text
1716 * (schema-qualified or not) depending on search path.
1718 * In 8.4 and up we can rely on the conislocal field to decide which
1719 * constraints must be dumped; much safer.
1721 * This function assumes all conislocal flags were initialized to TRUE.
1722 * It clears the flag on anything that seems to be inherited.
1725 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1731 for (i = 0; i < numTables; i++)
1733 TableInfo *tbinfo = &(tblinfo[i]);
1735 TableInfo **parents;
1738 /* Sequences and views never have parents */
1739 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1740 tbinfo->relkind == RELKIND_VIEW)
1743 /* Don't bother computing anything for non-target tables, either */
1744 if (!tbinfo->dobj.dump)
1747 numParents = tbinfo->numParents;
1748 parents = tbinfo->parents;
1750 if (numParents == 0)
1751 continue; /* nothing to see here, move along */
1753 /* scan for inherited CHECK constraints */
1754 for (j = 0; j < tbinfo->ncheck; j++)
1756 ConstraintInfo *constr;
1758 constr = &(tbinfo->checkexprs[j]);
1760 for (k = 0; k < numParents; k++)
1764 parent = parents[k];
1765 for (l = 0; l < parent->ncheck; l++)
1767 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1769 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1771 constr->conislocal = false;
1775 if (!constr->conislocal)
1785 * dump the database definition
1788 dumpDatabase(Archive *AH)
1790 PQExpBuffer dbQry = createPQExpBuffer();
1791 PQExpBuffer delQry = createPQExpBuffer();
1792 PQExpBuffer creaQry = createPQExpBuffer();
1805 const char *datname,
1813 datname = PQdb(g_conn);
1816 write_msg(NULL, "saving database definition\n");
1818 /* Make sure we are in proper schema */
1819 selectSourceSchema("pg_catalog");
1821 /* Get the database owner and parameters from pg_database */
1822 if (g_fout->remoteVersion >= 80400)
1824 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1825 "(%s datdba) AS dba, "
1826 "pg_encoding_to_char(encoding) AS encoding, "
1827 "datcollate, datctype, datfrozenxid, "
1828 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1829 "shobj_description(oid, 'pg_database') AS description "
1834 appendStringLiteralAH(dbQry, datname, AH);
1836 else if (g_fout->remoteVersion >= 80200)
1838 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1839 "(%s datdba) AS dba, "
1840 "pg_encoding_to_char(encoding) AS encoding, "
1841 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1842 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1843 "shobj_description(oid, 'pg_database') AS description "
1848 appendStringLiteralAH(dbQry, datname, AH);
1850 else if (g_fout->remoteVersion >= 80000)
1852 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1853 "(%s datdba) AS dba, "
1854 "pg_encoding_to_char(encoding) AS encoding, "
1855 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1856 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1860 appendStringLiteralAH(dbQry, datname, AH);
1862 else if (g_fout->remoteVersion >= 70100)
1864 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1865 "(%s datdba) AS dba, "
1866 "pg_encoding_to_char(encoding) AS encoding, "
1867 "NULL AS datcollate, NULL AS datctype, "
1868 "0 AS datfrozenxid, "
1869 "NULL AS tablespace "
1873 appendStringLiteralAH(dbQry, datname, AH);
1877 appendPQExpBuffer(dbQry, "SELECT "
1878 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1880 "(%s datdba) AS dba, "
1881 "pg_encoding_to_char(encoding) AS encoding, "
1882 "NULL AS datcollate, NULL AS datctype, "
1883 "0 AS datfrozenxid, "
1884 "NULL AS tablespace "
1888 appendStringLiteralAH(dbQry, datname, AH);
1891 res = PQexec(g_conn, dbQry->data);
1892 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1894 ntups = PQntuples(res);
1898 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1905 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1910 i_tableoid = PQfnumber(res, "tableoid");
1911 i_oid = PQfnumber(res, "oid");
1912 i_dba = PQfnumber(res, "dba");
1913 i_encoding = PQfnumber(res, "encoding");
1914 i_collate = PQfnumber(res, "datcollate");
1915 i_ctype = PQfnumber(res, "datctype");
1916 i_frozenxid = PQfnumber(res, "datfrozenxid");
1917 i_tablespace = PQfnumber(res, "tablespace");
1919 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1920 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1921 dba = PQgetvalue(res, 0, i_dba);
1922 encoding = PQgetvalue(res, 0, i_encoding);
1923 collate = PQgetvalue(res, 0, i_collate);
1924 ctype = PQgetvalue(res, 0, i_ctype);
1925 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1926 tablespace = PQgetvalue(res, 0, i_tablespace);
1928 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1930 if (strlen(encoding) > 0)
1932 appendPQExpBuffer(creaQry, " ENCODING = ");
1933 appendStringLiteralAH(creaQry, encoding, AH);
1935 if (strlen(collate) > 0)
1937 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1938 appendStringLiteralAH(creaQry, collate, AH);
1940 if (strlen(ctype) > 0)
1942 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1943 appendStringLiteralAH(creaQry, ctype, AH);
1945 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1946 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1948 appendPQExpBuffer(creaQry, ";\n");
1952 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1953 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1954 "SET datfrozenxid = '%u'\n"
1957 appendStringLiteralAH(creaQry, datname, AH);
1958 appendPQExpBuffer(creaQry, ";\n");
1962 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1965 dbDumpId = createDumpId();
1968 dbCatId, /* catalog ID */
1969 dbDumpId, /* dump ID */
1971 NULL, /* Namespace */
1972 NULL, /* Tablespace */
1974 false, /* with oids */
1975 "DATABASE", /* Desc */
1976 SECTION_PRE_DATA, /* Section */
1977 creaQry->data, /* Create */
1978 delQry->data, /* Del */
1983 NULL); /* Dumper Arg */
1986 * pg_largeobject and pg_largeobject_metadata come from the old system
1987 * intact, so set their relfrozenxids.
1992 PQExpBuffer loFrozenQry = createPQExpBuffer();
1993 PQExpBuffer loOutQry = createPQExpBuffer();
1999 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2000 "FROM pg_catalog.pg_class\n"
2001 "WHERE oid = %u;\n",
2002 LargeObjectRelationId);
2004 lo_res = PQexec(g_conn, loFrozenQry->data);
2005 check_sql_result(lo_res, g_conn, loFrozenQry->data, PGRES_TUPLES_OK);
2007 if (PQntuples(lo_res) != 1)
2009 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
2013 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2015 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2016 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2017 "SET relfrozenxid = '%u'\n"
2018 "WHERE oid = %u;\n",
2019 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2020 LargeObjectRelationId);
2021 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2022 "pg_largeobject", NULL, NULL, "",
2023 false, "pg_largeobject", SECTION_PRE_DATA,
2024 loOutQry->data, "", NULL,
2031 * pg_largeobject_metadata
2033 if (g_fout->remoteVersion >= 90000)
2035 resetPQExpBuffer(loFrozenQry);
2036 resetPQExpBuffer(loOutQry);
2038 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2039 "FROM pg_catalog.pg_class\n"
2040 "WHERE oid = %u;\n",
2041 LargeObjectMetadataRelationId);
2043 lo_res = PQexec(g_conn, loFrozenQry->data);
2044 check_sql_result(lo_res, g_conn, loFrozenQry->data, PGRES_TUPLES_OK);
2046 if (PQntuples(lo_res) != 1)
2048 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject_metadata.relfrozenxid\n");
2052 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2054 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2055 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2056 "SET relfrozenxid = '%u'\n"
2057 "WHERE oid = %u;\n",
2058 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2059 LargeObjectMetadataRelationId);
2060 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2061 "pg_largeobject_metadata", NULL, NULL, "",
2062 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2063 loOutQry->data, "", NULL,
2070 destroyPQExpBuffer(loFrozenQry);
2071 destroyPQExpBuffer(loOutQry);
2074 /* Dump DB comment if any */
2075 if (g_fout->remoteVersion >= 80200)
2078 * 8.2 keeps comments on shared objects in a shared table, so we
2079 * cannot use the dumpComment used for other database objects.
2081 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2083 if (comment && strlen(comment))
2085 resetPQExpBuffer(dbQry);
2088 * Generates warning when loaded into a differently-named
2091 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2092 appendStringLiteralAH(dbQry, comment, AH);
2093 appendPQExpBuffer(dbQry, ";\n");
2095 ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
2096 dba, false, "COMMENT", SECTION_NONE,
2097 dbQry->data, "", NULL,
2098 &dbDumpId, 1, NULL, NULL);
2103 resetPQExpBuffer(dbQry);
2104 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2105 dumpComment(AH, dbQry->data, NULL, "",
2106 dbCatId, 0, dbDumpId);
2111 /* Dump shared security label. */
2112 if (!no_security_labels && g_fout->remoteVersion >= 90200)
2114 PQExpBuffer seclabelQry = createPQExpBuffer();
2116 buildShSecLabelQuery(g_conn, "pg_database", dbCatId.oid, seclabelQry);
2117 res = PQexec(g_conn, seclabelQry->data);
2118 check_sql_result(res, g_conn, seclabelQry->data, PGRES_TUPLES_OK);
2119 resetPQExpBuffer(seclabelQry);
2120 emitShSecLabels(g_conn, res, seclabelQry, "DATABASE", datname);
2121 if (strlen(seclabelQry->data))
2122 ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
2123 dba, false, "SECURITY LABEL", SECTION_NONE,
2124 seclabelQry->data, "", NULL,
2125 &dbDumpId, 1, NULL, NULL);
2126 destroyPQExpBuffer(seclabelQry);
2129 destroyPQExpBuffer(dbQry);
2130 destroyPQExpBuffer(delQry);
2131 destroyPQExpBuffer(creaQry);
2136 * dumpEncoding: put the correct encoding into the archive
2139 dumpEncoding(Archive *AH)
2141 const char *encname = pg_encoding_to_char(AH->encoding);
2142 PQExpBuffer qry = createPQExpBuffer();
2145 write_msg(NULL, "saving encoding = %s\n", encname);
2147 appendPQExpBuffer(qry, "SET client_encoding = ");
2148 appendStringLiteralAH(qry, encname, AH);
2149 appendPQExpBuffer(qry, ";\n");
2151 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2152 "ENCODING", NULL, NULL, "",
2153 false, "ENCODING", SECTION_PRE_DATA,
2154 qry->data, "", NULL,
2158 destroyPQExpBuffer(qry);
2163 * dumpStdStrings: put the correct escape string behavior into the archive
2166 dumpStdStrings(Archive *AH)
2168 const char *stdstrings = AH->std_strings ? "on" : "off";
2169 PQExpBuffer qry = createPQExpBuffer();
2172 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2175 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2178 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2179 "STDSTRINGS", NULL, NULL, "",
2180 false, "STDSTRINGS", SECTION_PRE_DATA,
2181 qry->data, "", NULL,
2185 destroyPQExpBuffer(qry);
2191 * Collect schema-level data about large objects
2194 getBlobs(Archive *AH)
2196 PQExpBuffer blobQry = createPQExpBuffer();
2198 DumpableObject *bdata;
2203 /* Verbose message */
2205 write_msg(NULL, "reading large objects\n");
2207 /* Make sure we are in proper schema */
2208 selectSourceSchema("pg_catalog");
2210 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2211 if (AH->remoteVersion >= 90000)
2212 appendPQExpBuffer(blobQry,
2213 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2214 " FROM pg_largeobject_metadata",
2216 else if (AH->remoteVersion >= 70100)
2217 appendPQExpBuffer(blobQry,
2218 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2219 " FROM pg_largeobject");
2221 appendPQExpBuffer(blobQry,
2222 "SELECT oid, NULL::oid, NULL::oid"
2223 " FROM pg_class WHERE relkind = 'l'");
2225 res = PQexec(g_conn, blobQry->data);
2226 check_sql_result(res, g_conn, blobQry->data, PGRES_TUPLES_OK);
2228 ntups = PQntuples(res);
2232 * Each large object has its own BLOB archive entry.
2234 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2236 for (i = 0; i < ntups; i++)
2238 binfo[i].dobj.objType = DO_BLOB;
2239 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2240 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2241 AssignDumpId(&binfo[i].dobj);
2243 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2244 if (!PQgetisnull(res, i, 1))
2245 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2247 binfo[i].rolname = "";
2248 if (!PQgetisnull(res, i, 2))
2249 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2251 binfo[i].blobacl = NULL;
2255 * If we have any large objects, a "BLOBS" archive entry is needed.
2256 * This is just a placeholder for sorting; it carries no data now.
2258 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2259 bdata->objType = DO_BLOB_DATA;
2260 bdata->catId = nilCatalogId;
2261 AssignDumpId(bdata);
2262 bdata->name = pg_strdup("BLOBS");
2266 destroyPQExpBuffer(blobQry);
2272 * dump the definition (metadata) of the given large object
2275 dumpBlob(Archive *AH, BlobInfo *binfo)
2277 PQExpBuffer cquery = createPQExpBuffer();
2278 PQExpBuffer dquery = createPQExpBuffer();
2280 appendPQExpBuffer(cquery,
2281 "SELECT pg_catalog.lo_create('%s');\n",
2284 appendPQExpBuffer(dquery,
2285 "SELECT pg_catalog.lo_unlink('%s');\n",
2288 ArchiveEntry(AH, binfo->dobj.catId, binfo->dobj.dumpId,
2291 binfo->rolname, false,
2292 "BLOB", SECTION_PRE_DATA,
2293 cquery->data, dquery->data, NULL,
2294 binfo->dobj.dependencies, binfo->dobj.nDeps,
2297 /* set up tag for comment and/or ACL */
2298 resetPQExpBuffer(cquery);
2299 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2301 /* Dump comment if any */
2302 dumpComment(AH, cquery->data,
2303 NULL, binfo->rolname,
2304 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2306 /* Dump security label if any */
2307 dumpSecLabel(AH, cquery->data,
2308 NULL, binfo->rolname,
2309 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2311 /* Dump ACL if any */
2313 dumpACL(AH, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2314 binfo->dobj.name, NULL, cquery->data,
2315 NULL, binfo->rolname, binfo->blobacl);
2317 destroyPQExpBuffer(cquery);
2318 destroyPQExpBuffer(dquery);
2323 * dump the data contents of all large objects
2326 dumpBlobs(Archive *AH, void *arg)
2328 const char *blobQry;
2329 const char *blobFetchQry;
2331 char buf[LOBBUFSIZE];
2337 write_msg(NULL, "saving large objects\n");
2339 /* Make sure we are in proper schema */
2340 selectSourceSchema("pg_catalog");
2343 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2344 * the already-in-memory dumpable objects instead...
2346 if (AH->remoteVersion >= 90000)
2347 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2348 else if (AH->remoteVersion >= 70100)
2349 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2351 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2353 res = PQexec(g_conn, blobQry);
2354 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
2356 /* Command to fetch from cursor */
2357 blobFetchQry = "FETCH 1000 IN bloboid";
2364 res = PQexec(g_conn, blobFetchQry);
2365 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
2367 /* Process the tuples, if any */
2368 ntups = PQntuples(res);
2369 for (i = 0; i < ntups; i++)
2374 blobOid = atooid(PQgetvalue(res, i, 0));
2376 loFd = lo_open(g_conn, blobOid, INV_READ);
2379 write_msg(NULL, "could not open large object %u: %s",
2380 blobOid, PQerrorMessage(g_conn));
2384 StartBlob(AH, blobOid);
2386 /* Now read it in chunks, sending data to archive */
2389 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2392 write_msg(NULL, "error reading large object %u: %s",
2393 blobOid, PQerrorMessage(g_conn));
2397 WriteData(AH, buf, cnt);
2400 lo_close(g_conn, loFd);
2402 EndBlob(AH, blobOid);
2404 } while (ntups > 0);
2412 binary_upgrade_set_type_oids_by_type_oid(PQExpBuffer upgrade_buffer,
2415 PQExpBuffer upgrade_query = createPQExpBuffer();
2417 PGresult *upgrade_res;
2418 Oid pg_type_array_oid;
2420 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2421 appendPQExpBuffer(upgrade_buffer,
2422 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2425 /* we only support old >= 8.3 for binary upgrades */
2426 appendPQExpBuffer(upgrade_query,
2428 "FROM pg_catalog.pg_type "
2429 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2432 upgrade_res = PQexec(g_conn, upgrade_query->data);
2433 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2435 /* Expecting a single result only */
2436 ntups = PQntuples(upgrade_res);
2439 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2440 "query returned %d rows instead of one: %s\n",
2442 ntups, upgrade_query->data);
2446 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2448 if (OidIsValid(pg_type_array_oid))
2450 appendPQExpBuffer(upgrade_buffer,
2451 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2452 appendPQExpBuffer(upgrade_buffer,
2453 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2457 PQclear(upgrade_res);
2458 destroyPQExpBuffer(upgrade_query);
2462 binary_upgrade_set_type_oids_by_rel_oid(PQExpBuffer upgrade_buffer,
2465 PQExpBuffer upgrade_query = createPQExpBuffer();
2467 PGresult *upgrade_res;
2469 bool toast_set = false;
2471 /* we only support old >= 8.3 for binary upgrades */
2472 appendPQExpBuffer(upgrade_query,
2473 "SELECT c.reltype AS crel, t.reltype AS trel "
2474 "FROM pg_catalog.pg_class c "
2475 "LEFT JOIN pg_catalog.pg_class t ON "
2476 " (c.reltoastrelid = t.oid) "
2477 "WHERE c.oid = '%u'::pg_catalog.oid;",
2480 upgrade_res = PQexec(g_conn, upgrade_query->data);
2481 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2483 /* Expecting a single result only */
2484 ntups = PQntuples(upgrade_res);
2487 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2488 "query returned %d rows instead of one: %s\n",
2490 ntups, upgrade_query->data);
2494 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2496 binary_upgrade_set_type_oids_by_type_oid(upgrade_buffer, pg_type_oid);
2498 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2500 /* Toast tables do not have pg_type array rows */
2501 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2502 PQfnumber(upgrade_res, "trel")));
2504 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2505 appendPQExpBuffer(upgrade_buffer,
2506 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2512 PQclear(upgrade_res);
2513 destroyPQExpBuffer(upgrade_query);
2519 binary_upgrade_set_pg_class_oids(PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2522 PQExpBuffer upgrade_query = createPQExpBuffer();
2524 PGresult *upgrade_res;
2525 Oid pg_class_reltoastrelid;
2526 Oid pg_class_reltoastidxid;
2528 appendPQExpBuffer(upgrade_query,
2529 "SELECT c.reltoastrelid, t.reltoastidxid "
2530 "FROM pg_catalog.pg_class c LEFT JOIN "
2531 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2532 "WHERE c.oid = '%u'::pg_catalog.oid;",
2535 upgrade_res = PQexec(g_conn, upgrade_query->data);
2536 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2538 /* Expecting a single result only */
2539 ntups = PQntuples(upgrade_res);
2542 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2543 "query returned %d rows instead of one: %s\n",
2545 ntups, upgrade_query->data);
2549 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2550 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2552 appendPQExpBuffer(upgrade_buffer,
2553 "\n-- For binary upgrade, must preserve pg_class oids\n");
2557 appendPQExpBuffer(upgrade_buffer,
2558 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2560 /* only tables have toast tables, not indexes */
2561 if (OidIsValid(pg_class_reltoastrelid))
2564 * One complexity is that the table definition might not require
2565 * the creation of a TOAST table, and the TOAST table might have
2566 * been created long after table creation, when the table was
2567 * loaded with wide data. By setting the TOAST oid we force
2568 * creation of the TOAST heap and TOAST index by the backend so we
2569 * can cleanly copy the files during binary upgrade.
2572 appendPQExpBuffer(upgrade_buffer,
2573 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2574 pg_class_reltoastrelid);
2576 /* every toast table has an index */
2577 appendPQExpBuffer(upgrade_buffer,
2578 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2579 pg_class_reltoastidxid);
2583 appendPQExpBuffer(upgrade_buffer,
2584 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2587 appendPQExpBuffer(upgrade_buffer, "\n");
2589 PQclear(upgrade_res);
2590 destroyPQExpBuffer(upgrade_query);
2594 * If the DumpableObject is a member of an extension, add a suitable
2595 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2598 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2599 DumpableObject *dobj,
2600 const char *objlabel)
2602 DumpableObject *extobj = NULL;
2605 if (!dobj->ext_member)
2609 * Find the parent extension. We could avoid this search if we wanted to
2610 * add a link field to DumpableObject, but the space costs of that would
2611 * be considerable. We assume that member objects could only have a
2612 * direct dependency on their own extension, not any others.
2614 for (i = 0; i < dobj->nDeps; i++)
2616 extobj = findObjectByDumpId(dobj->dependencies[i]);
2617 if (extobj && extobj->objType == DO_EXTENSION)
2623 write_msg(NULL, "could not find parent extension for %s", objlabel);
2627 appendPQExpBuffer(upgrade_buffer,
2628 "\n-- For binary upgrade, handle extension membership the hard way\n");
2629 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2630 fmtId(extobj->name),
2636 * read all namespaces in the system catalogs and return them in the
2637 * NamespaceInfo* structure
2639 * numNamespaces is set to the number of namespaces read in
2642 getNamespaces(int *numNamespaces)
2648 NamespaceInfo *nsinfo;
2656 * Before 7.3, there are no real namespaces; create two dummy entries, one
2657 * for user stuff and one for system stuff.
2659 if (g_fout->remoteVersion < 70300)
2661 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2663 nsinfo[0].dobj.objType = DO_NAMESPACE;
2664 nsinfo[0].dobj.catId.tableoid = 0;
2665 nsinfo[0].dobj.catId.oid = 0;
2666 AssignDumpId(&nsinfo[0].dobj);
2667 nsinfo[0].dobj.name = pg_strdup("public");
2668 nsinfo[0].rolname = pg_strdup("");
2669 nsinfo[0].nspacl = pg_strdup("");
2671 selectDumpableNamespace(&nsinfo[0]);
2673 nsinfo[1].dobj.objType = DO_NAMESPACE;
2674 nsinfo[1].dobj.catId.tableoid = 0;
2675 nsinfo[1].dobj.catId.oid = 1;
2676 AssignDumpId(&nsinfo[1].dobj);
2677 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2678 nsinfo[1].rolname = pg_strdup("");
2679 nsinfo[1].nspacl = pg_strdup("");
2681 selectDumpableNamespace(&nsinfo[1]);
2683 g_namespaces = nsinfo;
2684 g_numNamespaces = *numNamespaces = 2;
2689 query = createPQExpBuffer();
2691 /* Make sure we are in proper schema */
2692 selectSourceSchema("pg_catalog");
2695 * we fetch all namespaces including system ones, so that every object we
2696 * read in can be linked to a containing namespace.
2698 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2699 "(%s nspowner) AS rolname, "
2700 "nspacl FROM pg_namespace",
2703 res = PQexec(g_conn, query->data);
2704 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2706 ntups = PQntuples(res);
2708 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2710 i_tableoid = PQfnumber(res, "tableoid");
2711 i_oid = PQfnumber(res, "oid");
2712 i_nspname = PQfnumber(res, "nspname");
2713 i_rolname = PQfnumber(res, "rolname");
2714 i_nspacl = PQfnumber(res, "nspacl");
2716 for (i = 0; i < ntups; i++)
2718 nsinfo[i].dobj.objType = DO_NAMESPACE;
2719 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2720 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2721 AssignDumpId(&nsinfo[i].dobj);
2722 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2723 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2724 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2726 /* Decide whether to dump this namespace */
2727 selectDumpableNamespace(&nsinfo[i]);
2729 if (strlen(nsinfo[i].rolname) == 0)
2730 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2731 nsinfo[i].dobj.name);
2735 destroyPQExpBuffer(query);
2737 g_namespaces = nsinfo;
2738 g_numNamespaces = *numNamespaces = ntups;
2745 * given a namespace OID and an object OID, look up the info read by
2748 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2749 * a system object or not. In 7.3 and later there is no guessing.
2751 static NamespaceInfo *
2752 findNamespace(Oid nsoid, Oid objoid)
2756 if (g_fout->remoteVersion >= 70300)
2758 for (i = 0; i < g_numNamespaces; i++)
2760 NamespaceInfo *nsinfo = &g_namespaces[i];
2762 if (nsoid == nsinfo->dobj.catId.oid)
2765 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2770 /* This code depends on the layout set up by getNamespaces. */
2771 if (objoid > g_last_builtin_oid)
2772 i = 0; /* user object */
2774 i = 1; /* system object */
2775 return &g_namespaces[i];
2778 return NULL; /* keep compiler quiet */
2783 * read all extensions in the system catalogs and return them in the
2784 * ExtensionInfo* structure
2786 * numExtensions is set to the number of extensions read in
2789 getExtensions(int *numExtensions)
2795 ExtensionInfo *extinfo;
2800 int i_extrelocatable;
2806 * Before 9.1, there are no extensions.
2808 if (g_fout->remoteVersion < 90100)
2814 query = createPQExpBuffer();
2816 /* Make sure we are in proper schema */
2817 selectSourceSchema("pg_catalog");
2819 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2820 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2821 "FROM pg_extension x "
2822 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2824 res = PQexec(g_conn, query->data);
2825 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2827 ntups = PQntuples(res);
2829 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2831 i_tableoid = PQfnumber(res, "tableoid");
2832 i_oid = PQfnumber(res, "oid");
2833 i_extname = PQfnumber(res, "extname");
2834 i_nspname = PQfnumber(res, "nspname");
2835 i_extrelocatable = PQfnumber(res, "extrelocatable");
2836 i_extversion = PQfnumber(res, "extversion");
2837 i_extconfig = PQfnumber(res, "extconfig");
2838 i_extcondition = PQfnumber(res, "extcondition");
2840 for (i = 0; i < ntups; i++)
2842 extinfo[i].dobj.objType = DO_EXTENSION;
2843 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2844 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2845 AssignDumpId(&extinfo[i].dobj);
2846 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2847 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2848 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2849 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2850 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2851 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2853 /* Decide whether we want to dump it */
2854 selectDumpableExtension(&(extinfo[i]));
2858 destroyPQExpBuffer(query);
2860 *numExtensions = ntups;
2867 * read all types in the system catalogs and return them in the
2868 * TypeInfo* structure
2870 * numTypes is set to the number of types read in
2872 * NB: this must run after getFuncs() because we assume we can do
2876 getTypes(int *numTypes)
2881 PQExpBuffer query = createPQExpBuffer();
2883 ShellTypeInfo *stinfo;
2899 * we include even the built-in types because those may be used as array
2900 * elements by user-defined types
2902 * we filter out the built-in types when we dump out the types
2904 * same approach for undefined (shell) types and array types
2906 * Note: as of 8.3 we can reliably detect whether a type is an
2907 * auto-generated array type by checking the element type's typarray.
2908 * (Before that the test is capable of generating false positives.) We
2909 * still check for name beginning with '_', though, so as to avoid the
2910 * cost of the subselect probe for all standard types. This would have to
2911 * be revisited if the backend ever allows renaming of array types.
2914 /* Make sure we are in proper schema */
2915 selectSourceSchema("pg_catalog");
2917 if (g_fout->remoteVersion >= 80300)
2919 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2921 "(%s typowner) AS rolname, "
2922 "typinput::oid AS typinput, "
2923 "typoutput::oid AS typoutput, typelem, typrelid, "
2924 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2925 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2926 "typtype, typisdefined, "
2927 "typname[0] = '_' AND typelem != 0 AND "
2928 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2932 else if (g_fout->remoteVersion >= 70300)
2934 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2936 "(%s typowner) AS rolname, "
2937 "typinput::oid AS typinput, "
2938 "typoutput::oid AS typoutput, typelem, typrelid, "
2939 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2940 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2941 "typtype, typisdefined, "
2942 "typname[0] = '_' AND typelem != 0 AS isarray "
2946 else if (g_fout->remoteVersion >= 70100)
2948 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2949 "0::oid AS typnamespace, "
2950 "(%s typowner) AS rolname, "
2951 "typinput::oid AS typinput, "
2952 "typoutput::oid AS typoutput, typelem, typrelid, "
2953 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2954 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2955 "typtype, typisdefined, "
2956 "typname[0] = '_' AND typelem != 0 AS isarray "
2962 appendPQExpBuffer(query, "SELECT "
2963 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2965 "0::oid AS typnamespace, "
2966 "(%s typowner) AS rolname, "
2967 "typinput::oid AS typinput, "
2968 "typoutput::oid AS typoutput, typelem, typrelid, "
2969 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2970 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2971 "typtype, typisdefined, "
2972 "typname[0] = '_' AND typelem != 0 AS isarray "
2977 res = PQexec(g_conn, query->data);
2978 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2980 ntups = PQntuples(res);
2982 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2984 i_tableoid = PQfnumber(res, "tableoid");
2985 i_oid = PQfnumber(res, "oid");
2986 i_typname = PQfnumber(res, "typname");
2987 i_typnamespace = PQfnumber(res, "typnamespace");
2988 i_rolname = PQfnumber(res, "rolname");
2989 i_typinput = PQfnumber(res, "typinput");
2990 i_typoutput = PQfnumber(res, "typoutput");
2991 i_typelem = PQfnumber(res, "typelem");
2992 i_typrelid = PQfnumber(res, "typrelid");
2993 i_typrelkind = PQfnumber(res, "typrelkind");
2994 i_typtype = PQfnumber(res, "typtype");
2995 i_typisdefined = PQfnumber(res, "typisdefined");
2996 i_isarray = PQfnumber(res, "isarray");
2998 for (i = 0; i < ntups; i++)
3000 tyinfo[i].dobj.objType = DO_TYPE;
3001 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3002 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3003 AssignDumpId(&tyinfo[i].dobj);
3004 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3005 tyinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
3006 tyinfo[i].dobj.catId.oid);
3007 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3008 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3009 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3010 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3011 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3012 tyinfo[i].shellType = NULL;
3014 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3015 tyinfo[i].isDefined = true;
3017 tyinfo[i].isDefined = false;
3019 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3020 tyinfo[i].isArray = true;
3022 tyinfo[i].isArray = false;
3024 /* Decide whether we want to dump it */
3025 selectDumpableType(&tyinfo[i]);
3028 * If it's a domain, fetch info about its constraints, if any
3030 tyinfo[i].nDomChecks = 0;
3031 tyinfo[i].domChecks = NULL;
3032 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3033 getDomainConstraints(&(tyinfo[i]));
3036 * If it's a base type, make a DumpableObject representing a shell
3037 * definition of the type. We will need to dump that ahead of the I/O
3038 * functions for the type. Similarly, range types need a shell
3039 * definition in case they have a canonicalize function.
3041 * Note: the shell type doesn't have a catId. You might think it
3042 * should copy the base type's catId, but then it might capture the
3043 * pg_depend entries for the type, which we don't want.
3045 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3046 tyinfo[i].typtype == TYPTYPE_RANGE))
3048 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3049 stinfo->dobj.objType = DO_SHELL_TYPE;
3050 stinfo->dobj.catId = nilCatalogId;
3051 AssignDumpId(&stinfo->dobj);
3052 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3053 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3054 stinfo->baseType = &(tyinfo[i]);
3055 tyinfo[i].shellType = stinfo;
3058 * Initially mark the shell type as not to be dumped. We'll only
3059 * dump it if the I/O or canonicalize functions need to be dumped;
3060 * this is taken care of while sorting dependencies.
3062 stinfo->dobj.dump = false;
3065 * However, if dumping from pre-7.3, there will be no dependency
3066 * info so we have to fake it here. We only need to worry about
3067 * typinput and typoutput since the other functions only exist
3070 if (g_fout->remoteVersion < 70300)
3076 typinput = atooid(PQgetvalue(res, i, i_typinput));
3077 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3079 funcInfo = findFuncByOid(typinput);
3080 if (funcInfo && funcInfo->dobj.dump)
3082 /* base type depends on function */
3083 addObjectDependency(&tyinfo[i].dobj,
3084 funcInfo->dobj.dumpId);
3085 /* function depends on shell type */
3086 addObjectDependency(&funcInfo->dobj,
3087 stinfo->dobj.dumpId);
3088 /* mark shell type as to be dumped */
3089 stinfo->dobj.dump = true;
3092 funcInfo = findFuncByOid(typoutput);
3093 if (funcInfo && funcInfo->dobj.dump)
3095 /* base type depends on function */
3096 addObjectDependency(&tyinfo[i].dobj,
3097 funcInfo->dobj.dumpId);
3098 /* function depends on shell type */
3099 addObjectDependency(&funcInfo->dobj,
3100 stinfo->dobj.dumpId);
3101 /* mark shell type as to be dumped */
3102 stinfo->dobj.dump = true;
3107 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3108 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3109 tyinfo[i].dobj.name);
3116 destroyPQExpBuffer(query);
3123 * read all operators in the system catalogs and return them in the
3124 * OprInfo* structure
3126 * numOprs is set to the number of operators read in
3129 getOperators(int *numOprs)
3134 PQExpBuffer query = createPQExpBuffer();
3145 * find all operators, including builtin operators; we filter out
3146 * system-defined operators at dump-out time.
3149 /* Make sure we are in proper schema */
3150 selectSourceSchema("pg_catalog");
3152 if (g_fout->remoteVersion >= 70300)
3154 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3156 "(%s oprowner) AS rolname, "
3158 "oprcode::oid AS oprcode "
3162 else if (g_fout->remoteVersion >= 70100)
3164 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3165 "0::oid AS oprnamespace, "
3166 "(%s oprowner) AS rolname, "
3168 "oprcode::oid AS oprcode "
3174 appendPQExpBuffer(query, "SELECT "
3175 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3177 "0::oid AS oprnamespace, "
3178 "(%s oprowner) AS rolname, "
3180 "oprcode::oid AS oprcode "
3185 res = PQexec(g_conn, query->data);
3186 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3188 ntups = PQntuples(res);
3191 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3193 i_tableoid = PQfnumber(res, "tableoid");
3194 i_oid = PQfnumber(res, "oid");
3195 i_oprname = PQfnumber(res, "oprname");
3196 i_oprnamespace = PQfnumber(res, "oprnamespace");
3197 i_rolname = PQfnumber(res, "rolname");
3198 i_oprkind = PQfnumber(res, "oprkind");
3199 i_oprcode = PQfnumber(res, "oprcode");
3201 for (i = 0; i < ntups; i++)
3203 oprinfo[i].dobj.objType = DO_OPERATOR;
3204 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3205 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3206 AssignDumpId(&oprinfo[i].dobj);
3207 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3208 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
3209 oprinfo[i].dobj.catId.oid);
3210 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3211 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3212 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3214 /* Decide whether we want to dump it */
3215 selectDumpableObject(&(oprinfo[i].dobj));
3217 if (strlen(oprinfo[i].rolname) == 0)
3218 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3219 oprinfo[i].dobj.name);
3224 destroyPQExpBuffer(query);
3231 * read all collations in the system catalogs and return them in the
3232 * CollInfo* structure
3234 * numCollations is set to the number of collations read in
3237 getCollations(int *numCollations)
3242 PQExpBuffer query = createPQExpBuffer();
3247 int i_collnamespace;
3250 /* Collations didn't exist pre-9.1 */
3251 if (g_fout->remoteVersion < 90100)
3258 * find all collations, including builtin collations; we filter out
3259 * system-defined collations at dump-out time.
3262 /* Make sure we are in proper schema */
3263 selectSourceSchema("pg_catalog");
3265 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3267 "(%s collowner) AS rolname "
3268 "FROM pg_collation",
3271 res = PQexec(g_conn, query->data);
3272 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3274 ntups = PQntuples(res);
3275 *numCollations = ntups;
3277 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3279 i_tableoid = PQfnumber(res, "tableoid");
3280 i_oid = PQfnumber(res, "oid");
3281 i_collname = PQfnumber(res, "collname");
3282 i_collnamespace = PQfnumber(res, "collnamespace");
3283 i_rolname = PQfnumber(res, "rolname");
3285 for (i = 0; i < ntups; i++)
3287 collinfo[i].dobj.objType = DO_COLLATION;
3288 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3289 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3290 AssignDumpId(&collinfo[i].dobj);
3291 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3292 collinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_collnamespace)),
3293 collinfo[i].dobj.catId.oid);
3294 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3296 /* Decide whether we want to dump it */
3297 selectDumpableObject(&(collinfo[i].dobj));
3302 destroyPQExpBuffer(query);
3309 * read all conversions in the system catalogs and return them in the
3310 * ConvInfo* structure
3312 * numConversions is set to the number of conversions read in
3315 getConversions(int *numConversions)
3320 PQExpBuffer query = createPQExpBuffer();
3328 /* Conversions didn't exist pre-7.3 */
3329 if (g_fout->remoteVersion < 70300)
3331 *numConversions = 0;
3336 * find all conversions, including builtin conversions; we filter out
3337 * system-defined conversions at dump-out time.
3340 /* Make sure we are in proper schema */
3341 selectSourceSchema("pg_catalog");
3343 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3345 "(%s conowner) AS rolname "
3346 "FROM pg_conversion",
3349 res = PQexec(g_conn, query->data);
3350 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3352 ntups = PQntuples(res);
3353 *numConversions = ntups;
3355 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3357 i_tableoid = PQfnumber(res, "tableoid");
3358 i_oid = PQfnumber(res, "oid");
3359 i_conname = PQfnumber(res, "conname");
3360 i_connamespace = PQfnumber(res, "connamespace");
3361 i_rolname = PQfnumber(res, "rolname");
3363 for (i = 0; i < ntups; i++)
3365 convinfo[i].dobj.objType = DO_CONVERSION;
3366 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3367 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3368 AssignDumpId(&convinfo[i].dobj);
3369 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3370 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
3371 convinfo[i].dobj.catId.oid);
3372 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3374 /* Decide whether we want to dump it */
3375 selectDumpableObject(&(convinfo[i].dobj));
3380 destroyPQExpBuffer(query);
3387 * read all opclasses in the system catalogs and return them in the
3388 * OpclassInfo* structure
3390 * numOpclasses is set to the number of opclasses read in
3393 getOpclasses(int *numOpclasses)
3398 PQExpBuffer query = createPQExpBuffer();
3399 OpclassInfo *opcinfo;
3407 * find all opclasses, including builtin opclasses; we filter out
3408 * system-defined opclasses at dump-out time.
3411 /* Make sure we are in proper schema */
3412 selectSourceSchema("pg_catalog");
3414 if (g_fout->remoteVersion >= 70300)
3416 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3418 "(%s opcowner) AS rolname "
3422 else if (g_fout->remoteVersion >= 70100)
3424 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3425 "0::oid AS opcnamespace, "
3426 "''::name AS rolname "
3431 appendPQExpBuffer(query, "SELECT "
3432 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3434 "0::oid AS opcnamespace, "
3435 "''::name AS rolname "
3439 res = PQexec(g_conn, query->data);
3440 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3442 ntups = PQntuples(res);
3443 *numOpclasses = ntups;
3445 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3447 i_tableoid = PQfnumber(res, "tableoid");
3448 i_oid = PQfnumber(res, "oid");
3449 i_opcname = PQfnumber(res, "opcname");
3450 i_opcnamespace = PQfnumber(res, "opcnamespace");
3451 i_rolname = PQfnumber(res, "rolname");
3453 for (i = 0; i < ntups; i++)
3455 opcinfo[i].dobj.objType = DO_OPCLASS;
3456 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3457 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3458 AssignDumpId(&opcinfo[i].dobj);
3459 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3460 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
3461 opcinfo[i].dobj.catId.oid);
3462 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3464 /* Decide whether we want to dump it */
3465 selectDumpableObject(&(opcinfo[i].dobj));
3467 if (g_fout->remoteVersion >= 70300)
3469 if (strlen(opcinfo[i].rolname) == 0)
3470 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3471 opcinfo[i].dobj.name);
3477 destroyPQExpBuffer(query);
3484 * read all opfamilies in the system catalogs and return them in the
3485 * OpfamilyInfo* structure
3487 * numOpfamilies is set to the number of opfamilies read in
3490 getOpfamilies(int *numOpfamilies)
3496 OpfamilyInfo *opfinfo;
3503 /* Before 8.3, there is no separate concept of opfamilies */
3504 if (g_fout->remoteVersion < 80300)
3510 query = createPQExpBuffer();
3513 * find all opfamilies, including builtin opfamilies; we filter out
3514 * system-defined opfamilies at dump-out time.
3517 /* Make sure we are in proper schema */
3518 selectSourceSchema("pg_catalog");
3520 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3522 "(%s opfowner) AS rolname "
3526 res = PQexec(g_conn, query->data);
3527 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3529 ntups = PQntuples(res);
3530 *numOpfamilies = ntups;
3532 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3534 i_tableoid = PQfnumber(res, "tableoid");
3535 i_oid = PQfnumber(res, "oid");
3536 i_opfname = PQfnumber(res, "opfname");
3537 i_opfnamespace = PQfnumber(res, "opfnamespace");
3538 i_rolname = PQfnumber(res, "rolname");
3540 for (i = 0; i < ntups; i++)
3542 opfinfo[i].dobj.objType = DO_OPFAMILY;
3543 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3544 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3545 AssignDumpId(&opfinfo[i].dobj);
3546 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3547 opfinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opfnamespace)),
3548 opfinfo[i].dobj.catId.oid);
3549 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3551 /* Decide whether we want to dump it */
3552 selectDumpableObject(&(opfinfo[i].dobj));
3554 if (g_fout->remoteVersion >= 70300)
3556 if (strlen(opfinfo[i].rolname) == 0)
3557 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3558 opfinfo[i].dobj.name);
3564 destroyPQExpBuffer(query);
3571 * read all the user-defined aggregates in the system catalogs and
3572 * return them in the AggInfo* structure
3574 * numAggs is set to the number of aggregates read in
3577 getAggregates(int *numAggs)
3582 PQExpBuffer query = createPQExpBuffer();
3593 /* Make sure we are in proper schema */
3594 selectSourceSchema("pg_catalog");
3597 * Find all user-defined aggregates. See comment in getFuncs() for the
3598 * rationale behind the filtering logic.
3601 if (g_fout->remoteVersion >= 80200)
3603 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3604 "pronamespace AS aggnamespace, "
3605 "pronargs, proargtypes, "
3606 "(%s proowner) AS rolname, "
3609 "WHERE proisagg AND ("
3611 "(SELECT oid FROM pg_namespace "
3612 "WHERE nspname = 'pg_catalog')",
3614 if (binary_upgrade && g_fout->remoteVersion >= 90100)
3615 appendPQExpBuffer(query,
3616 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3617 "classid = 'pg_proc'::regclass AND "
3618 "objid = p.oid AND "
3619 "refclassid = 'pg_extension'::regclass AND "
3621 appendPQExpBuffer(query, ")");
3623 else if (g_fout->remoteVersion >= 70300)
3625 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3626 "pronamespace AS aggnamespace, "
3627 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3629 "(%s proowner) AS rolname, "
3633 "AND pronamespace != "
3634 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3637 else if (g_fout->remoteVersion >= 70100)
3639 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3640 "0::oid AS aggnamespace, "
3641 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3642 "aggbasetype AS proargtypes, "
3643 "(%s aggowner) AS rolname, "
3645 "FROM pg_aggregate "
3646 "where oid > '%u'::oid",
3648 g_last_builtin_oid);
3652 appendPQExpBuffer(query, "SELECT "
3653 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3655 "0::oid AS aggnamespace, "
3656 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3657 "aggbasetype AS proargtypes, "
3658 "(%s aggowner) AS rolname, "
3660 "FROM pg_aggregate "
3661 "where oid > '%u'::oid",
3663 g_last_builtin_oid);
3666 res = PQexec(g_conn, query->data);
3667 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3669 ntups = PQntuples(res);
3672 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3674 i_tableoid = PQfnumber(res, "tableoid");
3675 i_oid = PQfnumber(res, "oid");
3676 i_aggname = PQfnumber(res, "aggname");
3677 i_aggnamespace = PQfnumber(res, "aggnamespace");
3678 i_pronargs = PQfnumber(res, "pronargs");
3679 i_proargtypes = PQfnumber(res, "proargtypes");
3680 i_rolname = PQfnumber(res, "rolname");
3681 i_aggacl = PQfnumber(res, "aggacl");
3683 for (i = 0; i < ntups; i++)
3685 agginfo[i].aggfn.dobj.objType = DO_AGG;
3686 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3687 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3688 AssignDumpId(&agginfo[i].aggfn.dobj);
3689 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3690 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
3691 agginfo[i].aggfn.dobj.catId.oid);
3692 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3693 if (strlen(agginfo[i].aggfn.rolname) == 0)
3694 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3695 agginfo[i].aggfn.dobj.name);
3696 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3697 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3698 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3699 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3700 if (agginfo[i].aggfn.nargs == 0)
3701 agginfo[i].aggfn.argtypes = NULL;
3704 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3705 if (g_fout->remoteVersion >= 70300)
3706 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3707 agginfo[i].aggfn.argtypes,
3708 agginfo[i].aggfn.nargs);
3710 /* it's just aggbasetype */
3711 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3714 /* Decide whether we want to dump it */
3715 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3720 destroyPQExpBuffer(query);
3727 * read all the user-defined functions in the system catalogs and
3728 * return them in the FuncInfo* structure
3730 * numFuncs is set to the number of functions read in
3733 getFuncs(int *numFuncs)
3738 PQExpBuffer query = createPQExpBuffer();
3751 /* Make sure we are in proper schema */
3752 selectSourceSchema("pg_catalog");
3755 * Find all user-defined functions. Normally we can exclude functions in
3756 * pg_catalog, which is worth doing since there are several thousand of
3757 * 'em. However, there are some extensions that create functions in
3758 * pg_catalog. In normal dumps we can still ignore those --- but in
3759 * binary-upgrade mode, we must dump the member objects of the extension,
3760 * so be sure to fetch any such functions.
3762 * Also, in 9.2 and up, exclude functions that are internally dependent on
3763 * something else, since presumably those will be created as a result of
3764 * creating the something else. This currently only acts to suppress
3765 * constructor functions for range types. Note that this is OK only
3766 * because the constructors don't have any dependencies the range type
3767 * doesn't have; otherwise we might not get creation ordering correct.
3770 if (g_fout->remoteVersion >= 70300)
3772 appendPQExpBuffer(query,
3773 "SELECT tableoid, oid, proname, prolang, "
3774 "pronargs, proargtypes, prorettype, proacl, "
3776 "(%s proowner) AS rolname "
3778 "WHERE NOT proisagg AND ("
3780 "(SELECT oid FROM pg_namespace "
3781 "WHERE nspname = 'pg_catalog')",
3783 if (g_fout->remoteVersion >= 90200)
3784 appendPQExpBuffer(query,
3785 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3786 "WHERE classid = 'pg_proc'::regclass AND "
3787 "objid = p.oid AND deptype = 'i')");
3788 if (binary_upgrade && g_fout->remoteVersion >= 90100)
3789 appendPQExpBuffer(query,
3790 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3791 "classid = 'pg_proc'::regclass AND "
3792 "objid = p.oid AND "
3793 "refclassid = 'pg_extension'::regclass AND "
3795 appendPQExpBuffer(query, ")");
3797 else if (g_fout->remoteVersion >= 70100)
3799 appendPQExpBuffer(query,
3800 "SELECT tableoid, oid, proname, prolang, "
3801 "pronargs, proargtypes, prorettype, "
3802 "'{=X}' AS proacl, "
3803 "0::oid AS pronamespace, "
3804 "(%s proowner) AS rolname "
3806 "WHERE pg_proc.oid > '%u'::oid",
3808 g_last_builtin_oid);
3812 appendPQExpBuffer(query,
3814 "(SELECT oid FROM pg_class "
3815 " WHERE relname = 'pg_proc') AS tableoid, "
3816 "oid, proname, prolang, "
3817 "pronargs, proargtypes, prorettype, "
3818 "'{=X}' AS proacl, "
3819 "0::oid AS pronamespace, "
3820 "(%s proowner) AS rolname "
3822 "where pg_proc.oid > '%u'::oid",
3824 g_last_builtin_oid);
3827 res = PQexec(g_conn, query->data);
3828 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3830 ntups = PQntuples(res);
3834 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3836 i_tableoid = PQfnumber(res, "tableoid");
3837 i_oid = PQfnumber(res, "oid");
3838 i_proname = PQfnumber(res, "proname");
3839 i_pronamespace = PQfnumber(res, "pronamespace");
3840 i_rolname = PQfnumber(res, "rolname");
3841 i_prolang = PQfnumber(res, "prolang");
3842 i_pronargs = PQfnumber(res, "pronargs");
3843 i_proargtypes = PQfnumber(res, "proargtypes");
3844 i_prorettype = PQfnumber(res, "prorettype");
3845 i_proacl = PQfnumber(res, "proacl");
3847 for (i = 0; i < ntups; i++)
3849 finfo[i].dobj.objType = DO_FUNC;
3850 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3851 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3852 AssignDumpId(&finfo[i].dobj);
3853 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3854 finfo[i].dobj.namespace =
3855 findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
3856 finfo[i].dobj.catId.oid);
3857 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3858 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3859 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3860 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3861 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3862 if (finfo[i].nargs == 0)
3863 finfo[i].argtypes = NULL;
3866 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3867 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3868 finfo[i].argtypes, finfo[i].nargs);
3871 /* Decide whether we want to dump it */
3872 selectDumpableObject(&(finfo[i].dobj));
3874 if (strlen(finfo[i].rolname) == 0)
3876 "WARNING: owner of function \"%s\" appears to be invalid\n",
3877 finfo[i].dobj.name);
3882 destroyPQExpBuffer(query);
3889 * read all the user-defined tables (no indexes, no catalogs)
3890 * in the system catalogs return them in the TableInfo* structure
3892 * numTables is set to the number of tables read in
3895 getTables(int *numTables)
3900 PQExpBuffer query = createPQExpBuffer();
3910 int i_relhastriggers;
3916 int i_toastfrozenxid;
3917 int i_relpersistence;
3920 int i_reltablespace;
3922 int i_toastreloptions;
3925 /* Make sure we are in proper schema */
3926 selectSourceSchema("pg_catalog");
3929 * Find all the tables (including views and sequences).
3931 * We include system catalogs, so that we can work if a user table is
3932 * defined to inherit from a system catalog (pretty weird, but...)
3934 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3935 * (sequence), 'v' (view), or 'c' (composite type).
3937 * Composite-type table entries won't be dumped as such, but we have to
3938 * make a DumpableObject for them so that we can track dependencies of the
3939 * composite type (pg_depend entries for columns of the composite type
3940 * link to the pg_class entry not the pg_type entry).
3942 * Note: in this phase we should collect only a minimal amount of
3943 * information about each table, basically just enough to decide if it is
3944 * interesting. We must fetch all tables in this phase because otherwise
3945 * we cannot correctly identify inherited columns, owned sequences, etc.
3948 if (g_fout->remoteVersion >= 90100)
3951 * Left join to pick up dependency info linking sequences to their
3952 * owning column, if any (note this dependency is AUTO as of 8.2)
3954 appendPQExpBuffer(query,
3955 "SELECT c.tableoid, c.oid, c.relname, "
3956 "c.relacl, c.relkind, c.relnamespace, "
3957 "(%s c.relowner) AS rolname, "
3958 "c.relchecks, c.relhastriggers, "
3959 "c.relhasindex, c.relhasrules, c.relhasoids, "
3960 "c.relfrozenxid, tc.oid AS toid, "
3961 "tc.relfrozenxid AS tfrozenxid, "
3962 "c.relpersistence, "
3963 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3964 "d.refobjid AS owning_tab, "
3965 "d.refobjsubid AS owning_col, "
3966 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3967 "array_to_string(c.reloptions, ', ') AS reloptions, "
3968 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3970 "LEFT JOIN pg_depend d ON "
3971 "(c.relkind = '%c' AND "
3972 "d.classid = c.tableoid AND d.objid = c.oid AND "
3973 "d.objsubid = 0 AND "
3974 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3975 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3976 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3980 RELKIND_RELATION, RELKIND_SEQUENCE,
3981 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3982 RELKIND_FOREIGN_TABLE);
3984 else if (g_fout->remoteVersion >= 90000)
3987 * Left join to pick up dependency info linking sequences to their
3988 * owning column, if any (note this dependency is AUTO as of 8.2)
3990 appendPQExpBuffer(query,
3991 "SELECT c.tableoid, c.oid, c.relname, "
3992 "c.relacl, c.relkind, c.relnamespace, "
3993 "(%s c.relowner) AS rolname, "
3994 "c.relchecks, c.relhastriggers, "
3995 "c.relhasindex, c.relhasrules, c.relhasoids, "
3996 "c.relfrozenxid, tc.oid AS toid, "
3997 "tc.relfrozenxid AS tfrozenxid, "
3998 "'p' AS relpersistence, "
3999 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4000 "d.refobjid AS owning_tab, "
4001 "d.refobjsubid AS owning_col, "
4002 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4003 "array_to_string(c.reloptions, ', ') AS reloptions, "
4004 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4006 "LEFT JOIN pg_depend d ON "
4007 "(c.relkind = '%c' AND "
4008 "d.classid = c.tableoid AND d.objid = c.oid AND "
4009 "d.objsubid = 0 AND "
4010 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4011 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4012 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4016 RELKIND_RELATION, RELKIND_SEQUENCE,
4017 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4019 else if (g_fout->remoteVersion >= 80400)
4022 * Left join to pick up dependency info linking sequences to their
4023 * owning column, if any (note this dependency is AUTO as of 8.2)
4025 appendPQExpBuffer(query,
4026 "SELECT c.tableoid, c.oid, c.relname, "
4027 "c.relacl, c.relkind, c.relnamespace, "
4028 "(%s c.relowner) AS rolname, "
4029 "c.relchecks, c.relhastriggers, "
4030 "c.relhasindex, c.relhasrules, c.relhasoids, "
4031 "c.relfrozenxid, tc.oid AS toid, "
4032 "tc.relfrozenxid AS tfrozenxid, "
4033 "'p' AS relpersistence, "
4034 "NULL AS reloftype, "
4035 "d.refobjid AS owning_tab, "
4036 "d.refobjsubid AS owning_col, "
4037 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4038 "array_to_string(c.reloptions, ', ') AS reloptions, "
4039 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4041 "LEFT JOIN pg_depend d ON "
4042 "(c.relkind = '%c' AND "
4043 "d.classid = c.tableoid AND d.objid = c.oid AND "
4044 "d.objsubid = 0 AND "
4045 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4046 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4047 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4051 RELKIND_RELATION, RELKIND_SEQUENCE,
4052 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4054 else if (g_fout->remoteVersion >= 80200)
4057 * Left join to pick up dependency info linking sequences to their
4058 * owning column, if any (note this dependency is AUTO as of 8.2)
4060 appendPQExpBuffer(query,
4061 "SELECT c.tableoid, c.oid, c.relname, "
4062 "c.relacl, c.relkind, c.relnamespace, "
4063 "(%s c.relowner) AS rolname, "
4064 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4065 "c.relhasindex, c.relhasrules, c.relhasoids, "
4066 "c.relfrozenxid, tc.oid AS toid, "
4067 "tc.relfrozenxid AS tfrozenxid, "
4068 "'p' AS relpersistence, "
4069 "NULL AS reloftype, "
4070 "d.refobjid AS owning_tab, "
4071 "d.refobjsubid AS owning_col, "
4072 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4073 "array_to_string(c.reloptions, ', ') AS reloptions, "
4074 "NULL AS toast_reloptions "
4076 "LEFT JOIN pg_depend d ON "
4077 "(c.relkind = '%c' AND "
4078 "d.classid = c.tableoid AND d.objid = c.oid AND "
4079 "d.objsubid = 0 AND "
4080 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4081 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4082 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4086 RELKIND_RELATION, RELKIND_SEQUENCE,
4087 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4089 else if (g_fout->remoteVersion >= 80000)
4092 * Left join to pick up dependency info linking sequences to their
4093 * owning column, if any
4095 appendPQExpBuffer(query,
4096 "SELECT c.tableoid, c.oid, relname, "
4097 "relacl, relkind, relnamespace, "
4098 "(%s relowner) AS rolname, "
4099 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4100 "relhasindex, relhasrules, relhasoids, "
4101 "0 AS relfrozenxid, "
4104 "'p' AS relpersistence, "
4105 "NULL AS reloftype, "
4106 "d.refobjid AS owning_tab, "
4107 "d.refobjsubid AS owning_col, "
4108 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4109 "NULL AS reloptions, "
4110 "NULL AS toast_reloptions "
4112 "LEFT JOIN pg_depend d ON "
4113 "(c.relkind = '%c' AND "
4114 "d.classid = c.tableoid AND d.objid = c.oid AND "
4115 "d.objsubid = 0 AND "
4116 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4117 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4121 RELKIND_RELATION, RELKIND_SEQUENCE,
4122 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4124 else if (g_fout->remoteVersion >= 70300)
4127 * Left join to pick up dependency info linking sequences to their
4128 * owning column, if any
4130 appendPQExpBuffer(query,
4131 "SELECT c.tableoid, c.oid, relname, "
4132 "relacl, relkind, relnamespace, "
4133 "(%s relowner) AS rolname, "
4134 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4135 "relhasindex, relhasrules, relhasoids, "
4136 "0 AS relfrozenxid, "
4139 "'p' AS relpersistence, "
4140 "NULL AS reloftype, "
4141 "d.refobjid AS owning_tab, "
4142 "d.refobjsubid AS owning_col, "
4143 "NULL AS reltablespace, "
4144 "NULL AS reloptions, "
4145 "NULL AS toast_reloptions "
4147 "LEFT JOIN pg_depend d ON "
4148 "(c.relkind = '%c' AND "
4149 "d.classid = c.tableoid AND d.objid = c.oid AND "
4150 "d.objsubid = 0 AND "
4151 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4152 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4156 RELKIND_RELATION, RELKIND_SEQUENCE,
4157 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4159 else if (g_fout->remoteVersion >= 70200)
4161 appendPQExpBuffer(query,
4162 "SELECT tableoid, oid, relname, relacl, relkind, "
4163 "0::oid AS relnamespace, "
4164 "(%s relowner) AS rolname, "
4165 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4166 "relhasindex, relhasrules, relhasoids, "
4167 "0 AS relfrozenxid, "
4170 "'p' AS relpersistence, "
4171 "NULL AS reloftype, "
4172 "NULL::oid AS owning_tab, "
4173 "NULL::int4 AS owning_col, "
4174 "NULL AS reltablespace, "
4175 "NULL AS reloptions, "
4176 "NULL AS toast_reloptions "
4178 "WHERE relkind IN ('%c', '%c', '%c') "
4181 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4183 else if (g_fout->remoteVersion >= 70100)
4185 /* all tables have oids in 7.1 */
4186 appendPQExpBuffer(query,
4187 "SELECT tableoid, oid, relname, relacl, relkind, "
4188 "0::oid AS relnamespace, "
4189 "(%s relowner) AS rolname, "
4190 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4191 "relhasindex, relhasrules, "
4192 "'t'::bool AS relhasoids, "
4193 "0 AS relfrozenxid, "
4196 "'p' AS relpersistence, "
4197 "NULL AS reloftype, "
4198 "NULL::oid AS owning_tab, "
4199 "NULL::int4 AS owning_col, "
4200 "NULL AS reltablespace, "
4201 "NULL AS reloptions, "
4202 "NULL AS toast_reloptions "
4204 "WHERE relkind IN ('%c', '%c', '%c') "
4207 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4212 * Before 7.1, view relkind was not set to 'v', so we must check if we
4213 * have a view by looking for a rule in pg_rewrite.
4215 appendPQExpBuffer(query,
4217 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4218 "oid, relname, relacl, "
4219 "CASE WHEN relhasrules and relkind = 'r' "
4220 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4221 " r.ev_class = c.oid AND r.ev_type = '1') "
4222 "THEN '%c'::\"char\" "
4223 "ELSE relkind END AS relkind,"
4224 "0::oid AS relnamespace, "
4225 "(%s relowner) AS rolname, "
4226 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4227 "relhasindex, relhasrules, "
4228 "'t'::bool AS relhasoids, "
4229 "0 as relfrozenxid, "
4232 "'p' AS relpersistence, "
4233 "NULL AS reloftype, "
4234 "NULL::oid AS owning_tab, "
4235 "NULL::int4 AS owning_col, "
4236 "NULL AS reltablespace, "
4237 "NULL AS reloptions, "
4238 "NULL AS toast_reloptions "
4240 "WHERE relkind IN ('%c', '%c') "
4244 RELKIND_RELATION, RELKIND_SEQUENCE);
4247 res = PQexec(g_conn, query->data);
4248 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4250 ntups = PQntuples(res);
4255 * Extract data from result and lock dumpable tables. We do the locking
4256 * before anything else, to minimize the window wherein a table could
4257 * disappear under us.
4259 * Note that we have to save info about all tables here, even when dumping
4260 * only one, because we don't yet know which tables might be inheritance
4261 * ancestors of the target table.
4263 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4265 i_reltableoid = PQfnumber(res, "tableoid");
4266 i_reloid = PQfnumber(res, "oid");
4267 i_relname = PQfnumber(res, "relname");
4268 i_relnamespace = PQfnumber(res, "relnamespace");
4269 i_relacl = PQfnumber(res, "relacl");
4270 i_relkind = PQfnumber(res, "relkind");
4271 i_rolname = PQfnumber(res, "rolname");
4272 i_relchecks = PQfnumber(res, "relchecks");
4273 i_relhastriggers = PQfnumber(res, "relhastriggers");
4274 i_relhasindex = PQfnumber(res, "relhasindex");
4275 i_relhasrules = PQfnumber(res, "relhasrules");
4276 i_relhasoids = PQfnumber(res, "relhasoids");
4277 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4278 i_toastoid = PQfnumber(res, "toid");
4279 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4280 i_relpersistence = PQfnumber(res, "relpersistence");
4281 i_owning_tab = PQfnumber(res, "owning_tab");
4282 i_owning_col = PQfnumber(res, "owning_col");
4283 i_reltablespace = PQfnumber(res, "reltablespace");
4284 i_reloptions = PQfnumber(res, "reloptions");
4285 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4286 i_reloftype = PQfnumber(res, "reloftype");
4288 if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
4291 * Arrange to fail instead of waiting forever for a table lock.
4293 * NB: this coding assumes that the only queries issued within the
4294 * following loop are LOCK TABLEs; else the timeout may be undesirably
4295 * applied to other things too.
4297 resetPQExpBuffer(query);
4298 appendPQExpBuffer(query, "SET statement_timeout = ");
4299 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
4300 do_sql_command(g_conn, query->data);
4303 for (i = 0; i < ntups; i++)
4305 tblinfo[i].dobj.objType = DO_TABLE;
4306 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4307 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4308 AssignDumpId(&tblinfo[i].dobj);
4309 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4310 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
4311 tblinfo[i].dobj.catId.oid);
4312 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4313 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4314 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4315 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4316 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4317 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4318 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4319 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4320 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4321 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4322 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4323 if (PQgetisnull(res, i, i_reloftype))
4324 tblinfo[i].reloftype = NULL;
4326 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4327 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4328 if (PQgetisnull(res, i, i_owning_tab))
4330 tblinfo[i].owning_tab = InvalidOid;
4331 tblinfo[i].owning_col = 0;
4335 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4336 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4338 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4339 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4340 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4342 /* other fields were zeroed above */
4345 * Decide whether we want to dump this table.
4347 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4348 tblinfo[i].dobj.dump = false;
4350 selectDumpableTable(&tblinfo[i]);
4351 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4354 * Read-lock target tables to make sure they aren't DROPPED or altered
4355 * in schema before we get around to dumping them.
4357 * Note that we don't explicitly lock parents of the target tables; we
4358 * assume our lock on the child is enough to prevent schema
4359 * alterations to parent tables.
4361 * NOTE: it'd be kinda nice to lock other relations too, not only
4362 * plain tables, but the backend doesn't presently allow that.
4364 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4366 resetPQExpBuffer(query);
4367 appendPQExpBuffer(query,
4368 "LOCK TABLE %s IN ACCESS SHARE MODE",
4369 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
4370 tblinfo[i].dobj.name));
4371 do_sql_command(g_conn, query->data);
4374 /* Emit notice if join for owner failed */
4375 if (strlen(tblinfo[i].rolname) == 0)
4376 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4377 tblinfo[i].dobj.name);
4380 if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
4382 do_sql_command(g_conn, "SET statement_timeout = 0");
4388 * Force sequences that are "owned" by table columns to be dumped whenever
4389 * their owning table is being dumped.
4391 for (i = 0; i < ntups; i++)
4393 TableInfo *seqinfo = &tblinfo[i];
4396 if (!OidIsValid(seqinfo->owning_tab))
4397 continue; /* not an owned sequence */
4398 if (seqinfo->dobj.dump)
4399 continue; /* no need to search */
4401 /* can't use findTableByOid yet, unfortunately */
4402 for (j = 0; j < ntups; j++)
4404 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4406 if (tblinfo[j].dobj.dump)
4408 seqinfo->interesting = true;
4409 seqinfo->dobj.dump = true;
4416 destroyPQExpBuffer(query);
4423 * read all the inheritance information
4424 * from the system catalogs return them in the InhInfo* structure
4426 * numInherits is set to the number of pairs read in
4429 getInherits(int *numInherits)
4434 PQExpBuffer query = createPQExpBuffer();
4440 /* Make sure we are in proper schema */
4441 selectSourceSchema("pg_catalog");
4443 /* find all the inheritance information */
4445 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4447 res = PQexec(g_conn, query->data);
4448 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4450 ntups = PQntuples(res);
4452 *numInherits = ntups;
4454 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4456 i_inhrelid = PQfnumber(res, "inhrelid");
4457 i_inhparent = PQfnumber(res, "inhparent");
4459 for (i = 0; i < ntups; i++)
4461 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4462 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4467 destroyPQExpBuffer(query);
4474 * get information about every index on a dumpable table
4476 * Note: index data is not returned directly to the caller, but it
4477 * does get entered into the DumpableObject tables.
4480 getIndexes(TableInfo tblinfo[], int numTables)
4484 PQExpBuffer query = createPQExpBuffer();
4487 ConstraintInfo *constrinfo;
4506 for (i = 0; i < numTables; i++)
4508 TableInfo *tbinfo = &tblinfo[i];
4510 /* Only plain tables have indexes */
4511 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4514 /* Ignore indexes of tables not to be dumped */
4515 if (!tbinfo->dobj.dump)
4519 write_msg(NULL, "reading indexes for table \"%s\"\n",
4522 /* Make sure we are in proper schema so indexdef is right */
4523 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4526 * The point of the messy-looking outer join is to find a constraint
4527 * that is related by an internal dependency link to the index. If we
4528 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4529 * assume an index won't have more than one internal dependency.
4531 * As of 9.0 we don't need to look at pg_depend but can check for a
4532 * match to pg_constraint.conindid. The check on conrelid is
4533 * redundant but useful because that column is indexed while conindid
4536 resetPQExpBuffer(query);
4537 if (g_fout->remoteVersion >= 90000)
4539 appendPQExpBuffer(query,
4540 "SELECT t.tableoid, t.oid, "
4541 "t.relname AS indexname, "
4542 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4543 "t.relnatts AS indnkeys, "
4544 "i.indkey, i.indisclustered, "
4545 "c.contype, c.conname, "
4546 "c.condeferrable, c.condeferred, "
4547 "c.tableoid AS contableoid, "
4549 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4550 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4551 "array_to_string(t.reloptions, ', ') AS options "
4552 "FROM pg_catalog.pg_index i "
4553 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4554 "LEFT JOIN pg_catalog.pg_constraint c "
4555 "ON (i.indrelid = c.conrelid AND "
4556 "i.indexrelid = c.conindid AND "
4557 "c.contype IN ('p','u','x')) "
4558 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4559 "ORDER BY indexname",
4560 tbinfo->dobj.catId.oid);
4562 else if (g_fout->remoteVersion >= 80200)
4564 appendPQExpBuffer(query,
4565 "SELECT t.tableoid, t.oid, "
4566 "t.relname AS indexname, "
4567 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4568 "t.relnatts AS indnkeys, "
4569 "i.indkey, i.indisclustered, "
4570 "c.contype, c.conname, "
4571 "c.condeferrable, c.condeferred, "
4572 "c.tableoid AS contableoid, "
4575 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4576 "array_to_string(t.reloptions, ', ') AS options "
4577 "FROM pg_catalog.pg_index i "
4578 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4579 "LEFT JOIN pg_catalog.pg_depend d "
4580 "ON (d.classid = t.tableoid "
4581 "AND d.objid = t.oid "
4582 "AND d.deptype = 'i') "
4583 "LEFT JOIN pg_catalog.pg_constraint c "
4584 "ON (d.refclassid = c.tableoid "
4585 "AND d.refobjid = c.oid) "
4586 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4587 "ORDER BY indexname",
4588 tbinfo->dobj.catId.oid);
4590 else if (g_fout->remoteVersion >= 80000)
4592 appendPQExpBuffer(query,
4593 "SELECT t.tableoid, t.oid, "
4594 "t.relname AS indexname, "
4595 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4596 "t.relnatts AS indnkeys, "
4597 "i.indkey, i.indisclustered, "
4598 "c.contype, c.conname, "
4599 "c.condeferrable, c.condeferred, "
4600 "c.tableoid AS contableoid, "
4603 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4605 "FROM pg_catalog.pg_index i "
4606 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4607 "LEFT JOIN pg_catalog.pg_depend d "
4608 "ON (d.classid = t.tableoid "
4609 "AND d.objid = t.oid "
4610 "AND d.deptype = 'i') "
4611 "LEFT JOIN pg_catalog.pg_constraint c "
4612 "ON (d.refclassid = c.tableoid "
4613 "AND d.refobjid = c.oid) "
4614 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4615 "ORDER BY indexname",
4616 tbinfo->dobj.catId.oid);
4618 else if (g_fout->remoteVersion >= 70300)
4620 appendPQExpBuffer(query,
4621 "SELECT t.tableoid, t.oid, "
4622 "t.relname AS indexname, "
4623 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4624 "t.relnatts AS indnkeys, "
4625 "i.indkey, i.indisclustered, "
4626 "c.contype, c.conname, "
4627 "c.condeferrable, c.condeferred, "
4628 "c.tableoid AS contableoid, "
4631 "NULL AS tablespace, "
4633 "FROM pg_catalog.pg_index i "
4634 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4635 "LEFT JOIN pg_catalog.pg_depend d "
4636 "ON (d.classid = t.tableoid "
4637 "AND d.objid = t.oid "
4638 "AND d.deptype = 'i') "
4639 "LEFT JOIN pg_catalog.pg_constraint c "
4640 "ON (d.refclassid = c.tableoid "
4641 "AND d.refobjid = c.oid) "
4642 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4643 "ORDER BY indexname",
4644 tbinfo->dobj.catId.oid);
4646 else if (g_fout->remoteVersion >= 70100)
4648 appendPQExpBuffer(query,
4649 "SELECT t.tableoid, t.oid, "
4650 "t.relname AS indexname, "
4651 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4652 "t.relnatts AS indnkeys, "
4653 "i.indkey, false AS indisclustered, "
4654 "CASE WHEN i.indisprimary THEN 'p'::char "
4655 "ELSE '0'::char END AS contype, "
4656 "t.relname AS conname, "
4657 "false AS condeferrable, "
4658 "false AS condeferred, "
4659 "0::oid AS contableoid, "
4662 "NULL AS tablespace, "
4664 "FROM pg_index i, pg_class t "
4665 "WHERE t.oid = i.indexrelid "
4666 "AND i.indrelid = '%u'::oid "
4667 "ORDER BY indexname",
4668 tbinfo->dobj.catId.oid);
4672 appendPQExpBuffer(query,
4674 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4676 "t.relname AS indexname, "
4677 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4678 "t.relnatts AS indnkeys, "
4679 "i.indkey, false AS indisclustered, "
4680 "CASE WHEN i.indisprimary THEN 'p'::char "
4681 "ELSE '0'::char END AS contype, "
4682 "t.relname AS conname, "
4683 "false AS condeferrable, "
4684 "false AS condeferred, "
4685 "0::oid AS contableoid, "
4688 "NULL AS tablespace, "
4690 "FROM pg_index i, pg_class t "
4691 "WHERE t.oid = i.indexrelid "
4692 "AND i.indrelid = '%u'::oid "
4693 "ORDER BY indexname",
4694 tbinfo->dobj.catId.oid);
4697 res = PQexec(g_conn, query->data);
4698 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4700 ntups = PQntuples(res);
4702 i_tableoid = PQfnumber(res, "tableoid");
4703 i_oid = PQfnumber(res, "oid");
4704 i_indexname = PQfnumber(res, "indexname");
4705 i_indexdef = PQfnumber(res, "indexdef");
4706 i_indnkeys = PQfnumber(res, "indnkeys");
4707 i_indkey = PQfnumber(res, "indkey");
4708 i_indisclustered = PQfnumber(res, "indisclustered");
4709 i_contype = PQfnumber(res, "contype");
4710 i_conname = PQfnumber(res, "conname");
4711 i_condeferrable = PQfnumber(res, "condeferrable");
4712 i_condeferred = PQfnumber(res, "condeferred");
4713 i_contableoid = PQfnumber(res, "contableoid");
4714 i_conoid = PQfnumber(res, "conoid");
4715 i_condef = PQfnumber(res, "condef");
4716 i_tablespace = PQfnumber(res, "tablespace");
4717 i_options = PQfnumber(res, "options");
4719 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4720 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4722 for (j = 0; j < ntups; j++)
4726 indxinfo[j].dobj.objType = DO_INDEX;
4727 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4728 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4729 AssignDumpId(&indxinfo[j].dobj);
4730 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4731 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4732 indxinfo[j].indextable = tbinfo;
4733 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4734 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4735 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4736 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4739 * In pre-7.4 releases, indkeys may contain more entries than
4740 * indnkeys says (since indnkeys will be 1 for a functional
4741 * index). We don't actually care about this case since we don't
4742 * examine indkeys except for indexes associated with PRIMARY and
4743 * UNIQUE constraints, which are never functional indexes. But we
4744 * have to allocate enough space to keep parseOidArray from
4747 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4748 parseOidArray(PQgetvalue(res, j, i_indkey),
4749 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4750 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4751 contype = *(PQgetvalue(res, j, i_contype));
4753 if (contype == 'p' || contype == 'u' || contype == 'x')
4756 * If we found a constraint matching the index, create an
4759 * In a pre-7.3 database, we take this path iff the index was
4760 * marked indisprimary.
4762 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4763 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4764 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4765 AssignDumpId(&constrinfo[j].dobj);
4766 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4767 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4768 constrinfo[j].contable = tbinfo;
4769 constrinfo[j].condomain = NULL;
4770 constrinfo[j].contype = contype;
4772 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4774 constrinfo[j].condef = NULL;
4775 constrinfo[j].confrelid = InvalidOid;
4776 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4777 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4778 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4779 constrinfo[j].conislocal = true;
4780 constrinfo[j].separate = true;
4782 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4784 /* If pre-7.3 DB, better make sure table comes first */
4785 addObjectDependency(&constrinfo[j].dobj,
4786 tbinfo->dobj.dumpId);
4790 /* Plain secondary index */
4791 indxinfo[j].indexconstraint = 0;
4798 destroyPQExpBuffer(query);
4804 * Get info about constraints on dumpable tables.
4806 * Currently handles foreign keys only.
4807 * Unique and primary key constraints are handled with indexes,
4808 * while check constraints are processed in getTableAttrs().
4811 getConstraints(TableInfo tblinfo[], int numTables)
4815 ConstraintInfo *constrinfo;
4825 /* pg_constraint was created in 7.3, so nothing to do if older */
4826 if (g_fout->remoteVersion < 70300)
4829 query = createPQExpBuffer();
4831 for (i = 0; i < numTables; i++)
4833 TableInfo *tbinfo = &tblinfo[i];
4835 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4839 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4843 * select table schema to ensure constraint expr is qualified if
4846 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4848 resetPQExpBuffer(query);
4849 appendPQExpBuffer(query,
4850 "SELECT tableoid, oid, conname, confrelid, "
4851 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4852 "FROM pg_catalog.pg_constraint "
4853 "WHERE conrelid = '%u'::pg_catalog.oid "
4854 "AND contype = 'f'",
4855 tbinfo->dobj.catId.oid);
4856 res = PQexec(g_conn, query->data);
4857 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4859 ntups = PQntuples(res);
4861 i_contableoid = PQfnumber(res, "tableoid");
4862 i_conoid = PQfnumber(res, "oid");
4863 i_conname = PQfnumber(res, "conname");
4864 i_confrelid = PQfnumber(res, "confrelid");
4865 i_condef = PQfnumber(res, "condef");
4867 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4869 for (j = 0; j < ntups; j++)
4871 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4872 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4873 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4874 AssignDumpId(&constrinfo[j].dobj);
4875 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4876 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4877 constrinfo[j].contable = tbinfo;
4878 constrinfo[j].condomain = NULL;
4879 constrinfo[j].contype = 'f';
4880 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4881 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4882 constrinfo[j].conindex = 0;
4883 constrinfo[j].condeferrable = false;
4884 constrinfo[j].condeferred = false;
4885 constrinfo[j].conislocal = true;
4886 constrinfo[j].separate = true;
4892 destroyPQExpBuffer(query);
4896 * getDomainConstraints
4898 * Get info about constraints on a domain.
4901 getDomainConstraints(TypeInfo *tyinfo)
4904 ConstraintInfo *constrinfo;
4913 /* pg_constraint was created in 7.3, so nothing to do if older */
4914 if (g_fout->remoteVersion < 70300)
4918 * select appropriate schema to ensure names in constraint are properly
4921 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
4923 query = createPQExpBuffer();
4925 if (g_fout->remoteVersion >= 90100)
4926 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4927 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4929 "FROM pg_catalog.pg_constraint "
4930 "WHERE contypid = '%u'::pg_catalog.oid "
4932 tyinfo->dobj.catId.oid);
4934 else if (g_fout->remoteVersion >= 70400)
4935 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4936 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4937 "true as convalidated "
4938 "FROM pg_catalog.pg_constraint "
4939 "WHERE contypid = '%u'::pg_catalog.oid "
4941 tyinfo->dobj.catId.oid);
4943 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4944 "'CHECK (' || consrc || ')' AS consrc, "
4945 "true as convalidated "
4946 "FROM pg_catalog.pg_constraint "
4947 "WHERE contypid = '%u'::pg_catalog.oid "
4949 tyinfo->dobj.catId.oid);
4951 res = PQexec(g_conn, query->data);
4952 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4954 ntups = PQntuples(res);
4956 i_tableoid = PQfnumber(res, "tableoid");
4957 i_oid = PQfnumber(res, "oid");
4958 i_conname = PQfnumber(res, "conname");
4959 i_consrc = PQfnumber(res, "consrc");
4961 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4963 tyinfo->nDomChecks = ntups;
4964 tyinfo->domChecks = constrinfo;
4966 for (i = 0; i < ntups; i++)
4968 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4970 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4971 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4972 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4973 AssignDumpId(&constrinfo[i].dobj);
4974 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4975 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4976 constrinfo[i].contable = NULL;
4977 constrinfo[i].condomain = tyinfo;
4978 constrinfo[i].contype = 'c';
4979 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4980 constrinfo[i].confrelid = InvalidOid;
4981 constrinfo[i].conindex = 0;
4982 constrinfo[i].condeferrable = false;
4983 constrinfo[i].condeferred = false;
4984 constrinfo[i].conislocal = true;
4986 constrinfo[i].separate = !validated;
4989 * Make the domain depend on the constraint, ensuring it won't be
4990 * output till any constraint dependencies are OK. If the constraint
4991 * has not been validated, it's going to be dumped after the domain
4992 * anyway, so this doesn't matter.
4995 addObjectDependency(&tyinfo->dobj,
4996 constrinfo[i].dobj.dumpId);
5001 destroyPQExpBuffer(query);
5006 * get basic information about every rule in the system
5008 * numRules is set to the number of rules read in
5011 getRules(int *numRules)
5016 PQExpBuffer query = createPQExpBuffer();
5026 /* Make sure we are in proper schema */
5027 selectSourceSchema("pg_catalog");
5029 if (g_fout->remoteVersion >= 80300)
5031 appendPQExpBuffer(query, "SELECT "
5032 "tableoid, oid, rulename, "
5033 "ev_class AS ruletable, ev_type, is_instead, "
5038 else if (g_fout->remoteVersion >= 70100)
5040 appendPQExpBuffer(query, "SELECT "
5041 "tableoid, oid, rulename, "
5042 "ev_class AS ruletable, ev_type, is_instead, "
5043 "'O'::char AS ev_enabled "
5049 appendPQExpBuffer(query, "SELECT "
5050 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5052 "ev_class AS ruletable, ev_type, is_instead, "
5053 "'O'::char AS ev_enabled "
5058 res = PQexec(g_conn, query->data);
5059 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5061 ntups = PQntuples(res);
5065 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5067 i_tableoid = PQfnumber(res, "tableoid");
5068 i_oid = PQfnumber(res, "oid");
5069 i_rulename = PQfnumber(res, "rulename");
5070 i_ruletable = PQfnumber(res, "ruletable");
5071 i_ev_type = PQfnumber(res, "ev_type");
5072 i_is_instead = PQfnumber(res, "is_instead");
5073 i_ev_enabled = PQfnumber(res, "ev_enabled");
5075 for (i = 0; i < ntups; i++)
5079 ruleinfo[i].dobj.objType = DO_RULE;
5080 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5081 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5082 AssignDumpId(&ruleinfo[i].dobj);
5083 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5084 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5085 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5086 if (ruleinfo[i].ruletable == NULL)
5088 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5090 ruleinfo[i].dobj.catId.oid);
5093 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5094 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5095 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5096 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5097 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5098 if (ruleinfo[i].ruletable)
5101 * If the table is a view, force its ON SELECT rule to be sorted
5102 * before the view itself --- this ensures that any dependencies
5103 * for the rule affect the table's positioning. Other rules are
5104 * forced to appear after their table.
5106 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5107 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5109 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5110 ruleinfo[i].dobj.dumpId);
5111 /* We'll merge the rule into CREATE VIEW, if possible */
5112 ruleinfo[i].separate = false;
5116 addObjectDependency(&ruleinfo[i].dobj,
5117 ruleinfo[i].ruletable->dobj.dumpId);
5118 ruleinfo[i].separate = true;
5122 ruleinfo[i].separate = true;
5127 destroyPQExpBuffer(query);
5134 * get information about every trigger on a dumpable table
5136 * Note: trigger data is not returned directly to the caller, but it
5137 * does get entered into the DumpableObject tables.
5140 getTriggers(TableInfo tblinfo[], int numTables)
5144 PQExpBuffer query = createPQExpBuffer();
5146 TriggerInfo *tginfo;
5164 for (i = 0; i < numTables; i++)
5166 TableInfo *tbinfo = &tblinfo[i];
5168 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5172 write_msg(NULL, "reading triggers for table \"%s\"\n",
5176 * select table schema to ensure regproc name is qualified if needed
5178 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
5180 resetPQExpBuffer(query);
5181 if (g_fout->remoteVersion >= 90000)
5184 * NB: think not to use pretty=true in pg_get_triggerdef. It
5185 * could result in non-forward-compatible dumps of WHEN clauses
5186 * due to under-parenthesization.
5188 appendPQExpBuffer(query,
5190 "tgfoid::pg_catalog.regproc AS tgfname, "
5191 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5192 "tgenabled, tableoid, oid "
5193 "FROM pg_catalog.pg_trigger t "
5194 "WHERE tgrelid = '%u'::pg_catalog.oid "
5195 "AND NOT tgisinternal",
5196 tbinfo->dobj.catId.oid);
5198 else if (g_fout->remoteVersion >= 80300)
5201 * We ignore triggers that are tied to a foreign-key constraint
5203 appendPQExpBuffer(query,
5205 "tgfoid::pg_catalog.regproc AS tgfname, "
5206 "tgtype, tgnargs, tgargs, tgenabled, "
5207 "tgisconstraint, tgconstrname, tgdeferrable, "
5208 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5209 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5210 "FROM pg_catalog.pg_trigger t "
5211 "WHERE tgrelid = '%u'::pg_catalog.oid "
5212 "AND tgconstraint = 0",
5213 tbinfo->dobj.catId.oid);
5215 else if (g_fout->remoteVersion >= 70300)
5218 * We ignore triggers that are tied to a foreign-key constraint,
5219 * but in these versions we have to grovel through pg_constraint
5222 appendPQExpBuffer(query,
5224 "tgfoid::pg_catalog.regproc AS tgfname, "
5225 "tgtype, tgnargs, tgargs, tgenabled, "
5226 "tgisconstraint, tgconstrname, tgdeferrable, "
5227 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5228 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5229 "FROM pg_catalog.pg_trigger t "
5230 "WHERE tgrelid = '%u'::pg_catalog.oid "
5231 "AND (NOT tgisconstraint "
5233 " (SELECT 1 FROM pg_catalog.pg_depend d "
5234 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5235 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5236 tbinfo->dobj.catId.oid);
5238 else if (g_fout->remoteVersion >= 70100)
5240 appendPQExpBuffer(query,
5241 "SELECT tgname, tgfoid::regproc AS tgfname, "
5242 "tgtype, tgnargs, tgargs, tgenabled, "
5243 "tgisconstraint, tgconstrname, tgdeferrable, "
5244 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5245 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5246 " AS tgconstrrelname "
5248 "WHERE tgrelid = '%u'::oid",
5249 tbinfo->dobj.catId.oid);
5253 appendPQExpBuffer(query,
5254 "SELECT tgname, tgfoid::regproc AS tgfname, "
5255 "tgtype, tgnargs, tgargs, tgenabled, "
5256 "tgisconstraint, tgconstrname, tgdeferrable, "
5257 "tgconstrrelid, tginitdeferred, "
5258 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5260 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5261 " AS tgconstrrelname "
5263 "WHERE tgrelid = '%u'::oid",
5264 tbinfo->dobj.catId.oid);
5266 res = PQexec(g_conn, query->data);
5267 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5269 ntups = PQntuples(res);
5271 i_tableoid = PQfnumber(res, "tableoid");
5272 i_oid = PQfnumber(res, "oid");
5273 i_tgname = PQfnumber(res, "tgname");
5274 i_tgfname = PQfnumber(res, "tgfname");
5275 i_tgtype = PQfnumber(res, "tgtype");
5276 i_tgnargs = PQfnumber(res, "tgnargs");
5277 i_tgargs = PQfnumber(res, "tgargs");
5278 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5279 i_tgconstrname = PQfnumber(res, "tgconstrname");
5280 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5281 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5282 i_tgenabled = PQfnumber(res, "tgenabled");
5283 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5284 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5285 i_tgdef = PQfnumber(res, "tgdef");
5287 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5289 for (j = 0; j < ntups; j++)
5291 tginfo[j].dobj.objType = DO_TRIGGER;
5292 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5293 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5294 AssignDumpId(&tginfo[j].dobj);
5295 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5296 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5297 tginfo[j].tgtable = tbinfo;
5298 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5301 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5303 /* remaining fields are not valid if we have tgdef */
5304 tginfo[j].tgfname = NULL;
5305 tginfo[j].tgtype = 0;
5306 tginfo[j].tgnargs = 0;
5307 tginfo[j].tgargs = NULL;
5308 tginfo[j].tgisconstraint = false;
5309 tginfo[j].tgdeferrable = false;
5310 tginfo[j].tginitdeferred = false;
5311 tginfo[j].tgconstrname = NULL;
5312 tginfo[j].tgconstrrelid = InvalidOid;
5313 tginfo[j].tgconstrrelname = NULL;
5317 tginfo[j].tgdef = NULL;
5319 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5320 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5321 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5322 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5323 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5324 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5325 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5327 if (tginfo[j].tgisconstraint)
5329 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5330 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5331 if (OidIsValid(tginfo[j].tgconstrrelid))
5333 if (PQgetisnull(res, j, i_tgconstrrelname))
5335 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5336 tginfo[j].dobj.name, tbinfo->dobj.name,
5337 tginfo[j].tgconstrrelid);
5340 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5343 tginfo[j].tgconstrrelname = NULL;
5347 tginfo[j].tgconstrname = NULL;
5348 tginfo[j].tgconstrrelid = InvalidOid;
5349 tginfo[j].tgconstrrelname = NULL;
5357 destroyPQExpBuffer(query);
5362 * get basic information about every procedural language in the system
5364 * numProcLangs is set to the number of langs read in
5366 * NB: this must run after getFuncs() because we assume we can do
5370 getProcLangs(int *numProcLangs)
5375 PQExpBuffer query = createPQExpBuffer();
5376 ProcLangInfo *planginfo;
5381 int i_lanplcallfoid;
5387 /* Make sure we are in proper schema */
5388 selectSourceSchema("pg_catalog");
5390 if (g_fout->remoteVersion >= 90000)
5392 /* pg_language has a laninline column */
5393 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5394 "lanname, lanpltrusted, lanplcallfoid, "
5395 "laninline, lanvalidator, lanacl, "
5396 "(%s lanowner) AS lanowner "
5402 else if (g_fout->remoteVersion >= 80300)
5404 /* pg_language has a lanowner column */
5405 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5406 "lanname, lanpltrusted, lanplcallfoid, "
5407 "lanvalidator, lanacl, "
5408 "(%s lanowner) AS lanowner "
5414 else if (g_fout->remoteVersion >= 80100)
5416 /* Languages are owned by the bootstrap superuser, OID 10 */
5417 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5418 "(%s '10') AS lanowner "
5424 else if (g_fout->remoteVersion >= 70400)
5426 /* Languages are owned by the bootstrap superuser, sysid 1 */
5427 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5428 "(%s '1') AS lanowner "
5434 else if (g_fout->remoteVersion >= 70100)
5436 /* No clear notion of an owner at all before 7.4 ... */
5437 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5443 appendPQExpBuffer(query, "SELECT "
5444 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5445 "oid, * FROM pg_language "
5450 res = PQexec(g_conn, query->data);
5451 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5453 ntups = PQntuples(res);
5455 *numProcLangs = ntups;
5457 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5459 i_tableoid = PQfnumber(res, "tableoid");
5460 i_oid = PQfnumber(res, "oid");
5461 i_lanname = PQfnumber(res, "lanname");
5462 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5463 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5464 /* these may fail and return -1: */
5465 i_laninline = PQfnumber(res, "laninline");
5466 i_lanvalidator = PQfnumber(res, "lanvalidator");
5467 i_lanacl = PQfnumber(res, "lanacl");
5468 i_lanowner = PQfnumber(res, "lanowner");
5470 for (i = 0; i < ntups; i++)
5472 planginfo[i].dobj.objType = DO_PROCLANG;
5473 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5474 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5475 AssignDumpId(&planginfo[i].dobj);
5477 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5478 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5479 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5480 if (i_laninline >= 0)
5481 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5483 planginfo[i].laninline = InvalidOid;
5484 if (i_lanvalidator >= 0)
5485 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5487 planginfo[i].lanvalidator = InvalidOid;
5489 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5491 planginfo[i].lanacl = pg_strdup("{=U}");
5492 if (i_lanowner >= 0)
5493 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5495 planginfo[i].lanowner = pg_strdup("");
5497 if (g_fout->remoteVersion < 70300)
5500 * We need to make a dependency to ensure the function will be
5501 * dumped first. (In 7.3 and later the regular dependency
5502 * mechanism will handle this for us.)
5504 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5507 addObjectDependency(&planginfo[i].dobj,
5508 funcInfo->dobj.dumpId);
5514 destroyPQExpBuffer(query);
5521 * get basic information about every cast in the system
5523 * numCasts is set to the number of casts read in
5526 getCasts(int *numCasts)
5531 PQExpBuffer query = createPQExpBuffer();
5541 /* Make sure we are in proper schema */
5542 selectSourceSchema("pg_catalog");
5544 if (g_fout->remoteVersion >= 80400)
5546 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5547 "castsource, casttarget, castfunc, castcontext, "
5549 "FROM pg_cast ORDER BY 3,4");
5551 else if (g_fout->remoteVersion >= 70300)
5553 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5554 "castsource, casttarget, castfunc, castcontext, "
5555 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5556 "FROM pg_cast ORDER BY 3,4");
5560 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5561 "t1.oid AS castsource, t2.oid AS casttarget, "
5562 "p.oid AS castfunc, 'e' AS castcontext, "
5563 "'f' AS castmethod "
5564 "FROM pg_type t1, pg_type t2, pg_proc p "
5565 "WHERE p.pronargs = 1 AND "
5566 "p.proargtypes[0] = t1.oid AND "
5567 "p.prorettype = t2.oid AND p.proname = t2.typname "
5571 res = PQexec(g_conn, query->data);
5572 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5574 ntups = PQntuples(res);
5578 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5580 i_tableoid = PQfnumber(res, "tableoid");
5581 i_oid = PQfnumber(res, "oid");
5582 i_castsource = PQfnumber(res, "castsource");
5583 i_casttarget = PQfnumber(res, "casttarget");
5584 i_castfunc = PQfnumber(res, "castfunc");
5585 i_castcontext = PQfnumber(res, "castcontext");
5586 i_castmethod = PQfnumber(res, "castmethod");
5588 for (i = 0; i < ntups; i++)
5590 PQExpBufferData namebuf;
5591 TypeInfo *sTypeInfo;
5592 TypeInfo *tTypeInfo;
5594 castinfo[i].dobj.objType = DO_CAST;
5595 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5596 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5597 AssignDumpId(&castinfo[i].dobj);
5598 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5599 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5600 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5601 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5602 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5605 * Try to name cast as concatenation of typnames. This is only used
5606 * for purposes of sorting. If we fail to find either type, the name
5607 * will be an empty string.
5609 initPQExpBuffer(&namebuf);
5610 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5611 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5612 if (sTypeInfo && tTypeInfo)
5613 appendPQExpBuffer(&namebuf, "%s %s",
5614 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5615 castinfo[i].dobj.name = namebuf.data;
5617 if (OidIsValid(castinfo[i].castfunc))
5620 * We need to make a dependency to ensure the function will be
5621 * dumped first. (In 7.3 and later the regular dependency
5622 * mechanism will handle this for us.)
5626 funcInfo = findFuncByOid(castinfo[i].castfunc);
5628 addObjectDependency(&castinfo[i].dobj,
5629 funcInfo->dobj.dumpId);
5635 destroyPQExpBuffer(query);
5642 * for each interesting table, read info about its attributes
5643 * (names, types, default values, CHECK constraints, etc)
5645 * This is implemented in a very inefficient way right now, looping
5646 * through the tblinfo and doing a join per table to find the attrs and their
5647 * types. However, because we want type names and so forth to be named
5648 * relative to the schema of each table, we couldn't do it in just one
5649 * query. (Maybe one query per schema?)
5654 getTableAttrs(TableInfo *tblinfo, int numTables)
5658 PQExpBuffer q = createPQExpBuffer();
5663 int i_attstattarget;
5674 int i_attfdwoptions;
5679 for (i = 0; i < numTables; i++)
5681 TableInfo *tbinfo = &tblinfo[i];
5683 /* Don't bother to collect info for sequences */
5684 if (tbinfo->relkind == RELKIND_SEQUENCE)
5687 /* Don't bother with uninteresting tables, either */
5688 if (!tbinfo->interesting)
5692 * Make sure we are in proper schema for this table; this allows
5693 * correct retrieval of formatted type names and default exprs
5695 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
5697 /* find all the user attributes and their types */
5700 * we must read the attribute names in attribute number order! because
5701 * we will use the attnum to index into the attnames array later. We
5702 * actually ask to order by "attrelid, attnum" because (at least up to
5703 * 7.3) the planner is not smart enough to realize it needn't re-sort
5704 * the output of an indexscan on pg_attribute_relid_attnum_index.
5707 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5710 resetPQExpBuffer(q);
5712 if (g_fout->remoteVersion >= 90200)
5715 * attfdwoptions is new in 9.2.
5717 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5718 "a.attstattarget, a.attstorage, t.typstorage, "
5719 "a.attnotnull, a.atthasdef, a.attisdropped, "
5720 "a.attlen, a.attalign, a.attislocal, "
5721 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5722 "array_to_string(a.attoptions, ', ') AS attoptions, "
5723 "CASE WHEN a.attcollation <> t.typcollation "
5724 "THEN a.attcollation ELSE 0 END AS attcollation, "
5725 "pg_catalog.array_to_string(ARRAY("
5726 "SELECT pg_catalog.quote_ident(option_name) || "
5727 "' ' || pg_catalog.quote_literal(option_value) "
5728 "FROM pg_catalog.pg_options_to_table(attfdwoptions)"
5729 "), E',\n ') AS attfdwoptions "
5730 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5731 "ON a.atttypid = t.oid "
5732 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5733 "AND a.attnum > 0::pg_catalog.int2 "
5734 "ORDER BY a.attrelid, a.attnum",
5735 tbinfo->dobj.catId.oid);
5737 else if (g_fout->remoteVersion >= 90100)
5740 * attcollation is new in 9.1. Since we only want to dump COLLATE
5741 * clauses for attributes whose collation is different from their
5742 * type's default, we use a CASE here to suppress uninteresting
5743 * attcollations cheaply.
5745 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5746 "a.attstattarget, a.attstorage, t.typstorage, "
5747 "a.attnotnull, a.atthasdef, a.attisdropped, "
5748 "a.attlen, a.attalign, a.attislocal, "
5749 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5750 "array_to_string(a.attoptions, ', ') AS attoptions, "
5751 "CASE WHEN a.attcollation <> t.typcollation "
5752 "THEN a.attcollation ELSE 0 END AS attcollation, "
5753 "NULL AS attfdwoptions "
5754 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5755 "ON a.atttypid = t.oid "
5756 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5757 "AND a.attnum > 0::pg_catalog.int2 "
5758 "ORDER BY a.attrelid, a.attnum",
5759 tbinfo->dobj.catId.oid);
5761 else if (g_fout->remoteVersion >= 90000)
5763 /* attoptions is new in 9.0 */
5764 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5765 "a.attstattarget, a.attstorage, t.typstorage, "
5766 "a.attnotnull, a.atthasdef, a.attisdropped, "
5767 "a.attlen, a.attalign, a.attislocal, "
5768 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5769 "array_to_string(a.attoptions, ', ') AS attoptions, "
5770 "0 AS attcollation, "
5771 "NULL AS attfdwoptions "
5772 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5773 "ON a.atttypid = t.oid "
5774 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5775 "AND a.attnum > 0::pg_catalog.int2 "
5776 "ORDER BY a.attrelid, a.attnum",
5777 tbinfo->dobj.catId.oid);
5779 else if (g_fout->remoteVersion >= 70300)
5781 /* need left join here to not fail on dropped columns ... */
5782 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5783 "a.attstattarget, a.attstorage, t.typstorage, "
5784 "a.attnotnull, a.atthasdef, a.attisdropped, "
5785 "a.attlen, a.attalign, a.attislocal, "
5786 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5787 "'' AS attoptions, 0 AS attcollation, "
5788 "NULL AS attfdwoptions "
5789 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5790 "ON a.atttypid = t.oid "
5791 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5792 "AND a.attnum > 0::pg_catalog.int2 "
5793 "ORDER BY a.attrelid, a.attnum",
5794 tbinfo->dobj.catId.oid);
5796 else if (g_fout->remoteVersion >= 70100)
5799 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5800 * we don't dump it because we can't tell whether it's been
5801 * explicitly set or was just a default.
5803 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5804 "-1 AS attstattarget, a.attstorage, "
5805 "t.typstorage, a.attnotnull, a.atthasdef, "
5806 "false AS attisdropped, a.attlen, "
5807 "a.attalign, false AS attislocal, "
5808 "format_type(t.oid,a.atttypmod) AS atttypname, "
5809 "'' AS attoptions, 0 AS attcollation, "
5810 "NULL AS attfdwoptions "
5811 "FROM pg_attribute a LEFT JOIN pg_type t "
5812 "ON a.atttypid = t.oid "
5813 "WHERE a.attrelid = '%u'::oid "
5814 "AND a.attnum > 0::int2 "
5815 "ORDER BY a.attrelid, a.attnum",
5816 tbinfo->dobj.catId.oid);
5820 /* format_type not available before 7.1 */
5821 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5822 "-1 AS attstattarget, "
5823 "attstorage, attstorage AS typstorage, "
5824 "attnotnull, atthasdef, false AS attisdropped, "
5825 "attlen, attalign, "
5826 "false AS attislocal, "
5827 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5828 "'' AS attoptions, 0 AS attcollation, "
5829 "NULL AS attfdwoptions "
5830 "FROM pg_attribute a "
5831 "WHERE attrelid = '%u'::oid "
5832 "AND attnum > 0::int2 "
5833 "ORDER BY attrelid, attnum",
5834 tbinfo->dobj.catId.oid);
5837 res = PQexec(g_conn, q->data);
5838 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5840 ntups = PQntuples(res);
5842 i_attnum = PQfnumber(res, "attnum");
5843 i_attname = PQfnumber(res, "attname");
5844 i_atttypname = PQfnumber(res, "atttypname");
5845 i_atttypmod = PQfnumber(res, "atttypmod");
5846 i_attstattarget = PQfnumber(res, "attstattarget");
5847 i_attstorage = PQfnumber(res, "attstorage");
5848 i_typstorage = PQfnumber(res, "typstorage");
5849 i_attnotnull = PQfnumber(res, "attnotnull");
5850 i_atthasdef = PQfnumber(res, "atthasdef");
5851 i_attisdropped = PQfnumber(res, "attisdropped");
5852 i_attlen = PQfnumber(res, "attlen");
5853 i_attalign = PQfnumber(res, "attalign");
5854 i_attislocal = PQfnumber(res, "attislocal");
5855 i_attoptions = PQfnumber(res, "attoptions");
5856 i_attcollation = PQfnumber(res, "attcollation");
5857 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5859 tbinfo->numatts = ntups;
5860 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5861 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5862 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5863 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5864 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5865 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5866 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5867 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5868 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5869 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5870 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5871 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5872 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5873 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5874 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5875 tbinfo->inhAttrs = (bool *) pg_malloc(ntups * sizeof(bool));
5876 tbinfo->inhAttrDef = (bool *) pg_malloc(ntups * sizeof(bool));
5877 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5878 hasdefaults = false;
5880 for (j = 0; j < ntups; j++)
5882 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5884 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5888 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5889 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5890 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5891 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5892 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5893 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5894 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5895 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5896 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5897 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5898 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5899 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5900 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5901 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5902 tbinfo->attrdefs[j] = NULL; /* fix below */
5903 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5905 /* these flags will be set in flagInhAttrs() */
5906 tbinfo->inhAttrs[j] = false;
5907 tbinfo->inhAttrDef[j] = false;
5908 tbinfo->inhNotNull[j] = false;
5914 * Get info about column defaults
5918 AttrDefInfo *attrdefs;
5922 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5925 resetPQExpBuffer(q);
5926 if (g_fout->remoteVersion >= 70300)
5928 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5929 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5930 "FROM pg_catalog.pg_attrdef "
5931 "WHERE adrelid = '%u'::pg_catalog.oid",
5932 tbinfo->dobj.catId.oid);
5934 else if (g_fout->remoteVersion >= 70200)
5936 /* 7.2 did not have OIDs in pg_attrdef */
5937 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5938 "pg_get_expr(adbin, adrelid) AS adsrc "
5940 "WHERE adrelid = '%u'::oid",
5941 tbinfo->dobj.catId.oid);
5943 else if (g_fout->remoteVersion >= 70100)
5945 /* no pg_get_expr, so must rely on adsrc */
5946 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5948 "WHERE adrelid = '%u'::oid",
5949 tbinfo->dobj.catId.oid);
5953 /* no pg_get_expr, no tableoid either */
5954 appendPQExpBuffer(q, "SELECT "
5955 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5956 "oid, adnum, adsrc "
5958 "WHERE adrelid = '%u'::oid",
5959 tbinfo->dobj.catId.oid);
5961 res = PQexec(g_conn, q->data);
5962 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5964 numDefaults = PQntuples(res);
5965 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5967 for (j = 0; j < numDefaults; j++)
5971 attrdefs[j].dobj.objType = DO_ATTRDEF;
5972 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5973 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5974 AssignDumpId(&attrdefs[j].dobj);
5975 attrdefs[j].adtable = tbinfo;
5976 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
5977 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5979 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5980 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5982 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5985 * Defaults on a VIEW must always be dumped as separate ALTER
5986 * TABLE commands. Defaults on regular tables are dumped as
5987 * part of the CREATE TABLE if possible. To check if it's
5988 * safe, we mark the default as needing to appear before the
5991 if (tbinfo->relkind == RELKIND_VIEW)
5993 attrdefs[j].separate = true;
5994 /* needed in case pre-7.3 DB: */
5995 addObjectDependency(&attrdefs[j].dobj,
5996 tbinfo->dobj.dumpId);
6000 attrdefs[j].separate = false;
6001 addObjectDependency(&tbinfo->dobj,
6002 attrdefs[j].dobj.dumpId);
6005 if (adnum <= 0 || adnum > ntups)
6007 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
6008 adnum, tbinfo->dobj.name);
6011 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6017 * Get info about table CHECK constraints
6019 if (tbinfo->ncheck > 0)
6021 ConstraintInfo *constrs;
6025 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6028 resetPQExpBuffer(q);
6029 if (g_fout->remoteVersion >= 90200)
6032 * conisonly and convalidated are new in 9.2 (actually, the latter
6033 * is there in 9.1, but it wasn't ever false for check constraints
6036 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6037 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6038 "conislocal, convalidated, conisonly "
6039 "FROM pg_catalog.pg_constraint "
6040 "WHERE conrelid = '%u'::pg_catalog.oid "
6041 " AND contype = 'c' "
6043 tbinfo->dobj.catId.oid);
6045 else if (g_fout->remoteVersion >= 80400)
6047 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6048 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6049 "conislocal, true AS convalidated, "
6050 "false as conisonly "
6051 "FROM pg_catalog.pg_constraint "
6052 "WHERE conrelid = '%u'::pg_catalog.oid "
6053 " AND contype = 'c' "
6055 tbinfo->dobj.catId.oid);
6057 else if (g_fout->remoteVersion >= 70400)
6059 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6060 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6061 "true AS conislocal, true AS convalidated, "
6062 "false as conisonly "
6063 "FROM pg_catalog.pg_constraint "
6064 "WHERE conrelid = '%u'::pg_catalog.oid "
6065 " AND contype = 'c' "
6067 tbinfo->dobj.catId.oid);
6069 else if (g_fout->remoteVersion >= 70300)
6071 /* no pg_get_constraintdef, must use consrc */
6072 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6073 "'CHECK (' || consrc || ')' AS consrc, "
6074 "true AS conislocal, true AS convalidated, "
6075 "false as conisonly "
6076 "FROM pg_catalog.pg_constraint "
6077 "WHERE conrelid = '%u'::pg_catalog.oid "
6078 " AND contype = 'c' "
6080 tbinfo->dobj.catId.oid);
6082 else if (g_fout->remoteVersion >= 70200)
6084 /* 7.2 did not have OIDs in pg_relcheck */
6085 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6086 "rcname AS conname, "
6087 "'CHECK (' || rcsrc || ')' AS consrc, "
6088 "true AS conislocal, true AS convalidated, "
6089 "false as conisonly "
6091 "WHERE rcrelid = '%u'::oid "
6093 tbinfo->dobj.catId.oid);
6095 else if (g_fout->remoteVersion >= 70100)
6097 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6098 "rcname AS conname, "
6099 "'CHECK (' || rcsrc || ')' AS consrc, "
6100 "true AS conislocal, true AS convalidated, "
6101 "false as conisonly "
6103 "WHERE rcrelid = '%u'::oid "
6105 tbinfo->dobj.catId.oid);
6109 /* no tableoid in 7.0 */
6110 appendPQExpBuffer(q, "SELECT "
6111 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6112 "oid, rcname AS conname, "
6113 "'CHECK (' || rcsrc || ')' AS consrc, "
6114 "true AS conislocal, true AS convalidated, "
6115 "false as conisonly "
6117 "WHERE rcrelid = '%u'::oid "
6119 tbinfo->dobj.catId.oid);
6121 res = PQexec(g_conn, q->data);
6122 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
6124 numConstrs = PQntuples(res);
6125 if (numConstrs != tbinfo->ncheck)
6127 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6128 "expected %d check constraints on table \"%s\" but found %d\n",
6130 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6131 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6135 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6136 tbinfo->checkexprs = constrs;
6138 for (j = 0; j < numConstrs; j++)
6140 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6141 bool isonly = PQgetvalue(res, j, 6)[0] == 't';
6143 constrs[j].dobj.objType = DO_CONSTRAINT;
6144 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6145 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6146 AssignDumpId(&constrs[j].dobj);
6147 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6148 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6149 constrs[j].contable = tbinfo;
6150 constrs[j].condomain = NULL;
6151 constrs[j].contype = 'c';
6152 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6153 constrs[j].confrelid = InvalidOid;
6154 constrs[j].conindex = 0;
6155 constrs[j].condeferrable = false;
6156 constrs[j].condeferred = false;
6157 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6158 constrs[j].conisonly = isonly;
6160 * An unvalidated constraint needs to be dumped separately, so
6161 * that potentially-violating existing data is loaded before
6162 * the constraint. An ONLY constraint needs to be dumped
6165 constrs[j].separate = !validated || isonly;
6167 constrs[j].dobj.dump = tbinfo->dobj.dump;
6170 * Mark the constraint as needing to appear before the table
6171 * --- this is so that any other dependencies of the
6172 * constraint will be emitted before we try to create the
6173 * table. If the constraint is to be dumped separately, it will be
6174 * dumped after data is loaded anyway, so don't do it. (There's
6175 * an automatic dependency in the opposite direction anyway, so
6176 * don't need to add one manually here.)
6178 if (!constrs[j].separate)
6179 addObjectDependency(&tbinfo->dobj,
6180 constrs[j].dobj.dumpId);
6183 * If the constraint is inherited, this will be detected later
6184 * (in pre-8.4 databases). We also detect later if the
6185 * constraint must be split out from the table definition.
6192 destroyPQExpBuffer(q);
6198 * read all text search parsers in the system catalogs and return them
6199 * in the TSParserInfo* structure
6201 * numTSParsers is set to the number of parsers read in
6204 getTSParsers(int *numTSParsers)
6209 PQExpBuffer query = createPQExpBuffer();
6210 TSParserInfo *prsinfo;
6221 /* Before 8.3, there is no built-in text search support */
6222 if (g_fout->remoteVersion < 80300)
6229 * find all text search objects, including builtin ones; we filter out
6230 * system-defined objects at dump-out time.
6233 /* Make sure we are in proper schema */
6234 selectSourceSchema("pg_catalog");
6236 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6237 "prsstart::oid, prstoken::oid, "
6238 "prsend::oid, prsheadline::oid, prslextype::oid "
6239 "FROM pg_ts_parser");
6241 res = PQexec(g_conn, query->data);
6242 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6244 ntups = PQntuples(res);
6245 *numTSParsers = ntups;
6247 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6249 i_tableoid = PQfnumber(res, "tableoid");
6250 i_oid = PQfnumber(res, "oid");
6251 i_prsname = PQfnumber(res, "prsname");
6252 i_prsnamespace = PQfnumber(res, "prsnamespace");
6253 i_prsstart = PQfnumber(res, "prsstart");
6254 i_prstoken = PQfnumber(res, "prstoken");
6255 i_prsend = PQfnumber(res, "prsend");
6256 i_prsheadline = PQfnumber(res, "prsheadline");
6257 i_prslextype = PQfnumber(res, "prslextype");
6259 for (i = 0; i < ntups; i++)
6261 prsinfo[i].dobj.objType = DO_TSPARSER;
6262 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6263 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6264 AssignDumpId(&prsinfo[i].dobj);
6265 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6266 prsinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_prsnamespace)),
6267 prsinfo[i].dobj.catId.oid);
6268 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6269 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6270 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6271 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6272 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6274 /* Decide whether we want to dump it */
6275 selectDumpableObject(&(prsinfo[i].dobj));
6280 destroyPQExpBuffer(query);
6286 * getTSDictionaries:
6287 * read all text search dictionaries in the system catalogs and return them
6288 * in the TSDictInfo* structure
6290 * numTSDicts is set to the number of dictionaries read in
6293 getTSDictionaries(int *numTSDicts)
6298 PQExpBuffer query = createPQExpBuffer();
6299 TSDictInfo *dictinfo;
6303 int i_dictnamespace;
6306 int i_dictinitoption;
6308 /* Before 8.3, there is no built-in text search support */
6309 if (g_fout->remoteVersion < 80300)
6315 /* Make sure we are in proper schema */
6316 selectSourceSchema("pg_catalog");
6318 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6319 "dictnamespace, (%s dictowner) AS rolname, "
6320 "dicttemplate, dictinitoption "
6324 res = PQexec(g_conn, query->data);
6325 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6327 ntups = PQntuples(res);
6328 *numTSDicts = ntups;
6330 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6332 i_tableoid = PQfnumber(res, "tableoid");
6333 i_oid = PQfnumber(res, "oid");
6334 i_dictname = PQfnumber(res, "dictname");
6335 i_dictnamespace = PQfnumber(res, "dictnamespace");
6336 i_rolname = PQfnumber(res, "rolname");
6337 i_dictinitoption = PQfnumber(res, "dictinitoption");
6338 i_dicttemplate = PQfnumber(res, "dicttemplate");
6340 for (i = 0; i < ntups; i++)
6342 dictinfo[i].dobj.objType = DO_TSDICT;
6343 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6344 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6345 AssignDumpId(&dictinfo[i].dobj);
6346 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6347 dictinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_dictnamespace)),
6348 dictinfo[i].dobj.catId.oid);
6349 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6350 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6351 if (PQgetisnull(res, i, i_dictinitoption))
6352 dictinfo[i].dictinitoption = NULL;
6354 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6356 /* Decide whether we want to dump it */
6357 selectDumpableObject(&(dictinfo[i].dobj));
6362 destroyPQExpBuffer(query);
6369 * read all text search templates in the system catalogs and return them
6370 * in the TSTemplateInfo* structure
6372 * numTSTemplates is set to the number of templates read in
6375 getTSTemplates(int *numTSTemplates)
6380 PQExpBuffer query = createPQExpBuffer();
6381 TSTemplateInfo *tmplinfo;
6385 int i_tmplnamespace;
6389 /* Before 8.3, there is no built-in text search support */
6390 if (g_fout->remoteVersion < 80300)
6392 *numTSTemplates = 0;
6396 /* Make sure we are in proper schema */
6397 selectSourceSchema("pg_catalog");
6399 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6400 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6401 "FROM pg_ts_template");
6403 res = PQexec(g_conn, query->data);
6404 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6406 ntups = PQntuples(res);
6407 *numTSTemplates = ntups;
6409 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6411 i_tableoid = PQfnumber(res, "tableoid");
6412 i_oid = PQfnumber(res, "oid");
6413 i_tmplname = PQfnumber(res, "tmplname");
6414 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6415 i_tmplinit = PQfnumber(res, "tmplinit");
6416 i_tmpllexize = PQfnumber(res, "tmpllexize");
6418 for (i = 0; i < ntups; i++)
6420 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6421 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6422 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6423 AssignDumpId(&tmplinfo[i].dobj);
6424 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6425 tmplinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_tmplnamespace)),
6426 tmplinfo[i].dobj.catId.oid);
6427 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6428 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6430 /* Decide whether we want to dump it */
6431 selectDumpableObject(&(tmplinfo[i].dobj));
6436 destroyPQExpBuffer(query);
6442 * getTSConfigurations:
6443 * read all text search configurations in the system catalogs and return
6444 * them in the TSConfigInfo* structure
6446 * numTSConfigs is set to the number of configurations read in
6449 getTSConfigurations(int *numTSConfigs)
6454 PQExpBuffer query = createPQExpBuffer();
6455 TSConfigInfo *cfginfo;
6463 /* Before 8.3, there is no built-in text search support */
6464 if (g_fout->remoteVersion < 80300)
6470 /* Make sure we are in proper schema */
6471 selectSourceSchema("pg_catalog");
6473 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6474 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6475 "FROM pg_ts_config",
6478 res = PQexec(g_conn, query->data);
6479 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6481 ntups = PQntuples(res);
6482 *numTSConfigs = ntups;
6484 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6486 i_tableoid = PQfnumber(res, "tableoid");
6487 i_oid = PQfnumber(res, "oid");
6488 i_cfgname = PQfnumber(res, "cfgname");
6489 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6490 i_rolname = PQfnumber(res, "rolname");
6491 i_cfgparser = PQfnumber(res, "cfgparser");
6493 for (i = 0; i < ntups; i++)
6495 cfginfo[i].dobj.objType = DO_TSCONFIG;
6496 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6497 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6498 AssignDumpId(&cfginfo[i].dobj);
6499 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6500 cfginfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_cfgnamespace)),
6501 cfginfo[i].dobj.catId.oid);
6502 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6503 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6505 /* Decide whether we want to dump it */
6506 selectDumpableObject(&(cfginfo[i].dobj));
6511 destroyPQExpBuffer(query);
6517 * getForeignDataWrappers:
6518 * read all foreign-data wrappers in the system catalogs and return
6519 * them in the FdwInfo* structure
6521 * numForeignDataWrappers is set to the number of fdws read in
6524 getForeignDataWrappers(int *numForeignDataWrappers)
6529 PQExpBuffer query = createPQExpBuffer();
6540 /* Before 8.4, there are no foreign-data wrappers */
6541 if (g_fout->remoteVersion < 80400)
6543 *numForeignDataWrappers = 0;
6547 /* Make sure we are in proper schema */
6548 selectSourceSchema("pg_catalog");
6550 if (g_fout->remoteVersion >= 90100)
6552 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6553 "(%s fdwowner) AS rolname, "
6554 "fdwhandler::pg_catalog.regproc, "
6555 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6556 "array_to_string(ARRAY("
6557 "SELECT quote_ident(option_name) || ' ' || "
6558 "quote_literal(option_value) "
6559 "FROM pg_options_to_table(fdwoptions)"
6560 "), E',\n ') AS fdwoptions "
6561 "FROM pg_foreign_data_wrapper",
6566 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6567 "(%s fdwowner) AS rolname, "
6568 "'-' AS fdwhandler, "
6569 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6570 "array_to_string(ARRAY("
6571 "SELECT quote_ident(option_name) || ' ' || "
6572 "quote_literal(option_value) "
6573 "FROM pg_options_to_table(fdwoptions)"
6574 "), E',\n ') AS fdwoptions "
6575 "FROM pg_foreign_data_wrapper",
6579 res = PQexec(g_conn, query->data);
6580 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6582 ntups = PQntuples(res);
6583 *numForeignDataWrappers = ntups;
6585 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6587 i_tableoid = PQfnumber(res, "tableoid");
6588 i_oid = PQfnumber(res, "oid");
6589 i_fdwname = PQfnumber(res, "fdwname");
6590 i_rolname = PQfnumber(res, "rolname");
6591 i_fdwhandler = PQfnumber(res, "fdwhandler");
6592 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6593 i_fdwacl = PQfnumber(res, "fdwacl");
6594 i_fdwoptions = PQfnumber(res, "fdwoptions");
6596 for (i = 0; i < ntups; i++)
6598 fdwinfo[i].dobj.objType = DO_FDW;
6599 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6600 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6601 AssignDumpId(&fdwinfo[i].dobj);
6602 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6603 fdwinfo[i].dobj.namespace = NULL;
6604 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6605 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6606 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6607 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6608 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6610 /* Decide whether we want to dump it */
6611 selectDumpableObject(&(fdwinfo[i].dobj));
6616 destroyPQExpBuffer(query);
6622 * getForeignServers:
6623 * read all foreign servers in the system catalogs and return
6624 * them in the ForeignServerInfo * structure
6626 * numForeignServers is set to the number of servers read in
6629 getForeignServers(int *numForeignServers)
6634 PQExpBuffer query = createPQExpBuffer();
6635 ForeignServerInfo *srvinfo;
6646 /* Before 8.4, there are no foreign servers */
6647 if (g_fout->remoteVersion < 80400)
6649 *numForeignServers = 0;
6653 /* Make sure we are in proper schema */
6654 selectSourceSchema("pg_catalog");
6656 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6657 "(%s srvowner) AS rolname, "
6658 "srvfdw, srvtype, srvversion, srvacl,"
6659 "array_to_string(ARRAY("
6660 "SELECT quote_ident(option_name) || ' ' || "
6661 "quote_literal(option_value) "
6662 "FROM pg_options_to_table(srvoptions)"
6663 "), E',\n ') AS srvoptions "
6664 "FROM pg_foreign_server",
6667 res = PQexec(g_conn, query->data);
6668 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6670 ntups = PQntuples(res);
6671 *numForeignServers = ntups;
6673 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6675 i_tableoid = PQfnumber(res, "tableoid");
6676 i_oid = PQfnumber(res, "oid");
6677 i_srvname = PQfnumber(res, "srvname");
6678 i_rolname = PQfnumber(res, "rolname");
6679 i_srvfdw = PQfnumber(res, "srvfdw");
6680 i_srvtype = PQfnumber(res, "srvtype");
6681 i_srvversion = PQfnumber(res, "srvversion");
6682 i_srvacl = PQfnumber(res, "srvacl");
6683 i_srvoptions = PQfnumber(res, "srvoptions");
6685 for (i = 0; i < ntups; i++)
6687 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6688 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6689 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6690 AssignDumpId(&srvinfo[i].dobj);
6691 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6692 srvinfo[i].dobj.namespace = NULL;
6693 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6694 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6695 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6696 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6697 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6698 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6700 /* Decide whether we want to dump it */
6701 selectDumpableObject(&(srvinfo[i].dobj));
6706 destroyPQExpBuffer(query);
6713 * read all default ACL information in the system catalogs and return
6714 * them in the DefaultACLInfo structure
6716 * numDefaultACLs is set to the number of ACLs read in
6719 getDefaultACLs(int *numDefaultACLs)
6721 DefaultACLInfo *daclinfo;
6727 int i_defaclnamespace;
6728 int i_defaclobjtype;
6733 if (g_fout->remoteVersion < 90000)
6735 *numDefaultACLs = 0;
6739 query = createPQExpBuffer();
6741 /* Make sure we are in proper schema */
6742 selectSourceSchema("pg_catalog");
6744 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6745 "(%s defaclrole) AS defaclrole, "
6749 "FROM pg_default_acl",
6752 res = PQexec(g_conn, query->data);
6753 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6755 ntups = PQntuples(res);
6756 *numDefaultACLs = ntups;
6758 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6760 i_oid = PQfnumber(res, "oid");
6761 i_tableoid = PQfnumber(res, "tableoid");
6762 i_defaclrole = PQfnumber(res, "defaclrole");
6763 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6764 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6765 i_defaclacl = PQfnumber(res, "defaclacl");
6767 for (i = 0; i < ntups; i++)
6769 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6771 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6772 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6773 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6774 AssignDumpId(&daclinfo[i].dobj);
6775 /* cheesy ... is it worth coming up with a better object name? */
6776 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6778 if (nspid != InvalidOid)
6779 daclinfo[i].dobj.namespace = findNamespace(nspid,
6780 daclinfo[i].dobj.catId.oid);
6782 daclinfo[i].dobj.namespace = NULL;
6784 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6785 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6786 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6788 /* Decide whether we want to dump it */
6789 selectDumpableDefaultACL(&(daclinfo[i]));
6794 destroyPQExpBuffer(query);
6802 * This routine is used to dump any comments associated with the
6803 * object handed to this routine. The routine takes a constant character
6804 * string for the target part of the comment-creation command, plus
6805 * the namespace and owner of the object (for labeling the ArchiveEntry),
6806 * plus catalog ID and subid which are the lookup key for pg_description,
6807 * plus the dump ID for the object (for setting a dependency).
6808 * If a matching pg_description entry is found, it is dumped.
6810 * Note: although this routine takes a dumpId for dependency purposes,
6811 * that purpose is just to mark the dependency in the emitted dump file
6812 * for possible future use by pg_restore. We do NOT use it for determining
6813 * ordering of the comment in the dump file, because this routine is called
6814 * after dependency sorting occurs. This routine should be called just after
6815 * calling ArchiveEntry() for the specified object.
6818 dumpComment(Archive *fout, const char *target,
6819 const char *namespace, const char *owner,
6820 CatalogId catalogId, int subid, DumpId dumpId)
6822 CommentItem *comments;
6825 /* Comments are schema not data ... except blob comments are data */
6826 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6837 /* Search for comments associated with catalogId, using table */
6838 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6841 /* Is there one matching the subid? */
6842 while (ncomments > 0)
6844 if (comments->objsubid == subid)
6850 /* If a comment exists, build COMMENT ON statement */
6853 PQExpBuffer query = createPQExpBuffer();
6855 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6856 appendStringLiteralAH(query, comments->descr, fout);
6857 appendPQExpBuffer(query, ";\n");
6860 * We mark comments as SECTION_NONE because they really belong in the
6861 * same section as their parent, whether that is pre-data or
6864 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6865 target, namespace, NULL, owner,
6866 false, "COMMENT", SECTION_NONE,
6867 query->data, "", NULL,
6871 destroyPQExpBuffer(query);
6876 * dumpTableComment --
6878 * As above, but dump comments for both the specified table (or view)
6882 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6883 const char *reltypename)
6885 CommentItem *comments;
6890 /* Comments are SCHEMA not data */
6894 /* Search for comments associated with relation, using table */
6895 ncomments = findComments(fout,
6896 tbinfo->dobj.catId.tableoid,
6897 tbinfo->dobj.catId.oid,
6900 /* If comments exist, build COMMENT ON statements */
6904 query = createPQExpBuffer();
6905 target = createPQExpBuffer();
6907 while (ncomments > 0)
6909 const char *descr = comments->descr;
6910 int objsubid = comments->objsubid;
6914 resetPQExpBuffer(target);
6915 appendPQExpBuffer(target, "%s %s", reltypename,
6916 fmtId(tbinfo->dobj.name));
6918 resetPQExpBuffer(query);
6919 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6920 appendStringLiteralAH(query, descr, fout);
6921 appendPQExpBuffer(query, ";\n");
6923 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6925 tbinfo->dobj.namespace->dobj.name,
6926 NULL, tbinfo->rolname,
6927 false, "COMMENT", SECTION_NONE,
6928 query->data, "", NULL,
6929 &(tbinfo->dobj.dumpId), 1,
6932 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6934 resetPQExpBuffer(target);
6935 appendPQExpBuffer(target, "COLUMN %s.",
6936 fmtId(tbinfo->dobj.name));
6937 appendPQExpBuffer(target, "%s",
6938 fmtId(tbinfo->attnames[objsubid - 1]));
6940 resetPQExpBuffer(query);
6941 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6942 appendStringLiteralAH(query, descr, fout);
6943 appendPQExpBuffer(query, ";\n");
6945 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6947 tbinfo->dobj.namespace->dobj.name,
6948 NULL, tbinfo->rolname,
6949 false, "COMMENT", SECTION_NONE,
6950 query->data, "", NULL,
6951 &(tbinfo->dobj.dumpId), 1,
6959 destroyPQExpBuffer(query);
6960 destroyPQExpBuffer(target);
6966 * Find the comment(s), if any, associated with the given object. All the
6967 * objsubid values associated with the given classoid/objoid are found with
6971 findComments(Archive *fout, Oid classoid, Oid objoid,
6972 CommentItem **items)
6974 /* static storage for table of comments */
6975 static CommentItem *comments = NULL;
6976 static int ncomments = -1;
6978 CommentItem *middle = NULL;
6983 /* Get comments if we didn't already */
6985 ncomments = collectComments(fout, &comments);
6988 * Pre-7.2, pg_description does not contain classoid, so collectComments
6989 * just stores a zero. If there's a collision on object OID, well, you
6990 * get duplicate comments.
6992 if (fout->remoteVersion < 70200)
6996 * Do binary search to find some item matching the object.
6999 high = &comments[ncomments - 1];
7002 middle = low + (high - low) / 2;
7004 if (classoid < middle->classoid)
7006 else if (classoid > middle->classoid)
7008 else if (objoid < middle->objoid)
7010 else if (objoid > middle->objoid)
7013 break; /* found a match */
7016 if (low > high) /* no matches */
7023 * Now determine how many items match the object. The search loop
7024 * invariant still holds: only items between low and high inclusive could
7028 while (middle > low)
7030 if (classoid != middle[-1].classoid ||
7031 objoid != middle[-1].objoid)
7040 while (middle <= high)
7042 if (classoid != middle->classoid ||
7043 objoid != middle->objoid)
7053 * collectComments --
7055 * Construct a table of all comments available for database objects.
7056 * We used to do per-object queries for the comments, but it's much faster
7057 * to pull them all over at once, and on most databases the memory cost
7060 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7063 collectComments(Archive *fout, CommentItem **items)
7073 CommentItem *comments;
7076 * Note we do NOT change source schema here; preserve the caller's
7080 query = createPQExpBuffer();
7082 if (fout->remoteVersion >= 70300)
7084 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7085 "FROM pg_catalog.pg_description "
7086 "ORDER BY classoid, objoid, objsubid");
7088 else if (fout->remoteVersion >= 70200)
7090 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7091 "FROM pg_description "
7092 "ORDER BY classoid, objoid, objsubid");
7096 /* Note: this will fail to find attribute comments in pre-7.2... */
7097 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7098 "FROM pg_description "
7102 res = PQexec(g_conn, query->data);
7103 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7105 /* Construct lookup table containing OIDs in numeric form */
7107 i_description = PQfnumber(res, "description");
7108 i_classoid = PQfnumber(res, "classoid");
7109 i_objoid = PQfnumber(res, "objoid");
7110 i_objsubid = PQfnumber(res, "objsubid");
7112 ntups = PQntuples(res);
7114 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7116 for (i = 0; i < ntups; i++)
7118 comments[i].descr = PQgetvalue(res, i, i_description);
7119 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7120 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7121 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7124 /* Do NOT free the PGresult since we are keeping pointers into it */
7125 destroyPQExpBuffer(query);
7132 * dumpDumpableObject
7134 * This routine and its subsidiaries are responsible for creating
7135 * ArchiveEntries (TOC objects) for each object to be dumped.
7138 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7143 switch (dobj->objType)
7148 case DO_FK_CONSTRAINT:
7150 skip = !(dumpSections & DUMP_POST_DATA);
7153 skip = !(dumpSections & DUMP_DATA);
7156 skip = !(dumpSections & DUMP_PRE_DATA);
7162 switch (dobj->objType)
7165 dumpNamespace(fout, (NamespaceInfo *) dobj);
7168 dumpExtension(fout, (ExtensionInfo *) dobj);
7171 dumpType(fout, (TypeInfo *) dobj);
7174 dumpShellType(fout, (ShellTypeInfo *) dobj);
7177 dumpFunc(fout, (FuncInfo *) dobj);
7180 dumpAgg(fout, (AggInfo *) dobj);
7183 dumpOpr(fout, (OprInfo *) dobj);
7186 dumpOpclass(fout, (OpclassInfo *) dobj);
7189 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7192 dumpCollation(fout, (CollInfo *) dobj);
7195 dumpConversion(fout, (ConvInfo *) dobj);
7198 dumpTable(fout, (TableInfo *) dobj);
7201 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7204 dumpIndex(fout, (IndxInfo *) dobj);
7207 dumpRule(fout, (RuleInfo *) dobj);
7210 dumpTrigger(fout, (TriggerInfo *) dobj);
7213 dumpConstraint(fout, (ConstraintInfo *) dobj);
7215 case DO_FK_CONSTRAINT:
7216 dumpConstraint(fout, (ConstraintInfo *) dobj);
7219 dumpProcLang(fout, (ProcLangInfo *) dobj);
7222 dumpCast(fout, (CastInfo *) dobj);
7225 dumpTableData(fout, (TableDataInfo *) dobj);
7228 /* table rowtypes and array types are never dumped separately */
7231 dumpTSParser(fout, (TSParserInfo *) dobj);
7234 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7237 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7240 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7243 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7245 case DO_FOREIGN_SERVER:
7246 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7248 case DO_DEFAULT_ACL:
7249 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7252 dumpBlob(fout, (BlobInfo *) dobj);
7255 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7256 dobj->name, NULL, NULL, "",
7257 false, "BLOBS", SECTION_DATA,
7259 dobj->dependencies, dobj->nDeps,
7267 * writes out to fout the queries to recreate a user-defined namespace
7270 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7277 /* Skip if not to be dumped */
7278 if (!nspinfo->dobj.dump || dataOnly)
7281 /* don't dump dummy namespace from pre-7.3 source */
7282 if (strlen(nspinfo->dobj.name) == 0)
7285 q = createPQExpBuffer();
7286 delq = createPQExpBuffer();
7287 labelq = createPQExpBuffer();
7289 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7291 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7293 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7295 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7298 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7300 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7304 false, "SCHEMA", SECTION_PRE_DATA,
7305 q->data, delq->data, NULL,
7306 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7309 /* Dump Schema Comments and Security Labels */
7310 dumpComment(fout, labelq->data,
7311 NULL, nspinfo->rolname,
7312 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7313 dumpSecLabel(fout, labelq->data,
7314 NULL, nspinfo->rolname,
7315 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7317 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7318 qnspname, NULL, nspinfo->dobj.name, NULL,
7319 nspinfo->rolname, nspinfo->nspacl);
7323 destroyPQExpBuffer(q);
7324 destroyPQExpBuffer(delq);
7325 destroyPQExpBuffer(labelq);
7330 * writes out to fout the queries to recreate an extension
7333 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7340 /* Skip if not to be dumped */
7341 if (!extinfo->dobj.dump || dataOnly)
7344 q = createPQExpBuffer();
7345 delq = createPQExpBuffer();
7346 labelq = createPQExpBuffer();
7348 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7350 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7352 if (!binary_upgrade)
7355 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7356 * problem if the extension already exists in the target database;
7357 * this is essential for installed-by-default extensions such as
7360 * In binary-upgrade mode, that doesn't work well, so instead we skip
7361 * built-in extensions based on their OIDs; see
7362 * selectDumpableExtension.
7364 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7365 qextname, fmtId(extinfo->namespace));
7372 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7373 appendPQExpBuffer(q,
7374 "SELECT binary_upgrade.create_empty_extension(");
7375 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7376 appendPQExpBuffer(q, ", ");
7377 appendStringLiteralAH(q, extinfo->namespace, fout);
7378 appendPQExpBuffer(q, ", ");
7379 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7380 appendStringLiteralAH(q, extinfo->extversion, fout);
7381 appendPQExpBuffer(q, ", ");
7384 * Note that we're pushing extconfig (an OID array) back into
7385 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7386 * preserved in binary upgrade.
7388 if (strlen(extinfo->extconfig) > 2)
7389 appendStringLiteralAH(q, extinfo->extconfig, fout);
7391 appendPQExpBuffer(q, "NULL");
7392 appendPQExpBuffer(q, ", ");
7393 if (strlen(extinfo->extcondition) > 2)
7394 appendStringLiteralAH(q, extinfo->extcondition, fout);
7396 appendPQExpBuffer(q, "NULL");
7397 appendPQExpBuffer(q, ", ");
7398 appendPQExpBuffer(q, "ARRAY[");
7400 for (i = 0; i < extinfo->dobj.nDeps; i++)
7402 DumpableObject *extobj;
7404 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7405 if (extobj && extobj->objType == DO_EXTENSION)
7408 appendPQExpBuffer(q, ",");
7409 appendStringLiteralAH(q, extobj->name, fout);
7412 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7413 appendPQExpBuffer(q, ");\n");
7416 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7418 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7422 false, "EXTENSION", SECTION_PRE_DATA,
7423 q->data, delq->data, NULL,
7424 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7427 /* Dump Extension Comments and Security Labels */
7428 dumpComment(fout, labelq->data,
7430 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7431 dumpSecLabel(fout, labelq->data,
7433 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7437 destroyPQExpBuffer(q);
7438 destroyPQExpBuffer(delq);
7439 destroyPQExpBuffer(labelq);
7444 * writes out to fout the queries to recreate a user-defined type
7447 dumpType(Archive *fout, TypeInfo *tyinfo)
7449 /* Skip if not to be dumped */
7450 if (!tyinfo->dobj.dump || dataOnly)
7453 /* Dump out in proper style */
7454 if (tyinfo->typtype == TYPTYPE_BASE)
7455 dumpBaseType(fout, tyinfo);
7456 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7457 dumpDomain(fout, tyinfo);
7458 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7459 dumpCompositeType(fout, tyinfo);
7460 else if (tyinfo->typtype == TYPTYPE_ENUM)
7461 dumpEnumType(fout, tyinfo);
7462 else if (tyinfo->typtype == TYPTYPE_RANGE)
7463 dumpRangeType(fout, tyinfo);
7465 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7471 * writes out to fout the queries to recreate a user-defined enum type
7474 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7476 PQExpBuffer q = createPQExpBuffer();
7477 PQExpBuffer delq = createPQExpBuffer();
7478 PQExpBuffer labelq = createPQExpBuffer();
7479 PQExpBuffer query = createPQExpBuffer();
7486 /* Set proper schema search path */
7487 selectSourceSchema("pg_catalog");
7489 if (fout->remoteVersion >= 90100)
7490 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7491 "FROM pg_catalog.pg_enum "
7492 "WHERE enumtypid = '%u'"
7493 "ORDER BY enumsortorder",
7494 tyinfo->dobj.catId.oid);
7496 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7497 "FROM pg_catalog.pg_enum "
7498 "WHERE enumtypid = '%u'"
7500 tyinfo->dobj.catId.oid);
7502 res = PQexec(g_conn, query->data);
7503 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7505 num = PQntuples(res);
7508 * DROP must be fully qualified in case same name appears in pg_catalog.
7509 * CASCADE shouldn't be required here as for normal types since the I/O
7510 * functions are generic and do not get dropped.
7512 appendPQExpBuffer(delq, "DROP TYPE %s.",
7513 fmtId(tyinfo->dobj.namespace->dobj.name));
7514 appendPQExpBuffer(delq, "%s;\n",
7515 fmtId(tyinfo->dobj.name));
7518 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7520 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7521 fmtId(tyinfo->dobj.name));
7523 if (!binary_upgrade)
7525 /* Labels with server-assigned oids */
7526 for (i = 0; i < num; i++)
7528 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7530 appendPQExpBuffer(q, ",");
7531 appendPQExpBuffer(q, "\n ");
7532 appendStringLiteralAH(q, label, fout);
7536 appendPQExpBuffer(q, "\n);\n");
7540 /* Labels with dump-assigned (preserved) oids */
7541 for (i = 0; i < num; i++)
7543 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7544 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7547 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7548 appendPQExpBuffer(q,
7549 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7551 appendPQExpBuffer(q, "ALTER TYPE %s.",
7552 fmtId(tyinfo->dobj.namespace->dobj.name));
7553 appendPQExpBuffer(q, "%s ADD VALUE ",
7554 fmtId(tyinfo->dobj.name));
7555 appendStringLiteralAH(q, label, fout);
7556 appendPQExpBuffer(q, ";\n\n");
7560 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7563 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7565 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7567 tyinfo->dobj.namespace->dobj.name,
7569 tyinfo->rolname, false,
7570 "TYPE", SECTION_PRE_DATA,
7571 q->data, delq->data, NULL,
7572 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7575 /* Dump Type Comments and Security Labels */
7576 dumpComment(fout, labelq->data,
7577 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7578 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7579 dumpSecLabel(fout, labelq->data,
7580 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7581 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7584 destroyPQExpBuffer(q);
7585 destroyPQExpBuffer(delq);
7586 destroyPQExpBuffer(labelq);
7587 destroyPQExpBuffer(query);
7592 * writes out to fout the queries to recreate a user-defined range type
7595 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7597 PQExpBuffer q = createPQExpBuffer();
7598 PQExpBuffer delq = createPQExpBuffer();
7599 PQExpBuffer labelq = createPQExpBuffer();
7600 PQExpBuffer query = createPQExpBuffer();
7606 * select appropriate schema to ensure names in CREATE are properly
7609 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7611 appendPQExpBuffer(query,
7612 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7613 "opc.opcname AS opcname, "
7614 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7615 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7617 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7618 " ELSE rngcollation END AS collation, "
7619 "rngcanonical, rngsubdiff "
7620 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7621 " pg_catalog.pg_opclass opc "
7622 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7624 tyinfo->dobj.catId.oid);
7626 res = PQexec(g_conn, query->data);
7627 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7628 if (PQntuples(res) != 1)
7630 write_msg(NULL, "query returned %d pg_range entries for range type \"%s\"\n",
7631 PQntuples(res), tyinfo->dobj.name);
7636 * DROP must be fully qualified in case same name appears in pg_catalog.
7637 * CASCADE shouldn't be required here as for normal types since the I/O
7638 * functions are generic and do not get dropped.
7640 appendPQExpBuffer(delq, "DROP TYPE %s.",
7641 fmtId(tyinfo->dobj.namespace->dobj.name));
7642 appendPQExpBuffer(delq, "%s;\n",
7643 fmtId(tyinfo->dobj.name));
7646 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7648 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7649 fmtId(tyinfo->dobj.name));
7651 appendPQExpBuffer(q, "\n subtype = %s",
7652 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7654 /* print subtype_opclass only if not default for subtype */
7655 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7657 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7658 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7660 /* always schema-qualify, don't try to be smart */
7661 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7663 appendPQExpBuffer(q, "%s", fmtId(opcname));
7666 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7667 if (OidIsValid(collationOid))
7669 CollInfo *coll = findCollationByOid(collationOid);
7673 /* always schema-qualify, don't try to be smart */
7674 appendPQExpBuffer(q, ",\n collation = %s.",
7675 fmtId(coll->dobj.namespace->dobj.name));
7676 appendPQExpBuffer(q, "%s",
7677 fmtId(coll->dobj.name));
7681 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7682 if (strcmp(procname, "-") != 0)
7683 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7685 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7686 if (strcmp(procname, "-") != 0)
7687 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7689 appendPQExpBuffer(q, "\n);\n");
7691 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7694 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7696 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7698 tyinfo->dobj.namespace->dobj.name,
7700 tyinfo->rolname, false,
7701 "TYPE", SECTION_PRE_DATA,
7702 q->data, delq->data, NULL,
7703 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7706 /* Dump Type Comments and Security Labels */
7707 dumpComment(fout, labelq->data,
7708 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7709 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7710 dumpSecLabel(fout, labelq->data,
7711 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7712 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7715 destroyPQExpBuffer(q);
7716 destroyPQExpBuffer(delq);
7717 destroyPQExpBuffer(labelq);
7718 destroyPQExpBuffer(query);
7723 * writes out to fout the queries to recreate a user-defined base type
7726 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7728 PQExpBuffer q = createPQExpBuffer();
7729 PQExpBuffer delq = createPQExpBuffer();
7730 PQExpBuffer labelq = createPQExpBuffer();
7731 PQExpBuffer query = createPQExpBuffer();
7748 char *typispreferred;
7753 char *typcollatable;
7755 bool typdefault_is_literal = false;
7757 /* Set proper schema search path so regproc references list correctly */
7758 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7760 /* Fetch type-specific details */
7761 if (fout->remoteVersion >= 90100)
7763 appendPQExpBuffer(query, "SELECT typlen, "
7764 "typinput, typoutput, typreceive, typsend, "
7765 "typmodin, typmodout, typanalyze, "
7766 "typreceive::pg_catalog.oid AS typreceiveoid, "
7767 "typsend::pg_catalog.oid AS typsendoid, "
7768 "typmodin::pg_catalog.oid AS typmodinoid, "
7769 "typmodout::pg_catalog.oid AS typmodoutoid, "
7770 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7771 "typcategory, typispreferred, "
7772 "typdelim, typbyval, typalign, typstorage, "
7773 "(typcollation <> 0) AS typcollatable, "
7774 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7775 "FROM pg_catalog.pg_type "
7776 "WHERE oid = '%u'::pg_catalog.oid",
7777 tyinfo->dobj.catId.oid);
7779 else if (fout->remoteVersion >= 80400)
7781 appendPQExpBuffer(query, "SELECT typlen, "
7782 "typinput, typoutput, typreceive, typsend, "
7783 "typmodin, typmodout, typanalyze, "
7784 "typreceive::pg_catalog.oid AS typreceiveoid, "
7785 "typsend::pg_catalog.oid AS typsendoid, "
7786 "typmodin::pg_catalog.oid AS typmodinoid, "
7787 "typmodout::pg_catalog.oid AS typmodoutoid, "
7788 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7789 "typcategory, typispreferred, "
7790 "typdelim, typbyval, typalign, typstorage, "
7791 "false AS typcollatable, "
7792 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7793 "FROM pg_catalog.pg_type "
7794 "WHERE oid = '%u'::pg_catalog.oid",
7795 tyinfo->dobj.catId.oid);
7797 else if (fout->remoteVersion >= 80300)
7799 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7800 appendPQExpBuffer(query, "SELECT typlen, "
7801 "typinput, typoutput, typreceive, typsend, "
7802 "typmodin, typmodout, typanalyze, "
7803 "typreceive::pg_catalog.oid AS typreceiveoid, "
7804 "typsend::pg_catalog.oid AS typsendoid, "
7805 "typmodin::pg_catalog.oid AS typmodinoid, "
7806 "typmodout::pg_catalog.oid AS typmodoutoid, "
7807 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7808 "'U' AS typcategory, false AS typispreferred, "
7809 "typdelim, typbyval, typalign, typstorage, "
7810 "false AS typcollatable, "
7811 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7812 "FROM pg_catalog.pg_type "
7813 "WHERE oid = '%u'::pg_catalog.oid",
7814 tyinfo->dobj.catId.oid);
7816 else if (fout->remoteVersion >= 80000)
7818 appendPQExpBuffer(query, "SELECT typlen, "
7819 "typinput, typoutput, typreceive, typsend, "
7820 "'-' AS typmodin, '-' AS typmodout, "
7822 "typreceive::pg_catalog.oid AS typreceiveoid, "
7823 "typsend::pg_catalog.oid AS typsendoid, "
7824 "0 AS typmodinoid, 0 AS typmodoutoid, "
7825 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7826 "'U' AS typcategory, false AS typispreferred, "
7827 "typdelim, typbyval, typalign, typstorage, "
7828 "false AS typcollatable, "
7829 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7830 "FROM pg_catalog.pg_type "
7831 "WHERE oid = '%u'::pg_catalog.oid",
7832 tyinfo->dobj.catId.oid);
7834 else if (fout->remoteVersion >= 70400)
7836 appendPQExpBuffer(query, "SELECT typlen, "
7837 "typinput, typoutput, typreceive, typsend, "
7838 "'-' AS typmodin, '-' AS typmodout, "
7839 "'-' AS typanalyze, "
7840 "typreceive::pg_catalog.oid AS typreceiveoid, "
7841 "typsend::pg_catalog.oid AS typsendoid, "
7842 "0 AS typmodinoid, 0 AS typmodoutoid, "
7843 "0 AS typanalyzeoid, "
7844 "'U' AS typcategory, false AS typispreferred, "
7845 "typdelim, typbyval, typalign, typstorage, "
7846 "false AS typcollatable, "
7847 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7848 "FROM pg_catalog.pg_type "
7849 "WHERE oid = '%u'::pg_catalog.oid",
7850 tyinfo->dobj.catId.oid);
7852 else if (fout->remoteVersion >= 70300)
7854 appendPQExpBuffer(query, "SELECT typlen, "
7855 "typinput, typoutput, "
7856 "'-' AS typreceive, '-' AS typsend, "
7857 "'-' AS typmodin, '-' AS typmodout, "
7858 "'-' AS typanalyze, "
7859 "0 AS typreceiveoid, 0 AS typsendoid, "
7860 "0 AS typmodinoid, 0 AS typmodoutoid, "
7861 "0 AS typanalyzeoid, "
7862 "'U' AS typcategory, false AS typispreferred, "
7863 "typdelim, typbyval, typalign, typstorage, "
7864 "false AS typcollatable, "
7865 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7866 "FROM pg_catalog.pg_type "
7867 "WHERE oid = '%u'::pg_catalog.oid",
7868 tyinfo->dobj.catId.oid);
7870 else if (fout->remoteVersion >= 70200)
7873 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7874 * ignore them because they are not right.
7876 appendPQExpBuffer(query, "SELECT typlen, "
7877 "typinput, typoutput, "
7878 "'-' AS typreceive, '-' AS typsend, "
7879 "'-' AS typmodin, '-' AS typmodout, "
7880 "'-' AS typanalyze, "
7881 "0 AS typreceiveoid, 0 AS typsendoid, "
7882 "0 AS typmodinoid, 0 AS typmodoutoid, "
7883 "0 AS typanalyzeoid, "
7884 "'U' AS typcategory, false AS typispreferred, "
7885 "typdelim, typbyval, typalign, typstorage, "
7886 "false AS typcollatable, "
7887 "NULL AS typdefaultbin, typdefault "
7889 "WHERE oid = '%u'::oid",
7890 tyinfo->dobj.catId.oid);
7892 else if (fout->remoteVersion >= 70100)
7895 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7898 appendPQExpBuffer(query, "SELECT typlen, "
7899 "typinput, typoutput, "
7900 "'-' AS typreceive, '-' AS typsend, "
7901 "'-' AS typmodin, '-' AS typmodout, "
7902 "'-' AS typanalyze, "
7903 "0 AS typreceiveoid, 0 AS typsendoid, "
7904 "0 AS typmodinoid, 0 AS typmodoutoid, "
7905 "0 AS typanalyzeoid, "
7906 "'U' AS typcategory, false AS typispreferred, "
7907 "typdelim, typbyval, typalign, typstorage, "
7908 "false AS typcollatable, "
7909 "NULL AS typdefaultbin, NULL AS typdefault "
7911 "WHERE oid = '%u'::oid",
7912 tyinfo->dobj.catId.oid);
7916 appendPQExpBuffer(query, "SELECT typlen, "
7917 "typinput, typoutput, "
7918 "'-' AS typreceive, '-' AS typsend, "
7919 "'-' AS typmodin, '-' AS typmodout, "
7920 "'-' AS typanalyze, "
7921 "0 AS typreceiveoid, 0 AS typsendoid, "
7922 "0 AS typmodinoid, 0 AS typmodoutoid, "
7923 "0 AS typanalyzeoid, "
7924 "'U' AS typcategory, false AS typispreferred, "
7925 "typdelim, typbyval, typalign, "
7926 "'p'::char AS typstorage, "
7927 "false AS typcollatable, "
7928 "NULL AS typdefaultbin, NULL AS typdefault "
7930 "WHERE oid = '%u'::oid",
7931 tyinfo->dobj.catId.oid);
7934 res = PQexec(g_conn, query->data);
7935 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7937 /* Expecting a single result only */
7938 ntups = PQntuples(res);
7941 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7942 "query returned %d rows instead of one: %s\n",
7944 ntups, query->data);
7948 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7949 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7950 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7951 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7952 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7953 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7954 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7955 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7956 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7957 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7958 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7959 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7960 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7961 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7962 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7963 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7964 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7965 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7966 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7967 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7968 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7969 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7970 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7972 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7973 typdefault_is_literal = true; /* it needs quotes */
7979 * DROP must be fully qualified in case same name appears in pg_catalog.
7980 * The reason we include CASCADE is that the circular dependency between
7981 * the type and its I/O functions makes it impossible to drop the type any
7984 appendPQExpBuffer(delq, "DROP TYPE %s.",
7985 fmtId(tyinfo->dobj.namespace->dobj.name));
7986 appendPQExpBuffer(delq, "%s CASCADE;\n",
7987 fmtId(tyinfo->dobj.name));
7989 /* We might already have a shell type, but setting pg_type_oid is harmless */
7991 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7993 appendPQExpBuffer(q,
7994 "CREATE TYPE %s (\n"
7995 " INTERNALLENGTH = %s",
7996 fmtId(tyinfo->dobj.name),
7997 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7999 if (fout->remoteVersion >= 70300)
8001 /* regproc result is correctly quoted as of 7.3 */
8002 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8003 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8004 if (OidIsValid(typreceiveoid))
8005 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8006 if (OidIsValid(typsendoid))
8007 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8008 if (OidIsValid(typmodinoid))
8009 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8010 if (OidIsValid(typmodoutoid))
8011 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8012 if (OidIsValid(typanalyzeoid))
8013 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8017 /* regproc delivers an unquoted name before 7.3 */
8018 /* cannot combine these because fmtId uses static result area */
8019 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8020 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8021 /* receive/send/typmodin/typmodout/analyze need not be printed */
8024 if (strcmp(typcollatable, "t") == 0)
8025 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8027 if (typdefault != NULL)
8029 appendPQExpBuffer(q, ",\n DEFAULT = ");
8030 if (typdefault_is_literal)
8031 appendStringLiteralAH(q, typdefault, fout);
8033 appendPQExpBufferStr(q, typdefault);
8036 if (OidIsValid(tyinfo->typelem))
8040 /* reselect schema in case changed by function dump */
8041 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
8042 elemType = getFormattedTypeName(tyinfo->typelem, zeroAsOpaque);
8043 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8047 if (strcmp(typcategory, "U") != 0)
8049 appendPQExpBuffer(q, ",\n CATEGORY = ");
8050 appendStringLiteralAH(q, typcategory, fout);
8053 if (strcmp(typispreferred, "t") == 0)
8054 appendPQExpBuffer(q, ",\n PREFERRED = true");
8056 if (typdelim && strcmp(typdelim, ",") != 0)
8058 appendPQExpBuffer(q, ",\n DELIMITER = ");
8059 appendStringLiteralAH(q, typdelim, fout);
8062 if (strcmp(typalign, "c") == 0)
8063 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8064 else if (strcmp(typalign, "s") == 0)
8065 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8066 else if (strcmp(typalign, "i") == 0)
8067 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8068 else if (strcmp(typalign, "d") == 0)
8069 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8071 if (strcmp(typstorage, "p") == 0)
8072 appendPQExpBuffer(q, ",\n STORAGE = plain");
8073 else if (strcmp(typstorage, "e") == 0)
8074 appendPQExpBuffer(q, ",\n STORAGE = external");
8075 else if (strcmp(typstorage, "x") == 0)
8076 appendPQExpBuffer(q, ",\n STORAGE = extended");
8077 else if (strcmp(typstorage, "m") == 0)
8078 appendPQExpBuffer(q, ",\n STORAGE = main");
8080 if (strcmp(typbyval, "t") == 0)
8081 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8083 appendPQExpBuffer(q, "\n);\n");
8085 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8088 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8090 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8092 tyinfo->dobj.namespace->dobj.name,
8094 tyinfo->rolname, false,
8095 "TYPE", SECTION_PRE_DATA,
8096 q->data, delq->data, NULL,
8097 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8100 /* Dump Type Comments and Security Labels */
8101 dumpComment(fout, labelq->data,
8102 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8103 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8104 dumpSecLabel(fout, labelq->data,
8105 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8106 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8109 destroyPQExpBuffer(q);
8110 destroyPQExpBuffer(delq);
8111 destroyPQExpBuffer(labelq);
8112 destroyPQExpBuffer(query);
8117 * writes out to fout the queries to recreate a user-defined domain
8120 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8122 PQExpBuffer q = createPQExpBuffer();
8123 PQExpBuffer delq = createPQExpBuffer();
8124 PQExpBuffer labelq = createPQExpBuffer();
8125 PQExpBuffer query = createPQExpBuffer();
8133 bool typdefault_is_literal = false;
8135 /* Set proper schema search path so type references list correctly */
8136 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
8138 /* Fetch domain specific details */
8139 if (g_fout->remoteVersion >= 90100)
8141 /* typcollation is new in 9.1 */
8142 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8143 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8144 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8146 "CASE WHEN t.typcollation <> u.typcollation "
8147 "THEN t.typcollation ELSE 0 END AS typcollation "
8148 "FROM pg_catalog.pg_type t "
8149 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8150 "WHERE t.oid = '%u'::pg_catalog.oid",
8151 tyinfo->dobj.catId.oid);
8155 /* We assume here that remoteVersion must be at least 70300 */
8156 appendPQExpBuffer(query, "SELECT typnotnull, "
8157 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8158 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8159 "typdefault, 0 AS typcollation "
8160 "FROM pg_catalog.pg_type "
8161 "WHERE oid = '%u'::pg_catalog.oid",
8162 tyinfo->dobj.catId.oid);
8165 res = PQexec(g_conn, query->data);
8166 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8168 /* Expecting a single result only */
8169 ntups = PQntuples(res);
8172 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8173 "query returned %d rows instead of one: %s\n",
8175 ntups, query->data);
8179 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8180 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8181 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8182 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8183 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8185 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8186 typdefault_is_literal = true; /* it needs quotes */
8190 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8193 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
8195 appendPQExpBuffer(q,
8196 "CREATE DOMAIN %s AS %s",
8197 fmtId(tyinfo->dobj.name),
8200 /* Print collation only if different from base type's collation */
8201 if (OidIsValid(typcollation))
8205 coll = findCollationByOid(typcollation);
8208 /* always schema-qualify, don't try to be smart */
8209 appendPQExpBuffer(q, " COLLATE %s.",
8210 fmtId(coll->dobj.namespace->dobj.name));
8211 appendPQExpBuffer(q, "%s",
8212 fmtId(coll->dobj.name));
8216 if (typnotnull[0] == 't')
8217 appendPQExpBuffer(q, " NOT NULL");
8219 if (typdefault != NULL)
8221 appendPQExpBuffer(q, " DEFAULT ");
8222 if (typdefault_is_literal)
8223 appendStringLiteralAH(q, typdefault, fout);
8225 appendPQExpBufferStr(q, typdefault);
8231 * Add any CHECK constraints for the domain
8233 for (i = 0; i < tyinfo->nDomChecks; i++)
8235 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8237 if (!domcheck->separate)
8238 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8239 fmtId(domcheck->dobj.name), domcheck->condef);
8242 appendPQExpBuffer(q, ";\n");
8245 * DROP must be fully qualified in case same name appears in pg_catalog
8247 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8248 fmtId(tyinfo->dobj.namespace->dobj.name));
8249 appendPQExpBuffer(delq, "%s;\n",
8250 fmtId(tyinfo->dobj.name));
8252 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8255 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8257 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8259 tyinfo->dobj.namespace->dobj.name,
8261 tyinfo->rolname, false,
8262 "DOMAIN", SECTION_PRE_DATA,
8263 q->data, delq->data, NULL,
8264 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8267 /* Dump Domain Comments and Security Labels */
8268 dumpComment(fout, labelq->data,
8269 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8270 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8271 dumpSecLabel(fout, labelq->data,
8272 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8273 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8275 destroyPQExpBuffer(q);
8276 destroyPQExpBuffer(delq);
8277 destroyPQExpBuffer(labelq);
8278 destroyPQExpBuffer(query);
8283 * writes out to fout the queries to recreate a user-defined stand-alone
8287 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8289 PQExpBuffer q = createPQExpBuffer();
8290 PQExpBuffer dropped = createPQExpBuffer();
8291 PQExpBuffer delq = createPQExpBuffer();
8292 PQExpBuffer labelq = createPQExpBuffer();
8293 PQExpBuffer query = createPQExpBuffer();
8306 /* Set proper schema search path so type references list correctly */
8307 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
8309 /* Fetch type specific details */
8310 if (fout->remoteVersion >= 90100)
8313 * attcollation is new in 9.1. Since we only want to dump COLLATE
8314 * clauses for attributes whose collation is different from their
8315 * type's default, we use a CASE here to suppress uninteresting
8316 * attcollations cheaply. atttypid will be 0 for dropped columns;
8317 * collation does not matter for those.
8319 appendPQExpBuffer(query, "SELECT a.attname, "
8320 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8321 "a.attlen, a.attalign, a.attisdropped, "
8322 "CASE WHEN a.attcollation <> at.typcollation "
8323 "THEN a.attcollation ELSE 0 END AS attcollation, "
8325 "FROM pg_catalog.pg_type ct "
8326 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8327 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8328 "WHERE ct.oid = '%u'::pg_catalog.oid "
8329 "ORDER BY a.attnum ",
8330 tyinfo->dobj.catId.oid);
8335 * We assume here that remoteVersion must be at least 70300. Since
8336 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8339 appendPQExpBuffer(query, "SELECT a.attname, "
8340 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8341 "a.attlen, a.attalign, a.attisdropped, "
8342 "0 AS attcollation, "
8344 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8345 "WHERE ct.oid = '%u'::pg_catalog.oid "
8346 "AND a.attrelid = ct.typrelid "
8347 "ORDER BY a.attnum ",
8348 tyinfo->dobj.catId.oid);
8351 res = PQexec(g_conn, query->data);
8352 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8354 ntups = PQntuples(res);
8356 i_attname = PQfnumber(res, "attname");
8357 i_atttypdefn = PQfnumber(res, "atttypdefn");
8358 i_attlen = PQfnumber(res, "attlen");
8359 i_attalign = PQfnumber(res, "attalign");
8360 i_attisdropped = PQfnumber(res, "attisdropped");
8361 i_attcollation = PQfnumber(res, "attcollation");
8362 i_typrelid = PQfnumber(res, "typrelid");
8366 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8368 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
8369 binary_upgrade_set_pg_class_oids(q, typrelid, false);
8372 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8373 fmtId(tyinfo->dobj.name));
8376 for (i = 0; i < ntups; i++)
8385 attname = PQgetvalue(res, i, i_attname);
8386 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8387 attlen = PQgetvalue(res, i, i_attlen);
8388 attalign = PQgetvalue(res, i, i_attalign);
8389 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8390 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8392 if (attisdropped && !binary_upgrade)
8395 /* Format properly if not first attr */
8396 if (actual_atts++ > 0)
8397 appendPQExpBuffer(q, ",");
8398 appendPQExpBuffer(q, "\n\t");
8402 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8404 /* Add collation if not default for the column type */
8405 if (OidIsValid(attcollation))
8409 coll = findCollationByOid(attcollation);
8412 /* always schema-qualify, don't try to be smart */
8413 appendPQExpBuffer(q, " COLLATE %s.",
8414 fmtId(coll->dobj.namespace->dobj.name));
8415 appendPQExpBuffer(q, "%s",
8416 fmtId(coll->dobj.name));
8423 * This is a dropped attribute and we're in binary_upgrade mode.
8424 * Insert a placeholder for it in the CREATE TYPE command, and set
8425 * length and alignment with direct UPDATE to the catalogs
8426 * afterwards. See similar code in dumpTableSchema().
8428 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8430 /* stash separately for insertion after the CREATE TYPE */
8431 appendPQExpBuffer(dropped,
8432 "\n-- For binary upgrade, recreate dropped column.\n");
8433 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8435 "attalign = '%s', attbyval = false\n"
8436 "WHERE attname = ", attlen, attalign);
8437 appendStringLiteralAH(dropped, attname, fout);
8438 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8439 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8440 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8442 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8443 fmtId(tyinfo->dobj.name));
8444 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8448 appendPQExpBuffer(q, "\n);\n");
8449 appendPQExpBufferStr(q, dropped->data);
8452 * DROP must be fully qualified in case same name appears in pg_catalog
8454 appendPQExpBuffer(delq, "DROP TYPE %s.",
8455 fmtId(tyinfo->dobj.namespace->dobj.name));
8456 appendPQExpBuffer(delq, "%s;\n",
8457 fmtId(tyinfo->dobj.name));
8459 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8462 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8464 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8466 tyinfo->dobj.namespace->dobj.name,
8468 tyinfo->rolname, false,
8469 "TYPE", SECTION_PRE_DATA,
8470 q->data, delq->data, NULL,
8471 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8475 /* Dump Type Comments and Security Labels */
8476 dumpComment(fout, labelq->data,
8477 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8478 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8479 dumpSecLabel(fout, labelq->data,
8480 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8481 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8484 destroyPQExpBuffer(q);
8485 destroyPQExpBuffer(dropped);
8486 destroyPQExpBuffer(delq);
8487 destroyPQExpBuffer(labelq);
8488 destroyPQExpBuffer(query);
8490 /* Dump any per-column comments */
8491 dumpCompositeTypeColComments(fout, tyinfo);
8495 * dumpCompositeTypeColComments
8496 * writes out to fout the queries to recreate comments on the columns of
8497 * a user-defined stand-alone composite type
8500 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8502 CommentItem *comments;
8513 query = createPQExpBuffer();
8515 /* We assume here that remoteVersion must be at least 70300 */
8516 appendPQExpBuffer(query,
8517 "SELECT c.tableoid, a.attname, a.attnum "
8518 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8519 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8520 " AND NOT a.attisdropped "
8521 "ORDER BY a.attnum ",
8524 /* Fetch column attnames */
8525 res = PQexec(g_conn, query->data);
8526 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8528 ntups = PQntuples(res);
8532 destroyPQExpBuffer(query);
8536 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8538 /* Search for comments associated with type's pg_class OID */
8539 ncomments = findComments(fout,
8544 /* If no comments exist, we're done */
8548 destroyPQExpBuffer(query);
8552 /* Build COMMENT ON statements */
8553 target = createPQExpBuffer();
8555 i_attnum = PQfnumber(res, "attnum");
8556 i_attname = PQfnumber(res, "attname");
8557 while (ncomments > 0)
8559 const char *attname;
8562 for (i = 0; i < ntups; i++)
8564 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8566 attname = PQgetvalue(res, i, i_attname);
8570 if (attname) /* just in case we don't find it */
8572 const char *descr = comments->descr;
8574 resetPQExpBuffer(target);
8575 appendPQExpBuffer(target, "COLUMN %s.",
8576 fmtId(tyinfo->dobj.name));
8577 appendPQExpBuffer(target, "%s",
8580 resetPQExpBuffer(query);
8581 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8582 appendStringLiteralAH(query, descr, fout);
8583 appendPQExpBuffer(query, ";\n");
8585 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8587 tyinfo->dobj.namespace->dobj.name,
8588 NULL, tyinfo->rolname,
8589 false, "COMMENT", SECTION_NONE,
8590 query->data, "", NULL,
8591 &(tyinfo->dobj.dumpId), 1,
8600 destroyPQExpBuffer(query);
8601 destroyPQExpBuffer(target);
8606 * writes out to fout the queries to create a shell type
8608 * We dump a shell definition in advance of the I/O functions for the type.
8611 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8615 /* Skip if not to be dumped */
8616 if (!stinfo->dobj.dump || dataOnly)
8619 q = createPQExpBuffer();
8622 * Note the lack of a DROP command for the shell type; any required DROP
8623 * is driven off the base type entry, instead. This interacts with
8624 * _printTocEntry()'s use of the presence of a DROP command to decide
8625 * whether an entry needs an ALTER OWNER command. We don't want to alter
8626 * the shell type's owner immediately on creation; that should happen only
8627 * after it's filled in, otherwise the backend complains.
8631 binary_upgrade_set_type_oids_by_type_oid(q,
8632 stinfo->baseType->dobj.catId.oid);
8634 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8635 fmtId(stinfo->dobj.name));
8637 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8639 stinfo->dobj.namespace->dobj.name,
8641 stinfo->baseType->rolname, false,
8642 "SHELL TYPE", SECTION_PRE_DATA,
8644 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8647 destroyPQExpBuffer(q);
8651 * Determine whether we want to dump definitions for procedural languages.
8652 * Since the languages themselves don't have schemas, we can't rely on
8653 * the normal schema-based selection mechanism. We choose to dump them
8654 * whenever neither --schema nor --table was given. (Before 8.1, we used
8655 * the dump flag of the PL's call handler function, but in 8.1 this will
8656 * probably always be false since call handlers are created in pg_catalog.)
8658 * For some backwards compatibility with the older behavior, we forcibly
8659 * dump a PL if its handler function (and validator if any) are in a
8660 * dumpable namespace. That case is not checked here.
8662 * Also, if the PL belongs to an extension, we do not use this heuristic.
8663 * That case isn't checked here either.
8666 shouldDumpProcLangs(void)
8668 if (!include_everything)
8670 /* And they're schema not data */
8678 * writes out to fout the queries to recreate a user-defined
8679 * procedural language
8682 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8691 FuncInfo *inlineInfo = NULL;
8692 FuncInfo *validatorInfo = NULL;
8694 /* Skip if not to be dumped */
8695 if (!plang->dobj.dump || dataOnly)
8699 * Try to find the support function(s). It is not an error if we don't
8700 * find them --- if the functions are in the pg_catalog schema, as is
8701 * standard in 8.1 and up, then we won't have loaded them. (In this case
8702 * we will emit a parameterless CREATE LANGUAGE command, which will
8703 * require PL template knowledge in the backend to reload.)
8706 funcInfo = findFuncByOid(plang->lanplcallfoid);
8707 if (funcInfo != NULL && !funcInfo->dobj.dump)
8708 funcInfo = NULL; /* treat not-dumped same as not-found */
8710 if (OidIsValid(plang->laninline))
8712 inlineInfo = findFuncByOid(plang->laninline);
8713 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8717 if (OidIsValid(plang->lanvalidator))
8719 validatorInfo = findFuncByOid(plang->lanvalidator);
8720 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8721 validatorInfo = NULL;
8725 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8726 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8729 * However, for a language that belongs to an extension, we must not use
8730 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8731 * told to (via dobj.dump). Generally the support functions will belong
8732 * to the same extension and so have the same dump flags ... if they
8733 * don't, this might not work terribly nicely.
8735 useParams = (funcInfo != NULL &&
8736 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8737 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8739 if (!plang->dobj.ext_member)
8741 if (!useParams && !shouldDumpProcLangs())
8745 defqry = createPQExpBuffer();
8746 delqry = createPQExpBuffer();
8747 labelq = createPQExpBuffer();
8749 qlanname = pg_strdup(fmtId(plang->dobj.name));
8752 * If dumping a HANDLER clause, treat the language as being in the handler
8753 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8754 * it doesn't really have a schema.
8757 lanschema = funcInfo->dobj.namespace->dobj.name;
8761 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8766 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8767 plang->lanpltrusted ? "TRUSTED " : "",
8769 appendPQExpBuffer(defqry, " HANDLER %s",
8770 fmtId(funcInfo->dobj.name));
8771 if (OidIsValid(plang->laninline))
8773 appendPQExpBuffer(defqry, " INLINE ");
8774 /* Cope with possibility that inline is in different schema */
8775 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8776 appendPQExpBuffer(defqry, "%s.",
8777 fmtId(inlineInfo->dobj.namespace->dobj.name));
8778 appendPQExpBuffer(defqry, "%s",
8779 fmtId(inlineInfo->dobj.name));
8781 if (OidIsValid(plang->lanvalidator))
8783 appendPQExpBuffer(defqry, " VALIDATOR ");
8784 /* Cope with possibility that validator is in different schema */
8785 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8786 appendPQExpBuffer(defqry, "%s.",
8787 fmtId(validatorInfo->dobj.namespace->dobj.name));
8788 appendPQExpBuffer(defqry, "%s",
8789 fmtId(validatorInfo->dobj.name));
8795 * If not dumping parameters, then use CREATE OR REPLACE so that the
8796 * command will not fail if the language is preinstalled in the target
8797 * database. We restrict the use of REPLACE to this case so as to
8798 * eliminate the risk of replacing a language with incompatible
8799 * parameter settings: this command will only succeed at all if there
8800 * is a pg_pltemplate entry, and if there is one, the existing entry
8801 * must match it too.
8803 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8806 appendPQExpBuffer(defqry, ";\n");
8808 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8811 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8813 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8815 lanschema, NULL, plang->lanowner,
8816 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8817 defqry->data, delqry->data, NULL,
8818 plang->dobj.dependencies, plang->dobj.nDeps,
8821 /* Dump Proc Lang Comments and Security Labels */
8822 dumpComment(fout, labelq->data,
8824 plang->dobj.catId, 0, plang->dobj.dumpId);
8825 dumpSecLabel(fout, labelq->data,
8827 plang->dobj.catId, 0, plang->dobj.dumpId);
8829 if (plang->lanpltrusted)
8830 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8831 qlanname, NULL, plang->dobj.name,
8833 plang->lanowner, plang->lanacl);
8837 destroyPQExpBuffer(defqry);
8838 destroyPQExpBuffer(delqry);
8839 destroyPQExpBuffer(labelq);
8843 * format_function_arguments: generate function name and argument list
8845 * This is used when we can rely on pg_get_function_arguments to format
8846 * the argument list.
8849 format_function_arguments(FuncInfo *finfo, char *funcargs)
8853 initPQExpBuffer(&fn);
8854 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8859 * format_function_arguments_old: generate function name and argument list
8861 * The argument type names are qualified if needed. The function name
8862 * is never qualified.
8864 * This is used only with pre-8.4 servers, so we aren't expecting to see
8865 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8867 * Any or all of allargtypes, argmodes, argnames may be NULL.
8870 format_function_arguments_old(FuncInfo *finfo, int nallargs,
8878 initPQExpBuffer(&fn);
8879 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8880 for (j = 0; j < nallargs; j++)
8884 const char *argmode;
8885 const char *argname;
8887 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8888 typname = getFormattedTypeName(typid, zeroAsOpaque);
8892 switch (argmodes[j][0])
8897 case PROARGMODE_OUT:
8900 case PROARGMODE_INOUT:
8904 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8912 argname = argnames ? argnames[j] : (char *) NULL;
8913 if (argname && argname[0] == '\0')
8916 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8917 (j > 0) ? ", " : "",
8919 argname ? fmtId(argname) : "",
8924 appendPQExpBuffer(&fn, ")");
8929 * format_function_signature: generate function name and argument list
8931 * This is like format_function_arguments_old except that only a minimal
8932 * list of input argument types is generated; this is sufficient to
8933 * reference the function, but not to define it.
8935 * If honor_quotes is false then the function name is never quoted.
8936 * This is appropriate for use in TOC tags, but not in SQL commands.
8939 format_function_signature(FuncInfo *finfo, bool honor_quotes)
8944 initPQExpBuffer(&fn);
8946 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8948 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8949 for (j = 0; j < finfo->nargs; j++)
8953 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
8955 appendPQExpBuffer(&fn, "%s%s",
8956 (j > 0) ? ", " : "",
8960 appendPQExpBuffer(&fn, ")");
8967 * dump out one function
8970 dumpFunc(Archive *fout, FuncInfo *finfo)
8978 char *funcsig; /* identity signature */
8979 char *funcfullsig; /* full signature */
8988 char *proallargtypes;
9001 char **allargtypes = NULL;
9002 char **argmodes = NULL;
9003 char **argnames = NULL;
9004 char **configitems = NULL;
9005 int nconfigitems = 0;
9008 /* Skip if not to be dumped */
9009 if (!finfo->dobj.dump || dataOnly)
9012 query = createPQExpBuffer();
9013 q = createPQExpBuffer();
9014 delqry = createPQExpBuffer();
9015 labelq = createPQExpBuffer();
9016 asPart = createPQExpBuffer();
9018 /* Set proper schema search path so type references list correctly */
9019 selectSourceSchema(finfo->dobj.namespace->dobj.name);
9021 /* Fetch function-specific details */
9022 if (g_fout->remoteVersion >= 80400)
9025 * In 8.4 and up we rely on pg_get_function_arguments and
9026 * pg_get_function_result instead of examining proallargtypes etc.
9028 appendPQExpBuffer(query,
9029 "SELECT proretset, prosrc, probin, "
9030 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9031 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9032 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9033 "proiswindow, provolatile, proisstrict, prosecdef, "
9034 "proconfig, procost, prorows, "
9035 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9036 "FROM pg_catalog.pg_proc "
9037 "WHERE oid = '%u'::pg_catalog.oid",
9038 finfo->dobj.catId.oid);
9040 else if (g_fout->remoteVersion >= 80300)
9042 appendPQExpBuffer(query,
9043 "SELECT proretset, prosrc, probin, "
9044 "proallargtypes, proargmodes, proargnames, "
9045 "false AS proiswindow, "
9046 "provolatile, proisstrict, prosecdef, "
9047 "proconfig, procost, prorows, "
9048 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9049 "FROM pg_catalog.pg_proc "
9050 "WHERE oid = '%u'::pg_catalog.oid",
9051 finfo->dobj.catId.oid);
9053 else if (g_fout->remoteVersion >= 80100)
9055 appendPQExpBuffer(query,
9056 "SELECT proretset, prosrc, probin, "
9057 "proallargtypes, proargmodes, proargnames, "
9058 "false AS proiswindow, "
9059 "provolatile, proisstrict, prosecdef, "
9060 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9061 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9062 "FROM pg_catalog.pg_proc "
9063 "WHERE oid = '%u'::pg_catalog.oid",
9064 finfo->dobj.catId.oid);
9066 else if (g_fout->remoteVersion >= 80000)
9068 appendPQExpBuffer(query,
9069 "SELECT proretset, prosrc, probin, "
9070 "null AS proallargtypes, "
9071 "null AS proargmodes, "
9073 "false AS proiswindow, "
9074 "provolatile, proisstrict, prosecdef, "
9075 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9076 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9077 "FROM pg_catalog.pg_proc "
9078 "WHERE oid = '%u'::pg_catalog.oid",
9079 finfo->dobj.catId.oid);
9081 else if (g_fout->remoteVersion >= 70300)
9083 appendPQExpBuffer(query,
9084 "SELECT proretset, prosrc, probin, "
9085 "null AS proallargtypes, "
9086 "null AS proargmodes, "
9087 "null AS proargnames, "
9088 "false AS proiswindow, "
9089 "provolatile, proisstrict, prosecdef, "
9090 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9091 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9092 "FROM pg_catalog.pg_proc "
9093 "WHERE oid = '%u'::pg_catalog.oid",
9094 finfo->dobj.catId.oid);
9096 else if (g_fout->remoteVersion >= 70100)
9098 appendPQExpBuffer(query,
9099 "SELECT proretset, prosrc, probin, "
9100 "null AS proallargtypes, "
9101 "null AS proargmodes, "
9102 "null AS proargnames, "
9103 "false AS proiswindow, "
9104 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9106 "false AS prosecdef, "
9107 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9108 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9110 "WHERE oid = '%u'::oid",
9111 finfo->dobj.catId.oid);
9115 appendPQExpBuffer(query,
9116 "SELECT proretset, prosrc, probin, "
9117 "null AS proallargtypes, "
9118 "null AS proargmodes, "
9119 "null AS proargnames, "
9120 "false AS proiswindow, "
9121 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9122 "false AS proisstrict, "
9123 "false AS prosecdef, "
9124 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9125 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9127 "WHERE oid = '%u'::oid",
9128 finfo->dobj.catId.oid);
9131 res = PQexec(g_conn, query->data);
9132 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9134 /* Expecting a single result only */
9135 ntups = PQntuples(res);
9138 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9139 "query returned %d rows instead of one: %s\n",
9141 ntups, query->data);
9145 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9146 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9147 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9148 if (g_fout->remoteVersion >= 80400)
9150 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9151 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9152 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9153 proallargtypes = proargmodes = proargnames = NULL;
9157 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9158 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9159 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9160 funcargs = funciargs = funcresult = NULL;
9162 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9163 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9164 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9165 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9166 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9167 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9168 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9169 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9172 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9173 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9174 * versions would set it to "-". There are no known cases in which prosrc
9175 * is unused, so the tests below for "-" are probably useless.
9177 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9179 appendPQExpBuffer(asPart, "AS ");
9180 appendStringLiteralAH(asPart, probin, fout);
9181 if (strcmp(prosrc, "-") != 0)
9183 appendPQExpBuffer(asPart, ", ");
9186 * where we have bin, use dollar quoting if allowed and src
9187 * contains quote or backslash; else use regular quoting.
9189 if (disable_dollar_quoting ||
9190 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9191 appendStringLiteralAH(asPart, prosrc, fout);
9193 appendStringLiteralDQ(asPart, prosrc, NULL);
9198 if (strcmp(prosrc, "-") != 0)
9200 appendPQExpBuffer(asPart, "AS ");
9201 /* with no bin, dollar quote src unconditionally if allowed */
9202 if (disable_dollar_quoting)
9203 appendStringLiteralAH(asPart, prosrc, fout);
9205 appendStringLiteralDQ(asPart, prosrc, NULL);
9209 nallargs = finfo->nargs; /* unless we learn different from allargs */
9211 if (proallargtypes && *proallargtypes)
9215 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9216 nitems < finfo->nargs)
9218 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9227 if (proargmodes && *proargmodes)
9231 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9234 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9241 if (proargnames && *proargnames)
9245 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9248 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9255 if (proconfig && *proconfig)
9257 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9259 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9269 /* 8.4 or later; we rely on server-side code for most of the work */
9270 funcfullsig = format_function_arguments(finfo, funcargs);
9271 funcsig = format_function_arguments(finfo, funciargs);
9275 /* pre-8.4, do it ourselves */
9276 funcsig = format_function_arguments_old(finfo, nallargs, allargtypes,
9277 argmodes, argnames);
9278 funcfullsig = funcsig;
9281 funcsig_tag = format_function_signature(finfo, false);
9284 * DROP must be fully qualified in case same name appears in pg_catalog
9286 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9287 fmtId(finfo->dobj.namespace->dobj.name),
9290 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9292 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9295 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
9296 appendPQExpBuffer(q, "RETURNS %s%s",
9297 (proretset[0] == 't') ? "SETOF " : "",
9302 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9304 if (proiswindow[0] == 't')
9305 appendPQExpBuffer(q, " WINDOW");
9307 if (provolatile[0] != PROVOLATILE_VOLATILE)
9309 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9310 appendPQExpBuffer(q, " IMMUTABLE");
9311 else if (provolatile[0] == PROVOLATILE_STABLE)
9312 appendPQExpBuffer(q, " STABLE");
9313 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9315 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
9321 if (proisstrict[0] == 't')
9322 appendPQExpBuffer(q, " STRICT");
9324 if (prosecdef[0] == 't')
9325 appendPQExpBuffer(q, " SECURITY DEFINER");
9328 * COST and ROWS are emitted only if present and not default, so as not to
9329 * break backwards-compatibility of the dump without need. Keep this code
9330 * in sync with the defaults in functioncmds.c.
9332 if (strcmp(procost, "0") != 0)
9334 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9336 /* default cost is 1 */
9337 if (strcmp(procost, "1") != 0)
9338 appendPQExpBuffer(q, " COST %s", procost);
9342 /* default cost is 100 */
9343 if (strcmp(procost, "100") != 0)
9344 appendPQExpBuffer(q, " COST %s", procost);
9347 if (proretset[0] == 't' &&
9348 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9349 appendPQExpBuffer(q, " ROWS %s", prorows);
9351 for (i = 0; i < nconfigitems; i++)
9353 /* we feel free to scribble on configitems[] here */
9354 char *configitem = configitems[i];
9357 pos = strchr(configitem, '=');
9361 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9364 * Some GUC variable names are 'LIST' type and hence must not be
9367 if (pg_strcasecmp(configitem, "DateStyle") == 0
9368 || pg_strcasecmp(configitem, "search_path") == 0)
9369 appendPQExpBuffer(q, "%s", pos);
9371 appendStringLiteralAH(q, pos, fout);
9374 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9376 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9379 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9381 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9383 finfo->dobj.namespace->dobj.name,
9385 finfo->rolname, false,
9386 "FUNCTION", SECTION_PRE_DATA,
9387 q->data, delqry->data, NULL,
9388 finfo->dobj.dependencies, finfo->dobj.nDeps,
9391 /* Dump Function Comments and Security Labels */
9392 dumpComment(fout, labelq->data,
9393 finfo->dobj.namespace->dobj.name, finfo->rolname,
9394 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9395 dumpSecLabel(fout, labelq->data,
9396 finfo->dobj.namespace->dobj.name, finfo->rolname,
9397 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9399 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9400 funcsig, NULL, funcsig_tag,
9401 finfo->dobj.namespace->dobj.name,
9402 finfo->rolname, finfo->proacl);
9406 destroyPQExpBuffer(query);
9407 destroyPQExpBuffer(q);
9408 destroyPQExpBuffer(delqry);
9409 destroyPQExpBuffer(labelq);
9410 destroyPQExpBuffer(asPart);
9425 * Dump a user-defined cast
9428 dumpCast(Archive *fout, CastInfo *cast)
9433 FuncInfo *funcInfo = NULL;
9435 /* Skip if not to be dumped */
9436 if (!cast->dobj.dump || dataOnly)
9439 /* Cannot dump if we don't have the cast function's info */
9440 if (OidIsValid(cast->castfunc))
9442 funcInfo = findFuncByOid(cast->castfunc);
9443 if (funcInfo == NULL)
9448 * As per discussion we dump casts if one or more of the underlying
9449 * objects (the conversion function and the two data types) are not
9450 * builtin AND if all of the non-builtin objects are included in the dump.
9451 * Builtin meaning, the namespace name does not start with "pg_".
9453 * However, for a cast that belongs to an extension, we must not use this
9454 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9456 if (!cast->dobj.ext_member)
9458 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9459 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9461 if (sourceInfo == NULL || targetInfo == NULL)
9465 * Skip this cast if all objects are from pg_
9467 if ((funcInfo == NULL ||
9468 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9469 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9470 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9474 * Skip cast if function isn't from pg_ and is not to be dumped.
9477 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9478 !funcInfo->dobj.dump)
9482 * Same for the source type
9484 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9485 !sourceInfo->dobj.dump)
9489 * and the target type.
9491 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9492 !targetInfo->dobj.dump)
9496 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9497 selectSourceSchema("pg_catalog");
9499 defqry = createPQExpBuffer();
9500 delqry = createPQExpBuffer();
9501 labelq = createPQExpBuffer();
9503 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9504 getFormattedTypeName(cast->castsource, zeroAsNone),
9505 getFormattedTypeName(cast->casttarget, zeroAsNone));
9507 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9508 getFormattedTypeName(cast->castsource, zeroAsNone),
9509 getFormattedTypeName(cast->casttarget, zeroAsNone));
9511 switch (cast->castmethod)
9513 case COERCION_METHOD_BINARY:
9514 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9516 case COERCION_METHOD_INOUT:
9517 appendPQExpBuffer(defqry, "WITH INOUT");
9519 case COERCION_METHOD_FUNCTION:
9522 * Always qualify the function name, in case it is not in
9523 * pg_catalog schema (format_function_signature won't qualify it).
9525 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
9526 fmtId(funcInfo->dobj.namespace->dobj.name));
9527 appendPQExpBuffer(defqry, "%s",
9528 format_function_signature(funcInfo, true));
9531 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9534 if (cast->castcontext == 'a')
9535 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9536 else if (cast->castcontext == 'i')
9537 appendPQExpBuffer(defqry, " AS IMPLICIT");
9538 appendPQExpBuffer(defqry, ";\n");
9540 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9541 getFormattedTypeName(cast->castsource, zeroAsNone),
9542 getFormattedTypeName(cast->casttarget, zeroAsNone));
9545 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9547 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9549 "pg_catalog", NULL, "",
9550 false, "CAST", SECTION_PRE_DATA,
9551 defqry->data, delqry->data, NULL,
9552 cast->dobj.dependencies, cast->dobj.nDeps,
9555 /* Dump Cast Comments */
9556 dumpComment(fout, labelq->data,
9558 cast->dobj.catId, 0, cast->dobj.dumpId);
9560 destroyPQExpBuffer(defqry);
9561 destroyPQExpBuffer(delqry);
9562 destroyPQExpBuffer(labelq);
9567 * write out a single operator definition
9570 dumpOpr(Archive *fout, OprInfo *oprinfo)
9577 PQExpBuffer details;
9602 /* Skip if not to be dumped */
9603 if (!oprinfo->dobj.dump || dataOnly)
9607 * some operators are invalid because they were the result of user
9608 * defining operators before commutators exist
9610 if (!OidIsValid(oprinfo->oprcode))
9613 query = createPQExpBuffer();
9614 q = createPQExpBuffer();
9615 delq = createPQExpBuffer();
9616 labelq = createPQExpBuffer();
9617 oprid = createPQExpBuffer();
9618 details = createPQExpBuffer();
9620 /* Make sure we are in proper schema so regoperator works correctly */
9621 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
9623 if (g_fout->remoteVersion >= 80300)
9625 appendPQExpBuffer(query, "SELECT oprkind, "
9626 "oprcode::pg_catalog.regprocedure, "
9627 "oprleft::pg_catalog.regtype, "
9628 "oprright::pg_catalog.regtype, "
9629 "oprcom::pg_catalog.regoperator, "
9630 "oprnegate::pg_catalog.regoperator, "
9631 "oprrest::pg_catalog.regprocedure, "
9632 "oprjoin::pg_catalog.regprocedure, "
9633 "oprcanmerge, oprcanhash "
9634 "FROM pg_catalog.pg_operator "
9635 "WHERE oid = '%u'::pg_catalog.oid",
9636 oprinfo->dobj.catId.oid);
9638 else if (g_fout->remoteVersion >= 70300)
9640 appendPQExpBuffer(query, "SELECT oprkind, "
9641 "oprcode::pg_catalog.regprocedure, "
9642 "oprleft::pg_catalog.regtype, "
9643 "oprright::pg_catalog.regtype, "
9644 "oprcom::pg_catalog.regoperator, "
9645 "oprnegate::pg_catalog.regoperator, "
9646 "oprrest::pg_catalog.regprocedure, "
9647 "oprjoin::pg_catalog.regprocedure, "
9648 "(oprlsortop != 0) AS oprcanmerge, "
9650 "FROM pg_catalog.pg_operator "
9651 "WHERE oid = '%u'::pg_catalog.oid",
9652 oprinfo->dobj.catId.oid);
9654 else if (g_fout->remoteVersion >= 70100)
9656 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9657 "CASE WHEN oprleft = 0 THEN '-' "
9658 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9659 "CASE WHEN oprright = 0 THEN '-' "
9660 "ELSE format_type(oprright, NULL) END AS oprright, "
9661 "oprcom, oprnegate, oprrest, oprjoin, "
9662 "(oprlsortop != 0) AS oprcanmerge, "
9665 "WHERE oid = '%u'::oid",
9666 oprinfo->dobj.catId.oid);
9670 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9671 "CASE WHEN oprleft = 0 THEN '-'::name "
9672 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9673 "CASE WHEN oprright = 0 THEN '-'::name "
9674 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9675 "oprcom, oprnegate, oprrest, oprjoin, "
9676 "(oprlsortop != 0) AS oprcanmerge, "
9679 "WHERE oid = '%u'::oid",
9680 oprinfo->dobj.catId.oid);
9683 res = PQexec(g_conn, query->data);
9684 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9686 /* Expecting a single result only */
9687 ntups = PQntuples(res);
9690 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9691 "query returned %d rows instead of one: %s\n",
9693 ntups, query->data);
9697 i_oprkind = PQfnumber(res, "oprkind");
9698 i_oprcode = PQfnumber(res, "oprcode");
9699 i_oprleft = PQfnumber(res, "oprleft");
9700 i_oprright = PQfnumber(res, "oprright");
9701 i_oprcom = PQfnumber(res, "oprcom");
9702 i_oprnegate = PQfnumber(res, "oprnegate");
9703 i_oprrest = PQfnumber(res, "oprrest");
9704 i_oprjoin = PQfnumber(res, "oprjoin");
9705 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9706 i_oprcanhash = PQfnumber(res, "oprcanhash");
9708 oprkind = PQgetvalue(res, 0, i_oprkind);
9709 oprcode = PQgetvalue(res, 0, i_oprcode);
9710 oprleft = PQgetvalue(res, 0, i_oprleft);
9711 oprright = PQgetvalue(res, 0, i_oprright);
9712 oprcom = PQgetvalue(res, 0, i_oprcom);
9713 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9714 oprrest = PQgetvalue(res, 0, i_oprrest);
9715 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9716 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9717 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9719 appendPQExpBuffer(details, " PROCEDURE = %s",
9720 convertRegProcReference(oprcode));
9722 appendPQExpBuffer(oprid, "%s (",
9723 oprinfo->dobj.name);
9726 * right unary means there's a left arg and left unary means there's a
9729 if (strcmp(oprkind, "r") == 0 ||
9730 strcmp(oprkind, "b") == 0)
9732 if (g_fout->remoteVersion >= 70100)
9735 name = fmtId(oprleft);
9736 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9737 appendPQExpBuffer(oprid, "%s", name);
9740 appendPQExpBuffer(oprid, "NONE");
9742 if (strcmp(oprkind, "l") == 0 ||
9743 strcmp(oprkind, "b") == 0)
9745 if (g_fout->remoteVersion >= 70100)
9748 name = fmtId(oprright);
9749 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9750 appendPQExpBuffer(oprid, ", %s)", name);
9753 appendPQExpBuffer(oprid, ", NONE)");
9755 name = convertOperatorReference(oprcom);
9757 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9759 name = convertOperatorReference(oprnegate);
9761 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9763 if (strcmp(oprcanmerge, "t") == 0)
9764 appendPQExpBuffer(details, ",\n MERGES");
9766 if (strcmp(oprcanhash, "t") == 0)
9767 appendPQExpBuffer(details, ",\n HASHES");
9769 name = convertRegProcReference(oprrest);
9771 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9773 name = convertRegProcReference(oprjoin);
9775 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9778 * DROP must be fully qualified in case same name appears in pg_catalog
9780 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9781 fmtId(oprinfo->dobj.namespace->dobj.name),
9784 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9785 oprinfo->dobj.name, details->data);
9787 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9790 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9792 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9794 oprinfo->dobj.namespace->dobj.name,
9797 false, "OPERATOR", SECTION_PRE_DATA,
9798 q->data, delq->data, NULL,
9799 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9802 /* Dump Operator Comments */
9803 dumpComment(fout, labelq->data,
9804 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9805 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9809 destroyPQExpBuffer(query);
9810 destroyPQExpBuffer(q);
9811 destroyPQExpBuffer(delq);
9812 destroyPQExpBuffer(labelq);
9813 destroyPQExpBuffer(oprid);
9814 destroyPQExpBuffer(details);
9818 * Convert a function reference obtained from pg_operator
9820 * Returns what to print, or NULL if function references is InvalidOid
9822 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9823 * argument-types part. In prior versions, the input is a REGPROC display.
9826 convertRegProcReference(const char *proc)
9828 /* In all cases "-" means a null reference */
9829 if (strcmp(proc, "-") == 0)
9832 if (g_fout->remoteVersion >= 70300)
9838 name = pg_strdup(proc);
9839 /* find non-double-quoted left paren */
9841 for (paren = name; *paren; paren++)
9843 if (*paren == '(' && !inquote)
9854 /* REGPROC before 7.3 does not quote its result */
9859 * Convert an operator cross-reference obtained from pg_operator
9861 * Returns what to print, or NULL to print nothing
9863 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9864 * argument-types part, and add OPERATOR() decoration if the name is
9865 * schema-qualified. In older versions, the input is just a numeric OID,
9866 * which we search our operator list for.
9869 convertOperatorReference(const char *opr)
9873 /* In all cases "0" means a null reference */
9874 if (strcmp(opr, "0") == 0)
9877 if (g_fout->remoteVersion >= 70300)
9885 name = pg_strdup(opr);
9886 /* find non-double-quoted left paren, and check for non-quoted dot */
9889 for (ptr = name; *ptr; ptr++)
9893 else if (*ptr == '.' && !inquote)
9895 else if (*ptr == '(' && !inquote)
9901 /* If not schema-qualified, don't need to add OPERATOR() */
9904 oname = pg_malloc(strlen(name) + 11);
9905 sprintf(oname, "OPERATOR(%s)", name);
9910 oprInfo = findOprByOid(atooid(opr));
9911 if (oprInfo == NULL)
9913 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9917 return oprInfo->dobj.name;
9921 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9923 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9924 * argument lists of these functions are predetermined. Note that the
9925 * caller should ensure we are in the proper schema, because the results
9926 * are search path dependent!
9929 convertTSFunction(Oid funcOid)
9936 snprintf(query, sizeof(query),
9937 "SELECT '%u'::pg_catalog.regproc", funcOid);
9938 res = PQexec(g_conn, query);
9939 check_sql_result(res, g_conn, query, PGRES_TUPLES_OK);
9941 ntups = PQntuples(res);
9944 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9945 "query returned %d rows instead of one: %s\n",
9951 result = pg_strdup(PQgetvalue(res, 0, 0));
9961 * write out a single operator class definition
9964 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9976 int i_opcfamilyname;
9983 int i_sortfamilynsp;
9986 int i_amproclefttype;
9987 int i_amprocrighttype;
9992 char *opcfamilyname;
9999 char *sortfamilynsp;
10002 char *amproclefttype;
10003 char *amprocrighttype;
10007 /* Skip if not to be dumped */
10008 if (!opcinfo->dobj.dump || dataOnly)
10012 * XXX currently we do not implement dumping of operator classes from
10013 * pre-7.3 databases. This could be done but it seems not worth the
10016 if (g_fout->remoteVersion < 70300)
10019 query = createPQExpBuffer();
10020 q = createPQExpBuffer();
10021 delq = createPQExpBuffer();
10022 labelq = createPQExpBuffer();
10024 /* Make sure we are in proper schema so regoperator works correctly */
10025 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
10027 /* Get additional fields from the pg_opclass row */
10028 if (g_fout->remoteVersion >= 80300)
10030 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10031 "opckeytype::pg_catalog.regtype, "
10032 "opcdefault, opcfamily, "
10033 "opfname AS opcfamilyname, "
10034 "nspname AS opcfamilynsp, "
10035 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10036 "FROM pg_catalog.pg_opclass c "
10037 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10038 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10039 "WHERE c.oid = '%u'::pg_catalog.oid",
10040 opcinfo->dobj.catId.oid);
10044 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10045 "opckeytype::pg_catalog.regtype, "
10046 "opcdefault, NULL AS opcfamily, "
10047 "NULL AS opcfamilyname, "
10048 "NULL AS opcfamilynsp, "
10049 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10050 "FROM pg_catalog.pg_opclass "
10051 "WHERE oid = '%u'::pg_catalog.oid",
10052 opcinfo->dobj.catId.oid);
10055 res = PQexec(g_conn, query->data);
10056 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10058 /* Expecting a single result only */
10059 ntups = PQntuples(res);
10062 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10063 "query returned %d rows instead of one: %s\n",
10065 ntups, query->data);
10069 i_opcintype = PQfnumber(res, "opcintype");
10070 i_opckeytype = PQfnumber(res, "opckeytype");
10071 i_opcdefault = PQfnumber(res, "opcdefault");
10072 i_opcfamily = PQfnumber(res, "opcfamily");
10073 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10074 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10075 i_amname = PQfnumber(res, "amname");
10077 opcintype = PQgetvalue(res, 0, i_opcintype);
10078 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10079 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10080 /* opcfamily will still be needed after we PQclear res */
10081 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10082 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10083 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10084 /* amname will still be needed after we PQclear res */
10085 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10088 * DROP must be fully qualified in case same name appears in pg_catalog
10090 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10091 fmtId(opcinfo->dobj.namespace->dobj.name));
10092 appendPQExpBuffer(delq, ".%s",
10093 fmtId(opcinfo->dobj.name));
10094 appendPQExpBuffer(delq, " USING %s;\n",
10097 /* Build the fixed portion of the CREATE command */
10098 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10099 fmtId(opcinfo->dobj.name));
10100 if (strcmp(opcdefault, "t") == 0)
10101 appendPQExpBuffer(q, "DEFAULT ");
10102 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10105 if (strlen(opcfamilyname) > 0 &&
10106 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10107 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10109 appendPQExpBuffer(q, " FAMILY ");
10110 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10111 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10112 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10114 appendPQExpBuffer(q, " AS\n ");
10118 if (strcmp(opckeytype, "-") != 0)
10120 appendPQExpBuffer(q, "STORAGE %s",
10128 * Now fetch and print the OPERATOR entries (pg_amop rows).
10130 * Print only those opfamily members that are tied to the opclass by
10131 * pg_depend entries.
10133 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10134 * older server's opclass in which it is used. This is to avoid
10135 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10136 * older server and then reload into that old version. This can go away
10137 * once 8.3 is so old as to not be of interest to anyone.
10139 resetPQExpBuffer(query);
10141 if (g_fout->remoteVersion >= 90100)
10143 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10144 "amopopr::pg_catalog.regoperator, "
10145 "opfname AS sortfamily, "
10146 "nspname AS sortfamilynsp "
10147 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10148 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10149 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10150 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10151 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10152 "AND refobjid = '%u'::pg_catalog.oid "
10153 "AND amopfamily = '%s'::pg_catalog.oid "
10154 "ORDER BY amopstrategy",
10155 opcinfo->dobj.catId.oid,
10158 else if (g_fout->remoteVersion >= 80400)
10160 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10161 "amopopr::pg_catalog.regoperator, "
10162 "NULL AS sortfamily, "
10163 "NULL AS sortfamilynsp "
10164 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10165 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10166 "AND refobjid = '%u'::pg_catalog.oid "
10167 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10168 "AND objid = ao.oid "
10169 "ORDER BY amopstrategy",
10170 opcinfo->dobj.catId.oid);
10172 else if (g_fout->remoteVersion >= 80300)
10174 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10175 "amopopr::pg_catalog.regoperator, "
10176 "NULL AS sortfamily, "
10177 "NULL AS sortfamilynsp "
10178 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10179 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10180 "AND refobjid = '%u'::pg_catalog.oid "
10181 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10182 "AND objid = ao.oid "
10183 "ORDER BY amopstrategy",
10184 opcinfo->dobj.catId.oid);
10189 * Here, we print all entries since there are no opfamilies and hence
10190 * no loose operators to worry about.
10192 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10193 "amopopr::pg_catalog.regoperator, "
10194 "NULL AS sortfamily, "
10195 "NULL AS sortfamilynsp "
10196 "FROM pg_catalog.pg_amop "
10197 "WHERE amopclaid = '%u'::pg_catalog.oid "
10198 "ORDER BY amopstrategy",
10199 opcinfo->dobj.catId.oid);
10202 res = PQexec(g_conn, query->data);
10203 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10205 ntups = PQntuples(res);
10207 i_amopstrategy = PQfnumber(res, "amopstrategy");
10208 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10209 i_amopopr = PQfnumber(res, "amopopr");
10210 i_sortfamily = PQfnumber(res, "sortfamily");
10211 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10213 for (i = 0; i < ntups; i++)
10215 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10216 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10217 amopopr = PQgetvalue(res, i, i_amopopr);
10218 sortfamily = PQgetvalue(res, i, i_sortfamily);
10219 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10222 appendPQExpBuffer(q, " ,\n ");
10224 appendPQExpBuffer(q, "OPERATOR %s %s",
10225 amopstrategy, amopopr);
10227 if (strlen(sortfamily) > 0)
10229 appendPQExpBuffer(q, " FOR ORDER BY ");
10230 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10231 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10232 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10235 if (strcmp(amopreqcheck, "t") == 0)
10236 appendPQExpBuffer(q, " RECHECK");
10244 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10246 * Print only those opfamily members that are tied to the opclass by
10247 * pg_depend entries.
10249 * We print the amproclefttype/amprocrighttype even though in most cases
10250 * the backend could deduce the right values, because of the corner case
10251 * of a btree sort support function for a cross-type comparison. That's
10252 * only allowed in 9.2 and later, but for simplicity print them in all
10253 * versions that have the columns.
10255 resetPQExpBuffer(query);
10257 if (g_fout->remoteVersion >= 80300)
10259 appendPQExpBuffer(query, "SELECT amprocnum, "
10260 "amproc::pg_catalog.regprocedure, "
10261 "amproclefttype::pg_catalog.regtype, "
10262 "amprocrighttype::pg_catalog.regtype "
10263 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10264 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10265 "AND refobjid = '%u'::pg_catalog.oid "
10266 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10267 "AND objid = ap.oid "
10268 "ORDER BY amprocnum",
10269 opcinfo->dobj.catId.oid);
10273 appendPQExpBuffer(query, "SELECT amprocnum, "
10274 "amproc::pg_catalog.regprocedure, "
10275 "'' AS amproclefttype, "
10276 "'' AS amprocrighttype "
10277 "FROM pg_catalog.pg_amproc "
10278 "WHERE amopclaid = '%u'::pg_catalog.oid "
10279 "ORDER BY amprocnum",
10280 opcinfo->dobj.catId.oid);
10283 res = PQexec(g_conn, query->data);
10284 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10286 ntups = PQntuples(res);
10288 i_amprocnum = PQfnumber(res, "amprocnum");
10289 i_amproc = PQfnumber(res, "amproc");
10290 i_amproclefttype = PQfnumber(res, "amproclefttype");
10291 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10293 for (i = 0; i < ntups; i++)
10295 amprocnum = PQgetvalue(res, i, i_amprocnum);
10296 amproc = PQgetvalue(res, i, i_amproc);
10297 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10298 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10301 appendPQExpBuffer(q, " ,\n ");
10303 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10305 if (*amproclefttype && *amprocrighttype)
10306 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10308 appendPQExpBuffer(q, " %s", amproc);
10315 appendPQExpBuffer(q, ";\n");
10317 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10318 fmtId(opcinfo->dobj.name));
10319 appendPQExpBuffer(labelq, " USING %s",
10322 if (binary_upgrade)
10323 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10325 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10326 opcinfo->dobj.name,
10327 opcinfo->dobj.namespace->dobj.name,
10330 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10331 q->data, delq->data, NULL,
10332 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10335 /* Dump Operator Class Comments */
10336 dumpComment(fout, labelq->data,
10337 NULL, opcinfo->rolname,
10338 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10341 destroyPQExpBuffer(query);
10342 destroyPQExpBuffer(q);
10343 destroyPQExpBuffer(delq);
10344 destroyPQExpBuffer(labelq);
10349 * write out a single operator family definition
10351 * Note: this also dumps any "loose" operator members that aren't bound to a
10352 * specific opclass within the opfamily.
10355 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10360 PQExpBuffer labelq;
10363 PGresult *res_procs;
10366 int i_amopstrategy;
10367 int i_amopreqcheck;
10370 int i_sortfamilynsp;
10373 int i_amproclefttype;
10374 int i_amprocrighttype;
10376 char *amopstrategy;
10377 char *amopreqcheck;
10380 char *sortfamilynsp;
10383 char *amproclefttype;
10384 char *amprocrighttype;
10388 /* Skip if not to be dumped */
10389 if (!opfinfo->dobj.dump || dataOnly)
10393 * We want to dump the opfamily only if (1) it contains "loose" operators
10394 * or functions, or (2) it contains an opclass with a different name or
10395 * owner. Otherwise it's sufficient to let it be created during creation
10396 * of the contained opclass, and not dumping it improves portability of
10397 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10401 query = createPQExpBuffer();
10402 q = createPQExpBuffer();
10403 delq = createPQExpBuffer();
10404 labelq = createPQExpBuffer();
10406 /* Make sure we are in proper schema so regoperator works correctly */
10407 selectSourceSchema(opfinfo->dobj.namespace->dobj.name);
10410 * Fetch only those opfamily members that are tied directly to the
10411 * opfamily by pg_depend entries.
10413 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10414 * older server's opclass in which it is used. This is to avoid
10415 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10416 * older server and then reload into that old version. This can go away
10417 * once 8.3 is so old as to not be of interest to anyone.
10419 if (g_fout->remoteVersion >= 90100)
10421 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10422 "amopopr::pg_catalog.regoperator, "
10423 "opfname AS sortfamily, "
10424 "nspname AS sortfamilynsp "
10425 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10426 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10427 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10428 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10429 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10430 "AND refobjid = '%u'::pg_catalog.oid "
10431 "AND amopfamily = '%u'::pg_catalog.oid "
10432 "ORDER BY amopstrategy",
10433 opfinfo->dobj.catId.oid,
10434 opfinfo->dobj.catId.oid);
10436 else if (g_fout->remoteVersion >= 80400)
10438 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10439 "amopopr::pg_catalog.regoperator, "
10440 "NULL AS sortfamily, "
10441 "NULL AS sortfamilynsp "
10442 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10443 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10444 "AND refobjid = '%u'::pg_catalog.oid "
10445 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10446 "AND objid = ao.oid "
10447 "ORDER BY amopstrategy",
10448 opfinfo->dobj.catId.oid);
10452 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10453 "amopopr::pg_catalog.regoperator, "
10454 "NULL AS sortfamily, "
10455 "NULL AS sortfamilynsp "
10456 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10457 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10458 "AND refobjid = '%u'::pg_catalog.oid "
10459 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10460 "AND objid = ao.oid "
10461 "ORDER BY amopstrategy",
10462 opfinfo->dobj.catId.oid);
10465 res_ops = PQexec(g_conn, query->data);
10466 check_sql_result(res_ops, g_conn, query->data, PGRES_TUPLES_OK);
10468 resetPQExpBuffer(query);
10470 appendPQExpBuffer(query, "SELECT amprocnum, "
10471 "amproc::pg_catalog.regprocedure, "
10472 "amproclefttype::pg_catalog.regtype, "
10473 "amprocrighttype::pg_catalog.regtype "
10474 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10475 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10476 "AND refobjid = '%u'::pg_catalog.oid "
10477 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10478 "AND objid = ap.oid "
10479 "ORDER BY amprocnum",
10480 opfinfo->dobj.catId.oid);
10482 res_procs = PQexec(g_conn, query->data);
10483 check_sql_result(res_procs, g_conn, query->data, PGRES_TUPLES_OK);
10485 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10487 /* No loose members, so check contained opclasses */
10488 resetPQExpBuffer(query);
10490 appendPQExpBuffer(query, "SELECT 1 "
10491 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10492 "WHERE f.oid = '%u'::pg_catalog.oid "
10493 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10494 "AND refobjid = f.oid "
10495 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10496 "AND objid = c.oid "
10497 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10499 opfinfo->dobj.catId.oid);
10501 res = PQexec(g_conn, query->data);
10502 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10504 if (PQntuples(res) == 0)
10506 /* no need to dump it, so bail out */
10509 PQclear(res_procs);
10510 destroyPQExpBuffer(query);
10511 destroyPQExpBuffer(q);
10512 destroyPQExpBuffer(delq);
10513 destroyPQExpBuffer(labelq);
10520 /* Get additional fields from the pg_opfamily row */
10521 resetPQExpBuffer(query);
10523 appendPQExpBuffer(query, "SELECT "
10524 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10525 "FROM pg_catalog.pg_opfamily "
10526 "WHERE oid = '%u'::pg_catalog.oid",
10527 opfinfo->dobj.catId.oid);
10529 res = PQexec(g_conn, query->data);
10530 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10532 /* Expecting a single result only */
10533 ntups = PQntuples(res);
10536 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10537 "query returned %d rows instead of one: %s\n",
10539 ntups, query->data);
10543 i_amname = PQfnumber(res, "amname");
10545 /* amname will still be needed after we PQclear res */
10546 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10549 * DROP must be fully qualified in case same name appears in pg_catalog
10551 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10552 fmtId(opfinfo->dobj.namespace->dobj.name));
10553 appendPQExpBuffer(delq, ".%s",
10554 fmtId(opfinfo->dobj.name));
10555 appendPQExpBuffer(delq, " USING %s;\n",
10558 /* Build the fixed portion of the CREATE command */
10559 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10560 fmtId(opfinfo->dobj.name));
10561 appendPQExpBuffer(q, " USING %s;\n",
10566 /* Do we need an ALTER to add loose members? */
10567 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10569 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10570 fmtId(opfinfo->dobj.name));
10571 appendPQExpBuffer(q, " USING %s ADD\n ",
10577 * Now fetch and print the OPERATOR entries (pg_amop rows).
10579 ntups = PQntuples(res_ops);
10581 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10582 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10583 i_amopopr = PQfnumber(res_ops, "amopopr");
10584 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10585 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10587 for (i = 0; i < ntups; i++)
10589 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10590 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10591 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10592 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10593 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10596 appendPQExpBuffer(q, " ,\n ");
10598 appendPQExpBuffer(q, "OPERATOR %s %s",
10599 amopstrategy, amopopr);
10601 if (strlen(sortfamily) > 0)
10603 appendPQExpBuffer(q, " FOR ORDER BY ");
10604 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10605 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10606 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10609 if (strcmp(amopreqcheck, "t") == 0)
10610 appendPQExpBuffer(q, " RECHECK");
10616 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10618 ntups = PQntuples(res_procs);
10620 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10621 i_amproc = PQfnumber(res_procs, "amproc");
10622 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10623 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10625 for (i = 0; i < ntups; i++)
10627 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10628 amproc = PQgetvalue(res_procs, i, i_amproc);
10629 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10630 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10633 appendPQExpBuffer(q, " ,\n ");
10635 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10636 amprocnum, amproclefttype, amprocrighttype,
10642 appendPQExpBuffer(q, ";\n");
10645 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10646 fmtId(opfinfo->dobj.name));
10647 appendPQExpBuffer(labelq, " USING %s",
10650 if (binary_upgrade)
10651 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10653 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10654 opfinfo->dobj.name,
10655 opfinfo->dobj.namespace->dobj.name,
10658 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10659 q->data, delq->data, NULL,
10660 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10663 /* Dump Operator Family Comments */
10664 dumpComment(fout, labelq->data,
10665 NULL, opfinfo->rolname,
10666 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10670 PQclear(res_procs);
10671 destroyPQExpBuffer(query);
10672 destroyPQExpBuffer(q);
10673 destroyPQExpBuffer(delq);
10674 destroyPQExpBuffer(labelq);
10679 * write out a single collation definition
10682 dumpCollation(Archive *fout, CollInfo *collinfo)
10687 PQExpBuffer labelq;
10692 const char *collcollate;
10693 const char *collctype;
10695 /* Skip if not to be dumped */
10696 if (!collinfo->dobj.dump || dataOnly)
10699 query = createPQExpBuffer();
10700 q = createPQExpBuffer();
10701 delq = createPQExpBuffer();
10702 labelq = createPQExpBuffer();
10704 /* Make sure we are in proper schema */
10705 selectSourceSchema(collinfo->dobj.namespace->dobj.name);
10707 /* Get conversion-specific details */
10708 appendPQExpBuffer(query, "SELECT "
10711 "FROM pg_catalog.pg_collation c "
10712 "WHERE c.oid = '%u'::pg_catalog.oid",
10713 collinfo->dobj.catId.oid);
10715 res = PQexec(g_conn, query->data);
10716 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10718 /* Expecting a single result only */
10719 ntups = PQntuples(res);
10722 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10723 "query returned %d rows instead of one: %s\n",
10725 ntups, query->data);
10729 i_collcollate = PQfnumber(res, "collcollate");
10730 i_collctype = PQfnumber(res, "collctype");
10732 collcollate = PQgetvalue(res, 0, i_collcollate);
10733 collctype = PQgetvalue(res, 0, i_collctype);
10736 * DROP must be fully qualified in case same name appears in pg_catalog
10738 appendPQExpBuffer(delq, "DROP COLLATION %s",
10739 fmtId(collinfo->dobj.namespace->dobj.name));
10740 appendPQExpBuffer(delq, ".%s;\n",
10741 fmtId(collinfo->dobj.name));
10743 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10744 fmtId(collinfo->dobj.name));
10745 appendStringLiteralAH(q, collcollate, fout);
10746 appendPQExpBuffer(q, ", lc_ctype = ");
10747 appendStringLiteralAH(q, collctype, fout);
10748 appendPQExpBuffer(q, ");\n");
10750 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10752 if (binary_upgrade)
10753 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10755 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10756 collinfo->dobj.name,
10757 collinfo->dobj.namespace->dobj.name,
10760 false, "COLLATION", SECTION_PRE_DATA,
10761 q->data, delq->data, NULL,
10762 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10765 /* Dump Collation Comments */
10766 dumpComment(fout, labelq->data,
10767 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10768 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10772 destroyPQExpBuffer(query);
10773 destroyPQExpBuffer(q);
10774 destroyPQExpBuffer(delq);
10775 destroyPQExpBuffer(labelq);
10780 * write out a single conversion definition
10783 dumpConversion(Archive *fout, ConvInfo *convinfo)
10788 PQExpBuffer labelq;
10791 int i_conforencoding;
10792 int i_contoencoding;
10795 const char *conforencoding;
10796 const char *contoencoding;
10797 const char *conproc;
10800 /* Skip if not to be dumped */
10801 if (!convinfo->dobj.dump || dataOnly)
10804 query = createPQExpBuffer();
10805 q = createPQExpBuffer();
10806 delq = createPQExpBuffer();
10807 labelq = createPQExpBuffer();
10809 /* Make sure we are in proper schema */
10810 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
10812 /* Get conversion-specific details */
10813 appendPQExpBuffer(query, "SELECT "
10814 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10815 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10816 "conproc, condefault "
10817 "FROM pg_catalog.pg_conversion c "
10818 "WHERE c.oid = '%u'::pg_catalog.oid",
10819 convinfo->dobj.catId.oid);
10821 res = PQexec(g_conn, query->data);
10822 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10824 /* Expecting a single result only */
10825 ntups = PQntuples(res);
10828 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10829 "query returned %d rows instead of one: %s\n",
10831 ntups, query->data);
10835 i_conforencoding = PQfnumber(res, "conforencoding");
10836 i_contoencoding = PQfnumber(res, "contoencoding");
10837 i_conproc = PQfnumber(res, "conproc");
10838 i_condefault = PQfnumber(res, "condefault");
10840 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10841 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10842 conproc = PQgetvalue(res, 0, i_conproc);
10843 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10846 * DROP must be fully qualified in case same name appears in pg_catalog
10848 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10849 fmtId(convinfo->dobj.namespace->dobj.name));
10850 appendPQExpBuffer(delq, ".%s;\n",
10851 fmtId(convinfo->dobj.name));
10853 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10854 (condefault) ? "DEFAULT " : "",
10855 fmtId(convinfo->dobj.name));
10856 appendStringLiteralAH(q, conforencoding, fout);
10857 appendPQExpBuffer(q, " TO ");
10858 appendStringLiteralAH(q, contoencoding, fout);
10859 /* regproc is automatically quoted in 7.3 and above */
10860 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10862 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10864 if (binary_upgrade)
10865 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10867 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10868 convinfo->dobj.name,
10869 convinfo->dobj.namespace->dobj.name,
10872 false, "CONVERSION", SECTION_PRE_DATA,
10873 q->data, delq->data, NULL,
10874 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10877 /* Dump Conversion Comments */
10878 dumpComment(fout, labelq->data,
10879 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10880 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10884 destroyPQExpBuffer(query);
10885 destroyPQExpBuffer(q);
10886 destroyPQExpBuffer(delq);
10887 destroyPQExpBuffer(labelq);
10891 * format_aggregate_signature: generate aggregate name and argument list
10893 * The argument type names are qualified if needed. The aggregate name
10894 * is never qualified.
10897 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10899 PQExpBufferData buf;
10902 initPQExpBuffer(&buf);
10904 appendPQExpBuffer(&buf, "%s",
10905 fmtId(agginfo->aggfn.dobj.name));
10907 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10909 if (agginfo->aggfn.nargs == 0)
10910 appendPQExpBuffer(&buf, "(*)");
10913 appendPQExpBuffer(&buf, "(");
10914 for (j = 0; j < agginfo->aggfn.nargs; j++)
10918 typname = getFormattedTypeName(agginfo->aggfn.argtypes[j], zeroAsOpaque);
10920 appendPQExpBuffer(&buf, "%s%s",
10921 (j > 0) ? ", " : "",
10925 appendPQExpBuffer(&buf, ")");
10932 * write out a single aggregate definition
10935 dumpAgg(Archive *fout, AggInfo *agginfo)
10940 PQExpBuffer labelq;
10941 PQExpBuffer details;
10949 int i_aggtranstype;
10952 const char *aggtransfn;
10953 const char *aggfinalfn;
10954 const char *aggsortop;
10955 const char *aggtranstype;
10956 const char *agginitval;
10959 /* Skip if not to be dumped */
10960 if (!agginfo->aggfn.dobj.dump || dataOnly)
10963 query = createPQExpBuffer();
10964 q = createPQExpBuffer();
10965 delq = createPQExpBuffer();
10966 labelq = createPQExpBuffer();
10967 details = createPQExpBuffer();
10969 /* Make sure we are in proper schema */
10970 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
10972 /* Get aggregate-specific details */
10973 if (g_fout->remoteVersion >= 80100)
10975 appendPQExpBuffer(query, "SELECT aggtransfn, "
10976 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10977 "aggsortop::pg_catalog.regoperator, "
10979 "'t'::boolean AS convertok "
10980 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10981 "WHERE a.aggfnoid = p.oid "
10982 "AND p.oid = '%u'::pg_catalog.oid",
10983 agginfo->aggfn.dobj.catId.oid);
10985 else if (g_fout->remoteVersion >= 70300)
10987 appendPQExpBuffer(query, "SELECT aggtransfn, "
10988 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10991 "'t'::boolean AS convertok "
10992 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10993 "WHERE a.aggfnoid = p.oid "
10994 "AND p.oid = '%u'::pg_catalog.oid",
10995 agginfo->aggfn.dobj.catId.oid);
10997 else if (g_fout->remoteVersion >= 70100)
10999 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11000 "format_type(aggtranstype, NULL) AS aggtranstype, "
11003 "'t'::boolean AS convertok "
11004 "FROM pg_aggregate "
11005 "WHERE oid = '%u'::oid",
11006 agginfo->aggfn.dobj.catId.oid);
11010 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11012 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11014 "agginitval1 AS agginitval, "
11015 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11016 "FROM pg_aggregate "
11017 "WHERE oid = '%u'::oid",
11018 agginfo->aggfn.dobj.catId.oid);
11021 res = PQexec(g_conn, query->data);
11022 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11024 /* Expecting a single result only */
11025 ntups = PQntuples(res);
11028 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11029 "query returned %d rows instead of one: %s\n",
11031 ntups, query->data);
11035 i_aggtransfn = PQfnumber(res, "aggtransfn");
11036 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11037 i_aggsortop = PQfnumber(res, "aggsortop");
11038 i_aggtranstype = PQfnumber(res, "aggtranstype");
11039 i_agginitval = PQfnumber(res, "agginitval");
11040 i_convertok = PQfnumber(res, "convertok");
11042 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11043 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11044 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11045 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11046 agginitval = PQgetvalue(res, 0, i_agginitval);
11047 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11049 aggsig = format_aggregate_signature(agginfo, fout, true);
11050 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11054 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11059 if (g_fout->remoteVersion >= 70300)
11061 /* If using 7.3's regproc or regtype, data is already quoted */
11062 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11066 else if (g_fout->remoteVersion >= 70100)
11068 /* format_type quotes, regproc does not */
11069 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11075 /* need quotes all around */
11076 appendPQExpBuffer(details, " SFUNC = %s,\n",
11077 fmtId(aggtransfn));
11078 appendPQExpBuffer(details, " STYPE = %s",
11079 fmtId(aggtranstype));
11082 if (!PQgetisnull(res, 0, i_agginitval))
11084 appendPQExpBuffer(details, ",\n INITCOND = ");
11085 appendStringLiteralAH(details, agginitval, fout);
11088 if (strcmp(aggfinalfn, "-") != 0)
11090 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11094 aggsortop = convertOperatorReference(aggsortop);
11097 appendPQExpBuffer(details, ",\n SORTOP = %s",
11102 * DROP must be fully qualified in case same name appears in pg_catalog
11104 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11105 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11108 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11109 aggsig, details->data);
11111 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11113 if (binary_upgrade)
11114 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11116 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11118 agginfo->aggfn.dobj.namespace->dobj.name,
11120 agginfo->aggfn.rolname,
11121 false, "AGGREGATE", SECTION_PRE_DATA,
11122 q->data, delq->data, NULL,
11123 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
11126 /* Dump Aggregate Comments */
11127 dumpComment(fout, labelq->data,
11128 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11129 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11130 dumpSecLabel(fout, labelq->data,
11131 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11132 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11135 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11136 * command look like a function's GRANT; in particular this affects the
11137 * syntax for zero-argument aggregates.
11142 aggsig = format_function_signature(&agginfo->aggfn, true);
11143 aggsig_tag = format_function_signature(&agginfo->aggfn, false);
11145 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11147 aggsig, NULL, aggsig_tag,
11148 agginfo->aggfn.dobj.namespace->dobj.name,
11149 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11156 destroyPQExpBuffer(query);
11157 destroyPQExpBuffer(q);
11158 destroyPQExpBuffer(delq);
11159 destroyPQExpBuffer(labelq);
11160 destroyPQExpBuffer(details);
11165 * write out a single text search parser
11168 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11172 PQExpBuffer labelq;
11174 /* Skip if not to be dumped */
11175 if (!prsinfo->dobj.dump || dataOnly)
11178 q = createPQExpBuffer();
11179 delq = createPQExpBuffer();
11180 labelq = createPQExpBuffer();
11182 /* Make sure we are in proper schema */
11183 selectSourceSchema(prsinfo->dobj.namespace->dobj.name);
11185 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11186 fmtId(prsinfo->dobj.name));
11188 appendPQExpBuffer(q, " START = %s,\n",
11189 convertTSFunction(prsinfo->prsstart));
11190 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11191 convertTSFunction(prsinfo->prstoken));
11192 appendPQExpBuffer(q, " END = %s,\n",
11193 convertTSFunction(prsinfo->prsend));
11194 if (prsinfo->prsheadline != InvalidOid)
11195 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11196 convertTSFunction(prsinfo->prsheadline));
11197 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11198 convertTSFunction(prsinfo->prslextype));
11201 * DROP must be fully qualified in case same name appears in pg_catalog
11203 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11204 fmtId(prsinfo->dobj.namespace->dobj.name));
11205 appendPQExpBuffer(delq, ".%s;\n",
11206 fmtId(prsinfo->dobj.name));
11208 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11209 fmtId(prsinfo->dobj.name));
11211 if (binary_upgrade)
11212 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11214 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11215 prsinfo->dobj.name,
11216 prsinfo->dobj.namespace->dobj.name,
11219 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11220 q->data, delq->data, NULL,
11221 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11224 /* Dump Parser Comments */
11225 dumpComment(fout, labelq->data,
11227 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11229 destroyPQExpBuffer(q);
11230 destroyPQExpBuffer(delq);
11231 destroyPQExpBuffer(labelq);
11236 * write out a single text search dictionary
11239 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11243 PQExpBuffer labelq;
11250 /* Skip if not to be dumped */
11251 if (!dictinfo->dobj.dump || dataOnly)
11254 q = createPQExpBuffer();
11255 delq = createPQExpBuffer();
11256 labelq = createPQExpBuffer();
11257 query = createPQExpBuffer();
11259 /* Fetch name and namespace of the dictionary's template */
11260 selectSourceSchema("pg_catalog");
11261 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11262 "FROM pg_ts_template p, pg_namespace n "
11263 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11264 dictinfo->dicttemplate);
11265 res = PQexec(g_conn, query->data);
11266 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11267 ntups = PQntuples(res);
11270 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11271 "query returned %d rows instead of one: %s\n",
11273 ntups, query->data);
11276 nspname = PQgetvalue(res, 0, 0);
11277 tmplname = PQgetvalue(res, 0, 1);
11279 /* Make sure we are in proper schema */
11280 selectSourceSchema(dictinfo->dobj.namespace->dobj.name);
11282 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11283 fmtId(dictinfo->dobj.name));
11285 appendPQExpBuffer(q, " TEMPLATE = ");
11286 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11287 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11288 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11292 /* the dictinitoption can be dumped straight into the command */
11293 if (dictinfo->dictinitoption)
11294 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11296 appendPQExpBuffer(q, " );\n");
11299 * DROP must be fully qualified in case same name appears in pg_catalog
11301 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11302 fmtId(dictinfo->dobj.namespace->dobj.name));
11303 appendPQExpBuffer(delq, ".%s;\n",
11304 fmtId(dictinfo->dobj.name));
11306 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11307 fmtId(dictinfo->dobj.name));
11309 if (binary_upgrade)
11310 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11312 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11313 dictinfo->dobj.name,
11314 dictinfo->dobj.namespace->dobj.name,
11317 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11318 q->data, delq->data, NULL,
11319 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11322 /* Dump Dictionary Comments */
11323 dumpComment(fout, labelq->data,
11324 NULL, dictinfo->rolname,
11325 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11327 destroyPQExpBuffer(q);
11328 destroyPQExpBuffer(delq);
11329 destroyPQExpBuffer(labelq);
11330 destroyPQExpBuffer(query);
11335 * write out a single text search template
11338 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11342 PQExpBuffer labelq;
11344 /* Skip if not to be dumped */
11345 if (!tmplinfo->dobj.dump || dataOnly)
11348 q = createPQExpBuffer();
11349 delq = createPQExpBuffer();
11350 labelq = createPQExpBuffer();
11352 /* Make sure we are in proper schema */
11353 selectSourceSchema(tmplinfo->dobj.namespace->dobj.name);
11355 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11356 fmtId(tmplinfo->dobj.name));
11358 if (tmplinfo->tmplinit != InvalidOid)
11359 appendPQExpBuffer(q, " INIT = %s,\n",
11360 convertTSFunction(tmplinfo->tmplinit));
11361 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11362 convertTSFunction(tmplinfo->tmpllexize));
11365 * DROP must be fully qualified in case same name appears in pg_catalog
11367 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11368 fmtId(tmplinfo->dobj.namespace->dobj.name));
11369 appendPQExpBuffer(delq, ".%s;\n",
11370 fmtId(tmplinfo->dobj.name));
11372 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11373 fmtId(tmplinfo->dobj.name));
11375 if (binary_upgrade)
11376 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11378 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11379 tmplinfo->dobj.name,
11380 tmplinfo->dobj.namespace->dobj.name,
11383 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11384 q->data, delq->data, NULL,
11385 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11388 /* Dump Template Comments */
11389 dumpComment(fout, labelq->data,
11391 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11393 destroyPQExpBuffer(q);
11394 destroyPQExpBuffer(delq);
11395 destroyPQExpBuffer(labelq);
11400 * write out a single text search configuration
11403 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11407 PQExpBuffer labelq;
11417 /* Skip if not to be dumped */
11418 if (!cfginfo->dobj.dump || dataOnly)
11421 q = createPQExpBuffer();
11422 delq = createPQExpBuffer();
11423 labelq = createPQExpBuffer();
11424 query = createPQExpBuffer();
11426 /* Fetch name and namespace of the config's parser */
11427 selectSourceSchema("pg_catalog");
11428 appendPQExpBuffer(query, "SELECT nspname, prsname "
11429 "FROM pg_ts_parser p, pg_namespace n "
11430 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11431 cfginfo->cfgparser);
11432 res = PQexec(g_conn, query->data);
11433 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11434 ntups = PQntuples(res);
11437 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11438 "query returned %d rows instead of one: %s\n",
11440 ntups, query->data);
11443 nspname = PQgetvalue(res, 0, 0);
11444 prsname = PQgetvalue(res, 0, 1);
11446 /* Make sure we are in proper schema */
11447 selectSourceSchema(cfginfo->dobj.namespace->dobj.name);
11449 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11450 fmtId(cfginfo->dobj.name));
11452 appendPQExpBuffer(q, " PARSER = ");
11453 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11454 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11455 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11459 resetPQExpBuffer(query);
11460 appendPQExpBuffer(query,
11462 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11463 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11464 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11465 "FROM pg_catalog.pg_ts_config_map AS m \n"
11466 "WHERE m.mapcfg = '%u' \n"
11467 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11468 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11470 res = PQexec(g_conn, query->data);
11471 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11472 ntups = PQntuples(res);
11474 i_tokenname = PQfnumber(res, "tokenname");
11475 i_dictname = PQfnumber(res, "dictname");
11477 for (i = 0; i < ntups; i++)
11479 char *tokenname = PQgetvalue(res, i, i_tokenname);
11480 char *dictname = PQgetvalue(res, i, i_dictname);
11483 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11485 /* starting a new token type, so start a new command */
11487 appendPQExpBuffer(q, ";\n");
11488 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11489 fmtId(cfginfo->dobj.name));
11490 /* tokenname needs quoting, dictname does NOT */
11491 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11492 fmtId(tokenname), dictname);
11495 appendPQExpBuffer(q, ", %s", dictname);
11499 appendPQExpBuffer(q, ";\n");
11504 * DROP must be fully qualified in case same name appears in pg_catalog
11506 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11507 fmtId(cfginfo->dobj.namespace->dobj.name));
11508 appendPQExpBuffer(delq, ".%s;\n",
11509 fmtId(cfginfo->dobj.name));
11511 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11512 fmtId(cfginfo->dobj.name));
11514 if (binary_upgrade)
11515 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11517 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11518 cfginfo->dobj.name,
11519 cfginfo->dobj.namespace->dobj.name,
11522 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11523 q->data, delq->data, NULL,
11524 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11527 /* Dump Configuration Comments */
11528 dumpComment(fout, labelq->data,
11529 NULL, cfginfo->rolname,
11530 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11532 destroyPQExpBuffer(q);
11533 destroyPQExpBuffer(delq);
11534 destroyPQExpBuffer(labelq);
11535 destroyPQExpBuffer(query);
11539 * dumpForeignDataWrapper
11540 * write out a single foreign-data wrapper definition
11543 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11547 PQExpBuffer labelq;
11550 /* Skip if not to be dumped */
11551 if (!fdwinfo->dobj.dump || dataOnly)
11555 * FDWs that belong to an extension are dumped based on their "dump"
11556 * field. Otherwise omit them if we are only dumping some specific object.
11558 if (!fdwinfo->dobj.ext_member)
11559 if (!include_everything)
11562 q = createPQExpBuffer();
11563 delq = createPQExpBuffer();
11564 labelq = createPQExpBuffer();
11566 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11568 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11571 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11572 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11574 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11575 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11577 if (strlen(fdwinfo->fdwoptions) > 0)
11578 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11580 appendPQExpBuffer(q, ";\n");
11582 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11585 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11588 if (binary_upgrade)
11589 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11591 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11592 fdwinfo->dobj.name,
11596 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11597 q->data, delq->data, NULL,
11598 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11601 /* Handle the ACL */
11602 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11603 "FOREIGN DATA WRAPPER",
11604 qfdwname, NULL, fdwinfo->dobj.name,
11605 NULL, fdwinfo->rolname,
11608 /* Dump Foreign Data Wrapper Comments */
11609 dumpComment(fout, labelq->data,
11610 NULL, fdwinfo->rolname,
11611 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11615 destroyPQExpBuffer(q);
11616 destroyPQExpBuffer(delq);
11617 destroyPQExpBuffer(labelq);
11621 * dumpForeignServer
11622 * write out a foreign server definition
11625 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11629 PQExpBuffer labelq;
11636 /* Skip if not to be dumped */
11637 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11640 q = createPQExpBuffer();
11641 delq = createPQExpBuffer();
11642 labelq = createPQExpBuffer();
11643 query = createPQExpBuffer();
11645 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11647 /* look up the foreign-data wrapper */
11648 selectSourceSchema("pg_catalog");
11649 appendPQExpBuffer(query, "SELECT fdwname "
11650 "FROM pg_foreign_data_wrapper w "
11651 "WHERE w.oid = '%u'",
11653 res = PQexec(g_conn, query->data);
11654 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11655 ntups = PQntuples(res);
11658 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11659 "query returned %d rows instead of one: %s\n",
11661 ntups, query->data);
11664 fdwname = PQgetvalue(res, 0, 0);
11666 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11667 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11669 appendPQExpBuffer(q, " TYPE ");
11670 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11672 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11674 appendPQExpBuffer(q, " VERSION ");
11675 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11678 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11679 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11681 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11682 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11684 appendPQExpBuffer(q, ";\n");
11686 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11689 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11691 if (binary_upgrade)
11692 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11694 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11695 srvinfo->dobj.name,
11699 false, "SERVER", SECTION_PRE_DATA,
11700 q->data, delq->data, NULL,
11701 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11704 /* Handle the ACL */
11705 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11707 qsrvname, NULL, srvinfo->dobj.name,
11708 NULL, srvinfo->rolname,
11711 /* Dump user mappings */
11712 dumpUserMappings(fout,
11713 srvinfo->dobj.name, NULL,
11715 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11717 /* Dump Foreign Server Comments */
11718 dumpComment(fout, labelq->data,
11719 NULL, srvinfo->rolname,
11720 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11724 destroyPQExpBuffer(q);
11725 destroyPQExpBuffer(delq);
11726 destroyPQExpBuffer(labelq);
11732 * This routine is used to dump any user mappings associated with the
11733 * server handed to this routine. Should be called after ArchiveEntry()
11737 dumpUserMappings(Archive *fout,
11738 const char *servername, const char *namespace,
11740 CatalogId catalogId, DumpId dumpId)
11752 q = createPQExpBuffer();
11753 tag = createPQExpBuffer();
11754 delq = createPQExpBuffer();
11755 query = createPQExpBuffer();
11758 * We read from the publicly accessible view pg_user_mappings, so as not
11759 * to fail if run by a non-superuser. Note that the view will show
11760 * umoptions as null if the user hasn't got privileges for the associated
11761 * server; this means that pg_dump will dump such a mapping, but with no
11762 * OPTIONS clause. A possible alternative is to skip such mappings
11763 * altogether, but it's not clear that that's an improvement.
11765 selectSourceSchema("pg_catalog");
11767 appendPQExpBuffer(query,
11769 "array_to_string(ARRAY("
11770 "SELECT quote_ident(option_name) || ' ' || "
11771 "quote_literal(option_value) "
11772 "FROM pg_options_to_table(umoptions)"
11773 "), E',\n ') AS umoptions "
11774 "FROM pg_user_mappings "
11775 "WHERE srvid = '%u' "
11776 "ORDER BY usename",
11779 res = PQexec(g_conn, query->data);
11780 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11782 ntups = PQntuples(res);
11783 i_usename = PQfnumber(res, "usename");
11784 i_umoptions = PQfnumber(res, "umoptions");
11786 for (i = 0; i < ntups; i++)
11791 usename = PQgetvalue(res, i, i_usename);
11792 umoptions = PQgetvalue(res, i, i_umoptions);
11794 resetPQExpBuffer(q);
11795 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11796 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11798 if (umoptions && strlen(umoptions) > 0)
11799 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11801 appendPQExpBuffer(q, ";\n");
11803 resetPQExpBuffer(delq);
11804 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11805 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11807 resetPQExpBuffer(tag);
11808 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11809 usename, servername);
11811 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11816 "USER MAPPING", SECTION_PRE_DATA,
11817 q->data, delq->data, NULL,
11824 destroyPQExpBuffer(query);
11825 destroyPQExpBuffer(delq);
11826 destroyPQExpBuffer(q);
11830 * Write out default privileges information
11833 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11839 /* Skip if not to be dumped */
11840 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11843 q = createPQExpBuffer();
11844 tag = createPQExpBuffer();
11846 switch (daclinfo->defaclobjtype)
11848 case DEFACLOBJ_RELATION:
11851 case DEFACLOBJ_SEQUENCE:
11852 type = "SEQUENCES";
11854 case DEFACLOBJ_FUNCTION:
11855 type = "FUNCTIONS";
11858 /* shouldn't get here */
11859 write_msg(NULL, "unknown object type (%d) in default privileges\n",
11860 (int) daclinfo->defaclobjtype);
11862 type = ""; /* keep compiler quiet */
11865 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11867 /* build the actual command(s) for this tuple */
11868 if (!buildDefaultACLCommands(type,
11869 daclinfo->dobj.namespace != NULL ?
11870 daclinfo->dobj.namespace->dobj.name : NULL,
11871 daclinfo->defaclacl,
11872 daclinfo->defaclrole,
11873 fout->remoteVersion,
11876 write_msg(NULL, "could not parse default ACL list (%s)\n",
11877 daclinfo->defaclacl);
11881 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11883 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11885 daclinfo->defaclrole,
11886 false, "DEFAULT ACL", SECTION_NONE,
11888 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11891 destroyPQExpBuffer(tag);
11892 destroyPQExpBuffer(q);
11896 * Write out grant/revoke information
11898 * 'objCatId' is the catalog ID of the underlying object.
11899 * 'objDumpId' is the dump ID of the underlying object.
11900 * 'type' must be one of
11901 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11902 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11903 * 'name' is the formatted name of the object. Must be quoted etc. already.
11904 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11905 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11906 * 'nspname' is the namespace the object is in (NULL if none).
11907 * 'owner' is the owner, NULL if there is no owner (for languages).
11908 * 'acls' is the string read out of the fooacl system catalog field;
11909 * it will be parsed here.
11913 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11914 const char *type, const char *name, const char *subname,
11915 const char *tag, const char *nspname, const char *owner,
11920 /* Do nothing if ACL dump is not enabled */
11924 /* --data-only skips ACLs *except* BLOB ACLs */
11925 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11928 sql = createPQExpBuffer();
11930 if (!buildACLCommands(name, subname, type, acls, owner,
11931 "", fout->remoteVersion, sql))
11933 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11939 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11942 owner ? owner : "",
11943 false, "ACL", SECTION_NONE,
11944 sql->data, "", NULL,
11948 destroyPQExpBuffer(sql);
11954 * This routine is used to dump any security labels associated with the
11955 * object handed to this routine. The routine takes a constant character
11956 * string for the target part of the security-label command, plus
11957 * the namespace and owner of the object (for labeling the ArchiveEntry),
11958 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11959 * plus the dump ID for the object (for setting a dependency).
11960 * If a matching pg_seclabel entry is found, it is dumped.
11962 * Note: although this routine takes a dumpId for dependency purposes,
11963 * that purpose is just to mark the dependency in the emitted dump file
11964 * for possible future use by pg_restore. We do NOT use it for determining
11965 * ordering of the label in the dump file, because this routine is called
11966 * after dependency sorting occurs. This routine should be called just after
11967 * calling ArchiveEntry() for the specified object.
11970 dumpSecLabel(Archive *fout, const char *target,
11971 const char *namespace, const char *owner,
11972 CatalogId catalogId, int subid, DumpId dumpId)
11974 SecLabelItem *labels;
11979 /* do nothing, if --no-security-labels is supplied */
11980 if (no_security_labels)
11983 /* Comments are schema not data ... except blob comments are data */
11984 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11995 /* Search for security labels associated with catalogId, using table */
11996 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11998 query = createPQExpBuffer();
12000 for (i = 0; i < nlabels; i++)
12003 * Ignore label entries for which the subid doesn't match.
12005 if (labels[i].objsubid != subid)
12008 appendPQExpBuffer(query,
12009 "SECURITY LABEL FOR %s ON %s IS ",
12010 fmtId(labels[i].provider), target);
12011 appendStringLiteralAH(query, labels[i].label, fout);
12012 appendPQExpBuffer(query, ";\n");
12015 if (query->len > 0)
12017 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12018 target, namespace, NULL, owner,
12019 false, "SECURITY LABEL", SECTION_NONE,
12020 query->data, "", NULL,
12024 destroyPQExpBuffer(query);
12028 * dumpTableSecLabel
12030 * As above, but dump security label for both the specified table (or view)
12034 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12036 SecLabelItem *labels;
12040 PQExpBuffer target;
12042 /* do nothing, if --no-security-labels is supplied */
12043 if (no_security_labels)
12046 /* SecLabel are SCHEMA not data */
12050 /* Search for comments associated with relation, using table */
12051 nlabels = findSecLabels(fout,
12052 tbinfo->dobj.catId.tableoid,
12053 tbinfo->dobj.catId.oid,
12056 /* If security labels exist, build SECURITY LABEL statements */
12060 query = createPQExpBuffer();
12061 target = createPQExpBuffer();
12063 for (i = 0; i < nlabels; i++)
12065 const char *colname;
12066 const char *provider = labels[i].provider;
12067 const char *label = labels[i].label;
12068 int objsubid = labels[i].objsubid;
12070 resetPQExpBuffer(target);
12073 appendPQExpBuffer(target, "%s %s", reltypename,
12074 fmtId(tbinfo->dobj.name));
12078 colname = getAttrName(objsubid, tbinfo);
12079 /* first fmtId result must be consumed before calling it again */
12080 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12081 appendPQExpBuffer(target, ".%s", fmtId(colname));
12083 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12084 fmtId(provider), target->data);
12085 appendStringLiteralAH(query, label, fout);
12086 appendPQExpBuffer(query, ";\n");
12088 if (query->len > 0)
12090 resetPQExpBuffer(target);
12091 appendPQExpBuffer(target, "%s %s", reltypename,
12092 fmtId(tbinfo->dobj.name));
12093 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12095 tbinfo->dobj.namespace->dobj.name,
12096 NULL, tbinfo->rolname,
12097 false, "SECURITY LABEL", SECTION_NONE,
12098 query->data, "", NULL,
12099 &(tbinfo->dobj.dumpId), 1,
12102 destroyPQExpBuffer(query);
12103 destroyPQExpBuffer(target);
12109 * Find the security label(s), if any, associated with the given object.
12110 * All the objsubid values associated with the given classoid/objoid are
12111 * found with one search.
12114 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12116 /* static storage for table of security labels */
12117 static SecLabelItem *labels = NULL;
12118 static int nlabels = -1;
12120 SecLabelItem *middle = NULL;
12122 SecLabelItem *high;
12125 /* Get security labels if we didn't already */
12127 nlabels = collectSecLabels(fout, &labels);
12129 if (nlabels <= 0) /* no labels, so no match is possible */
12136 * Do binary search to find some item matching the object.
12139 high = &labels[nlabels - 1];
12140 while (low <= high)
12142 middle = low + (high - low) / 2;
12144 if (classoid < middle->classoid)
12146 else if (classoid > middle->classoid)
12148 else if (objoid < middle->objoid)
12150 else if (objoid > middle->objoid)
12153 break; /* found a match */
12156 if (low > high) /* no matches */
12163 * Now determine how many items match the object. The search loop
12164 * invariant still holds: only items between low and high inclusive could
12168 while (middle > low)
12170 if (classoid != middle[-1].classoid ||
12171 objoid != middle[-1].objoid)
12180 while (middle <= high)
12182 if (classoid != middle->classoid ||
12183 objoid != middle->objoid)
12195 * Construct a table of all security labels available for database objects.
12196 * It's much faster to pull them all at once.
12198 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12201 collectSecLabels(Archive *fout, SecLabelItem **items)
12212 SecLabelItem *labels;
12214 query = createPQExpBuffer();
12216 appendPQExpBuffer(query,
12217 "SELECT label, provider, classoid, objoid, objsubid "
12218 "FROM pg_catalog.pg_seclabel "
12219 "ORDER BY classoid, objoid, objsubid");
12221 res = PQexec(g_conn, query->data);
12222 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12224 /* Construct lookup table containing OIDs in numeric form */
12225 i_label = PQfnumber(res, "label");
12226 i_provider = PQfnumber(res, "provider");
12227 i_classoid = PQfnumber(res, "classoid");
12228 i_objoid = PQfnumber(res, "objoid");
12229 i_objsubid = PQfnumber(res, "objsubid");
12231 ntups = PQntuples(res);
12233 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12235 for (i = 0; i < ntups; i++)
12237 labels[i].label = PQgetvalue(res, i, i_label);
12238 labels[i].provider = PQgetvalue(res, i, i_provider);
12239 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12240 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12241 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12244 /* Do NOT free the PGresult since we are keeping pointers into it */
12245 destroyPQExpBuffer(query);
12253 * write out to fout the declarations (not data) of a user-defined table
12256 dumpTable(Archive *fout, TableInfo *tbinfo)
12258 if (tbinfo->dobj.dump)
12262 if (tbinfo->relkind == RELKIND_SEQUENCE)
12263 dumpSequence(fout, tbinfo);
12264 else if (!dataOnly)
12265 dumpTableSchema(fout, tbinfo);
12267 /* Handle the ACL here */
12268 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12269 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12270 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12272 namecopy, NULL, tbinfo->dobj.name,
12273 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12277 * Handle column ACLs, if any. Note: we pull these with a separate
12278 * query rather than trying to fetch them during getTableAttrs, so
12279 * that we won't miss ACLs on system columns.
12281 if (g_fout->remoteVersion >= 80400)
12283 PQExpBuffer query = createPQExpBuffer();
12287 appendPQExpBuffer(query,
12288 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12289 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12291 tbinfo->dobj.catId.oid);
12292 res = PQexec(g_conn, query->data);
12293 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12295 for (i = 0; i < PQntuples(res); i++)
12297 char *attname = PQgetvalue(res, i, 0);
12298 char *attacl = PQgetvalue(res, i, 1);
12302 attnamecopy = pg_strdup(fmtId(attname));
12303 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12304 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12305 /* Column's GRANT type is always TABLE */
12306 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12307 namecopy, attnamecopy, acltag,
12308 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12314 destroyPQExpBuffer(query);
12323 * write the declaration (not data) of one user-defined table or view
12326 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12328 PQExpBuffer query = createPQExpBuffer();
12329 PQExpBuffer q = createPQExpBuffer();
12330 PQExpBuffer delq = createPQExpBuffer();
12331 PQExpBuffer labelq = createPQExpBuffer();
12334 TableInfo **parents;
12335 int actual_atts; /* number of attrs in this CREATE statment */
12336 const char *reltypename;
12343 /* Make sure we are in proper schema */
12344 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
12346 if (binary_upgrade)
12347 binary_upgrade_set_type_oids_by_rel_oid(q,
12348 tbinfo->dobj.catId.oid);
12350 /* Is it a table or a view? */
12351 if (tbinfo->relkind == RELKIND_VIEW)
12355 reltypename = "VIEW";
12357 /* Fetch the view definition */
12358 if (g_fout->remoteVersion >= 70300)
12360 /* Beginning in 7.3, viewname is not unique; rely on OID */
12361 appendPQExpBuffer(query,
12362 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12363 tbinfo->dobj.catId.oid);
12367 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12368 "FROM pg_views WHERE viewname = ");
12369 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12370 appendPQExpBuffer(query, ";");
12373 res = PQexec(g_conn, query->data);
12374 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12376 if (PQntuples(res) != 1)
12378 if (PQntuples(res) < 1)
12379 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12380 tbinfo->dobj.name);
12382 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12383 tbinfo->dobj.name);
12387 viewdef = PQgetvalue(res, 0, 0);
12389 if (strlen(viewdef) == 0)
12391 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12392 tbinfo->dobj.name);
12397 * DROP must be fully qualified in case same name appears in
12400 appendPQExpBuffer(delq, "DROP VIEW %s.",
12401 fmtId(tbinfo->dobj.namespace->dobj.name));
12402 appendPQExpBuffer(delq, "%s;\n",
12403 fmtId(tbinfo->dobj.name));
12405 if (binary_upgrade)
12406 binary_upgrade_set_pg_class_oids(q, tbinfo->dobj.catId.oid, false);
12408 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12409 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12410 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12411 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12413 appendPQExpBuffer(labelq, "VIEW %s",
12414 fmtId(tbinfo->dobj.name));
12420 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12425 reltypename = "FOREIGN TABLE";
12427 /* retrieve name of foreign server and generic options */
12428 appendPQExpBuffer(query,
12429 "SELECT fs.srvname, "
12430 "pg_catalog.array_to_string(ARRAY("
12431 "SELECT pg_catalog.quote_ident(option_name) || "
12432 "' ' || pg_catalog.quote_literal(option_value) "
12433 "FROM pg_catalog.pg_options_to_table(ftoptions)"
12434 "), E',\n ') AS ftoptions "
12435 "FROM pg_catalog.pg_foreign_table ft "
12436 "JOIN pg_catalog.pg_foreign_server fs "
12437 "ON (fs.oid = ft.ftserver) "
12438 "WHERE ft.ftrelid = '%u'",
12439 tbinfo->dobj.catId.oid);
12440 res = PQexec(g_conn, query->data);
12441 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12442 if (PQntuples(res) != 1)
12444 write_msg(NULL, ngettext("query returned %d foreign server entry for foreign table \"%s\"\n",
12445 "query returned %d foreign server entries for foreign table \"%s\"\n",
12447 PQntuples(res), tbinfo->dobj.name);
12450 i_srvname = PQfnumber(res, "srvname");
12451 i_ftoptions = PQfnumber(res, "ftoptions");
12452 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12453 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12458 reltypename = "TABLE";
12462 numParents = tbinfo->numParents;
12463 parents = tbinfo->parents;
12466 * DROP must be fully qualified in case same name appears in
12469 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12470 fmtId(tbinfo->dobj.namespace->dobj.name));
12471 appendPQExpBuffer(delq, "%s;\n",
12472 fmtId(tbinfo->dobj.name));
12474 appendPQExpBuffer(labelq, "%s %s", reltypename,
12475 fmtId(tbinfo->dobj.name));
12477 if (binary_upgrade)
12478 binary_upgrade_set_pg_class_oids(q, tbinfo->dobj.catId.oid, false);
12480 appendPQExpBuffer(q, "CREATE %s%s %s",
12481 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12484 fmtId(tbinfo->dobj.name));
12487 * In case of a binary upgrade, we dump the table normally and attach
12488 * it to the type afterward.
12490 if (tbinfo->reloftype && !binary_upgrade)
12491 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12493 for (j = 0; j < tbinfo->numatts; j++)
12496 * Normally, dump if it's one of the table's own attrs, and not
12497 * dropped. But for binary upgrade, dump all the columns.
12499 if ((!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j]) ||
12503 * Default value --- suppress if inherited (except in
12504 * binary-upgrade case, where we're not doing normal
12505 * inheritance) or if it's to be printed separately.
12507 bool has_default = (tbinfo->attrdefs[j] != NULL
12508 && (!tbinfo->inhAttrDef[j] || binary_upgrade)
12509 && !tbinfo->attrdefs[j]->separate);
12512 * Not Null constraint --- suppress if inherited, except in
12513 * binary-upgrade case.
12515 bool has_notnull = (tbinfo->notnull[j]
12516 && (!tbinfo->inhNotNull[j] || binary_upgrade));
12518 if (tbinfo->reloftype && !has_default && !has_notnull && !binary_upgrade)
12521 /* Format properly if not first attr */
12522 if (actual_atts == 0)
12523 appendPQExpBuffer(q, " (");
12525 appendPQExpBuffer(q, ",");
12526 appendPQExpBuffer(q, "\n ");
12529 /* Attribute name */
12530 appendPQExpBuffer(q, "%s ",
12531 fmtId(tbinfo->attnames[j]));
12533 if (tbinfo->attisdropped[j])
12536 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12537 * so we will not have gotten a valid type name; insert
12538 * INTEGER as a stopgap. We'll clean things up later.
12540 appendPQExpBuffer(q, "INTEGER /* dummy */");
12541 /* Skip all the rest, too */
12545 /* Attribute type */
12546 if (tbinfo->reloftype && !binary_upgrade)
12548 appendPQExpBuffer(q, "WITH OPTIONS");
12550 else if (g_fout->remoteVersion >= 70100)
12552 appendPQExpBuffer(q, "%s",
12553 tbinfo->atttypnames[j]);
12557 /* If no format_type, fake it */
12558 appendPQExpBuffer(q, "%s",
12559 myFormatType(tbinfo->atttypnames[j],
12560 tbinfo->atttypmod[j]));
12563 /* Add collation if not default for the type */
12564 if (OidIsValid(tbinfo->attcollation[j]))
12568 coll = findCollationByOid(tbinfo->attcollation[j]);
12571 /* always schema-qualify, don't try to be smart */
12572 appendPQExpBuffer(q, " COLLATE %s.",
12573 fmtId(coll->dobj.namespace->dobj.name));
12574 appendPQExpBuffer(q, "%s",
12575 fmtId(coll->dobj.name));
12580 appendPQExpBuffer(q, " DEFAULT %s",
12581 tbinfo->attrdefs[j]->adef_expr);
12584 appendPQExpBuffer(q, " NOT NULL");
12589 * Add non-inherited CHECK constraints, if any.
12591 for (j = 0; j < tbinfo->ncheck; j++)
12593 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12595 if (constr->separate || !constr->conislocal)
12598 if (actual_atts == 0)
12599 appendPQExpBuffer(q, " (\n ");
12601 appendPQExpBuffer(q, ",\n ");
12603 appendPQExpBuffer(q, "CONSTRAINT %s ",
12604 fmtId(constr->dobj.name));
12605 appendPQExpBuffer(q, "%s", constr->condef);
12611 appendPQExpBuffer(q, "\n)");
12612 else if (!(tbinfo->reloftype && !binary_upgrade))
12615 * We must have a parenthesized attribute list, even though empty,
12616 * when not using the OF TYPE syntax.
12618 appendPQExpBuffer(q, " (\n)");
12621 if (numParents > 0 && !binary_upgrade)
12623 appendPQExpBuffer(q, "\nINHERITS (");
12624 for (k = 0; k < numParents; k++)
12626 TableInfo *parentRel = parents[k];
12629 appendPQExpBuffer(q, ", ");
12630 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12631 appendPQExpBuffer(q, "%s.",
12632 fmtId(parentRel->dobj.namespace->dobj.name));
12633 appendPQExpBuffer(q, "%s",
12634 fmtId(parentRel->dobj.name));
12636 appendPQExpBuffer(q, ")");
12639 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12640 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12642 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12643 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12645 bool addcomma = false;
12647 appendPQExpBuffer(q, "\nWITH (");
12648 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12651 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12653 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12655 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12656 tbinfo->toast_reloptions);
12658 appendPQExpBuffer(q, ")");
12661 /* Dump generic options if any */
12662 if (ftoptions && ftoptions[0])
12663 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12665 appendPQExpBuffer(q, ";\n");
12668 * To create binary-compatible heap files, we have to ensure the same
12669 * physical column order, including dropped columns, as in the
12670 * original. Therefore, we create dropped columns above and drop them
12671 * here, also updating their attlen/attalign values so that the
12672 * dropped column can be skipped properly. (We do not bother with
12673 * restoring the original attbyval setting.) Also, inheritance
12674 * relationships are set up by doing ALTER INHERIT rather than using
12675 * an INHERITS clause --- the latter would possibly mess up the column
12676 * order. That also means we have to take care about setting
12677 * attislocal correctly, plus fix up any inherited CHECK constraints.
12678 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12680 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12682 for (j = 0; j < tbinfo->numatts; j++)
12684 if (tbinfo->attisdropped[j])
12686 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12687 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12688 "SET attlen = %d, "
12689 "attalign = '%c', attbyval = false\n"
12690 "WHERE attname = ",
12692 tbinfo->attalign[j]);
12693 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12694 appendPQExpBuffer(q, "\n AND attrelid = ");
12695 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12696 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12698 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12699 fmtId(tbinfo->dobj.name));
12700 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12701 fmtId(tbinfo->attnames[j]));
12703 else if (!tbinfo->attislocal[j])
12705 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12706 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12707 "SET attislocal = false\n"
12708 "WHERE attname = ");
12709 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12710 appendPQExpBuffer(q, "\n AND attrelid = ");
12711 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12712 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12716 for (k = 0; k < tbinfo->ncheck; k++)
12718 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12720 if (constr->separate || constr->conislocal)
12723 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12724 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12725 fmtId(tbinfo->dobj.name));
12726 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12727 fmtId(constr->dobj.name));
12728 appendPQExpBuffer(q, "%s;\n", constr->condef);
12729 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12730 "SET conislocal = false\n"
12731 "WHERE contype = 'c' AND conname = ");
12732 appendStringLiteralAH(q, constr->dobj.name, fout);
12733 appendPQExpBuffer(q, "\n AND conrelid = ");
12734 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12735 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12738 if (numParents > 0)
12740 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12741 for (k = 0; k < numParents; k++)
12743 TableInfo *parentRel = parents[k];
12745 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12746 fmtId(tbinfo->dobj.name));
12747 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12748 appendPQExpBuffer(q, "%s.",
12749 fmtId(parentRel->dobj.namespace->dobj.name));
12750 appendPQExpBuffer(q, "%s;\n",
12751 fmtId(parentRel->dobj.name));
12755 if (tbinfo->reloftype)
12757 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12758 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12759 fmtId(tbinfo->dobj.name),
12760 tbinfo->reloftype);
12763 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12764 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12765 "SET relfrozenxid = '%u'\n"
12767 tbinfo->frozenxid);
12768 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12769 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12771 if (tbinfo->toast_oid)
12773 /* We preserve the toast oids, so we can use it during restore */
12774 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12775 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12776 "SET relfrozenxid = '%u'\n"
12777 "WHERE oid = '%u';\n",
12778 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12782 /* Loop dumping statistics and storage statements */
12783 for (j = 0; j < tbinfo->numatts; j++)
12786 * Dump per-column statistics information. We only issue an ALTER
12787 * TABLE statement if the attstattarget entry for this column is
12788 * non-negative (i.e. it's not the default value)
12790 if (tbinfo->attstattarget[j] >= 0 &&
12791 !tbinfo->attisdropped[j])
12793 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12794 fmtId(tbinfo->dobj.name));
12795 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12796 fmtId(tbinfo->attnames[j]));
12797 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12798 tbinfo->attstattarget[j]);
12802 * Dump per-column storage information. The statement is only
12803 * dumped if the storage has been changed from the type's default.
12805 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
12807 switch (tbinfo->attstorage[j])
12813 storage = "EXTERNAL";
12819 storage = "EXTENDED";
12826 * Only dump the statement if it's a storage type we recognize
12828 if (storage != NULL)
12830 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12831 fmtId(tbinfo->dobj.name));
12832 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12833 fmtId(tbinfo->attnames[j]));
12834 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12840 * Dump per-column attributes.
12842 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12844 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12845 fmtId(tbinfo->dobj.name));
12846 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12847 fmtId(tbinfo->attnames[j]));
12848 appendPQExpBuffer(q, "SET (%s);\n",
12849 tbinfo->attoptions[j]);
12853 * Dump per-column fdw options.
12855 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12856 tbinfo->attfdwoptions[j] &&
12857 tbinfo->attfdwoptions[j][0] != '\0')
12859 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12860 fmtId(tbinfo->dobj.name));
12861 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12862 fmtId(tbinfo->attnames[j]));
12863 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12864 tbinfo->attfdwoptions[j]);
12869 if (binary_upgrade)
12870 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12872 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12874 tbinfo->dobj.namespace->dobj.name,
12875 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12877 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12878 reltypename, SECTION_PRE_DATA,
12879 q->data, delq->data, NULL,
12880 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12884 /* Dump Table Comments */
12885 dumpTableComment(fout, tbinfo, reltypename);
12887 /* Dump Table Security Labels */
12888 dumpTableSecLabel(fout, tbinfo, reltypename);
12890 /* Dump comments on inlined table constraints */
12891 for (j = 0; j < tbinfo->ncheck; j++)
12893 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12895 if (constr->separate || !constr->conislocal)
12898 dumpTableConstraintComment(fout, constr);
12901 destroyPQExpBuffer(query);
12902 destroyPQExpBuffer(q);
12903 destroyPQExpBuffer(delq);
12904 destroyPQExpBuffer(labelq);
12908 * dumpAttrDef --- dump an attribute's default-value declaration
12911 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12913 TableInfo *tbinfo = adinfo->adtable;
12914 int adnum = adinfo->adnum;
12918 /* Only print it if "separate" mode is selected */
12919 if (!tbinfo->dobj.dump || !adinfo->separate || dataOnly)
12922 /* Don't print inherited defaults, either, except for binary upgrade */
12923 if (tbinfo->inhAttrDef[adnum - 1] && !binary_upgrade)
12926 q = createPQExpBuffer();
12927 delq = createPQExpBuffer();
12929 appendPQExpBuffer(q, "ALTER TABLE %s ",
12930 fmtId(tbinfo->dobj.name));
12931 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12932 fmtId(tbinfo->attnames[adnum - 1]),
12933 adinfo->adef_expr);
12936 * DROP must be fully qualified in case same name appears in pg_catalog
12938 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12939 fmtId(tbinfo->dobj.namespace->dobj.name));
12940 appendPQExpBuffer(delq, "%s ",
12941 fmtId(tbinfo->dobj.name));
12942 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12943 fmtId(tbinfo->attnames[adnum - 1]));
12945 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12946 tbinfo->attnames[adnum - 1],
12947 tbinfo->dobj.namespace->dobj.name,
12950 false, "DEFAULT", SECTION_PRE_DATA,
12951 q->data, delq->data, NULL,
12952 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12955 destroyPQExpBuffer(q);
12956 destroyPQExpBuffer(delq);
12960 * getAttrName: extract the correct name for an attribute
12962 * The array tblInfo->attnames[] only provides names of user attributes;
12963 * if a system attribute number is supplied, we have to fake it.
12964 * We also do a little bit of bounds checking for safety's sake.
12966 static const char *
12967 getAttrName(int attrnum, TableInfo *tblInfo)
12969 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12970 return tblInfo->attnames[attrnum - 1];
12973 case SelfItemPointerAttributeNumber:
12975 case ObjectIdAttributeNumber:
12977 case MinTransactionIdAttributeNumber:
12979 case MinCommandIdAttributeNumber:
12981 case MaxTransactionIdAttributeNumber:
12983 case MaxCommandIdAttributeNumber:
12985 case TableOidAttributeNumber:
12988 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
12989 attrnum, tblInfo->dobj.name);
12991 return NULL; /* keep compiler quiet */
12996 * write out to fout a user-defined index
12999 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13001 TableInfo *tbinfo = indxinfo->indextable;
13004 PQExpBuffer labelq;
13009 q = createPQExpBuffer();
13010 delq = createPQExpBuffer();
13011 labelq = createPQExpBuffer();
13013 appendPQExpBuffer(labelq, "INDEX %s",
13014 fmtId(indxinfo->dobj.name));
13017 * If there's an associated constraint, don't dump the index per se, but
13018 * do dump any comment for it. (This is safe because dependency ordering
13019 * will have ensured the constraint is emitted first.)
13021 if (indxinfo->indexconstraint == 0)
13023 if (binary_upgrade)
13024 binary_upgrade_set_pg_class_oids(q, indxinfo->dobj.catId.oid, true);
13026 /* Plain secondary index */
13027 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13029 /* If the index is clustered, we need to record that. */
13030 if (indxinfo->indisclustered)
13032 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13033 fmtId(tbinfo->dobj.name));
13034 appendPQExpBuffer(q, " ON %s;\n",
13035 fmtId(indxinfo->dobj.name));
13039 * DROP must be fully qualified in case same name appears in
13042 appendPQExpBuffer(delq, "DROP INDEX %s.",
13043 fmtId(tbinfo->dobj.namespace->dobj.name));
13044 appendPQExpBuffer(delq, "%s;\n",
13045 fmtId(indxinfo->dobj.name));
13047 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13048 indxinfo->dobj.name,
13049 tbinfo->dobj.namespace->dobj.name,
13050 indxinfo->tablespace,
13051 tbinfo->rolname, false,
13052 "INDEX", SECTION_POST_DATA,
13053 q->data, delq->data, NULL,
13054 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
13058 /* Dump Index Comments */
13059 dumpComment(fout, labelq->data,
13060 tbinfo->dobj.namespace->dobj.name,
13062 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13064 destroyPQExpBuffer(q);
13065 destroyPQExpBuffer(delq);
13066 destroyPQExpBuffer(labelq);
13071 * write out to fout a user-defined constraint
13074 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13076 TableInfo *tbinfo = coninfo->contable;
13080 /* Skip if not to be dumped */
13081 if (!coninfo->dobj.dump || dataOnly)
13084 q = createPQExpBuffer();
13085 delq = createPQExpBuffer();
13087 if (coninfo->contype == 'p' ||
13088 coninfo->contype == 'u' ||
13089 coninfo->contype == 'x')
13091 /* Index-related constraint */
13092 IndxInfo *indxinfo;
13095 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13097 if (indxinfo == NULL)
13099 write_msg(NULL, "missing index for constraint \"%s\"\n",
13100 coninfo->dobj.name);
13104 if (binary_upgrade)
13105 binary_upgrade_set_pg_class_oids(q, indxinfo->dobj.catId.oid, true);
13107 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13108 fmtId(tbinfo->dobj.name));
13109 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13110 fmtId(coninfo->dobj.name));
13112 if (coninfo->condef)
13114 /* pg_get_constraintdef should have provided everything */
13115 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13119 appendPQExpBuffer(q, "%s (",
13120 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13121 for (k = 0; k < indxinfo->indnkeys; k++)
13123 int indkey = (int) indxinfo->indkeys[k];
13124 const char *attname;
13126 if (indkey == InvalidAttrNumber)
13128 attname = getAttrName(indkey, tbinfo);
13130 appendPQExpBuffer(q, "%s%s",
13131 (k == 0) ? "" : ", ",
13135 appendPQExpBuffer(q, ")");
13137 if (indxinfo->options && strlen(indxinfo->options) > 0)
13138 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13140 if (coninfo->condeferrable)
13142 appendPQExpBuffer(q, " DEFERRABLE");
13143 if (coninfo->condeferred)
13144 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13147 appendPQExpBuffer(q, ";\n");
13150 /* If the index is clustered, we need to record that. */
13151 if (indxinfo->indisclustered)
13153 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13154 fmtId(tbinfo->dobj.name));
13155 appendPQExpBuffer(q, " ON %s;\n",
13156 fmtId(indxinfo->dobj.name));
13160 * DROP must be fully qualified in case same name appears in
13163 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13164 fmtId(tbinfo->dobj.namespace->dobj.name));
13165 appendPQExpBuffer(delq, "%s ",
13166 fmtId(tbinfo->dobj.name));
13167 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13168 fmtId(coninfo->dobj.name));
13170 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13171 coninfo->dobj.name,
13172 tbinfo->dobj.namespace->dobj.name,
13173 indxinfo->tablespace,
13174 tbinfo->rolname, false,
13175 "CONSTRAINT", SECTION_POST_DATA,
13176 q->data, delq->data, NULL,
13177 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13180 else if (coninfo->contype == 'f')
13183 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13184 * current table data is not processed
13186 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13187 fmtId(tbinfo->dobj.name));
13188 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13189 fmtId(coninfo->dobj.name),
13193 * DROP must be fully qualified in case same name appears in
13196 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13197 fmtId(tbinfo->dobj.namespace->dobj.name));
13198 appendPQExpBuffer(delq, "%s ",
13199 fmtId(tbinfo->dobj.name));
13200 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13201 fmtId(coninfo->dobj.name));
13203 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13204 coninfo->dobj.name,
13205 tbinfo->dobj.namespace->dobj.name,
13207 tbinfo->rolname, false,
13208 "FK CONSTRAINT", SECTION_POST_DATA,
13209 q->data, delq->data, NULL,
13210 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13213 else if (coninfo->contype == 'c' && tbinfo)
13215 /* CHECK constraint on a table */
13217 /* Ignore if not to be dumped separately */
13218 if (coninfo->separate)
13220 /* add ONLY if we do not want it to propagate to children */
13221 appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13222 coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13223 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13224 fmtId(coninfo->dobj.name),
13228 * DROP must be fully qualified in case same name appears in
13231 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13232 fmtId(tbinfo->dobj.namespace->dobj.name));
13233 appendPQExpBuffer(delq, "%s ",
13234 fmtId(tbinfo->dobj.name));
13235 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13236 fmtId(coninfo->dobj.name));
13238 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13239 coninfo->dobj.name,
13240 tbinfo->dobj.namespace->dobj.name,
13242 tbinfo->rolname, false,
13243 "CHECK CONSTRAINT", SECTION_POST_DATA,
13244 q->data, delq->data, NULL,
13245 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13249 else if (coninfo->contype == 'c' && tbinfo == NULL)
13251 /* CHECK constraint on a domain */
13252 TypeInfo *tyinfo = coninfo->condomain;
13254 /* Ignore if not to be dumped separately */
13255 if (coninfo->separate)
13257 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13258 fmtId(tyinfo->dobj.name));
13259 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13260 fmtId(coninfo->dobj.name),
13264 * DROP must be fully qualified in case same name appears in
13267 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13268 fmtId(tyinfo->dobj.namespace->dobj.name));
13269 appendPQExpBuffer(delq, "%s ",
13270 fmtId(tyinfo->dobj.name));
13271 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13272 fmtId(coninfo->dobj.name));
13274 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13275 coninfo->dobj.name,
13276 tyinfo->dobj.namespace->dobj.name,
13278 tyinfo->rolname, false,
13279 "CHECK CONSTRAINT", SECTION_POST_DATA,
13280 q->data, delq->data, NULL,
13281 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13287 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
13291 /* Dump Constraint Comments --- only works for table constraints */
13292 if (tbinfo && coninfo->separate)
13293 dumpTableConstraintComment(fout, coninfo);
13295 destroyPQExpBuffer(q);
13296 destroyPQExpBuffer(delq);
13300 * dumpTableConstraintComment --- dump a constraint's comment if any
13302 * This is split out because we need the function in two different places
13303 * depending on whether the constraint is dumped as part of CREATE TABLE
13304 * or as a separate ALTER command.
13307 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13309 TableInfo *tbinfo = coninfo->contable;
13310 PQExpBuffer labelq = createPQExpBuffer();
13312 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13313 fmtId(coninfo->dobj.name));
13314 appendPQExpBuffer(labelq, "ON %s",
13315 fmtId(tbinfo->dobj.name));
13316 dumpComment(fout, labelq->data,
13317 tbinfo->dobj.namespace->dobj.name,
13319 coninfo->dobj.catId, 0,
13320 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13322 destroyPQExpBuffer(labelq);
13326 * findLastBuiltInOid -
13327 * find the last built in oid
13329 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13330 * pg_database entry for the current database
13333 findLastBuiltinOid_V71(const char *dbname)
13338 PQExpBuffer query = createPQExpBuffer();
13340 resetPQExpBuffer(query);
13341 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13342 appendStringLiteralAH(query, dbname, g_fout);
13344 res = PQexec(g_conn, query->data);
13345 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13347 ntups = PQntuples(res);
13350 write_msg(NULL, "missing pg_database entry for this database\n");
13355 write_msg(NULL, "found more than one pg_database entry for this database\n");
13358 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13360 destroyPQExpBuffer(query);
13365 * findLastBuiltInOid -
13366 * find the last built in oid
13368 * For 7.0, we do this by assuming that the last thing that initdb does is to
13369 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13370 * initdb won't be changing anymore, it'll do.
13373 findLastBuiltinOid_V70(void)
13379 res = PQexec(g_conn,
13380 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13381 check_sql_result(res, g_conn,
13382 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
13384 ntups = PQntuples(res);
13387 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
13392 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
13395 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13401 dumpSequence(Archive *fout, TableInfo *tbinfo)
13414 PQExpBuffer query = createPQExpBuffer();
13415 PQExpBuffer delqry = createPQExpBuffer();
13416 PQExpBuffer labelq = createPQExpBuffer();
13418 /* Make sure we are in proper schema */
13419 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
13421 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13422 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13424 if (g_fout->remoteVersion >= 80400)
13426 appendPQExpBuffer(query,
13427 "SELECT sequence_name, "
13428 "start_value, last_value, increment_by, "
13429 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13430 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13432 "END AS max_value, "
13433 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13434 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13436 "END AS min_value, "
13437 "cache_value, is_cycled, is_called from %s",
13439 fmtId(tbinfo->dobj.name));
13443 appendPQExpBuffer(query,
13444 "SELECT sequence_name, "
13445 "0 AS start_value, last_value, increment_by, "
13446 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13447 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13449 "END AS max_value, "
13450 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13451 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13453 "END AS min_value, "
13454 "cache_value, is_cycled, is_called from %s",
13456 fmtId(tbinfo->dobj.name));
13459 res = PQexec(g_conn, query->data);
13460 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13462 if (PQntuples(res) != 1)
13464 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13465 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13467 tbinfo->dobj.name, PQntuples(res));
13471 /* Disable this check: it fails if sequence has been renamed */
13473 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13475 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13476 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13481 startv = PQgetvalue(res, 0, 1);
13482 last = PQgetvalue(res, 0, 2);
13483 incby = PQgetvalue(res, 0, 3);
13484 if (!PQgetisnull(res, 0, 4))
13485 maxv = PQgetvalue(res, 0, 4);
13486 if (!PQgetisnull(res, 0, 5))
13487 minv = PQgetvalue(res, 0, 5);
13488 cache = PQgetvalue(res, 0, 6);
13489 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13490 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13493 * The logic we use for restoring sequences is as follows:
13495 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13496 * last_val for start if called is false, else use min_val for start_val).
13497 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13498 * BY command for it.
13500 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13505 * DROP must be fully qualified in case same name appears in
13508 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13509 fmtId(tbinfo->dobj.namespace->dobj.name));
13510 appendPQExpBuffer(delqry, "%s;\n",
13511 fmtId(tbinfo->dobj.name));
13513 resetPQExpBuffer(query);
13515 if (binary_upgrade)
13517 binary_upgrade_set_pg_class_oids(query, tbinfo->dobj.catId.oid, false);
13518 binary_upgrade_set_type_oids_by_rel_oid(query, tbinfo->dobj.catId.oid);
13521 appendPQExpBuffer(query,
13522 "CREATE SEQUENCE %s\n",
13523 fmtId(tbinfo->dobj.name));
13525 if (g_fout->remoteVersion >= 80400)
13526 appendPQExpBuffer(query, " START WITH %s\n", startv);
13530 * Versions before 8.4 did not remember the true start value. If
13531 * is_called is false then the sequence has never been incremented
13532 * so we can use last_val. Otherwise punt and let it default.
13535 appendPQExpBuffer(query, " START WITH %s\n", last);
13538 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13541 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13543 appendPQExpBuffer(query, " NO MINVALUE\n");
13546 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13548 appendPQExpBuffer(query, " NO MAXVALUE\n");
13550 appendPQExpBuffer(query,
13552 cache, (cycled ? "\n CYCLE" : ""));
13554 appendPQExpBuffer(query, ";\n");
13556 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13558 /* binary_upgrade: no need to clear TOAST table oid */
13560 if (binary_upgrade)
13561 binary_upgrade_extension_member(query, &tbinfo->dobj,
13564 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13566 tbinfo->dobj.namespace->dobj.name,
13569 false, "SEQUENCE", SECTION_PRE_DATA,
13570 query->data, delqry->data, NULL,
13571 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13575 * If the sequence is owned by a table column, emit the ALTER for it
13576 * as a separate TOC entry immediately following the sequence's own
13577 * entry. It's OK to do this rather than using full sorting logic,
13578 * because the dependency that tells us it's owned will have forced
13579 * the table to be created first. We can't just include the ALTER in
13580 * the TOC entry because it will fail if we haven't reassigned the
13581 * sequence owner to match the table's owner.
13583 * We need not schema-qualify the table reference because both
13584 * sequence and table must be in the same schema.
13586 if (OidIsValid(tbinfo->owning_tab))
13588 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13590 if (owning_tab && owning_tab->dobj.dump)
13592 resetPQExpBuffer(query);
13593 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13594 fmtId(tbinfo->dobj.name));
13595 appendPQExpBuffer(query, " OWNED BY %s",
13596 fmtId(owning_tab->dobj.name));
13597 appendPQExpBuffer(query, ".%s;\n",
13598 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13600 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13602 tbinfo->dobj.namespace->dobj.name,
13605 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13606 query->data, "", NULL,
13607 &(tbinfo->dobj.dumpId), 1,
13612 /* Dump Sequence Comments and Security Labels */
13613 dumpComment(fout, labelq->data,
13614 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13615 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13616 dumpSecLabel(fout, labelq->data,
13617 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13618 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13623 resetPQExpBuffer(query);
13624 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13625 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13626 appendPQExpBuffer(query, ", %s, %s);\n",
13627 last, (called ? "true" : "false"));
13629 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13631 tbinfo->dobj.namespace->dobj.name,
13634 false, "SEQUENCE SET", SECTION_PRE_DATA,
13635 query->data, "", NULL,
13636 &(tbinfo->dobj.dumpId), 1,
13642 destroyPQExpBuffer(query);
13643 destroyPQExpBuffer(delqry);
13644 destroyPQExpBuffer(labelq);
13648 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13650 TableInfo *tbinfo = tginfo->tgtable;
13652 PQExpBuffer delqry;
13653 PQExpBuffer labelq;
13662 query = createPQExpBuffer();
13663 delqry = createPQExpBuffer();
13664 labelq = createPQExpBuffer();
13667 * DROP must be fully qualified in case same name appears in pg_catalog
13669 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13670 fmtId(tginfo->dobj.name));
13671 appendPQExpBuffer(delqry, "ON %s.",
13672 fmtId(tbinfo->dobj.namespace->dobj.name));
13673 appendPQExpBuffer(delqry, "%s;\n",
13674 fmtId(tbinfo->dobj.name));
13678 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13682 if (tginfo->tgisconstraint)
13684 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13685 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13689 appendPQExpBuffer(query, "CREATE TRIGGER ");
13690 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13692 appendPQExpBuffer(query, "\n ");
13695 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13696 appendPQExpBuffer(query, "BEFORE");
13697 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13698 appendPQExpBuffer(query, "AFTER");
13699 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13700 appendPQExpBuffer(query, "INSTEAD OF");
13703 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13708 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13710 appendPQExpBuffer(query, " INSERT");
13713 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13716 appendPQExpBuffer(query, " OR DELETE");
13718 appendPQExpBuffer(query, " DELETE");
13721 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13724 appendPQExpBuffer(query, " OR UPDATE");
13726 appendPQExpBuffer(query, " UPDATE");
13729 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13732 appendPQExpBuffer(query, " OR TRUNCATE");
13734 appendPQExpBuffer(query, " TRUNCATE");
13737 appendPQExpBuffer(query, " ON %s\n",
13738 fmtId(tbinfo->dobj.name));
13740 if (tginfo->tgisconstraint)
13742 if (OidIsValid(tginfo->tgconstrrelid))
13744 /* If we are using regclass, name is already quoted */
13745 if (g_fout->remoteVersion >= 70300)
13746 appendPQExpBuffer(query, " FROM %s\n ",
13747 tginfo->tgconstrrelname);
13749 appendPQExpBuffer(query, " FROM %s\n ",
13750 fmtId(tginfo->tgconstrrelname));
13752 if (!tginfo->tgdeferrable)
13753 appendPQExpBuffer(query, "NOT ");
13754 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13755 if (tginfo->tginitdeferred)
13756 appendPQExpBuffer(query, "DEFERRED\n");
13758 appendPQExpBuffer(query, "IMMEDIATE\n");
13761 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13762 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13764 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13766 /* In 7.3, result of regproc is already quoted */
13767 if (g_fout->remoteVersion >= 70300)
13768 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13771 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13772 fmtId(tginfo->tgfname));
13774 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13777 for (findx = 0; findx < tginfo->tgnargs; findx++)
13779 /* find the embedded null that terminates this trigger argument */
13780 size_t tlen = strlen(p);
13782 if (p + tlen >= tgargs + lentgargs)
13784 /* hm, not found before end of bytea value... */
13785 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13788 tbinfo->dobj.name);
13793 appendPQExpBuffer(query, ", ");
13794 appendStringLiteralAH(query, p, fout);
13798 appendPQExpBuffer(query, ");\n");
13801 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13803 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13804 fmtId(tbinfo->dobj.name));
13805 switch (tginfo->tgenabled)
13809 appendPQExpBuffer(query, "DISABLE");
13812 appendPQExpBuffer(query, "ENABLE ALWAYS");
13815 appendPQExpBuffer(query, "ENABLE REPLICA");
13818 appendPQExpBuffer(query, "ENABLE");
13821 appendPQExpBuffer(query, " TRIGGER %s;\n",
13822 fmtId(tginfo->dobj.name));
13825 appendPQExpBuffer(labelq, "TRIGGER %s ",
13826 fmtId(tginfo->dobj.name));
13827 appendPQExpBuffer(labelq, "ON %s",
13828 fmtId(tbinfo->dobj.name));
13830 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13832 tbinfo->dobj.namespace->dobj.name,
13834 tbinfo->rolname, false,
13835 "TRIGGER", SECTION_POST_DATA,
13836 query->data, delqry->data, NULL,
13837 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13840 dumpComment(fout, labelq->data,
13841 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13842 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13844 destroyPQExpBuffer(query);
13845 destroyPQExpBuffer(delqry);
13846 destroyPQExpBuffer(labelq);
13854 dumpRule(Archive *fout, RuleInfo *rinfo)
13856 TableInfo *tbinfo = rinfo->ruletable;
13859 PQExpBuffer delcmd;
13860 PQExpBuffer labelq;
13863 /* Skip if not to be dumped */
13864 if (!rinfo->dobj.dump || dataOnly)
13868 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13869 * we do not want to dump it as a separate object.
13871 if (!rinfo->separate)
13875 * Make sure we are in proper schema.
13877 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
13879 query = createPQExpBuffer();
13880 cmd = createPQExpBuffer();
13881 delcmd = createPQExpBuffer();
13882 labelq = createPQExpBuffer();
13884 if (g_fout->remoteVersion >= 70300)
13886 appendPQExpBuffer(query,
13887 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13888 rinfo->dobj.catId.oid);
13892 /* Rule name was unique before 7.3 ... */
13893 appendPQExpBuffer(query,
13894 "SELECT pg_get_ruledef('%s') AS definition",
13898 res = PQexec(g_conn, query->data);
13899 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13901 if (PQntuples(res) != 1)
13903 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13904 rinfo->dobj.name, tbinfo->dobj.name);
13908 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13911 * Add the command to alter the rules replication firing semantics if it
13912 * differs from the default.
13914 if (rinfo->ev_enabled != 'O')
13916 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13917 fmtId(tbinfo->dobj.namespace->dobj.name));
13918 appendPQExpBuffer(cmd, "%s ",
13919 fmtId(tbinfo->dobj.name));
13920 switch (rinfo->ev_enabled)
13923 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13924 fmtId(rinfo->dobj.name));
13927 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13928 fmtId(rinfo->dobj.name));
13931 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13932 fmtId(rinfo->dobj.name));
13938 * DROP must be fully qualified in case same name appears in pg_catalog
13940 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13941 fmtId(rinfo->dobj.name));
13942 appendPQExpBuffer(delcmd, "ON %s.",
13943 fmtId(tbinfo->dobj.namespace->dobj.name));
13944 appendPQExpBuffer(delcmd, "%s;\n",
13945 fmtId(tbinfo->dobj.name));
13947 appendPQExpBuffer(labelq, "RULE %s",
13948 fmtId(rinfo->dobj.name));
13949 appendPQExpBuffer(labelq, " ON %s",
13950 fmtId(tbinfo->dobj.name));
13952 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13954 tbinfo->dobj.namespace->dobj.name,
13956 tbinfo->rolname, false,
13957 "RULE", SECTION_POST_DATA,
13958 cmd->data, delcmd->data, NULL,
13959 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13962 /* Dump rule comments */
13963 dumpComment(fout, labelq->data,
13964 tbinfo->dobj.namespace->dobj.name,
13966 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13970 destroyPQExpBuffer(query);
13971 destroyPQExpBuffer(cmd);
13972 destroyPQExpBuffer(delcmd);
13973 destroyPQExpBuffer(labelq);
13977 * getExtensionMembership --- obtain extension membership data
13980 getExtensionMembership(ExtensionInfo extinfo[], int numExtensions)
13990 DumpableObject *dobj,
13993 /* Nothing to do if no extensions */
13994 if (numExtensions == 0)
13997 /* Make sure we are in proper schema */
13998 selectSourceSchema("pg_catalog");
14000 query = createPQExpBuffer();
14002 /* refclassid constraint is redundant but may speed the search */
14003 appendPQExpBuffer(query, "SELECT "
14004 "classid, objid, refclassid, refobjid "
14006 "WHERE refclassid = 'pg_extension'::regclass "
14007 "AND deptype = 'e' "
14010 res = PQexec(g_conn, query->data);
14011 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
14013 ntups = PQntuples(res);
14015 i_classid = PQfnumber(res, "classid");
14016 i_objid = PQfnumber(res, "objid");
14017 i_refclassid = PQfnumber(res, "refclassid");
14018 i_refobjid = PQfnumber(res, "refobjid");
14021 * Since we ordered the SELECT by referenced ID, we can expect that
14022 * multiple entries for the same extension will appear together; this
14023 * saves on searches.
14027 for (i = 0; i < ntups; i++)
14030 CatalogId refobjId;
14032 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14033 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14034 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14035 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14037 if (refdobj == NULL ||
14038 refdobj->catId.tableoid != refobjId.tableoid ||
14039 refdobj->catId.oid != refobjId.oid)
14040 refdobj = findObjectByCatalogId(refobjId);
14043 * Failure to find objects mentioned in pg_depend is not unexpected,
14044 * since for example we don't collect info about TOAST tables.
14046 if (refdobj == NULL)
14049 fprintf(stderr, "no referenced object %u %u\n",
14050 refobjId.tableoid, refobjId.oid);
14055 dobj = findObjectByCatalogId(objId);
14060 fprintf(stderr, "no referencing object %u %u\n",
14061 objId.tableoid, objId.oid);
14066 /* Record dependency so that getDependencies needn't repeat this */
14067 addObjectDependency(dobj, refdobj->dumpId);
14069 dobj->ext_member = true;
14072 * Normally, mark the member object as not to be dumped. But in
14073 * binary upgrades, we still dump the members individually, since the
14074 * idea is to exactly reproduce the database contents rather than
14075 * replace the extension contents with something different.
14077 if (!binary_upgrade)
14078 dobj->dump = false;
14080 dobj->dump = refdobj->dump;
14086 * Now identify extension configuration tables and create TableDataInfo
14087 * objects for them, ensuring their data will be dumped even though the
14088 * tables themselves won't be.
14090 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14091 * user data in a configuration table is treated like schema data. This
14092 * seems appropriate since system data in a config table would get
14093 * reloaded by CREATE EXTENSION.
14095 for (i = 0; i < numExtensions; i++)
14097 char *extconfig = extinfo[i].extconfig;
14098 char *extcondition = extinfo[i].extcondition;
14099 char **extconfigarray = NULL;
14100 char **extconditionarray = NULL;
14102 int nconditionitems;
14104 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14105 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14106 nconfigitems == nconditionitems)
14110 for (j = 0; j < nconfigitems; j++)
14112 TableInfo *configtbl;
14114 configtbl = findTableByOid(atooid(extconfigarray[j]));
14115 if (configtbl && configtbl->dataObj == NULL)
14118 * Note: config tables are dumped without OIDs regardless
14119 * of the --oids setting. This is because row filtering
14120 * conditions aren't compatible with dumping OIDs.
14122 makeTableDataInfo(configtbl, false);
14123 if (strlen(extconditionarray[j]) > 0)
14124 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14128 if (extconfigarray)
14129 free(extconfigarray);
14130 if (extconditionarray)
14131 free(extconditionarray);
14134 destroyPQExpBuffer(query);
14138 * getDependencies --- obtain available dependency data
14141 getDependencies(void)
14152 DumpableObject *dobj,
14155 /* No dependency info available before 7.3 */
14156 if (g_fout->remoteVersion < 70300)
14160 write_msg(NULL, "reading dependency data\n");
14162 /* Make sure we are in proper schema */
14163 selectSourceSchema("pg_catalog");
14165 query = createPQExpBuffer();
14168 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14169 * already processed by getExtensionMembership.
14171 appendPQExpBuffer(query, "SELECT "
14172 "classid, objid, refclassid, refobjid, deptype "
14174 "WHERE deptype != 'p' AND deptype != 'e' "
14177 res = PQexec(g_conn, query->data);
14178 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
14180 ntups = PQntuples(res);
14182 i_classid = PQfnumber(res, "classid");
14183 i_objid = PQfnumber(res, "objid");
14184 i_refclassid = PQfnumber(res, "refclassid");
14185 i_refobjid = PQfnumber(res, "refobjid");
14186 i_deptype = PQfnumber(res, "deptype");
14189 * Since we ordered the SELECT by referencing ID, we can expect that
14190 * multiple entries for the same object will appear together; this saves
14195 for (i = 0; i < ntups; i++)
14198 CatalogId refobjId;
14201 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14202 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14203 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14204 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14205 deptype = *(PQgetvalue(res, i, i_deptype));
14207 if (dobj == NULL ||
14208 dobj->catId.tableoid != objId.tableoid ||
14209 dobj->catId.oid != objId.oid)
14210 dobj = findObjectByCatalogId(objId);
14213 * Failure to find objects mentioned in pg_depend is not unexpected,
14214 * since for example we don't collect info about TOAST tables.
14219 fprintf(stderr, "no referencing object %u %u\n",
14220 objId.tableoid, objId.oid);
14225 refdobj = findObjectByCatalogId(refobjId);
14227 if (refdobj == NULL)
14230 fprintf(stderr, "no referenced object %u %u\n",
14231 refobjId.tableoid, refobjId.oid);
14237 * Ordinarily, table rowtypes have implicit dependencies on their
14238 * tables. However, for a composite type the implicit dependency goes
14239 * the other way in pg_depend; which is the right thing for DROP but
14240 * it doesn't produce the dependency ordering we need. So in that one
14241 * case, we reverse the direction of the dependency.
14243 if (deptype == 'i' &&
14244 dobj->objType == DO_TABLE &&
14245 refdobj->objType == DO_TYPE)
14246 addObjectDependency(refdobj, dobj->dumpId);
14249 addObjectDependency(dobj, refdobj->dumpId);
14254 destroyPQExpBuffer(query);
14259 * selectSourceSchema - make the specified schema the active search path
14260 * in the source database.
14262 * NB: pg_catalog is explicitly searched after the specified schema;
14263 * so user names are only qualified if they are cross-schema references,
14264 * and system names are only qualified if they conflict with a user name
14265 * in the current schema.
14267 * Whenever the selected schema is not pg_catalog, be careful to qualify
14268 * references to system catalogs and types in our emitted commands!
14271 selectSourceSchema(const char *schemaName)
14273 static char *curSchemaName = NULL;
14276 /* Not relevant if fetching from pre-7.3 DB */
14277 if (g_fout->remoteVersion < 70300)
14279 /* Ignore null schema names */
14280 if (schemaName == NULL || *schemaName == '\0')
14282 /* Optimize away repeated selection of same schema */
14283 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14286 query = createPQExpBuffer();
14287 appendPQExpBuffer(query, "SET search_path = %s",
14288 fmtId(schemaName));
14289 if (strcmp(schemaName, "pg_catalog") != 0)
14290 appendPQExpBuffer(query, ", pg_catalog");
14292 do_sql_command(g_conn, query->data);
14294 destroyPQExpBuffer(query);
14296 free(curSchemaName);
14297 curSchemaName = pg_strdup(schemaName);
14301 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14304 * NB: in 7.3 and up the result may depend on the currently-selected
14305 * schema; this is why we don't try to cache the names.
14308 getFormattedTypeName(Oid oid, OidOptions opts)
14317 if ((opts & zeroAsOpaque) != 0)
14318 return pg_strdup(g_opaque_type);
14319 else if ((opts & zeroAsAny) != 0)
14320 return pg_strdup("'any'");
14321 else if ((opts & zeroAsStar) != 0)
14322 return pg_strdup("*");
14323 else if ((opts & zeroAsNone) != 0)
14324 return pg_strdup("NONE");
14327 query = createPQExpBuffer();
14328 if (g_fout->remoteVersion >= 70300)
14330 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14333 else if (g_fout->remoteVersion >= 70100)
14335 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14340 appendPQExpBuffer(query, "SELECT typname "
14342 "WHERE oid = '%u'::oid",
14346 res = PQexec(g_conn, query->data);
14347 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
14349 /* Expecting a single result only */
14350 ntups = PQntuples(res);
14353 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
14354 "query returned %d rows instead of one: %s\n",
14356 ntups, query->data);
14360 if (g_fout->remoteVersion >= 70100)
14362 /* already quoted */
14363 result = pg_strdup(PQgetvalue(res, 0, 0));
14367 /* may need to quote it */
14368 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14372 destroyPQExpBuffer(query);
14378 * myFormatType --- local implementation of format_type for use with 7.0.
14381 myFormatType(const char *typname, int32 typmod)
14384 bool isarray = false;
14385 PQExpBuffer buf = createPQExpBuffer();
14387 /* Handle array types */
14388 if (typname[0] == '_')
14394 /* Show lengths on bpchar and varchar */
14395 if (strcmp(typname, "bpchar") == 0)
14397 int len = (typmod - VARHDRSZ);
14399 appendPQExpBuffer(buf, "character");
14401 appendPQExpBuffer(buf, "(%d)",
14402 typmod - VARHDRSZ);
14404 else if (strcmp(typname, "varchar") == 0)
14406 appendPQExpBuffer(buf, "character varying");
14408 appendPQExpBuffer(buf, "(%d)",
14409 typmod - VARHDRSZ);
14411 else if (strcmp(typname, "numeric") == 0)
14413 appendPQExpBuffer(buf, "numeric");
14420 tmp_typmod = typmod - VARHDRSZ;
14421 precision = (tmp_typmod >> 16) & 0xffff;
14422 scale = tmp_typmod & 0xffff;
14423 appendPQExpBuffer(buf, "(%d,%d)",
14429 * char is an internal single-byte data type; Let's make sure we force it
14430 * through with quotes. - thomas 1998-12-13
14432 else if (strcmp(typname, "char") == 0)
14433 appendPQExpBuffer(buf, "\"char\"");
14435 appendPQExpBuffer(buf, "%s", fmtId(typname));
14437 /* Append array qualifier for array types */
14439 appendPQExpBuffer(buf, "[]");
14441 result = pg_strdup(buf->data);
14442 destroyPQExpBuffer(buf);
14448 * fmtQualifiedId - convert a qualified name to the proper format for
14449 * the source database.
14451 * Like fmtId, use the result before calling again.
14453 static const char *
14454 fmtQualifiedId(const char *schema, const char *id)
14456 static PQExpBuffer id_return = NULL;
14458 if (id_return) /* first time through? */
14459 resetPQExpBuffer(id_return);
14461 id_return = createPQExpBuffer();
14463 /* Suppress schema name if fetching from pre-7.3 DB */
14464 if (g_fout->remoteVersion >= 70300 && schema && *schema)
14466 appendPQExpBuffer(id_return, "%s.",
14469 appendPQExpBuffer(id_return, "%s",
14472 return id_return->data;
14476 * Return a column list clause for the given relation.
14478 * Special case: if there are no undropped columns in the relation, return
14479 * "", not an invalid "()" column list.
14481 static const char *
14482 fmtCopyColumnList(const TableInfo *ti)
14484 static PQExpBuffer q = NULL;
14485 int numatts = ti->numatts;
14486 char **attnames = ti->attnames;
14487 bool *attisdropped = ti->attisdropped;
14491 if (q) /* first time through? */
14492 resetPQExpBuffer(q);
14494 q = createPQExpBuffer();
14496 appendPQExpBuffer(q, "(");
14498 for (i = 0; i < numatts; i++)
14500 if (attisdropped[i])
14503 appendPQExpBuffer(q, ", ");
14504 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14509 return ""; /* no undropped columns */
14511 appendPQExpBuffer(q, ")");
14516 * Convenience subroutine to execute a SQL command and check for
14517 * COMMAND_OK status.
14520 do_sql_command(PGconn *conn, const char *query)
14524 res = PQexec(conn, query);
14525 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
14530 * Convenience subroutine to verify a SQL command succeeded,
14531 * and exit with a useful error message if not.
14534 check_sql_result(PGresult *res, PGconn *conn, const char *query,
14535 ExecStatusType expected)
14539 if (res && PQresultStatus(res) == expected)
14542 write_msg(NULL, "SQL command failed\n");
14544 err = PQresultErrorMessage(res);
14546 err = PQerrorMessage(conn);
14547 write_msg(NULL, "Error message from server: %s", err);
14548 write_msg(NULL, "The command was: %s\n", query);