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"
60 #include "pg_backup_db.h"
62 #include "dumputils.h"
71 const char *descr; /* comment for an object */
72 Oid classoid; /* object class (catalog OID) */
73 Oid objoid; /* object OID */
74 int objsubid; /* subobject (table column #) */
79 const char *provider; /* label provider of this security label */
80 const char *label; /* security label for an object */
81 Oid classoid; /* object class (catalog OID) */
82 Oid objoid; /* object OID */
83 int objsubid; /* subobject (table column #) */
87 bool g_verbose; /* User wants verbose narration of our
90 /* various user-settable parameters */
93 int dumpSections; /* bitmask of chosen sections */
95 const char *lockWaitTimeout;
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
100 /* obsolete as of 7.3: */
101 static Oid g_last_builtin_oid; /* value of the last builtin oid */
104 * Object inclusion/exclusion lists
106 * The string lists record the patterns given by command-line switches,
107 * which we then convert to lists of OIDs of matching objects.
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
124 char g_opaque_type[10]; /* name for the opaque type */
126 /* placeholders for the delimiters for comments */
127 char g_comment_start[10];
128 char g_comment_end[10];
130 static const CatalogId nilCatalogId = {0, 0};
132 /* these are to avoid passing around info for findNamespace() */
133 static NamespaceInfo *g_namespaces;
134 static int g_numNamespaces;
136 /* flags for various command-line long options */
137 static int binary_upgrade = 0;
138 static int disable_dollar_quoting = 0;
139 static int dump_inserts = 0;
140 static int column_inserts = 0;
141 static int no_security_labels = 0;
142 static int no_unlogged_table_data = 0;
143 static int serializable_deferrable = 0;
146 static void help(const char *progname);
147 static void pgdump_cleanup_at_exit(int code, void *arg);
148 static void setup_connection(Archive *AH, const char *dumpencoding,
150 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
151 static void expand_schema_name_patterns(Archive *fout,
152 SimpleStringList *patterns,
153 SimpleOidList *oids);
154 static void expand_table_name_patterns(Archive *fout,
155 SimpleStringList *patterns,
156 SimpleOidList *oids);
157 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
158 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *target,
161 const char *namespace, const char *owner,
162 CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164 CommentItem **items);
165 static int collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *target,
167 const char *namespace, const char *owner,
168 CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170 SecLabelItem **items);
171 static int collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
182 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
183 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
184 static void dumpFunc(Archive *fout, FuncInfo *finfo);
185 static void dumpCast(Archive *fout, CastInfo *cast);
186 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
187 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
188 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
189 static void dumpCollation(Archive *fout, CollInfo *convinfo);
190 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
191 static void dumpRule(Archive *fout, RuleInfo *rinfo);
192 static void dumpAgg(Archive *fout, AggInfo *agginfo);
193 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
194 static void dumpTable(Archive *fout, TableInfo *tbinfo);
195 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
196 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
197 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
198 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
199 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
201 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
202 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
203 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
204 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
205 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
206 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
207 static void dumpUserMappings(Archive *fout,
208 const char *servername, const char *namespace,
209 const char *owner, CatalogId catalogId, DumpId dumpId);
210 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
212 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
213 const char *type, const char *name, const char *subname,
214 const char *tag, const char *nspname, const char *owner,
217 static void getDependencies(Archive *fout);
218 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
219 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
220 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
221 static void getTableDataFKConstraints(void);
222 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
223 static char *format_function_arguments_old(Archive *fout,
224 FuncInfo *finfo, int nallargs,
228 static char *format_function_signature(Archive *fout,
229 FuncInfo *finfo, bool honor_quotes);
230 static const char *convertRegProcReference(Archive *fout,
232 static const char *convertOperatorReference(Archive *fout, const char *opr);
233 static const char *convertTSFunction(Archive *fout, Oid funcOid);
234 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
235 static Oid findLastBuiltinOid_V70(Archive *fout);
236 static void selectSourceSchema(Archive *fout, const char *schemaName);
237 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
238 static char *myFormatType(const char *typname, int32 typmod);
239 static const char *fmtQualifiedId(Archive *fout,
240 const char *schema, const char *id);
241 static void getBlobs(Archive *fout);
242 static void dumpBlob(Archive *fout, BlobInfo *binfo);
243 static int dumpBlobs(Archive *fout, void *arg);
244 static void dumpDatabase(Archive *AH);
245 static void dumpEncoding(Archive *AH);
246 static void dumpStdStrings(Archive *AH);
247 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
248 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
249 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
250 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
251 static void binary_upgrade_set_pg_class_oids(Archive *fout,
252 PQExpBuffer upgrade_buffer,
253 Oid pg_class_oid, bool is_index);
254 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
255 DumpableObject *dobj,
256 const char *objlabel);
257 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
258 static const char *fmtCopyColumnList(const TableInfo *ti);
259 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
262 main(int argc, char **argv)
265 const char *filename = NULL;
266 const char *format = "p";
267 const char *dbname = NULL;
268 const char *pghost = NULL;
269 const char *pgport = NULL;
270 const char *username = NULL;
271 const char *dumpencoding = NULL;
275 DumpableObject **dobjs;
278 enum trivalue prompt_password = TRI_DEFAULT;
279 int compressLevel = -1;
282 int outputCreateDB = 0;
283 bool outputBlobs = false;
284 int outputNoOwner = 0;
285 char *outputSuperuser = NULL;
286 char *use_role = NULL;
289 RestoreOptions *ropt;
290 ArchiveFormat archiveFormat = archUnknown;
291 ArchiveMode archiveMode;
292 Archive *fout; /* the script file */
294 static int disable_triggers = 0;
295 static int outputNoTablespaces = 0;
296 static int use_setsessauth = 0;
298 static struct option long_options[] = {
299 {"data-only", no_argument, NULL, 'a'},
300 {"blobs", no_argument, NULL, 'b'},
301 {"clean", no_argument, NULL, 'c'},
302 {"create", no_argument, NULL, 'C'},
303 {"file", required_argument, NULL, 'f'},
304 {"format", required_argument, NULL, 'F'},
305 {"host", required_argument, NULL, 'h'},
306 {"ignore-version", no_argument, NULL, 'i'},
307 {"no-reconnect", no_argument, NULL, 'R'},
308 {"oids", no_argument, NULL, 'o'},
309 {"no-owner", no_argument, NULL, 'O'},
310 {"port", required_argument, NULL, 'p'},
311 {"schema", required_argument, NULL, 'n'},
312 {"exclude-schema", required_argument, NULL, 'N'},
313 {"schema-only", no_argument, NULL, 's'},
314 {"superuser", required_argument, NULL, 'S'},
315 {"table", required_argument, NULL, 't'},
316 {"exclude-table", required_argument, NULL, 'T'},
317 {"no-password", no_argument, NULL, 'w'},
318 {"password", no_argument, NULL, 'W'},
319 {"username", required_argument, NULL, 'U'},
320 {"verbose", no_argument, NULL, 'v'},
321 {"no-privileges", no_argument, NULL, 'x'},
322 {"no-acl", no_argument, NULL, 'x'},
323 {"compress", required_argument, NULL, 'Z'},
324 {"encoding", required_argument, NULL, 'E'},
325 {"help", no_argument, NULL, '?'},
326 {"version", no_argument, NULL, 'V'},
329 * the following options don't have an equivalent short option letter
331 {"attribute-inserts", no_argument, &column_inserts, 1},
332 {"binary-upgrade", no_argument, &binary_upgrade, 1},
333 {"column-inserts", no_argument, &column_inserts, 1},
334 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
335 {"disable-triggers", no_argument, &disable_triggers, 1},
336 {"exclude-table-data", required_argument, NULL, 4},
337 {"inserts", no_argument, &dump_inserts, 1},
338 {"lock-wait-timeout", required_argument, NULL, 2},
339 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
340 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
341 {"role", required_argument, NULL, 3},
342 {"section", required_argument, NULL, 5},
343 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
344 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
345 {"no-security-labels", no_argument, &no_security_labels, 1},
346 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
351 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
355 strcpy(g_comment_start, "-- ");
356 g_comment_end[0] = '\0';
357 strcpy(g_opaque_type, "opaque");
359 dataOnly = schemaOnly = false;
360 dumpSections = DUMP_UNSECTIONED;
361 lockWaitTimeout = NULL;
363 progname = get_progname(argv[0]);
365 /* Set default options based on progname */
366 if (strcmp(progname, "pg_backup") == 0)
371 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
376 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
378 puts("pg_dump (PostgreSQL) " PG_VERSION);
383 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
384 long_options, &optindex)) != -1)
388 case 'a': /* Dump data only */
392 case 'b': /* Dump blobs */
396 case 'c': /* clean (i.e., drop) schema prior to create */
400 case 'C': /* Create DB */
404 case 'E': /* Dump encoding */
405 dumpencoding = optarg;
416 case 'h': /* server host */
421 /* ignored, deprecated option */
424 case 'n': /* include schema(s) */
425 simple_string_list_append(&schema_include_patterns, optarg);
426 include_everything = false;
429 case 'N': /* exclude schema(s) */
430 simple_string_list_append(&schema_exclude_patterns, optarg);
433 case 'o': /* Dump oids */
437 case 'O': /* Don't reconnect to match owner */
441 case 'p': /* server port */
446 /* no-op, still accepted for backwards compatibility */
449 case 's': /* dump schema only */
453 case 'S': /* Username for superuser in plain text output */
454 outputSuperuser = pg_strdup(optarg);
457 case 't': /* include table(s) */
458 simple_string_list_append(&table_include_patterns, optarg);
459 include_everything = false;
462 case 'T': /* exclude table(s) */
463 simple_string_list_append(&table_exclude_patterns, optarg);
470 case 'v': /* verbose */
475 prompt_password = TRI_NO;
479 prompt_password = TRI_YES;
482 case 'x': /* skip ACL dump */
486 case 'Z': /* Compression Level */
487 compressLevel = atoi(optarg);
491 /* This covers the long options. */
494 case 2: /* lock-wait-timeout */
495 lockWaitTimeout = optarg;
498 case 3: /* SET ROLE */
502 case 4: /* exclude table(s) data */
503 simple_string_list_append(&tabledata_exclude_patterns, optarg);
506 case 5: /* section */
507 set_section(optarg, &dumpSections);
511 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
516 /* Get database name from command line */
518 dbname = argv[optind++];
520 /* Complain if any arguments remain */
523 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
524 progname, argv[optind]);
525 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
530 /* --column-inserts implies --inserts */
534 if (dataOnly && schemaOnly)
535 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
537 if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
538 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
541 dumpSections = DUMP_DATA;
543 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
544 else if ( dumpSections != DUMP_UNSECTIONED)
546 dataOnly = dumpSections == DUMP_DATA;
547 schemaOnly = !(dumpSections & DUMP_DATA);
550 if (dataOnly && outputClean)
551 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
553 if (dump_inserts && oids)
555 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
556 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
560 /* Identify archive format to emit */
561 archiveFormat = parseArchiveFormat(format, &archiveMode);
563 /* archiveFormat specific setup */
564 if (archiveFormat == archNull)
567 /* Custom and directory formats are compressed by default, others not */
568 if (compressLevel == -1)
570 if (archiveFormat == archCustom || archiveFormat == archDirectory)
571 compressLevel = Z_DEFAULT_COMPRESSION;
576 /* Open the output file */
577 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
578 on_exit_nicely(pgdump_cleanup_at_exit, fout);
581 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
583 /* Let the archiver know how noisy to be */
584 fout->verbose = g_verbose;
586 my_version = parse_version(PG_VERSION);
588 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
591 * We allow the server to be back to 7.0, and up to any minor release of
592 * our own major version. (See also version check in pg_dumpall.c.)
594 fout->minRemoteVersion = 70000;
595 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
598 * Open the database using the Archiver, so it knows about it. Errors mean
601 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
602 setup_connection(fout, dumpencoding, use_role);
605 * Disable security label support if server version < v9.1.x (prevents
606 * access to nonexistent pg_seclabel catalog)
608 if (fout->remoteVersion < 90100)
609 no_security_labels = 1;
612 * Start transaction-snapshot mode transaction to dump consistent data.
614 ExecuteSqlStatement(fout, "BEGIN");
615 if (fout->remoteVersion >= 90100)
617 if (serializable_deferrable)
618 ExecuteSqlStatement(fout,
619 "SET TRANSACTION ISOLATION LEVEL "
620 "SERIALIZABLE, READ ONLY, DEFERRABLE");
622 ExecuteSqlStatement(fout,
623 "SET TRANSACTION ISOLATION LEVEL "
627 ExecuteSqlStatement(fout,
628 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
630 /* Select the appropriate subquery to convert user IDs to names */
631 if (fout->remoteVersion >= 80100)
632 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
633 else if (fout->remoteVersion >= 70300)
634 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
636 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
638 /* Find the last built-in OID, if needed */
639 if (fout->remoteVersion < 70300)
641 if (fout->remoteVersion >= 70100)
642 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
643 PQdb(GetConnection(fout)));
645 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
647 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
650 /* Expand schema selection patterns into OID lists */
651 if (schema_include_patterns.head != NULL)
653 expand_schema_name_patterns(fout, &schema_include_patterns,
654 &schema_include_oids);
655 if (schema_include_oids.head == NULL)
656 exit_horribly(NULL, "No matching schemas were found\n");
658 expand_schema_name_patterns(fout, &schema_exclude_patterns,
659 &schema_exclude_oids);
660 /* non-matching exclusion patterns aren't an error */
662 /* Expand table selection patterns into OID lists */
663 if (table_include_patterns.head != NULL)
665 expand_table_name_patterns(fout, &table_include_patterns,
666 &table_include_oids);
667 if (table_include_oids.head == NULL)
668 exit_horribly(NULL, "No matching tables were found\n");
670 expand_table_name_patterns(fout, &table_exclude_patterns,
671 &table_exclude_oids);
673 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
674 &tabledata_exclude_oids);
676 /* non-matching exclusion patterns aren't an error */
679 * Dumping blobs is now default unless we saw an inclusion switch or -s
680 * ... but even if we did see one of these, -b turns it back on.
682 if (include_everything && !schemaOnly)
686 * Now scan the database and create DumpableObject structs for all the
687 * objects we intend to dump.
689 tblinfo = getSchemaData(fout, &numTables);
691 if (fout->remoteVersion < 80400)
692 guessConstraintInheritance(tblinfo, numTables);
696 getTableData(tblinfo, numTables, oids);
698 getTableDataFKConstraints();
705 * Collect dependency data to assist in ordering the objects.
707 getDependencies(fout);
710 * Sort the objects into a safe dump order (no forward references).
712 * In 7.3 or later, we can rely on dependency information to help us
713 * determine a safe order, so the initial sort is mostly for cosmetic
714 * purposes: we sort by name to ensure that logically identical schemas
715 * will dump identically. Before 7.3 we don't have dependencies and we
716 * use OID ordering as an (unreliable) guide to creation order.
718 getDumpableObjects(&dobjs, &numObjs);
720 if (fout->remoteVersion >= 70300)
721 sortDumpableObjectsByTypeName(dobjs, numObjs);
723 sortDumpableObjectsByTypeOid(dobjs, numObjs);
725 sortDumpableObjects(dobjs, numObjs);
728 * Create archive TOC entries for all the objects to be dumped, in a safe
732 /* First the special ENCODING and STDSTRINGS entries. */
734 dumpStdStrings(fout);
736 /* The database item is always next, unless we don't want it at all */
737 if (include_everything && !dataOnly)
740 /* Now the rearrangeable objects. */
741 for (i = 0; i < numObjs; i++)
742 dumpDumpableObject(fout, dobjs[i]);
745 * And finally we can do the actual output.
749 ropt = NewRestoreOptions();
750 ropt->filename = filename;
751 ropt->dropSchema = outputClean;
752 ropt->aclsSkip = aclsSkip;
753 ropt->superuser = outputSuperuser;
754 ropt->createDB = outputCreateDB;
755 ropt->noOwner = outputNoOwner;
756 ropt->noTablespace = outputNoTablespaces;
757 ropt->disable_triggers = disable_triggers;
758 ropt->use_setsessauth = use_setsessauth;
759 ropt->dataOnly = dataOnly;
761 if (compressLevel == -1)
762 ropt->compression = 0;
764 ropt->compression = compressLevel;
766 ropt->suppressDumpWarnings = true; /* We've already shown them */
768 RestoreArchive(fout, ropt);
778 help(const char *progname)
780 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
781 printf(_("Usage:\n"));
782 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
784 printf(_("\nGeneral options:\n"));
785 printf(_(" -f, --file=FILENAME output file or directory name\n"));
786 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
787 " plain text (default))\n"));
788 printf(_(" -v, --verbose verbose mode\n"));
789 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
790 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
791 printf(_(" --help show this help, then exit\n"));
792 printf(_(" --version output version information, then exit\n"));
794 printf(_("\nOptions controlling the output content:\n"));
795 printf(_(" -a, --data-only dump only the data, not the schema\n"));
796 printf(_(" -b, --blobs include large objects in dump\n"));
797 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
798 printf(_(" -C, --create include commands to create database in dump\n"));
799 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
800 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
801 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
802 printf(_(" -o, --oids include OIDs in dump\n"));
803 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
804 " plain-text format\n"));
805 printf(_(" -s, --schema-only dump only the schema, no data\n"));
806 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
807 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
808 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
809 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
810 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
811 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
812 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
813 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
814 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
815 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
816 printf(_(" --no-security-labels do not dump security label assignments\n"));
817 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
818 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
819 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
820 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
821 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
822 printf(_(" --use-set-session-authorization\n"
823 " use SET SESSION AUTHORIZATION commands instead of\n"
824 " ALTER OWNER commands to set ownership\n"));
826 printf(_("\nConnection options:\n"));
827 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
828 printf(_(" -p, --port=PORT database server port number\n"));
829 printf(_(" -U, --username=NAME connect as specified database user\n"));
830 printf(_(" -w, --no-password never prompt for password\n"));
831 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
832 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
834 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
835 "variable value is used.\n\n"));
836 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
840 pgdump_cleanup_at_exit(int code, void *arg)
842 Archive *AH = (Archive *) arg;
844 DisconnectDatabase(AH);
848 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
850 PGconn *conn = GetConnection(AH);
851 const char *std_strings;
853 /* Set the client encoding if requested */
856 if (PQsetClientEncoding(conn, dumpencoding) < 0)
857 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
862 * Get the active encoding and the standard_conforming_strings setting, so
863 * we know how to escape strings.
865 AH->encoding = PQclientEncoding(conn);
867 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
868 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
870 /* Set the role if requested */
871 if (use_role && AH->remoteVersion >= 80100)
873 PQExpBuffer query = createPQExpBuffer();
875 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
876 ExecuteSqlStatement(AH, query->data);
877 destroyPQExpBuffer(query);
880 /* Set the datestyle to ISO to ensure the dump's portability */
881 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
883 /* Likewise, avoid using sql_standard intervalstyle */
884 if (AH->remoteVersion >= 80400)
885 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
888 * If supported, set extra_float_digits so that we can dump float data
889 * exactly (given correctly implemented float I/O code, anyway)
891 if (AH->remoteVersion >= 90000)
892 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
893 else if (AH->remoteVersion >= 70400)
894 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
897 * If synchronized scanning is supported, disable it, to prevent
898 * unpredictable changes in row ordering across a dump and reload.
900 if (AH->remoteVersion >= 80300)
901 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
904 * Disable timeouts if supported.
906 if (AH->remoteVersion >= 70300)
907 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
910 * Quote all identifiers, if requested.
912 if (quote_all_identifiers && AH->remoteVersion >= 90100)
913 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
917 parseArchiveFormat(const char *format, ArchiveMode *mode)
919 ArchiveFormat archiveFormat;
921 *mode = archModeWrite;
923 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
925 /* This is used by pg_dumpall, and is not documented */
926 archiveFormat = archNull;
927 *mode = archModeAppend;
929 else if (pg_strcasecmp(format, "c") == 0)
930 archiveFormat = archCustom;
931 else if (pg_strcasecmp(format, "custom") == 0)
932 archiveFormat = archCustom;
933 else if (pg_strcasecmp(format, "d") == 0)
934 archiveFormat = archDirectory;
935 else if (pg_strcasecmp(format, "directory") == 0)
936 archiveFormat = archDirectory;
937 else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
940 * Dump files into the current directory; for demonstration only, not
943 archiveFormat = archFiles;
944 else if (pg_strcasecmp(format, "p") == 0)
945 archiveFormat = archNull;
946 else if (pg_strcasecmp(format, "plain") == 0)
947 archiveFormat = archNull;
948 else if (pg_strcasecmp(format, "t") == 0)
949 archiveFormat = archTar;
950 else if (pg_strcasecmp(format, "tar") == 0)
951 archiveFormat = archTar;
953 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
954 return archiveFormat;
958 * Find the OIDs of all schemas matching the given list of patterns,
959 * and append them to the given OID list.
962 expand_schema_name_patterns(Archive *fout,
963 SimpleStringList *patterns,
968 SimpleStringListCell *cell;
971 if (patterns->head == NULL)
972 return; /* nothing to do */
974 if (fout->remoteVersion < 70300)
975 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
977 query = createPQExpBuffer();
980 * We use UNION ALL rather than UNION; this might sometimes result in
981 * duplicate entries in the OID list, but we don't care.
984 for (cell = patterns->head; cell; cell = cell->next)
986 if (cell != patterns->head)
987 appendPQExpBuffer(query, "UNION ALL\n");
988 appendPQExpBuffer(query,
989 "SELECT oid FROM pg_catalog.pg_namespace n\n");
990 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
991 false, NULL, "n.nspname", NULL, NULL);
994 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
996 for (i = 0; i < PQntuples(res); i++)
998 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1002 destroyPQExpBuffer(query);
1006 * Find the OIDs of all tables matching the given list of patterns,
1007 * and append them to the given OID list.
1010 expand_table_name_patterns(Archive *fout,
1011 SimpleStringList *patterns, SimpleOidList *oids)
1015 SimpleStringListCell *cell;
1018 if (patterns->head == NULL)
1019 return; /* nothing to do */
1021 query = createPQExpBuffer();
1024 * We use UNION ALL rather than UNION; this might sometimes result in
1025 * duplicate entries in the OID list, but we don't care.
1028 for (cell = patterns->head; cell; cell = cell->next)
1030 if (cell != patterns->head)
1031 appendPQExpBuffer(query, "UNION ALL\n");
1032 appendPQExpBuffer(query,
1034 "\nFROM pg_catalog.pg_class c"
1035 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1036 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1037 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1038 RELKIND_FOREIGN_TABLE);
1039 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1040 false, "n.nspname", "c.relname", NULL,
1041 "pg_catalog.pg_table_is_visible(c.oid)");
1044 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1046 for (i = 0; i < PQntuples(res); i++)
1048 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1052 destroyPQExpBuffer(query);
1056 * selectDumpableNamespace: policy-setting subroutine
1057 * Mark a namespace as to be dumped or not
1060 selectDumpableNamespace(NamespaceInfo *nsinfo)
1063 * If specific tables are being dumped, do not dump any complete
1064 * namespaces. If specific namespaces are being dumped, dump just those
1065 * namespaces. Otherwise, dump all non-system namespaces.
1067 if (table_include_oids.head != NULL)
1068 nsinfo->dobj.dump = false;
1069 else if (schema_include_oids.head != NULL)
1070 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1071 nsinfo->dobj.catId.oid);
1072 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1073 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1074 nsinfo->dobj.dump = false;
1076 nsinfo->dobj.dump = true;
1079 * In any case, a namespace can be excluded by an exclusion switch
1081 if (nsinfo->dobj.dump &&
1082 simple_oid_list_member(&schema_exclude_oids,
1083 nsinfo->dobj.catId.oid))
1084 nsinfo->dobj.dump = false;
1088 * selectDumpableTable: policy-setting subroutine
1089 * Mark a table as to be dumped or not
1092 selectDumpableTable(TableInfo *tbinfo)
1095 * If specific tables are being dumped, dump just those tables; else, dump
1096 * according to the parent namespace's dump flag.
1098 if (table_include_oids.head != NULL)
1099 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1100 tbinfo->dobj.catId.oid);
1102 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1105 * In any case, a table can be excluded by an exclusion switch
1107 if (tbinfo->dobj.dump &&
1108 simple_oid_list_member(&table_exclude_oids,
1109 tbinfo->dobj.catId.oid))
1110 tbinfo->dobj.dump = false;
1114 * selectDumpableType: policy-setting subroutine
1115 * Mark a type as to be dumped or not
1117 * If it's a table's rowtype or an autogenerated array type, we also apply a
1118 * special type code to facilitate sorting into the desired order. (We don't
1119 * want to consider those to be ordinary types because that would bring tables
1120 * up into the datatype part of the dump order.) We still set the object's
1121 * dump flag; that's not going to cause the dummy type to be dumped, but we
1122 * need it so that casts involving such types will be dumped correctly -- see
1123 * dumpCast. This means the flag should be set the same as for the underlying
1124 * object (the table or base type).
1127 selectDumpableType(TypeInfo *tyinfo)
1129 /* skip complex types, except for standalone composite types */
1130 if (OidIsValid(tyinfo->typrelid) &&
1131 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1133 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1135 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1136 if (tytable != NULL)
1137 tyinfo->dobj.dump = tytable->dobj.dump;
1139 tyinfo->dobj.dump = false;
1143 /* skip auto-generated array types */
1144 if (tyinfo->isArray)
1146 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1148 * Fall through to set the dump flag; we assume that the subsequent
1149 * rules will do the same thing as they would for the array's base
1150 * type. (We cannot reliably look up the base type here, since
1151 * getTypes may not have processed it yet.)
1155 /* dump only types in dumpable namespaces */
1156 if (!tyinfo->dobj.namespace->dobj.dump)
1157 tyinfo->dobj.dump = false;
1159 /* skip undefined placeholder types */
1160 else if (!tyinfo->isDefined)
1161 tyinfo->dobj.dump = false;
1164 tyinfo->dobj.dump = true;
1168 * selectDumpableDefaultACL: policy-setting subroutine
1169 * Mark a default ACL as to be dumped or not
1171 * For per-schema default ACLs, dump if the schema is to be dumped.
1172 * Otherwise dump if we are dumping "everything". Note that dataOnly
1173 * and aclsSkip are checked separately.
1176 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1178 if (dinfo->dobj.namespace)
1179 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1181 dinfo->dobj.dump = include_everything;
1185 * selectDumpableExtension: policy-setting subroutine
1186 * Mark an extension as to be dumped or not
1188 * Normally, we dump all extensions, or none of them if include_everything
1189 * is false (i.e., a --schema or --table switch was given). However, in
1190 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1191 * assume those will already be installed in the target database. We identify
1192 * such extensions by their having OIDs in the range reserved for initdb.
1195 selectDumpableExtension(ExtensionInfo *extinfo)
1197 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1198 extinfo->dobj.dump = false;
1200 extinfo->dobj.dump = include_everything;
1204 * selectDumpableObject: policy-setting subroutine
1205 * Mark a generic dumpable object as to be dumped or not
1207 * Use this only for object types without a special-case routine above.
1210 selectDumpableObject(DumpableObject *dobj)
1213 * Default policy is to dump if parent namespace is dumpable, or always
1214 * for non-namespace-associated items.
1216 if (dobj->namespace)
1217 dobj->dump = dobj->namespace->dobj.dump;
1223 * Dump a table's contents for loading using the COPY command
1224 * - this routine is called by the Archiver when it wants the table
1229 dumpTableData_copy(Archive *fout, void *dcontext)
1231 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1232 TableInfo *tbinfo = tdinfo->tdtable;
1233 const char *classname = tbinfo->dobj.name;
1234 const bool hasoids = tbinfo->hasoids;
1235 const bool oids = tdinfo->oids;
1236 PQExpBuffer q = createPQExpBuffer();
1237 PGconn *conn = GetConnection(fout);
1241 const char *column_list;
1244 write_msg(NULL, "dumping contents of table %s\n", classname);
1247 * Make sure we are in proper schema. We will qualify the table name
1248 * below anyway (in case its name conflicts with a pg_catalog table); but
1249 * this ensures reproducible results in case the table contains regproc,
1250 * regclass, etc columns.
1252 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1255 * If possible, specify the column list explicitly so that we have no
1256 * possibility of retrieving data in the wrong column order. (The default
1257 * column ordering of COPY will not be what we want in certain corner
1258 * cases involving ADD COLUMN and inheritance.)
1260 if (fout->remoteVersion >= 70300)
1261 column_list = fmtCopyColumnList(tbinfo);
1263 column_list = ""; /* can't select columns in COPY */
1265 if (oids && hasoids)
1267 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1268 fmtQualifiedId(fout,
1269 tbinfo->dobj.namespace->dobj.name,
1273 else if (tdinfo->filtercond)
1275 /* Note: this syntax is only supported in 8.2 and up */
1276 appendPQExpBufferStr(q, "COPY (SELECT ");
1277 /* klugery to get rid of parens in column list */
1278 if (strlen(column_list) > 2)
1280 appendPQExpBufferStr(q, column_list + 1);
1281 q->data[q->len - 1] = ' ';
1284 appendPQExpBufferStr(q, "* ");
1285 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1286 fmtQualifiedId(fout,
1287 tbinfo->dobj.namespace->dobj.name,
1289 tdinfo->filtercond);
1293 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1294 fmtQualifiedId(fout,
1295 tbinfo->dobj.namespace->dobj.name,
1299 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1304 ret = PQgetCopyData(conn, ©buf, 0);
1307 break; /* done or error */
1311 WriteData(fout, copybuf, ret);
1318 * There was considerable discussion in late July, 2000 regarding
1319 * slowing down pg_dump when backing up large tables. Users with both
1320 * slow & fast (multi-processor) machines experienced performance
1321 * degradation when doing a backup.
1323 * Initial attempts based on sleeping for a number of ms for each ms
1324 * of work were deemed too complex, then a simple 'sleep in each loop'
1325 * implementation was suggested. The latter failed because the loop
1326 * was too tight. Finally, the following was implemented:
1328 * If throttle is non-zero, then
1329 * See how long since the last sleep.
1330 * Work out how long to sleep (based on ratio).
1331 * If sleep is more than 100ms, then
1337 * where the throttle value was the number of ms to sleep per ms of
1338 * work. The calculation was done in each loop.
1340 * Most of the hard work is done in the backend, and this solution
1341 * still did not work particularly well: on slow machines, the ratio
1342 * was 50:1, and on medium paced machines, 1:1, and on fast
1343 * multi-processor machines, it had little or no effect, for reasons
1344 * that were unclear.
1346 * Further discussion ensued, and the proposal was dropped.
1348 * For those people who want this feature, it can be implemented using
1349 * gettimeofday in each loop, calculating the time since last sleep,
1350 * multiplying that by the sleep ratio, then if the result is more
1351 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1352 * function to sleep for a subsecond period ie.
1354 * select(0, NULL, NULL, NULL, &tvi);
1356 * This will return after the interval specified in the structure tvi.
1357 * Finally, call gettimeofday again to save the 'last sleep time'.
1361 archprintf(fout, "\\.\n\n\n");
1365 /* copy data transfer failed */
1366 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1367 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1368 write_msg(NULL, "The command was: %s\n", q->data);
1372 /* Check command status and return to normal libpq state */
1373 res = PQgetResult(conn);
1374 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1376 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1377 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1378 write_msg(NULL, "The command was: %s\n", q->data);
1383 destroyPQExpBuffer(q);
1388 * Dump table data using INSERT commands.
1390 * Caution: when we restore from an archive file direct to database, the
1391 * INSERT commands emitted by this function have to be parsed by
1392 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1393 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1396 dumpTableData_insert(Archive *fout, void *dcontext)
1398 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1399 TableInfo *tbinfo = tdinfo->tdtable;
1400 const char *classname = tbinfo->dobj.name;
1401 PQExpBuffer q = createPQExpBuffer();
1408 * Make sure we are in proper schema. We will qualify the table name
1409 * below anyway (in case its name conflicts with a pg_catalog table); but
1410 * this ensures reproducible results in case the table contains regproc,
1411 * regclass, etc columns.
1413 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1415 if (fout->remoteVersion >= 70100)
1417 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1418 "SELECT * FROM ONLY %s",
1419 fmtQualifiedId(fout,
1420 tbinfo->dobj.namespace->dobj.name,
1425 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1427 fmtQualifiedId(fout,
1428 tbinfo->dobj.namespace->dobj.name,
1431 if (tdinfo->filtercond)
1432 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1434 ExecuteSqlStatement(fout, q->data);
1438 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1440 nfields = PQnfields(res);
1441 for (tuple = 0; tuple < PQntuples(res); tuple++)
1443 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1446 /* corner case for zero-column table */
1447 archprintf(fout, "DEFAULT VALUES;\n");
1452 resetPQExpBuffer(q);
1453 appendPQExpBuffer(q, "(");
1454 for (field = 0; field < nfields; field++)
1457 appendPQExpBuffer(q, ", ");
1458 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1460 appendPQExpBuffer(q, ") ");
1461 archputs(q->data, fout);
1463 archprintf(fout, "VALUES (");
1464 for (field = 0; field < nfields; field++)
1467 archprintf(fout, ", ");
1468 if (PQgetisnull(res, tuple, field))
1470 archprintf(fout, "NULL");
1474 /* XXX This code is partially duplicated in ruleutils.c */
1475 switch (PQftype(res, field))
1486 * These types are printed without quotes unless
1487 * they contain values that aren't accepted by the
1488 * scanner unquoted (e.g., 'NaN'). Note that
1489 * strtod() and friends might accept NaN, so we
1490 * can't use that to test.
1492 * In reality we only need to defend against
1493 * infinity and NaN, so we need not get too crazy
1494 * about pattern matching here.
1496 const char *s = PQgetvalue(res, tuple, field);
1498 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1499 archprintf(fout, "%s", s);
1501 archprintf(fout, "'%s'", s);
1507 archprintf(fout, "B'%s'",
1508 PQgetvalue(res, tuple, field));
1512 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1513 archprintf(fout, "true");
1515 archprintf(fout, "false");
1519 /* All other types are printed as string literals. */
1520 resetPQExpBuffer(q);
1521 appendStringLiteralAH(q,
1522 PQgetvalue(res, tuple, field),
1524 archputs(q->data, fout);
1528 archprintf(fout, ");\n");
1531 if (PQntuples(res) <= 0)
1539 archprintf(fout, "\n\n");
1541 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1543 destroyPQExpBuffer(q);
1550 * dump the contents of a single table
1552 * Actually, this just makes an ArchiveEntry for the table contents.
1555 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1557 TableInfo *tbinfo = tdinfo->tdtable;
1558 PQExpBuffer copyBuf = createPQExpBuffer();
1559 DataDumperPtr dumpFn;
1564 /* Dump/restore using COPY */
1565 dumpFn = dumpTableData_copy;
1566 /* must use 2 steps here 'cause fmtId is nonreentrant */
1567 appendPQExpBuffer(copyBuf, "COPY %s ",
1568 fmtId(tbinfo->dobj.name));
1569 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1570 fmtCopyColumnList(tbinfo),
1571 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1572 copyStmt = copyBuf->data;
1576 /* Restore using INSERT */
1577 dumpFn = dumpTableData_insert;
1581 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1582 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1583 NULL, tbinfo->rolname,
1584 false, "TABLE DATA", SECTION_DATA,
1586 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1589 destroyPQExpBuffer(copyBuf);
1594 * set up dumpable objects representing the contents of tables
1597 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1601 for (i = 0; i < numTables; i++)
1603 if (tblinfo[i].dobj.dump)
1604 makeTableDataInfo(&(tblinfo[i]), oids);
1609 * Make a dumpable object for the data of this specific table
1611 * Note: we make a TableDataInfo if and only if we are going to dump the
1612 * table data; the "dump" flag in such objects isn't used.
1615 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1617 TableDataInfo *tdinfo;
1620 * Nothing to do if we already decided to dump the table. This will
1621 * happen for "config" tables.
1623 if (tbinfo->dataObj != NULL)
1626 /* Skip VIEWs (no data to dump) */
1627 if (tbinfo->relkind == RELKIND_VIEW)
1629 /* Skip SEQUENCEs (handled elsewhere) */
1630 if (tbinfo->relkind == RELKIND_SEQUENCE)
1632 /* Skip FOREIGN TABLEs (no data to dump) */
1633 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1636 /* Don't dump data in unlogged tables, if so requested */
1637 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1638 no_unlogged_table_data)
1641 /* Check that the data is not explicitly excluded */
1642 if (simple_oid_list_member(&tabledata_exclude_oids,
1643 tbinfo->dobj.catId.oid))
1646 /* OK, let's dump it */
1647 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1649 tdinfo->dobj.objType = DO_TABLE_DATA;
1652 * Note: use tableoid 0 so that this object won't be mistaken for
1653 * something that pg_depend entries apply to.
1655 tdinfo->dobj.catId.tableoid = 0;
1656 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1657 AssignDumpId(&tdinfo->dobj);
1658 tdinfo->dobj.name = tbinfo->dobj.name;
1659 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1660 tdinfo->tdtable = tbinfo;
1661 tdinfo->oids = oids;
1662 tdinfo->filtercond = NULL; /* might get set later */
1663 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1665 tbinfo->dataObj = tdinfo;
1669 * getTableDataFKConstraints -
1670 * add dump-order dependencies reflecting foreign key constraints
1672 * This code is executed only in a data-only dump --- in schema+data dumps
1673 * we handle foreign key issues by not creating the FK constraints until
1674 * after the data is loaded. In a data-only dump, however, we want to
1675 * order the table data objects in such a way that a table's referenced
1676 * tables are restored first. (In the presence of circular references or
1677 * self-references this may be impossible; we'll detect and complain about
1678 * that during the dependency sorting step.)
1681 getTableDataFKConstraints(void)
1683 DumpableObject **dobjs;
1687 /* Search through all the dumpable objects for FK constraints */
1688 getDumpableObjects(&dobjs, &numObjs);
1689 for (i = 0; i < numObjs; i++)
1691 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1693 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1696 /* Not interesting unless both tables are to be dumped */
1697 if (cinfo->contable == NULL ||
1698 cinfo->contable->dataObj == NULL)
1700 ftable = findTableByOid(cinfo->confrelid);
1701 if (ftable == NULL ||
1702 ftable->dataObj == NULL)
1706 * Okay, make referencing table's TABLE_DATA object depend on the
1707 * referenced table's TABLE_DATA object.
1709 addObjectDependency(&cinfo->contable->dataObj->dobj,
1710 ftable->dataObj->dobj.dumpId);
1718 * guessConstraintInheritance:
1719 * In pre-8.4 databases, we can't tell for certain which constraints
1720 * are inherited. We assume a CHECK constraint is inherited if its name
1721 * matches the name of any constraint in the parent. Originally this code
1722 * tried to compare the expression texts, but that can fail for various
1723 * reasons --- for example, if the parent and child tables are in different
1724 * schemas, reverse-listing of function calls may produce different text
1725 * (schema-qualified or not) depending on search path.
1727 * In 8.4 and up we can rely on the conislocal field to decide which
1728 * constraints must be dumped; much safer.
1730 * This function assumes all conislocal flags were initialized to TRUE.
1731 * It clears the flag on anything that seems to be inherited.
1734 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1740 for (i = 0; i < numTables; i++)
1742 TableInfo *tbinfo = &(tblinfo[i]);
1744 TableInfo **parents;
1747 /* Sequences and views never have parents */
1748 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1749 tbinfo->relkind == RELKIND_VIEW)
1752 /* Don't bother computing anything for non-target tables, either */
1753 if (!tbinfo->dobj.dump)
1756 numParents = tbinfo->numParents;
1757 parents = tbinfo->parents;
1759 if (numParents == 0)
1760 continue; /* nothing to see here, move along */
1762 /* scan for inherited CHECK constraints */
1763 for (j = 0; j < tbinfo->ncheck; j++)
1765 ConstraintInfo *constr;
1767 constr = &(tbinfo->checkexprs[j]);
1769 for (k = 0; k < numParents; k++)
1773 parent = parents[k];
1774 for (l = 0; l < parent->ncheck; l++)
1776 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1778 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1780 constr->conislocal = false;
1784 if (!constr->conislocal)
1794 * dump the database definition
1797 dumpDatabase(Archive *fout)
1799 PQExpBuffer dbQry = createPQExpBuffer();
1800 PQExpBuffer delQry = createPQExpBuffer();
1801 PQExpBuffer creaQry = createPQExpBuffer();
1802 PGconn *conn = GetConnection(fout);
1814 const char *datname,
1822 datname = PQdb(conn);
1825 write_msg(NULL, "saving database definition\n");
1827 /* Make sure we are in proper schema */
1828 selectSourceSchema(fout, "pg_catalog");
1830 /* Get the database owner and parameters from pg_database */
1831 if (fout->remoteVersion >= 80400)
1833 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1834 "(%s datdba) AS dba, "
1835 "pg_encoding_to_char(encoding) AS encoding, "
1836 "datcollate, datctype, datfrozenxid, "
1837 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1838 "shobj_description(oid, 'pg_database') AS description "
1843 appendStringLiteralAH(dbQry, datname, fout);
1845 else if (fout->remoteVersion >= 80200)
1847 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1848 "(%s datdba) AS dba, "
1849 "pg_encoding_to_char(encoding) AS encoding, "
1850 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1851 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1852 "shobj_description(oid, 'pg_database') AS description "
1857 appendStringLiteralAH(dbQry, datname, fout);
1859 else if (fout->remoteVersion >= 80000)
1861 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1862 "(%s datdba) AS dba, "
1863 "pg_encoding_to_char(encoding) AS encoding, "
1864 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1865 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1869 appendStringLiteralAH(dbQry, datname, fout);
1871 else if (fout->remoteVersion >= 70100)
1873 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1874 "(%s datdba) AS dba, "
1875 "pg_encoding_to_char(encoding) AS encoding, "
1876 "NULL AS datcollate, NULL AS datctype, "
1877 "0 AS datfrozenxid, "
1878 "NULL AS tablespace "
1882 appendStringLiteralAH(dbQry, datname, fout);
1886 appendPQExpBuffer(dbQry, "SELECT "
1887 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1889 "(%s datdba) AS dba, "
1890 "pg_encoding_to_char(encoding) AS encoding, "
1891 "NULL AS datcollate, NULL AS datctype, "
1892 "0 AS datfrozenxid, "
1893 "NULL AS tablespace "
1897 appendStringLiteralAH(dbQry, datname, fout);
1900 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1902 i_tableoid = PQfnumber(res, "tableoid");
1903 i_oid = PQfnumber(res, "oid");
1904 i_dba = PQfnumber(res, "dba");
1905 i_encoding = PQfnumber(res, "encoding");
1906 i_collate = PQfnumber(res, "datcollate");
1907 i_ctype = PQfnumber(res, "datctype");
1908 i_frozenxid = PQfnumber(res, "datfrozenxid");
1909 i_tablespace = PQfnumber(res, "tablespace");
1911 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1912 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1913 dba = PQgetvalue(res, 0, i_dba);
1914 encoding = PQgetvalue(res, 0, i_encoding);
1915 collate = PQgetvalue(res, 0, i_collate);
1916 ctype = PQgetvalue(res, 0, i_ctype);
1917 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1918 tablespace = PQgetvalue(res, 0, i_tablespace);
1920 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1922 if (strlen(encoding) > 0)
1924 appendPQExpBuffer(creaQry, " ENCODING = ");
1925 appendStringLiteralAH(creaQry, encoding, fout);
1927 if (strlen(collate) > 0)
1929 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1930 appendStringLiteralAH(creaQry, collate, fout);
1932 if (strlen(ctype) > 0)
1934 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1935 appendStringLiteralAH(creaQry, ctype, fout);
1937 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1938 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1940 appendPQExpBuffer(creaQry, ";\n");
1944 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1945 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1946 "SET datfrozenxid = '%u'\n"
1949 appendStringLiteralAH(creaQry, datname, fout);
1950 appendPQExpBuffer(creaQry, ";\n");
1954 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1957 dbDumpId = createDumpId();
1960 dbCatId, /* catalog ID */
1961 dbDumpId, /* dump ID */
1963 NULL, /* Namespace */
1964 NULL, /* Tablespace */
1966 false, /* with oids */
1967 "DATABASE", /* Desc */
1968 SECTION_PRE_DATA, /* Section */
1969 creaQry->data, /* Create */
1970 delQry->data, /* Del */
1975 NULL); /* Dumper Arg */
1978 * pg_largeobject and pg_largeobject_metadata come from the old system
1979 * intact, so set their relfrozenxids.
1984 PQExpBuffer loFrozenQry = createPQExpBuffer();
1985 PQExpBuffer loOutQry = createPQExpBuffer();
1991 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1992 "FROM pg_catalog.pg_class\n"
1993 "WHERE oid = %u;\n",
1994 LargeObjectRelationId);
1996 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1998 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2000 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2001 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2002 "SET relfrozenxid = '%u'\n"
2003 "WHERE oid = %u;\n",
2004 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2005 LargeObjectRelationId);
2006 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2007 "pg_largeobject", NULL, NULL, "",
2008 false, "pg_largeobject", SECTION_PRE_DATA,
2009 loOutQry->data, "", NULL,
2016 * pg_largeobject_metadata
2018 if (fout->remoteVersion >= 90000)
2020 resetPQExpBuffer(loFrozenQry);
2021 resetPQExpBuffer(loOutQry);
2023 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2024 "FROM pg_catalog.pg_class\n"
2025 "WHERE oid = %u;\n",
2026 LargeObjectMetadataRelationId);
2028 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2030 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2032 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2033 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2034 "SET relfrozenxid = '%u'\n"
2035 "WHERE oid = %u;\n",
2036 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2037 LargeObjectMetadataRelationId);
2038 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2039 "pg_largeobject_metadata", NULL, NULL, "",
2040 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2041 loOutQry->data, "", NULL,
2048 destroyPQExpBuffer(loFrozenQry);
2049 destroyPQExpBuffer(loOutQry);
2052 /* Dump DB comment if any */
2053 if (fout->remoteVersion >= 80200)
2056 * 8.2 keeps comments on shared objects in a shared table, so we
2057 * cannot use the dumpComment used for other database objects.
2059 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2061 if (comment && strlen(comment))
2063 resetPQExpBuffer(dbQry);
2066 * Generates warning when loaded into a differently-named
2069 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2070 appendStringLiteralAH(dbQry, comment, fout);
2071 appendPQExpBuffer(dbQry, ";\n");
2073 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2074 dba, false, "COMMENT", SECTION_NONE,
2075 dbQry->data, "", NULL,
2076 &dbDumpId, 1, NULL, NULL);
2081 resetPQExpBuffer(dbQry);
2082 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2083 dumpComment(fout, dbQry->data, NULL, "",
2084 dbCatId, 0, dbDumpId);
2089 /* Dump shared security label. */
2090 if (!no_security_labels && fout->remoteVersion >= 90200)
2092 PQExpBuffer seclabelQry = createPQExpBuffer();
2094 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2095 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2096 resetPQExpBuffer(seclabelQry);
2097 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2098 if (strlen(seclabelQry->data))
2099 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2100 dba, false, "SECURITY LABEL", SECTION_NONE,
2101 seclabelQry->data, "", NULL,
2102 &dbDumpId, 1, NULL, NULL);
2103 destroyPQExpBuffer(seclabelQry);
2106 destroyPQExpBuffer(dbQry);
2107 destroyPQExpBuffer(delQry);
2108 destroyPQExpBuffer(creaQry);
2113 * dumpEncoding: put the correct encoding into the archive
2116 dumpEncoding(Archive *AH)
2118 const char *encname = pg_encoding_to_char(AH->encoding);
2119 PQExpBuffer qry = createPQExpBuffer();
2122 write_msg(NULL, "saving encoding = %s\n", encname);
2124 appendPQExpBuffer(qry, "SET client_encoding = ");
2125 appendStringLiteralAH(qry, encname, AH);
2126 appendPQExpBuffer(qry, ";\n");
2128 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2129 "ENCODING", NULL, NULL, "",
2130 false, "ENCODING", SECTION_PRE_DATA,
2131 qry->data, "", NULL,
2135 destroyPQExpBuffer(qry);
2140 * dumpStdStrings: put the correct escape string behavior into the archive
2143 dumpStdStrings(Archive *AH)
2145 const char *stdstrings = AH->std_strings ? "on" : "off";
2146 PQExpBuffer qry = createPQExpBuffer();
2149 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2152 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2155 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2156 "STDSTRINGS", NULL, NULL, "",
2157 false, "STDSTRINGS", SECTION_PRE_DATA,
2158 qry->data, "", NULL,
2162 destroyPQExpBuffer(qry);
2168 * Collect schema-level data about large objects
2171 getBlobs(Archive *fout)
2173 PQExpBuffer blobQry = createPQExpBuffer();
2175 DumpableObject *bdata;
2180 /* Verbose message */
2182 write_msg(NULL, "reading large objects\n");
2184 /* Make sure we are in proper schema */
2185 selectSourceSchema(fout, "pg_catalog");
2187 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2188 if (fout->remoteVersion >= 90000)
2189 appendPQExpBuffer(blobQry,
2190 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2191 " FROM pg_largeobject_metadata",
2193 else if (fout->remoteVersion >= 70100)
2194 appendPQExpBuffer(blobQry,
2195 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2196 " FROM pg_largeobject");
2198 appendPQExpBuffer(blobQry,
2199 "SELECT oid, NULL::oid, NULL::oid"
2200 " FROM pg_class WHERE relkind = 'l'");
2202 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2204 ntups = PQntuples(res);
2208 * Each large object has its own BLOB archive entry.
2210 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2212 for (i = 0; i < ntups; i++)
2214 binfo[i].dobj.objType = DO_BLOB;
2215 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2216 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2217 AssignDumpId(&binfo[i].dobj);
2219 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2220 if (!PQgetisnull(res, i, 1))
2221 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2223 binfo[i].rolname = "";
2224 if (!PQgetisnull(res, i, 2))
2225 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2227 binfo[i].blobacl = NULL;
2231 * If we have any large objects, a "BLOBS" archive entry is needed.
2232 * This is just a placeholder for sorting; it carries no data now.
2234 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2235 bdata->objType = DO_BLOB_DATA;
2236 bdata->catId = nilCatalogId;
2237 AssignDumpId(bdata);
2238 bdata->name = pg_strdup("BLOBS");
2242 destroyPQExpBuffer(blobQry);
2248 * dump the definition (metadata) of the given large object
2251 dumpBlob(Archive *fout, BlobInfo *binfo)
2253 PQExpBuffer cquery = createPQExpBuffer();
2254 PQExpBuffer dquery = createPQExpBuffer();
2256 appendPQExpBuffer(cquery,
2257 "SELECT pg_catalog.lo_create('%s');\n",
2260 appendPQExpBuffer(dquery,
2261 "SELECT pg_catalog.lo_unlink('%s');\n",
2264 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2267 binfo->rolname, false,
2268 "BLOB", SECTION_PRE_DATA,
2269 cquery->data, dquery->data, NULL,
2270 binfo->dobj.dependencies, binfo->dobj.nDeps,
2273 /* set up tag for comment and/or ACL */
2274 resetPQExpBuffer(cquery);
2275 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2277 /* Dump comment if any */
2278 dumpComment(fout, cquery->data,
2279 NULL, binfo->rolname,
2280 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2282 /* Dump security label if any */
2283 dumpSecLabel(fout, cquery->data,
2284 NULL, binfo->rolname,
2285 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2287 /* Dump ACL if any */
2289 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2290 binfo->dobj.name, NULL, cquery->data,
2291 NULL, binfo->rolname, binfo->blobacl);
2293 destroyPQExpBuffer(cquery);
2294 destroyPQExpBuffer(dquery);
2299 * dump the data contents of all large objects
2302 dumpBlobs(Archive *fout, void *arg)
2304 const char *blobQry;
2305 const char *blobFetchQry;
2306 PGconn *conn = GetConnection(fout);
2308 char buf[LOBBUFSIZE];
2314 write_msg(NULL, "saving large objects\n");
2316 /* Make sure we are in proper schema */
2317 selectSourceSchema(fout, "pg_catalog");
2320 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2321 * the already-in-memory dumpable objects instead...
2323 if (fout->remoteVersion >= 90000)
2324 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2325 else if (fout->remoteVersion >= 70100)
2326 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2328 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2330 ExecuteSqlStatement(fout, blobQry);
2332 /* Command to fetch from cursor */
2333 blobFetchQry = "FETCH 1000 IN bloboid";
2338 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2340 /* Process the tuples, if any */
2341 ntups = PQntuples(res);
2342 for (i = 0; i < ntups; i++)
2347 blobOid = atooid(PQgetvalue(res, i, 0));
2349 loFd = lo_open(conn, blobOid, INV_READ);
2351 exit_horribly(NULL, "could not open large object %u: %s",
2352 blobOid, PQerrorMessage(conn));
2354 StartBlob(fout, blobOid);
2356 /* Now read it in chunks, sending data to archive */
2359 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2361 exit_horribly(NULL, "error reading large object %u: %s",
2362 blobOid, PQerrorMessage(conn));
2364 WriteData(fout, buf, cnt);
2367 lo_close(conn, loFd);
2369 EndBlob(fout, blobOid);
2373 } while (ntups > 0);
2379 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2380 PQExpBuffer upgrade_buffer,
2383 PQExpBuffer upgrade_query = createPQExpBuffer();
2384 PGresult *upgrade_res;
2385 Oid pg_type_array_oid;
2387 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2388 appendPQExpBuffer(upgrade_buffer,
2389 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2392 /* we only support old >= 8.3 for binary upgrades */
2393 appendPQExpBuffer(upgrade_query,
2395 "FROM pg_catalog.pg_type "
2396 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2399 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2401 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2403 if (OidIsValid(pg_type_array_oid))
2405 appendPQExpBuffer(upgrade_buffer,
2406 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2407 appendPQExpBuffer(upgrade_buffer,
2408 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2412 PQclear(upgrade_res);
2413 destroyPQExpBuffer(upgrade_query);
2417 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2418 PQExpBuffer upgrade_buffer,
2421 PQExpBuffer upgrade_query = createPQExpBuffer();
2422 PGresult *upgrade_res;
2424 bool toast_set = false;
2426 /* we only support old >= 8.3 for binary upgrades */
2427 appendPQExpBuffer(upgrade_query,
2428 "SELECT c.reltype AS crel, t.reltype AS trel "
2429 "FROM pg_catalog.pg_class c "
2430 "LEFT JOIN pg_catalog.pg_class t ON "
2431 " (c.reltoastrelid = t.oid) "
2432 "WHERE c.oid = '%u'::pg_catalog.oid;",
2435 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2437 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2439 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2442 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2444 /* Toast tables do not have pg_type array rows */
2445 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2446 PQfnumber(upgrade_res, "trel")));
2448 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2449 appendPQExpBuffer(upgrade_buffer,
2450 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2456 PQclear(upgrade_res);
2457 destroyPQExpBuffer(upgrade_query);
2463 binary_upgrade_set_pg_class_oids(Archive *fout,
2464 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2467 PQExpBuffer upgrade_query = createPQExpBuffer();
2468 PGresult *upgrade_res;
2469 Oid pg_class_reltoastrelid;
2470 Oid pg_class_reltoastidxid;
2472 appendPQExpBuffer(upgrade_query,
2473 "SELECT c.reltoastrelid, t.reltoastidxid "
2474 "FROM pg_catalog.pg_class c LEFT JOIN "
2475 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2476 "WHERE c.oid = '%u'::pg_catalog.oid;",
2479 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2481 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2482 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2484 appendPQExpBuffer(upgrade_buffer,
2485 "\n-- For binary upgrade, must preserve pg_class oids\n");
2489 appendPQExpBuffer(upgrade_buffer,
2490 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2492 /* only tables have toast tables, not indexes */
2493 if (OidIsValid(pg_class_reltoastrelid))
2496 * One complexity is that the table definition might not require
2497 * the creation of a TOAST table, and the TOAST table might have
2498 * been created long after table creation, when the table was
2499 * loaded with wide data. By setting the TOAST oid we force
2500 * creation of the TOAST heap and TOAST index by the backend so we
2501 * can cleanly copy the files during binary upgrade.
2504 appendPQExpBuffer(upgrade_buffer,
2505 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2506 pg_class_reltoastrelid);
2508 /* every toast table has an index */
2509 appendPQExpBuffer(upgrade_buffer,
2510 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2511 pg_class_reltoastidxid);
2515 appendPQExpBuffer(upgrade_buffer,
2516 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2519 appendPQExpBuffer(upgrade_buffer, "\n");
2521 PQclear(upgrade_res);
2522 destroyPQExpBuffer(upgrade_query);
2526 * If the DumpableObject is a member of an extension, add a suitable
2527 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2530 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2531 DumpableObject *dobj,
2532 const char *objlabel)
2534 DumpableObject *extobj = NULL;
2537 if (!dobj->ext_member)
2541 * Find the parent extension. We could avoid this search if we wanted to
2542 * add a link field to DumpableObject, but the space costs of that would
2543 * be considerable. We assume that member objects could only have a
2544 * direct dependency on their own extension, not any others.
2546 for (i = 0; i < dobj->nDeps; i++)
2548 extobj = findObjectByDumpId(dobj->dependencies[i]);
2549 if (extobj && extobj->objType == DO_EXTENSION)
2554 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2556 appendPQExpBuffer(upgrade_buffer,
2557 "\n-- For binary upgrade, handle extension membership the hard way\n");
2558 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2559 fmtId(extobj->name),
2565 * read all namespaces in the system catalogs and return them in the
2566 * NamespaceInfo* structure
2568 * numNamespaces is set to the number of namespaces read in
2571 getNamespaces(Archive *fout, int *numNamespaces)
2577 NamespaceInfo *nsinfo;
2585 * Before 7.3, there are no real namespaces; create two dummy entries, one
2586 * for user stuff and one for system stuff.
2588 if (fout->remoteVersion < 70300)
2590 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2592 nsinfo[0].dobj.objType = DO_NAMESPACE;
2593 nsinfo[0].dobj.catId.tableoid = 0;
2594 nsinfo[0].dobj.catId.oid = 0;
2595 AssignDumpId(&nsinfo[0].dobj);
2596 nsinfo[0].dobj.name = pg_strdup("public");
2597 nsinfo[0].rolname = pg_strdup("");
2598 nsinfo[0].nspacl = pg_strdup("");
2600 selectDumpableNamespace(&nsinfo[0]);
2602 nsinfo[1].dobj.objType = DO_NAMESPACE;
2603 nsinfo[1].dobj.catId.tableoid = 0;
2604 nsinfo[1].dobj.catId.oid = 1;
2605 AssignDumpId(&nsinfo[1].dobj);
2606 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2607 nsinfo[1].rolname = pg_strdup("");
2608 nsinfo[1].nspacl = pg_strdup("");
2610 selectDumpableNamespace(&nsinfo[1]);
2612 g_namespaces = nsinfo;
2613 g_numNamespaces = *numNamespaces = 2;
2618 query = createPQExpBuffer();
2620 /* Make sure we are in proper schema */
2621 selectSourceSchema(fout, "pg_catalog");
2624 * we fetch all namespaces including system ones, so that every object we
2625 * read in can be linked to a containing namespace.
2627 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2628 "(%s nspowner) AS rolname, "
2629 "nspacl FROM pg_namespace",
2632 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2634 ntups = PQntuples(res);
2636 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2638 i_tableoid = PQfnumber(res, "tableoid");
2639 i_oid = PQfnumber(res, "oid");
2640 i_nspname = PQfnumber(res, "nspname");
2641 i_rolname = PQfnumber(res, "rolname");
2642 i_nspacl = PQfnumber(res, "nspacl");
2644 for (i = 0; i < ntups; i++)
2646 nsinfo[i].dobj.objType = DO_NAMESPACE;
2647 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2648 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2649 AssignDumpId(&nsinfo[i].dobj);
2650 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2651 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2652 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2654 /* Decide whether to dump this namespace */
2655 selectDumpableNamespace(&nsinfo[i]);
2657 if (strlen(nsinfo[i].rolname) == 0)
2658 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2659 nsinfo[i].dobj.name);
2663 destroyPQExpBuffer(query);
2665 g_namespaces = nsinfo;
2666 g_numNamespaces = *numNamespaces = ntups;
2673 * given a namespace OID and an object OID, look up the info read by
2676 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2677 * a system object or not. In 7.3 and later there is no guessing.
2679 static NamespaceInfo *
2680 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2684 if (fout->remoteVersion >= 70300)
2686 for (i = 0; i < g_numNamespaces; i++)
2688 NamespaceInfo *nsinfo = &g_namespaces[i];
2690 if (nsoid == nsinfo->dobj.catId.oid)
2693 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2697 /* This code depends on the layout set up by getNamespaces. */
2698 if (objoid > g_last_builtin_oid)
2699 i = 0; /* user object */
2701 i = 1; /* system object */
2702 return &g_namespaces[i];
2705 return NULL; /* keep compiler quiet */
2710 * read all extensions in the system catalogs and return them in the
2711 * ExtensionInfo* structure
2713 * numExtensions is set to the number of extensions read in
2716 getExtensions(Archive *fout, int *numExtensions)
2722 ExtensionInfo *extinfo;
2727 int i_extrelocatable;
2733 * Before 9.1, there are no extensions.
2735 if (fout->remoteVersion < 90100)
2741 query = createPQExpBuffer();
2743 /* Make sure we are in proper schema */
2744 selectSourceSchema(fout, "pg_catalog");
2746 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2747 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2748 "FROM pg_extension x "
2749 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2751 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2753 ntups = PQntuples(res);
2755 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2757 i_tableoid = PQfnumber(res, "tableoid");
2758 i_oid = PQfnumber(res, "oid");
2759 i_extname = PQfnumber(res, "extname");
2760 i_nspname = PQfnumber(res, "nspname");
2761 i_extrelocatable = PQfnumber(res, "extrelocatable");
2762 i_extversion = PQfnumber(res, "extversion");
2763 i_extconfig = PQfnumber(res, "extconfig");
2764 i_extcondition = PQfnumber(res, "extcondition");
2766 for (i = 0; i < ntups; i++)
2768 extinfo[i].dobj.objType = DO_EXTENSION;
2769 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2770 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2771 AssignDumpId(&extinfo[i].dobj);
2772 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2773 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2774 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2775 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2776 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2777 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2779 /* Decide whether we want to dump it */
2780 selectDumpableExtension(&(extinfo[i]));
2784 destroyPQExpBuffer(query);
2786 *numExtensions = ntups;
2793 * read all types in the system catalogs and return them in the
2794 * TypeInfo* structure
2796 * numTypes is set to the number of types read in
2798 * NB: this must run after getFuncs() because we assume we can do
2802 getTypes(Archive *fout, int *numTypes)
2807 PQExpBuffer query = createPQExpBuffer();
2809 ShellTypeInfo *stinfo;
2825 * we include even the built-in types because those may be used as array
2826 * elements by user-defined types
2828 * we filter out the built-in types when we dump out the types
2830 * same approach for undefined (shell) types and array types
2832 * Note: as of 8.3 we can reliably detect whether a type is an
2833 * auto-generated array type by checking the element type's typarray.
2834 * (Before that the test is capable of generating false positives.) We
2835 * still check for name beginning with '_', though, so as to avoid the
2836 * cost of the subselect probe for all standard types. This would have to
2837 * be revisited if the backend ever allows renaming of array types.
2840 /* Make sure we are in proper schema */
2841 selectSourceSchema(fout, "pg_catalog");
2843 if (fout->remoteVersion >= 80300)
2845 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2847 "(%s typowner) AS rolname, "
2848 "typinput::oid AS typinput, "
2849 "typoutput::oid AS typoutput, typelem, typrelid, "
2850 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2851 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2852 "typtype, typisdefined, "
2853 "typname[0] = '_' AND typelem != 0 AND "
2854 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2858 else if (fout->remoteVersion >= 70300)
2860 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2862 "(%s typowner) AS rolname, "
2863 "typinput::oid AS typinput, "
2864 "typoutput::oid AS typoutput, typelem, typrelid, "
2865 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2866 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2867 "typtype, typisdefined, "
2868 "typname[0] = '_' AND typelem != 0 AS isarray "
2872 else if (fout->remoteVersion >= 70100)
2874 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2875 "0::oid AS typnamespace, "
2876 "(%s typowner) AS rolname, "
2877 "typinput::oid AS typinput, "
2878 "typoutput::oid AS typoutput, typelem, typrelid, "
2879 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2880 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2881 "typtype, typisdefined, "
2882 "typname[0] = '_' AND typelem != 0 AS isarray "
2888 appendPQExpBuffer(query, "SELECT "
2889 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2891 "0::oid AS typnamespace, "
2892 "(%s typowner) AS rolname, "
2893 "typinput::oid AS typinput, "
2894 "typoutput::oid AS typoutput, typelem, typrelid, "
2895 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2896 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2897 "typtype, typisdefined, "
2898 "typname[0] = '_' AND typelem != 0 AS isarray "
2903 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2905 ntups = PQntuples(res);
2907 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2909 i_tableoid = PQfnumber(res, "tableoid");
2910 i_oid = PQfnumber(res, "oid");
2911 i_typname = PQfnumber(res, "typname");
2912 i_typnamespace = PQfnumber(res, "typnamespace");
2913 i_rolname = PQfnumber(res, "rolname");
2914 i_typinput = PQfnumber(res, "typinput");
2915 i_typoutput = PQfnumber(res, "typoutput");
2916 i_typelem = PQfnumber(res, "typelem");
2917 i_typrelid = PQfnumber(res, "typrelid");
2918 i_typrelkind = PQfnumber(res, "typrelkind");
2919 i_typtype = PQfnumber(res, "typtype");
2920 i_typisdefined = PQfnumber(res, "typisdefined");
2921 i_isarray = PQfnumber(res, "isarray");
2923 for (i = 0; i < ntups; i++)
2925 tyinfo[i].dobj.objType = DO_TYPE;
2926 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2927 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2928 AssignDumpId(&tyinfo[i].dobj);
2929 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2930 tyinfo[i].dobj.namespace =
2932 atooid(PQgetvalue(res, i, i_typnamespace)),
2933 tyinfo[i].dobj.catId.oid);
2934 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2935 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2936 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2937 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2938 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2939 tyinfo[i].shellType = NULL;
2941 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2942 tyinfo[i].isDefined = true;
2944 tyinfo[i].isDefined = false;
2946 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2947 tyinfo[i].isArray = true;
2949 tyinfo[i].isArray = false;
2951 /* Decide whether we want to dump it */
2952 selectDumpableType(&tyinfo[i]);
2955 * If it's a domain, fetch info about its constraints, if any
2957 tyinfo[i].nDomChecks = 0;
2958 tyinfo[i].domChecks = NULL;
2959 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2960 getDomainConstraints(fout, &(tyinfo[i]));
2963 * If it's a base type, make a DumpableObject representing a shell
2964 * definition of the type. We will need to dump that ahead of the I/O
2965 * functions for the type. Similarly, range types need a shell
2966 * definition in case they have a canonicalize function.
2968 * Note: the shell type doesn't have a catId. You might think it
2969 * should copy the base type's catId, but then it might capture the
2970 * pg_depend entries for the type, which we don't want.
2972 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2973 tyinfo[i].typtype == TYPTYPE_RANGE))
2975 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2976 stinfo->dobj.objType = DO_SHELL_TYPE;
2977 stinfo->dobj.catId = nilCatalogId;
2978 AssignDumpId(&stinfo->dobj);
2979 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2980 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2981 stinfo->baseType = &(tyinfo[i]);
2982 tyinfo[i].shellType = stinfo;
2985 * Initially mark the shell type as not to be dumped. We'll only
2986 * dump it if the I/O or canonicalize functions need to be dumped;
2987 * this is taken care of while sorting dependencies.
2989 stinfo->dobj.dump = false;
2992 * However, if dumping from pre-7.3, there will be no dependency
2993 * info so we have to fake it here. We only need to worry about
2994 * typinput and typoutput since the other functions only exist
2997 if (fout->remoteVersion < 70300)
3003 typinput = atooid(PQgetvalue(res, i, i_typinput));
3004 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3006 funcInfo = findFuncByOid(typinput);
3007 if (funcInfo && funcInfo->dobj.dump)
3009 /* base type depends on function */
3010 addObjectDependency(&tyinfo[i].dobj,
3011 funcInfo->dobj.dumpId);
3012 /* function depends on shell type */
3013 addObjectDependency(&funcInfo->dobj,
3014 stinfo->dobj.dumpId);
3015 /* mark shell type as to be dumped */
3016 stinfo->dobj.dump = true;
3019 funcInfo = findFuncByOid(typoutput);
3020 if (funcInfo && funcInfo->dobj.dump)
3022 /* base type depends on function */
3023 addObjectDependency(&tyinfo[i].dobj,
3024 funcInfo->dobj.dumpId);
3025 /* function depends on shell type */
3026 addObjectDependency(&funcInfo->dobj,
3027 stinfo->dobj.dumpId);
3028 /* mark shell type as to be dumped */
3029 stinfo->dobj.dump = true;
3034 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3035 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3036 tyinfo[i].dobj.name);
3043 destroyPQExpBuffer(query);
3050 * read all operators in the system catalogs and return them in the
3051 * OprInfo* structure
3053 * numOprs is set to the number of operators read in
3056 getOperators(Archive *fout, int *numOprs)
3061 PQExpBuffer query = createPQExpBuffer();
3072 * find all operators, including builtin operators; we filter out
3073 * system-defined operators at dump-out time.
3076 /* Make sure we are in proper schema */
3077 selectSourceSchema(fout, "pg_catalog");
3079 if (fout->remoteVersion >= 70300)
3081 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3083 "(%s oprowner) AS rolname, "
3085 "oprcode::oid AS oprcode "
3089 else if (fout->remoteVersion >= 70100)
3091 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3092 "0::oid AS oprnamespace, "
3093 "(%s oprowner) AS rolname, "
3095 "oprcode::oid AS oprcode "
3101 appendPQExpBuffer(query, "SELECT "
3102 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3104 "0::oid AS oprnamespace, "
3105 "(%s oprowner) AS rolname, "
3107 "oprcode::oid AS oprcode "
3112 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3114 ntups = PQntuples(res);
3117 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3119 i_tableoid = PQfnumber(res, "tableoid");
3120 i_oid = PQfnumber(res, "oid");
3121 i_oprname = PQfnumber(res, "oprname");
3122 i_oprnamespace = PQfnumber(res, "oprnamespace");
3123 i_rolname = PQfnumber(res, "rolname");
3124 i_oprkind = PQfnumber(res, "oprkind");
3125 i_oprcode = PQfnumber(res, "oprcode");
3127 for (i = 0; i < ntups; i++)
3129 oprinfo[i].dobj.objType = DO_OPERATOR;
3130 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3131 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3132 AssignDumpId(&oprinfo[i].dobj);
3133 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3134 oprinfo[i].dobj.namespace =
3136 atooid(PQgetvalue(res, i, i_oprnamespace)),
3137 oprinfo[i].dobj.catId.oid);
3138 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3139 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3140 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3142 /* Decide whether we want to dump it */
3143 selectDumpableObject(&(oprinfo[i].dobj));
3145 if (strlen(oprinfo[i].rolname) == 0)
3146 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3147 oprinfo[i].dobj.name);
3152 destroyPQExpBuffer(query);
3159 * read all collations in the system catalogs and return them in the
3160 * CollInfo* structure
3162 * numCollations is set to the number of collations read in
3165 getCollations(Archive *fout, int *numCollations)
3175 int i_collnamespace;
3178 /* Collations didn't exist pre-9.1 */
3179 if (fout->remoteVersion < 90100)
3185 query = createPQExpBuffer();
3188 * find all collations, including builtin collations; we filter out
3189 * system-defined collations at dump-out time.
3192 /* Make sure we are in proper schema */
3193 selectSourceSchema(fout, "pg_catalog");
3195 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3197 "(%s collowner) AS rolname "
3198 "FROM pg_collation",
3201 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3203 ntups = PQntuples(res);
3204 *numCollations = ntups;
3206 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3208 i_tableoid = PQfnumber(res, "tableoid");
3209 i_oid = PQfnumber(res, "oid");
3210 i_collname = PQfnumber(res, "collname");
3211 i_collnamespace = PQfnumber(res, "collnamespace");
3212 i_rolname = PQfnumber(res, "rolname");
3214 for (i = 0; i < ntups; i++)
3216 collinfo[i].dobj.objType = DO_COLLATION;
3217 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3218 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3219 AssignDumpId(&collinfo[i].dobj);
3220 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3221 collinfo[i].dobj.namespace =
3223 atooid(PQgetvalue(res, i, i_collnamespace)),
3224 collinfo[i].dobj.catId.oid);
3225 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3227 /* Decide whether we want to dump it */
3228 selectDumpableObject(&(collinfo[i].dobj));
3233 destroyPQExpBuffer(query);
3240 * read all conversions in the system catalogs and return them in the
3241 * ConvInfo* structure
3243 * numConversions is set to the number of conversions read in
3246 getConversions(Archive *fout, int *numConversions)
3251 PQExpBuffer query = createPQExpBuffer();
3259 /* Conversions didn't exist pre-7.3 */
3260 if (fout->remoteVersion < 70300)
3262 *numConversions = 0;
3267 * find all conversions, including builtin conversions; we filter out
3268 * system-defined conversions at dump-out time.
3271 /* Make sure we are in proper schema */
3272 selectSourceSchema(fout, "pg_catalog");
3274 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3276 "(%s conowner) AS rolname "
3277 "FROM pg_conversion",
3280 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3282 ntups = PQntuples(res);
3283 *numConversions = ntups;
3285 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3287 i_tableoid = PQfnumber(res, "tableoid");
3288 i_oid = PQfnumber(res, "oid");
3289 i_conname = PQfnumber(res, "conname");
3290 i_connamespace = PQfnumber(res, "connamespace");
3291 i_rolname = PQfnumber(res, "rolname");
3293 for (i = 0; i < ntups; i++)
3295 convinfo[i].dobj.objType = DO_CONVERSION;
3296 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3297 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3298 AssignDumpId(&convinfo[i].dobj);
3299 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3300 convinfo[i].dobj.namespace =
3302 atooid(PQgetvalue(res, i, i_connamespace)),
3303 convinfo[i].dobj.catId.oid);
3304 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3306 /* Decide whether we want to dump it */
3307 selectDumpableObject(&(convinfo[i].dobj));
3312 destroyPQExpBuffer(query);
3319 * read all opclasses in the system catalogs and return them in the
3320 * OpclassInfo* structure
3322 * numOpclasses is set to the number of opclasses read in
3325 getOpclasses(Archive *fout, int *numOpclasses)
3330 PQExpBuffer query = createPQExpBuffer();
3331 OpclassInfo *opcinfo;
3339 * find all opclasses, including builtin opclasses; we filter out
3340 * system-defined opclasses at dump-out time.
3343 /* Make sure we are in proper schema */
3344 selectSourceSchema(fout, "pg_catalog");
3346 if (fout->remoteVersion >= 70300)
3348 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3350 "(%s opcowner) AS rolname "
3354 else if (fout->remoteVersion >= 70100)
3356 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3357 "0::oid AS opcnamespace, "
3358 "''::name AS rolname "
3363 appendPQExpBuffer(query, "SELECT "
3364 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3366 "0::oid AS opcnamespace, "
3367 "''::name AS rolname "
3371 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3373 ntups = PQntuples(res);
3374 *numOpclasses = ntups;
3376 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3378 i_tableoid = PQfnumber(res, "tableoid");
3379 i_oid = PQfnumber(res, "oid");
3380 i_opcname = PQfnumber(res, "opcname");
3381 i_opcnamespace = PQfnumber(res, "opcnamespace");
3382 i_rolname = PQfnumber(res, "rolname");
3384 for (i = 0; i < ntups; i++)
3386 opcinfo[i].dobj.objType = DO_OPCLASS;
3387 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3388 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3389 AssignDumpId(&opcinfo[i].dobj);
3390 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3391 opcinfo[i].dobj.namespace =
3393 atooid(PQgetvalue(res, i, i_opcnamespace)),
3394 opcinfo[i].dobj.catId.oid);
3395 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3397 /* Decide whether we want to dump it */
3398 selectDumpableObject(&(opcinfo[i].dobj));
3400 if (fout->remoteVersion >= 70300)
3402 if (strlen(opcinfo[i].rolname) == 0)
3403 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3404 opcinfo[i].dobj.name);
3410 destroyPQExpBuffer(query);
3417 * read all opfamilies in the system catalogs and return them in the
3418 * OpfamilyInfo* structure
3420 * numOpfamilies is set to the number of opfamilies read in
3423 getOpfamilies(Archive *fout, int *numOpfamilies)
3429 OpfamilyInfo *opfinfo;
3436 /* Before 8.3, there is no separate concept of opfamilies */
3437 if (fout->remoteVersion < 80300)
3443 query = createPQExpBuffer();
3446 * find all opfamilies, including builtin opfamilies; we filter out
3447 * system-defined opfamilies at dump-out time.
3450 /* Make sure we are in proper schema */
3451 selectSourceSchema(fout, "pg_catalog");
3453 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3455 "(%s opfowner) AS rolname "
3459 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3461 ntups = PQntuples(res);
3462 *numOpfamilies = ntups;
3464 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3466 i_tableoid = PQfnumber(res, "tableoid");
3467 i_oid = PQfnumber(res, "oid");
3468 i_opfname = PQfnumber(res, "opfname");
3469 i_opfnamespace = PQfnumber(res, "opfnamespace");
3470 i_rolname = PQfnumber(res, "rolname");
3472 for (i = 0; i < ntups; i++)
3474 opfinfo[i].dobj.objType = DO_OPFAMILY;
3475 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3476 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3477 AssignDumpId(&opfinfo[i].dobj);
3478 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3479 opfinfo[i].dobj.namespace =
3481 atooid(PQgetvalue(res, i, i_opfnamespace)),
3482 opfinfo[i].dobj.catId.oid);
3483 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3485 /* Decide whether we want to dump it */
3486 selectDumpableObject(&(opfinfo[i].dobj));
3488 if (fout->remoteVersion >= 70300)
3490 if (strlen(opfinfo[i].rolname) == 0)
3491 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3492 opfinfo[i].dobj.name);
3498 destroyPQExpBuffer(query);
3505 * read all the user-defined aggregates in the system catalogs and
3506 * return them in the AggInfo* structure
3508 * numAggs is set to the number of aggregates read in
3511 getAggregates(Archive *fout, int *numAggs)
3516 PQExpBuffer query = createPQExpBuffer();
3527 /* Make sure we are in proper schema */
3528 selectSourceSchema(fout, "pg_catalog");
3531 * Find all user-defined aggregates. See comment in getFuncs() for the
3532 * rationale behind the filtering logic.
3535 if (fout->remoteVersion >= 80200)
3537 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3538 "pronamespace AS aggnamespace, "
3539 "pronargs, proargtypes, "
3540 "(%s proowner) AS rolname, "
3543 "WHERE proisagg AND ("
3545 "(SELECT oid FROM pg_namespace "
3546 "WHERE nspname = 'pg_catalog')",
3548 if (binary_upgrade && fout->remoteVersion >= 90100)
3549 appendPQExpBuffer(query,
3550 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3551 "classid = 'pg_proc'::regclass AND "
3552 "objid = p.oid AND "
3553 "refclassid = 'pg_extension'::regclass AND "
3555 appendPQExpBuffer(query, ")");
3557 else if (fout->remoteVersion >= 70300)
3559 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3560 "pronamespace AS aggnamespace, "
3561 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3563 "(%s proowner) AS rolname, "
3567 "AND pronamespace != "
3568 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3571 else if (fout->remoteVersion >= 70100)
3573 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3574 "0::oid AS aggnamespace, "
3575 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3576 "aggbasetype AS proargtypes, "
3577 "(%s aggowner) AS rolname, "
3579 "FROM pg_aggregate "
3580 "where oid > '%u'::oid",
3582 g_last_builtin_oid);
3586 appendPQExpBuffer(query, "SELECT "
3587 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3589 "0::oid AS aggnamespace, "
3590 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3591 "aggbasetype AS proargtypes, "
3592 "(%s aggowner) AS rolname, "
3594 "FROM pg_aggregate "
3595 "where oid > '%u'::oid",
3597 g_last_builtin_oid);
3600 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3602 ntups = PQntuples(res);
3605 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3607 i_tableoid = PQfnumber(res, "tableoid");
3608 i_oid = PQfnumber(res, "oid");
3609 i_aggname = PQfnumber(res, "aggname");
3610 i_aggnamespace = PQfnumber(res, "aggnamespace");
3611 i_pronargs = PQfnumber(res, "pronargs");
3612 i_proargtypes = PQfnumber(res, "proargtypes");
3613 i_rolname = PQfnumber(res, "rolname");
3614 i_aggacl = PQfnumber(res, "aggacl");
3616 for (i = 0; i < ntups; i++)
3618 agginfo[i].aggfn.dobj.objType = DO_AGG;
3619 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3620 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3621 AssignDumpId(&agginfo[i].aggfn.dobj);
3622 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3623 agginfo[i].aggfn.dobj.namespace =
3625 atooid(PQgetvalue(res, i, i_aggnamespace)),
3626 agginfo[i].aggfn.dobj.catId.oid);
3627 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3628 if (strlen(agginfo[i].aggfn.rolname) == 0)
3629 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3630 agginfo[i].aggfn.dobj.name);
3631 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3632 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3633 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3634 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3635 if (agginfo[i].aggfn.nargs == 0)
3636 agginfo[i].aggfn.argtypes = NULL;
3639 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3640 if (fout->remoteVersion >= 70300)
3641 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3642 agginfo[i].aggfn.argtypes,
3643 agginfo[i].aggfn.nargs);
3645 /* it's just aggbasetype */
3646 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3649 /* Decide whether we want to dump it */
3650 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3655 destroyPQExpBuffer(query);
3662 * read all the user-defined functions in the system catalogs and
3663 * return them in the FuncInfo* structure
3665 * numFuncs is set to the number of functions read in
3668 getFuncs(Archive *fout, int *numFuncs)
3673 PQExpBuffer query = createPQExpBuffer();
3686 /* Make sure we are in proper schema */
3687 selectSourceSchema(fout, "pg_catalog");
3690 * Find all user-defined functions. Normally we can exclude functions in
3691 * pg_catalog, which is worth doing since there are several thousand of
3692 * 'em. However, there are some extensions that create functions in
3693 * pg_catalog. In normal dumps we can still ignore those --- but in
3694 * binary-upgrade mode, we must dump the member objects of the extension,
3695 * so be sure to fetch any such functions.
3697 * Also, in 9.2 and up, exclude functions that are internally dependent on
3698 * something else, since presumably those will be created as a result of
3699 * creating the something else. This currently only acts to suppress
3700 * constructor functions for range types. Note that this is OK only
3701 * because the constructors don't have any dependencies the range type
3702 * doesn't have; otherwise we might not get creation ordering correct.
3705 if (fout->remoteVersion >= 70300)
3707 appendPQExpBuffer(query,
3708 "SELECT tableoid, oid, proname, prolang, "
3709 "pronargs, proargtypes, prorettype, proacl, "
3711 "(%s proowner) AS rolname "
3713 "WHERE NOT proisagg AND ("
3715 "(SELECT oid FROM pg_namespace "
3716 "WHERE nspname = 'pg_catalog')",
3718 if (fout->remoteVersion >= 90200)
3719 appendPQExpBuffer(query,
3720 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3721 "WHERE classid = 'pg_proc'::regclass AND "
3722 "objid = p.oid AND deptype = 'i')");
3723 if (binary_upgrade && fout->remoteVersion >= 90100)
3724 appendPQExpBuffer(query,
3725 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3726 "classid = 'pg_proc'::regclass AND "
3727 "objid = p.oid AND "
3728 "refclassid = 'pg_extension'::regclass AND "
3730 appendPQExpBuffer(query, ")");
3732 else if (fout->remoteVersion >= 70100)
3734 appendPQExpBuffer(query,
3735 "SELECT tableoid, oid, proname, prolang, "
3736 "pronargs, proargtypes, prorettype, "
3737 "'{=X}' AS proacl, "
3738 "0::oid AS pronamespace, "
3739 "(%s proowner) AS rolname "
3741 "WHERE pg_proc.oid > '%u'::oid",
3743 g_last_builtin_oid);
3747 appendPQExpBuffer(query,
3749 "(SELECT oid FROM pg_class "
3750 " WHERE relname = 'pg_proc') AS tableoid, "
3751 "oid, proname, prolang, "
3752 "pronargs, proargtypes, prorettype, "
3753 "'{=X}' AS proacl, "
3754 "0::oid AS pronamespace, "
3755 "(%s proowner) AS rolname "
3757 "where pg_proc.oid > '%u'::oid",
3759 g_last_builtin_oid);
3762 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3764 ntups = PQntuples(res);
3768 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3770 i_tableoid = PQfnumber(res, "tableoid");
3771 i_oid = PQfnumber(res, "oid");
3772 i_proname = PQfnumber(res, "proname");
3773 i_pronamespace = PQfnumber(res, "pronamespace");
3774 i_rolname = PQfnumber(res, "rolname");
3775 i_prolang = PQfnumber(res, "prolang");
3776 i_pronargs = PQfnumber(res, "pronargs");
3777 i_proargtypes = PQfnumber(res, "proargtypes");
3778 i_prorettype = PQfnumber(res, "prorettype");
3779 i_proacl = PQfnumber(res, "proacl");
3781 for (i = 0; i < ntups; i++)
3783 finfo[i].dobj.objType = DO_FUNC;
3784 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3785 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3786 AssignDumpId(&finfo[i].dobj);
3787 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3788 finfo[i].dobj.namespace =
3790 atooid(PQgetvalue(res, i, i_pronamespace)),
3791 finfo[i].dobj.catId.oid);
3792 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3793 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3794 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3795 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3796 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3797 if (finfo[i].nargs == 0)
3798 finfo[i].argtypes = NULL;
3801 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3802 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3803 finfo[i].argtypes, finfo[i].nargs);
3806 /* Decide whether we want to dump it */
3807 selectDumpableObject(&(finfo[i].dobj));
3809 if (strlen(finfo[i].rolname) == 0)
3811 "WARNING: owner of function \"%s\" appears to be invalid\n",
3812 finfo[i].dobj.name);
3817 destroyPQExpBuffer(query);
3824 * read all the user-defined tables (no indexes, no catalogs)
3825 * in the system catalogs return them in the TableInfo* structure
3827 * numTables is set to the number of tables read in
3830 getTables(Archive *fout, int *numTables)
3835 PQExpBuffer query = createPQExpBuffer();
3845 int i_relhastriggers;
3851 int i_toastfrozenxid;
3852 int i_relpersistence;
3855 int i_reltablespace;
3857 int i_toastreloptions;
3860 /* Make sure we are in proper schema */
3861 selectSourceSchema(fout, "pg_catalog");
3864 * Find all the tables (including views and sequences).
3866 * We include system catalogs, so that we can work if a user table is
3867 * defined to inherit from a system catalog (pretty weird, but...)
3869 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3870 * (sequence), 'v' (view), or 'c' (composite type).
3872 * Composite-type table entries won't be dumped as such, but we have to
3873 * make a DumpableObject for them so that we can track dependencies of the
3874 * composite type (pg_depend entries for columns of the composite type
3875 * link to the pg_class entry not the pg_type entry).
3877 * Note: in this phase we should collect only a minimal amount of
3878 * information about each table, basically just enough to decide if it is
3879 * interesting. We must fetch all tables in this phase because otherwise
3880 * we cannot correctly identify inherited columns, owned sequences, etc.
3883 if (fout->remoteVersion >= 90100)
3886 * Left join to pick up dependency info linking sequences to their
3887 * owning column, if any (note this dependency is AUTO as of 8.2)
3889 appendPQExpBuffer(query,
3890 "SELECT c.tableoid, c.oid, c.relname, "
3891 "c.relacl, c.relkind, c.relnamespace, "
3892 "(%s c.relowner) AS rolname, "
3893 "c.relchecks, c.relhastriggers, "
3894 "c.relhasindex, c.relhasrules, c.relhasoids, "
3895 "c.relfrozenxid, tc.oid AS toid, "
3896 "tc.relfrozenxid AS tfrozenxid, "
3897 "c.relpersistence, "
3898 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3899 "d.refobjid AS owning_tab, "
3900 "d.refobjsubid AS owning_col, "
3901 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3902 "array_to_string(c.reloptions, ', ') AS reloptions, "
3903 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3905 "LEFT JOIN pg_depend d ON "
3906 "(c.relkind = '%c' AND "
3907 "d.classid = c.tableoid AND d.objid = c.oid AND "
3908 "d.objsubid = 0 AND "
3909 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3910 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3911 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3915 RELKIND_RELATION, RELKIND_SEQUENCE,
3916 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3917 RELKIND_FOREIGN_TABLE);
3919 else if (fout->remoteVersion >= 90000)
3922 * Left join to pick up dependency info linking sequences to their
3923 * owning column, if any (note this dependency is AUTO as of 8.2)
3925 appendPQExpBuffer(query,
3926 "SELECT c.tableoid, c.oid, c.relname, "
3927 "c.relacl, c.relkind, c.relnamespace, "
3928 "(%s c.relowner) AS rolname, "
3929 "c.relchecks, c.relhastriggers, "
3930 "c.relhasindex, c.relhasrules, c.relhasoids, "
3931 "c.relfrozenxid, tc.oid AS toid, "
3932 "tc.relfrozenxid AS tfrozenxid, "
3933 "'p' AS relpersistence, "
3934 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3935 "d.refobjid AS owning_tab, "
3936 "d.refobjsubid AS owning_col, "
3937 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3938 "array_to_string(c.reloptions, ', ') AS reloptions, "
3939 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3941 "LEFT JOIN pg_depend d ON "
3942 "(c.relkind = '%c' AND "
3943 "d.classid = c.tableoid AND d.objid = c.oid AND "
3944 "d.objsubid = 0 AND "
3945 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3946 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3947 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3951 RELKIND_RELATION, RELKIND_SEQUENCE,
3952 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3954 else if (fout->remoteVersion >= 80400)
3957 * Left join to pick up dependency info linking sequences to their
3958 * owning column, if any (note this dependency is AUTO as of 8.2)
3960 appendPQExpBuffer(query,
3961 "SELECT c.tableoid, c.oid, c.relname, "
3962 "c.relacl, c.relkind, c.relnamespace, "
3963 "(%s c.relowner) AS rolname, "
3964 "c.relchecks, c.relhastriggers, "
3965 "c.relhasindex, c.relhasrules, c.relhasoids, "
3966 "c.relfrozenxid, tc.oid AS toid, "
3967 "tc.relfrozenxid AS tfrozenxid, "
3968 "'p' AS relpersistence, "
3969 "NULL AS reloftype, "
3970 "d.refobjid AS owning_tab, "
3971 "d.refobjsubid AS owning_col, "
3972 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3973 "array_to_string(c.reloptions, ', ') AS reloptions, "
3974 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3976 "LEFT JOIN pg_depend d ON "
3977 "(c.relkind = '%c' AND "
3978 "d.classid = c.tableoid AND d.objid = c.oid AND "
3979 "d.objsubid = 0 AND "
3980 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3981 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3982 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3986 RELKIND_RELATION, RELKIND_SEQUENCE,
3987 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3989 else if (fout->remoteVersion >= 80200)
3992 * Left join to pick up dependency info linking sequences to their
3993 * owning column, if any (note this dependency is AUTO as of 8.2)
3995 appendPQExpBuffer(query,
3996 "SELECT c.tableoid, c.oid, c.relname, "
3997 "c.relacl, c.relkind, c.relnamespace, "
3998 "(%s c.relowner) AS rolname, "
3999 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4000 "c.relhasindex, c.relhasrules, c.relhasoids, "
4001 "c.relfrozenxid, tc.oid AS toid, "
4002 "tc.relfrozenxid AS tfrozenxid, "
4003 "'p' AS relpersistence, "
4004 "NULL AS reloftype, "
4005 "d.refobjid AS owning_tab, "
4006 "d.refobjsubid AS owning_col, "
4007 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4008 "array_to_string(c.reloptions, ', ') AS reloptions, "
4009 "NULL AS toast_reloptions "
4011 "LEFT JOIN pg_depend d ON "
4012 "(c.relkind = '%c' AND "
4013 "d.classid = c.tableoid AND d.objid = c.oid AND "
4014 "d.objsubid = 0 AND "
4015 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4016 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4017 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4021 RELKIND_RELATION, RELKIND_SEQUENCE,
4022 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4024 else if (fout->remoteVersion >= 80000)
4027 * Left join to pick up dependency info linking sequences to their
4028 * owning column, if any
4030 appendPQExpBuffer(query,
4031 "SELECT c.tableoid, c.oid, relname, "
4032 "relacl, relkind, relnamespace, "
4033 "(%s relowner) AS rolname, "
4034 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4035 "relhasindex, relhasrules, relhasoids, "
4036 "0 AS relfrozenxid, "
4039 "'p' AS relpersistence, "
4040 "NULL AS reloftype, "
4041 "d.refobjid AS owning_tab, "
4042 "d.refobjsubid AS owning_col, "
4043 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4044 "NULL AS reloptions, "
4045 "NULL AS toast_reloptions "
4047 "LEFT JOIN pg_depend d ON "
4048 "(c.relkind = '%c' AND "
4049 "d.classid = c.tableoid AND d.objid = c.oid AND "
4050 "d.objsubid = 0 AND "
4051 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4052 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4056 RELKIND_RELATION, RELKIND_SEQUENCE,
4057 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4059 else if (fout->remoteVersion >= 70300)
4062 * Left join to pick up dependency info linking sequences to their
4063 * owning column, if any
4065 appendPQExpBuffer(query,
4066 "SELECT c.tableoid, c.oid, relname, "
4067 "relacl, relkind, relnamespace, "
4068 "(%s relowner) AS rolname, "
4069 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4070 "relhasindex, relhasrules, relhasoids, "
4071 "0 AS relfrozenxid, "
4074 "'p' AS relpersistence, "
4075 "NULL AS reloftype, "
4076 "d.refobjid AS owning_tab, "
4077 "d.refobjsubid AS owning_col, "
4078 "NULL AS reltablespace, "
4079 "NULL AS reloptions, "
4080 "NULL AS toast_reloptions "
4082 "LEFT JOIN pg_depend d ON "
4083 "(c.relkind = '%c' AND "
4084 "d.classid = c.tableoid AND d.objid = c.oid AND "
4085 "d.objsubid = 0 AND "
4086 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4087 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4091 RELKIND_RELATION, RELKIND_SEQUENCE,
4092 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4094 else if (fout->remoteVersion >= 70200)
4096 appendPQExpBuffer(query,
4097 "SELECT tableoid, oid, relname, relacl, relkind, "
4098 "0::oid AS relnamespace, "
4099 "(%s relowner) AS rolname, "
4100 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4101 "relhasindex, relhasrules, relhasoids, "
4102 "0 AS relfrozenxid, "
4105 "'p' AS relpersistence, "
4106 "NULL AS reloftype, "
4107 "NULL::oid AS owning_tab, "
4108 "NULL::int4 AS owning_col, "
4109 "NULL AS reltablespace, "
4110 "NULL AS reloptions, "
4111 "NULL AS toast_reloptions "
4113 "WHERE relkind IN ('%c', '%c', '%c') "
4116 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4118 else if (fout->remoteVersion >= 70100)
4120 /* all tables have oids in 7.1 */
4121 appendPQExpBuffer(query,
4122 "SELECT tableoid, oid, relname, relacl, relkind, "
4123 "0::oid AS relnamespace, "
4124 "(%s relowner) AS rolname, "
4125 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4126 "relhasindex, relhasrules, "
4127 "'t'::bool AS relhasoids, "
4128 "0 AS relfrozenxid, "
4131 "'p' AS relpersistence, "
4132 "NULL AS reloftype, "
4133 "NULL::oid AS owning_tab, "
4134 "NULL::int4 AS owning_col, "
4135 "NULL AS reltablespace, "
4136 "NULL AS reloptions, "
4137 "NULL AS toast_reloptions "
4139 "WHERE relkind IN ('%c', '%c', '%c') "
4142 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4147 * Before 7.1, view relkind was not set to 'v', so we must check if we
4148 * have a view by looking for a rule in pg_rewrite.
4150 appendPQExpBuffer(query,
4152 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4153 "oid, relname, relacl, "
4154 "CASE WHEN relhasrules and relkind = 'r' "
4155 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4156 " r.ev_class = c.oid AND r.ev_type = '1') "
4157 "THEN '%c'::\"char\" "
4158 "ELSE relkind END AS relkind,"
4159 "0::oid AS relnamespace, "
4160 "(%s relowner) AS rolname, "
4161 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4162 "relhasindex, relhasrules, "
4163 "'t'::bool AS relhasoids, "
4164 "0 as relfrozenxid, "
4167 "'p' AS relpersistence, "
4168 "NULL AS reloftype, "
4169 "NULL::oid AS owning_tab, "
4170 "NULL::int4 AS owning_col, "
4171 "NULL AS reltablespace, "
4172 "NULL AS reloptions, "
4173 "NULL AS toast_reloptions "
4175 "WHERE relkind IN ('%c', '%c') "
4179 RELKIND_RELATION, RELKIND_SEQUENCE);
4182 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4184 ntups = PQntuples(res);
4189 * Extract data from result and lock dumpable tables. We do the locking
4190 * before anything else, to minimize the window wherein a table could
4191 * disappear under us.
4193 * Note that we have to save info about all tables here, even when dumping
4194 * only one, because we don't yet know which tables might be inheritance
4195 * ancestors of the target table.
4197 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4199 i_reltableoid = PQfnumber(res, "tableoid");
4200 i_reloid = PQfnumber(res, "oid");
4201 i_relname = PQfnumber(res, "relname");
4202 i_relnamespace = PQfnumber(res, "relnamespace");
4203 i_relacl = PQfnumber(res, "relacl");
4204 i_relkind = PQfnumber(res, "relkind");
4205 i_rolname = PQfnumber(res, "rolname");
4206 i_relchecks = PQfnumber(res, "relchecks");
4207 i_relhastriggers = PQfnumber(res, "relhastriggers");
4208 i_relhasindex = PQfnumber(res, "relhasindex");
4209 i_relhasrules = PQfnumber(res, "relhasrules");
4210 i_relhasoids = PQfnumber(res, "relhasoids");
4211 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4212 i_toastoid = PQfnumber(res, "toid");
4213 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4214 i_relpersistence = PQfnumber(res, "relpersistence");
4215 i_owning_tab = PQfnumber(res, "owning_tab");
4216 i_owning_col = PQfnumber(res, "owning_col");
4217 i_reltablespace = PQfnumber(res, "reltablespace");
4218 i_reloptions = PQfnumber(res, "reloptions");
4219 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4220 i_reloftype = PQfnumber(res, "reloftype");
4222 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4225 * Arrange to fail instead of waiting forever for a table lock.
4227 * NB: this coding assumes that the only queries issued within the
4228 * following loop are LOCK TABLEs; else the timeout may be undesirably
4229 * applied to other things too.
4231 resetPQExpBuffer(query);
4232 appendPQExpBuffer(query, "SET statement_timeout = ");
4233 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4234 ExecuteSqlStatement(fout, query->data);
4237 for (i = 0; i < ntups; i++)
4239 tblinfo[i].dobj.objType = DO_TABLE;
4240 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4241 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4242 AssignDumpId(&tblinfo[i].dobj);
4243 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4244 tblinfo[i].dobj.namespace =
4246 atooid(PQgetvalue(res, i, i_relnamespace)),
4247 tblinfo[i].dobj.catId.oid);
4248 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4249 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4250 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4251 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4252 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4253 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4254 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4255 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4256 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4257 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4258 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4259 if (PQgetisnull(res, i, i_reloftype))
4260 tblinfo[i].reloftype = NULL;
4262 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4263 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4264 if (PQgetisnull(res, i, i_owning_tab))
4266 tblinfo[i].owning_tab = InvalidOid;
4267 tblinfo[i].owning_col = 0;
4271 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4272 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4274 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4275 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4276 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4278 /* other fields were zeroed above */
4281 * Decide whether we want to dump this table.
4283 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4284 tblinfo[i].dobj.dump = false;
4286 selectDumpableTable(&tblinfo[i]);
4287 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4290 * Read-lock target tables to make sure they aren't DROPPED or altered
4291 * in schema before we get around to dumping them.
4293 * Note that we don't explicitly lock parents of the target tables; we
4294 * assume our lock on the child is enough to prevent schema
4295 * alterations to parent tables.
4297 * NOTE: it'd be kinda nice to lock other relations too, not only
4298 * plain tables, but the backend doesn't presently allow that.
4300 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4302 resetPQExpBuffer(query);
4303 appendPQExpBuffer(query,
4304 "LOCK TABLE %s IN ACCESS SHARE MODE",
4305 fmtQualifiedId(fout,
4306 tblinfo[i].dobj.namespace->dobj.name,
4307 tblinfo[i].dobj.name));
4308 ExecuteSqlStatement(fout, query->data);
4311 /* Emit notice if join for owner failed */
4312 if (strlen(tblinfo[i].rolname) == 0)
4313 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4314 tblinfo[i].dobj.name);
4317 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4319 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4325 * Force sequences that are "owned" by table columns to be dumped whenever
4326 * their owning table is being dumped.
4328 for (i = 0; i < ntups; i++)
4330 TableInfo *seqinfo = &tblinfo[i];
4333 if (!OidIsValid(seqinfo->owning_tab))
4334 continue; /* not an owned sequence */
4335 if (seqinfo->dobj.dump)
4336 continue; /* no need to search */
4338 /* can't use findTableByOid yet, unfortunately */
4339 for (j = 0; j < ntups; j++)
4341 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4343 if (tblinfo[j].dobj.dump)
4345 seqinfo->interesting = true;
4346 seqinfo->dobj.dump = true;
4353 destroyPQExpBuffer(query);
4360 * read all the inheritance information
4361 * from the system catalogs return them in the InhInfo* structure
4363 * numInherits is set to the number of pairs read in
4366 getInherits(Archive *fout, int *numInherits)
4371 PQExpBuffer query = createPQExpBuffer();
4377 /* Make sure we are in proper schema */
4378 selectSourceSchema(fout, "pg_catalog");
4380 /* find all the inheritance information */
4382 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4384 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4386 ntups = PQntuples(res);
4388 *numInherits = ntups;
4390 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4392 i_inhrelid = PQfnumber(res, "inhrelid");
4393 i_inhparent = PQfnumber(res, "inhparent");
4395 for (i = 0; i < ntups; i++)
4397 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4398 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4403 destroyPQExpBuffer(query);
4410 * get information about every index on a dumpable table
4412 * Note: index data is not returned directly to the caller, but it
4413 * does get entered into the DumpableObject tables.
4416 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4420 PQExpBuffer query = createPQExpBuffer();
4423 ConstraintInfo *constrinfo;
4442 for (i = 0; i < numTables; i++)
4444 TableInfo *tbinfo = &tblinfo[i];
4446 /* Only plain tables have indexes */
4447 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4450 /* Ignore indexes of tables not to be dumped */
4451 if (!tbinfo->dobj.dump)
4455 write_msg(NULL, "reading indexes for table \"%s\"\n",
4458 /* Make sure we are in proper schema so indexdef is right */
4459 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4462 * The point of the messy-looking outer join is to find a constraint
4463 * that is related by an internal dependency link to the index. If we
4464 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4465 * assume an index won't have more than one internal dependency.
4467 * As of 9.0 we don't need to look at pg_depend but can check for a
4468 * match to pg_constraint.conindid. The check on conrelid is
4469 * redundant but useful because that column is indexed while conindid
4472 resetPQExpBuffer(query);
4473 if (fout->remoteVersion >= 90000)
4475 appendPQExpBuffer(query,
4476 "SELECT t.tableoid, t.oid, "
4477 "t.relname AS indexname, "
4478 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4479 "t.relnatts AS indnkeys, "
4480 "i.indkey, i.indisclustered, "
4481 "c.contype, c.conname, "
4482 "c.condeferrable, c.condeferred, "
4483 "c.tableoid AS contableoid, "
4485 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4486 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4487 "array_to_string(t.reloptions, ', ') AS options "
4488 "FROM pg_catalog.pg_index i "
4489 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4490 "LEFT JOIN pg_catalog.pg_constraint c "
4491 "ON (i.indrelid = c.conrelid AND "
4492 "i.indexrelid = c.conindid AND "
4493 "c.contype IN ('p','u','x')) "
4494 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4495 "ORDER BY indexname",
4496 tbinfo->dobj.catId.oid);
4498 else if (fout->remoteVersion >= 80200)
4500 appendPQExpBuffer(query,
4501 "SELECT t.tableoid, t.oid, "
4502 "t.relname AS indexname, "
4503 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4504 "t.relnatts AS indnkeys, "
4505 "i.indkey, i.indisclustered, "
4506 "c.contype, c.conname, "
4507 "c.condeferrable, c.condeferred, "
4508 "c.tableoid AS contableoid, "
4511 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4512 "array_to_string(t.reloptions, ', ') AS options "
4513 "FROM pg_catalog.pg_index i "
4514 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4515 "LEFT JOIN pg_catalog.pg_depend d "
4516 "ON (d.classid = t.tableoid "
4517 "AND d.objid = t.oid "
4518 "AND d.deptype = 'i') "
4519 "LEFT JOIN pg_catalog.pg_constraint c "
4520 "ON (d.refclassid = c.tableoid "
4521 "AND d.refobjid = c.oid) "
4522 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4523 "ORDER BY indexname",
4524 tbinfo->dobj.catId.oid);
4526 else if (fout->remoteVersion >= 80000)
4528 appendPQExpBuffer(query,
4529 "SELECT t.tableoid, t.oid, "
4530 "t.relname AS indexname, "
4531 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4532 "t.relnatts AS indnkeys, "
4533 "i.indkey, i.indisclustered, "
4534 "c.contype, c.conname, "
4535 "c.condeferrable, c.condeferred, "
4536 "c.tableoid AS contableoid, "
4539 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4541 "FROM pg_catalog.pg_index i "
4542 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4543 "LEFT JOIN pg_catalog.pg_depend d "
4544 "ON (d.classid = t.tableoid "
4545 "AND d.objid = t.oid "
4546 "AND d.deptype = 'i') "
4547 "LEFT JOIN pg_catalog.pg_constraint c "
4548 "ON (d.refclassid = c.tableoid "
4549 "AND d.refobjid = c.oid) "
4550 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4551 "ORDER BY indexname",
4552 tbinfo->dobj.catId.oid);
4554 else if (fout->remoteVersion >= 70300)
4556 appendPQExpBuffer(query,
4557 "SELECT t.tableoid, t.oid, "
4558 "t.relname AS indexname, "
4559 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4560 "t.relnatts AS indnkeys, "
4561 "i.indkey, i.indisclustered, "
4562 "c.contype, c.conname, "
4563 "c.condeferrable, c.condeferred, "
4564 "c.tableoid AS contableoid, "
4567 "NULL AS tablespace, "
4569 "FROM pg_catalog.pg_index i "
4570 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4571 "LEFT JOIN pg_catalog.pg_depend d "
4572 "ON (d.classid = t.tableoid "
4573 "AND d.objid = t.oid "
4574 "AND d.deptype = 'i') "
4575 "LEFT JOIN pg_catalog.pg_constraint c "
4576 "ON (d.refclassid = c.tableoid "
4577 "AND d.refobjid = c.oid) "
4578 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4579 "ORDER BY indexname",
4580 tbinfo->dobj.catId.oid);
4582 else if (fout->remoteVersion >= 70100)
4584 appendPQExpBuffer(query,
4585 "SELECT t.tableoid, t.oid, "
4586 "t.relname AS indexname, "
4587 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4588 "t.relnatts AS indnkeys, "
4589 "i.indkey, false AS indisclustered, "
4590 "CASE WHEN i.indisprimary THEN 'p'::char "
4591 "ELSE '0'::char END AS contype, "
4592 "t.relname AS conname, "
4593 "false AS condeferrable, "
4594 "false AS condeferred, "
4595 "0::oid AS contableoid, "
4598 "NULL AS tablespace, "
4600 "FROM pg_index i, pg_class t "
4601 "WHERE t.oid = i.indexrelid "
4602 "AND i.indrelid = '%u'::oid "
4603 "ORDER BY indexname",
4604 tbinfo->dobj.catId.oid);
4608 appendPQExpBuffer(query,
4610 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4612 "t.relname AS indexname, "
4613 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4614 "t.relnatts AS indnkeys, "
4615 "i.indkey, false AS indisclustered, "
4616 "CASE WHEN i.indisprimary THEN 'p'::char "
4617 "ELSE '0'::char END AS contype, "
4618 "t.relname AS conname, "
4619 "false AS condeferrable, "
4620 "false AS condeferred, "
4621 "0::oid AS contableoid, "
4624 "NULL AS tablespace, "
4626 "FROM pg_index i, pg_class t "
4627 "WHERE t.oid = i.indexrelid "
4628 "AND i.indrelid = '%u'::oid "
4629 "ORDER BY indexname",
4630 tbinfo->dobj.catId.oid);
4633 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4635 ntups = PQntuples(res);
4637 i_tableoid = PQfnumber(res, "tableoid");
4638 i_oid = PQfnumber(res, "oid");
4639 i_indexname = PQfnumber(res, "indexname");
4640 i_indexdef = PQfnumber(res, "indexdef");
4641 i_indnkeys = PQfnumber(res, "indnkeys");
4642 i_indkey = PQfnumber(res, "indkey");
4643 i_indisclustered = PQfnumber(res, "indisclustered");
4644 i_contype = PQfnumber(res, "contype");
4645 i_conname = PQfnumber(res, "conname");
4646 i_condeferrable = PQfnumber(res, "condeferrable");
4647 i_condeferred = PQfnumber(res, "condeferred");
4648 i_contableoid = PQfnumber(res, "contableoid");
4649 i_conoid = PQfnumber(res, "conoid");
4650 i_condef = PQfnumber(res, "condef");
4651 i_tablespace = PQfnumber(res, "tablespace");
4652 i_options = PQfnumber(res, "options");
4654 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4655 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4657 for (j = 0; j < ntups; j++)
4661 indxinfo[j].dobj.objType = DO_INDEX;
4662 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4663 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4664 AssignDumpId(&indxinfo[j].dobj);
4665 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4666 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4667 indxinfo[j].indextable = tbinfo;
4668 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4669 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4670 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4671 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4674 * In pre-7.4 releases, indkeys may contain more entries than
4675 * indnkeys says (since indnkeys will be 1 for a functional
4676 * index). We don't actually care about this case since we don't
4677 * examine indkeys except for indexes associated with PRIMARY and
4678 * UNIQUE constraints, which are never functional indexes. But we
4679 * have to allocate enough space to keep parseOidArray from
4682 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4683 parseOidArray(PQgetvalue(res, j, i_indkey),
4684 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4685 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4686 contype = *(PQgetvalue(res, j, i_contype));
4688 if (contype == 'p' || contype == 'u' || contype == 'x')
4691 * If we found a constraint matching the index, create an
4694 * In a pre-7.3 database, we take this path iff the index was
4695 * marked indisprimary.
4697 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4698 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4699 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4700 AssignDumpId(&constrinfo[j].dobj);
4701 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4702 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4703 constrinfo[j].contable = tbinfo;
4704 constrinfo[j].condomain = NULL;
4705 constrinfo[j].contype = contype;
4707 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4709 constrinfo[j].condef = NULL;
4710 constrinfo[j].confrelid = InvalidOid;
4711 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4712 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4713 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4714 constrinfo[j].conislocal = true;
4715 constrinfo[j].separate = true;
4717 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4719 /* If pre-7.3 DB, better make sure table comes first */
4720 addObjectDependency(&constrinfo[j].dobj,
4721 tbinfo->dobj.dumpId);
4725 /* Plain secondary index */
4726 indxinfo[j].indexconstraint = 0;
4733 destroyPQExpBuffer(query);
4739 * Get info about constraints on dumpable tables.
4741 * Currently handles foreign keys only.
4742 * Unique and primary key constraints are handled with indexes,
4743 * while check constraints are processed in getTableAttrs().
4746 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4750 ConstraintInfo *constrinfo;
4760 /* pg_constraint was created in 7.3, so nothing to do if older */
4761 if (fout->remoteVersion < 70300)
4764 query = createPQExpBuffer();
4766 for (i = 0; i < numTables; i++)
4768 TableInfo *tbinfo = &tblinfo[i];
4770 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4774 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4778 * select table schema to ensure constraint expr is qualified if
4781 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4783 resetPQExpBuffer(query);
4784 appendPQExpBuffer(query,
4785 "SELECT tableoid, oid, conname, confrelid, "
4786 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4787 "FROM pg_catalog.pg_constraint "
4788 "WHERE conrelid = '%u'::pg_catalog.oid "
4789 "AND contype = 'f'",
4790 tbinfo->dobj.catId.oid);
4791 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4793 ntups = PQntuples(res);
4795 i_contableoid = PQfnumber(res, "tableoid");
4796 i_conoid = PQfnumber(res, "oid");
4797 i_conname = PQfnumber(res, "conname");
4798 i_confrelid = PQfnumber(res, "confrelid");
4799 i_condef = PQfnumber(res, "condef");
4801 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4803 for (j = 0; j < ntups; j++)
4805 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4806 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4807 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4808 AssignDumpId(&constrinfo[j].dobj);
4809 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4810 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4811 constrinfo[j].contable = tbinfo;
4812 constrinfo[j].condomain = NULL;
4813 constrinfo[j].contype = 'f';
4814 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4815 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4816 constrinfo[j].conindex = 0;
4817 constrinfo[j].condeferrable = false;
4818 constrinfo[j].condeferred = false;
4819 constrinfo[j].conislocal = true;
4820 constrinfo[j].separate = true;
4826 destroyPQExpBuffer(query);
4830 * getDomainConstraints
4832 * Get info about constraints on a domain.
4835 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4838 ConstraintInfo *constrinfo;
4847 /* pg_constraint was created in 7.3, so nothing to do if older */
4848 if (fout->remoteVersion < 70300)
4852 * select appropriate schema to ensure names in constraint are properly
4855 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4857 query = createPQExpBuffer();
4859 if (fout->remoteVersion >= 90100)
4860 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4861 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4863 "FROM pg_catalog.pg_constraint "
4864 "WHERE contypid = '%u'::pg_catalog.oid "
4866 tyinfo->dobj.catId.oid);
4868 else if (fout->remoteVersion >= 70400)
4869 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4870 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4871 "true as convalidated "
4872 "FROM pg_catalog.pg_constraint "
4873 "WHERE contypid = '%u'::pg_catalog.oid "
4875 tyinfo->dobj.catId.oid);
4877 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4878 "'CHECK (' || consrc || ')' AS consrc, "
4879 "true as convalidated "
4880 "FROM pg_catalog.pg_constraint "
4881 "WHERE contypid = '%u'::pg_catalog.oid "
4883 tyinfo->dobj.catId.oid);
4885 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4887 ntups = PQntuples(res);
4889 i_tableoid = PQfnumber(res, "tableoid");
4890 i_oid = PQfnumber(res, "oid");
4891 i_conname = PQfnumber(res, "conname");
4892 i_consrc = PQfnumber(res, "consrc");
4894 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4896 tyinfo->nDomChecks = ntups;
4897 tyinfo->domChecks = constrinfo;
4899 for (i = 0; i < ntups; i++)
4901 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4903 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4904 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4905 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4906 AssignDumpId(&constrinfo[i].dobj);
4907 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4908 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4909 constrinfo[i].contable = NULL;
4910 constrinfo[i].condomain = tyinfo;
4911 constrinfo[i].contype = 'c';
4912 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4913 constrinfo[i].confrelid = InvalidOid;
4914 constrinfo[i].conindex = 0;
4915 constrinfo[i].condeferrable = false;
4916 constrinfo[i].condeferred = false;
4917 constrinfo[i].conislocal = true;
4919 constrinfo[i].separate = !validated;
4922 * Make the domain depend on the constraint, ensuring it won't be
4923 * output till any constraint dependencies are OK. If the constraint
4924 * has not been validated, it's going to be dumped after the domain
4925 * anyway, so this doesn't matter.
4928 addObjectDependency(&tyinfo->dobj,
4929 constrinfo[i].dobj.dumpId);
4934 destroyPQExpBuffer(query);
4939 * get basic information about every rule in the system
4941 * numRules is set to the number of rules read in
4944 getRules(Archive *fout, int *numRules)
4949 PQExpBuffer query = createPQExpBuffer();
4959 /* Make sure we are in proper schema */
4960 selectSourceSchema(fout, "pg_catalog");
4962 if (fout->remoteVersion >= 80300)
4964 appendPQExpBuffer(query, "SELECT "
4965 "tableoid, oid, rulename, "
4966 "ev_class AS ruletable, ev_type, is_instead, "
4971 else if (fout->remoteVersion >= 70100)
4973 appendPQExpBuffer(query, "SELECT "
4974 "tableoid, oid, rulename, "
4975 "ev_class AS ruletable, ev_type, is_instead, "
4976 "'O'::char AS ev_enabled "
4982 appendPQExpBuffer(query, "SELECT "
4983 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4985 "ev_class AS ruletable, ev_type, is_instead, "
4986 "'O'::char AS ev_enabled "
4991 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4993 ntups = PQntuples(res);
4997 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
4999 i_tableoid = PQfnumber(res, "tableoid");
5000 i_oid = PQfnumber(res, "oid");
5001 i_rulename = PQfnumber(res, "rulename");
5002 i_ruletable = PQfnumber(res, "ruletable");
5003 i_ev_type = PQfnumber(res, "ev_type");
5004 i_is_instead = PQfnumber(res, "is_instead");
5005 i_ev_enabled = PQfnumber(res, "ev_enabled");
5007 for (i = 0; i < ntups; i++)
5011 ruleinfo[i].dobj.objType = DO_RULE;
5012 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5013 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5014 AssignDumpId(&ruleinfo[i].dobj);
5015 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5016 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5017 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5018 if (ruleinfo[i].ruletable == NULL)
5019 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5020 ruletableoid, ruleinfo[i].dobj.catId.oid);
5021 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5022 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5023 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5024 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5025 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5026 if (ruleinfo[i].ruletable)
5029 * If the table is a view, force its ON SELECT rule to be sorted
5030 * before the view itself --- this ensures that any dependencies
5031 * for the rule affect the table's positioning. Other rules are
5032 * forced to appear after their table.
5034 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5035 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5037 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5038 ruleinfo[i].dobj.dumpId);
5039 /* We'll merge the rule into CREATE VIEW, if possible */
5040 ruleinfo[i].separate = false;
5044 addObjectDependency(&ruleinfo[i].dobj,
5045 ruleinfo[i].ruletable->dobj.dumpId);
5046 ruleinfo[i].separate = true;
5050 ruleinfo[i].separate = true;
5055 destroyPQExpBuffer(query);
5062 * get information about every trigger on a dumpable table
5064 * Note: trigger data is not returned directly to the caller, but it
5065 * does get entered into the DumpableObject tables.
5068 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5072 PQExpBuffer query = createPQExpBuffer();
5074 TriggerInfo *tginfo;
5092 for (i = 0; i < numTables; i++)
5094 TableInfo *tbinfo = &tblinfo[i];
5096 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5100 write_msg(NULL, "reading triggers for table \"%s\"\n",
5104 * select table schema to ensure regproc name is qualified if needed
5106 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5108 resetPQExpBuffer(query);
5109 if (fout->remoteVersion >= 90000)
5112 * NB: think not to use pretty=true in pg_get_triggerdef. It
5113 * could result in non-forward-compatible dumps of WHEN clauses
5114 * due to under-parenthesization.
5116 appendPQExpBuffer(query,
5118 "tgfoid::pg_catalog.regproc AS tgfname, "
5119 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5120 "tgenabled, tableoid, oid "
5121 "FROM pg_catalog.pg_trigger t "
5122 "WHERE tgrelid = '%u'::pg_catalog.oid "
5123 "AND NOT tgisinternal",
5124 tbinfo->dobj.catId.oid);
5126 else if (fout->remoteVersion >= 80300)
5129 * We ignore triggers that are tied to a foreign-key constraint
5131 appendPQExpBuffer(query,
5133 "tgfoid::pg_catalog.regproc AS tgfname, "
5134 "tgtype, tgnargs, tgargs, tgenabled, "
5135 "tgisconstraint, tgconstrname, tgdeferrable, "
5136 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5137 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5138 "FROM pg_catalog.pg_trigger t "
5139 "WHERE tgrelid = '%u'::pg_catalog.oid "
5140 "AND tgconstraint = 0",
5141 tbinfo->dobj.catId.oid);
5143 else if (fout->remoteVersion >= 70300)
5146 * We ignore triggers that are tied to a foreign-key constraint,
5147 * but in these versions we have to grovel through pg_constraint
5150 appendPQExpBuffer(query,
5152 "tgfoid::pg_catalog.regproc AS tgfname, "
5153 "tgtype, tgnargs, tgargs, tgenabled, "
5154 "tgisconstraint, tgconstrname, tgdeferrable, "
5155 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5156 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5157 "FROM pg_catalog.pg_trigger t "
5158 "WHERE tgrelid = '%u'::pg_catalog.oid "
5159 "AND (NOT tgisconstraint "
5161 " (SELECT 1 FROM pg_catalog.pg_depend d "
5162 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5163 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5164 tbinfo->dobj.catId.oid);
5166 else if (fout->remoteVersion >= 70100)
5168 appendPQExpBuffer(query,
5169 "SELECT tgname, tgfoid::regproc AS tgfname, "
5170 "tgtype, tgnargs, tgargs, tgenabled, "
5171 "tgisconstraint, tgconstrname, tgdeferrable, "
5172 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5173 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5174 " AS tgconstrrelname "
5176 "WHERE tgrelid = '%u'::oid",
5177 tbinfo->dobj.catId.oid);
5181 appendPQExpBuffer(query,
5182 "SELECT tgname, tgfoid::regproc AS tgfname, "
5183 "tgtype, tgnargs, tgargs, tgenabled, "
5184 "tgisconstraint, tgconstrname, tgdeferrable, "
5185 "tgconstrrelid, tginitdeferred, "
5186 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5188 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5189 " AS tgconstrrelname "
5191 "WHERE tgrelid = '%u'::oid",
5192 tbinfo->dobj.catId.oid);
5194 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5196 ntups = PQntuples(res);
5198 i_tableoid = PQfnumber(res, "tableoid");
5199 i_oid = PQfnumber(res, "oid");
5200 i_tgname = PQfnumber(res, "tgname");
5201 i_tgfname = PQfnumber(res, "tgfname");
5202 i_tgtype = PQfnumber(res, "tgtype");
5203 i_tgnargs = PQfnumber(res, "tgnargs");
5204 i_tgargs = PQfnumber(res, "tgargs");
5205 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5206 i_tgconstrname = PQfnumber(res, "tgconstrname");
5207 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5208 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5209 i_tgenabled = PQfnumber(res, "tgenabled");
5210 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5211 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5212 i_tgdef = PQfnumber(res, "tgdef");
5214 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5216 for (j = 0; j < ntups; j++)
5218 tginfo[j].dobj.objType = DO_TRIGGER;
5219 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5220 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5221 AssignDumpId(&tginfo[j].dobj);
5222 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5223 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5224 tginfo[j].tgtable = tbinfo;
5225 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5228 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5230 /* remaining fields are not valid if we have tgdef */
5231 tginfo[j].tgfname = NULL;
5232 tginfo[j].tgtype = 0;
5233 tginfo[j].tgnargs = 0;
5234 tginfo[j].tgargs = NULL;
5235 tginfo[j].tgisconstraint = false;
5236 tginfo[j].tgdeferrable = false;
5237 tginfo[j].tginitdeferred = false;
5238 tginfo[j].tgconstrname = NULL;
5239 tginfo[j].tgconstrrelid = InvalidOid;
5240 tginfo[j].tgconstrrelname = NULL;
5244 tginfo[j].tgdef = NULL;
5246 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5247 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5248 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5249 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5250 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5251 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5252 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5254 if (tginfo[j].tgisconstraint)
5256 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5257 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5258 if (OidIsValid(tginfo[j].tgconstrrelid))
5260 if (PQgetisnull(res, j, i_tgconstrrelname))
5261 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5262 tginfo[j].dobj.name,
5264 tginfo[j].tgconstrrelid);
5265 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5268 tginfo[j].tgconstrrelname = NULL;
5272 tginfo[j].tgconstrname = NULL;
5273 tginfo[j].tgconstrrelid = InvalidOid;
5274 tginfo[j].tgconstrrelname = NULL;
5282 destroyPQExpBuffer(query);
5287 * get basic information about every procedural language in the system
5289 * numProcLangs is set to the number of langs read in
5291 * NB: this must run after getFuncs() because we assume we can do
5295 getProcLangs(Archive *fout, int *numProcLangs)
5300 PQExpBuffer query = createPQExpBuffer();
5301 ProcLangInfo *planginfo;
5306 int i_lanplcallfoid;
5312 /* Make sure we are in proper schema */
5313 selectSourceSchema(fout, "pg_catalog");
5315 if (fout->remoteVersion >= 90000)
5317 /* pg_language has a laninline column */
5318 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5319 "lanname, lanpltrusted, lanplcallfoid, "
5320 "laninline, lanvalidator, lanacl, "
5321 "(%s lanowner) AS lanowner "
5327 else if (fout->remoteVersion >= 80300)
5329 /* pg_language has a lanowner column */
5330 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5331 "lanname, lanpltrusted, lanplcallfoid, "
5332 "lanvalidator, lanacl, "
5333 "(%s lanowner) AS lanowner "
5339 else if (fout->remoteVersion >= 80100)
5341 /* Languages are owned by the bootstrap superuser, OID 10 */
5342 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5343 "(%s '10') AS lanowner "
5349 else if (fout->remoteVersion >= 70400)
5351 /* Languages are owned by the bootstrap superuser, sysid 1 */
5352 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5353 "(%s '1') AS lanowner "
5359 else if (fout->remoteVersion >= 70100)
5361 /* No clear notion of an owner at all before 7.4 ... */
5362 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5368 appendPQExpBuffer(query, "SELECT "
5369 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5370 "oid, * FROM pg_language "
5375 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5377 ntups = PQntuples(res);
5379 *numProcLangs = ntups;
5381 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5383 i_tableoid = PQfnumber(res, "tableoid");
5384 i_oid = PQfnumber(res, "oid");
5385 i_lanname = PQfnumber(res, "lanname");
5386 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5387 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5388 /* these may fail and return -1: */
5389 i_laninline = PQfnumber(res, "laninline");
5390 i_lanvalidator = PQfnumber(res, "lanvalidator");
5391 i_lanacl = PQfnumber(res, "lanacl");
5392 i_lanowner = PQfnumber(res, "lanowner");
5394 for (i = 0; i < ntups; i++)
5396 planginfo[i].dobj.objType = DO_PROCLANG;
5397 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5398 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5399 AssignDumpId(&planginfo[i].dobj);
5401 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5402 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5403 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5404 if (i_laninline >= 0)
5405 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5407 planginfo[i].laninline = InvalidOid;
5408 if (i_lanvalidator >= 0)
5409 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5411 planginfo[i].lanvalidator = InvalidOid;
5413 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5415 planginfo[i].lanacl = pg_strdup("{=U}");
5416 if (i_lanowner >= 0)
5417 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5419 planginfo[i].lanowner = pg_strdup("");
5421 if (fout->remoteVersion < 70300)
5424 * We need to make a dependency to ensure the function will be
5425 * dumped first. (In 7.3 and later the regular dependency
5426 * mechanism will handle this for us.)
5428 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5431 addObjectDependency(&planginfo[i].dobj,
5432 funcInfo->dobj.dumpId);
5438 destroyPQExpBuffer(query);
5445 * get basic information about every cast in the system
5447 * numCasts is set to the number of casts read in
5450 getCasts(Archive *fout, int *numCasts)
5455 PQExpBuffer query = createPQExpBuffer();
5465 /* Make sure we are in proper schema */
5466 selectSourceSchema(fout, "pg_catalog");
5468 if (fout->remoteVersion >= 80400)
5470 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5471 "castsource, casttarget, castfunc, castcontext, "
5473 "FROM pg_cast ORDER BY 3,4");
5475 else if (fout->remoteVersion >= 70300)
5477 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5478 "castsource, casttarget, castfunc, castcontext, "
5479 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5480 "FROM pg_cast ORDER BY 3,4");
5484 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5485 "t1.oid AS castsource, t2.oid AS casttarget, "
5486 "p.oid AS castfunc, 'e' AS castcontext, "
5487 "'f' AS castmethod "
5488 "FROM pg_type t1, pg_type t2, pg_proc p "
5489 "WHERE p.pronargs = 1 AND "
5490 "p.proargtypes[0] = t1.oid AND "
5491 "p.prorettype = t2.oid AND p.proname = t2.typname "
5495 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5497 ntups = PQntuples(res);
5501 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5503 i_tableoid = PQfnumber(res, "tableoid");
5504 i_oid = PQfnumber(res, "oid");
5505 i_castsource = PQfnumber(res, "castsource");
5506 i_casttarget = PQfnumber(res, "casttarget");
5507 i_castfunc = PQfnumber(res, "castfunc");
5508 i_castcontext = PQfnumber(res, "castcontext");
5509 i_castmethod = PQfnumber(res, "castmethod");
5511 for (i = 0; i < ntups; i++)
5513 PQExpBufferData namebuf;
5514 TypeInfo *sTypeInfo;
5515 TypeInfo *tTypeInfo;
5517 castinfo[i].dobj.objType = DO_CAST;
5518 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5519 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5520 AssignDumpId(&castinfo[i].dobj);
5521 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5522 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5523 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5524 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5525 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5528 * Try to name cast as concatenation of typnames. This is only used
5529 * for purposes of sorting. If we fail to find either type, the name
5530 * will be an empty string.
5532 initPQExpBuffer(&namebuf);
5533 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5534 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5535 if (sTypeInfo && tTypeInfo)
5536 appendPQExpBuffer(&namebuf, "%s %s",
5537 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5538 castinfo[i].dobj.name = namebuf.data;
5540 if (OidIsValid(castinfo[i].castfunc))
5543 * We need to make a dependency to ensure the function will be
5544 * dumped first. (In 7.3 and later the regular dependency
5545 * mechanism will handle this for us.)
5549 funcInfo = findFuncByOid(castinfo[i].castfunc);
5551 addObjectDependency(&castinfo[i].dobj,
5552 funcInfo->dobj.dumpId);
5558 destroyPQExpBuffer(query);
5565 * for each interesting table, read info about its attributes
5566 * (names, types, default values, CHECK constraints, etc)
5568 * This is implemented in a very inefficient way right now, looping
5569 * through the tblinfo and doing a join per table to find the attrs and their
5570 * types. However, because we want type names and so forth to be named
5571 * relative to the schema of each table, we couldn't do it in just one
5572 * query. (Maybe one query per schema?)
5577 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5581 PQExpBuffer q = createPQExpBuffer();
5586 int i_attstattarget;
5597 int i_attfdwoptions;
5602 for (i = 0; i < numTables; i++)
5604 TableInfo *tbinfo = &tblinfo[i];
5606 /* Don't bother to collect info for sequences */
5607 if (tbinfo->relkind == RELKIND_SEQUENCE)
5610 /* Don't bother with uninteresting tables, either */
5611 if (!tbinfo->interesting)
5615 * Make sure we are in proper schema for this table; this allows
5616 * correct retrieval of formatted type names and default exprs
5618 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5620 /* find all the user attributes and their types */
5623 * we must read the attribute names in attribute number order! because
5624 * we will use the attnum to index into the attnames array later. We
5625 * actually ask to order by "attrelid, attnum" because (at least up to
5626 * 7.3) the planner is not smart enough to realize it needn't re-sort
5627 * the output of an indexscan on pg_attribute_relid_attnum_index.
5630 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5633 resetPQExpBuffer(q);
5635 if (fout->remoteVersion >= 90200)
5638 * attfdwoptions is new in 9.2.
5640 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5641 "a.attstattarget, a.attstorage, t.typstorage, "
5642 "a.attnotnull, a.atthasdef, a.attisdropped, "
5643 "a.attlen, a.attalign, a.attislocal, "
5644 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5645 "array_to_string(a.attoptions, ', ') AS attoptions, "
5646 "CASE WHEN a.attcollation <> t.typcollation "
5647 "THEN a.attcollation ELSE 0 END AS attcollation, "
5648 "pg_catalog.array_to_string(ARRAY("
5649 "SELECT pg_catalog.quote_ident(option_name) || "
5650 "' ' || pg_catalog.quote_literal(option_value) "
5651 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5652 "ORDER BY option_name"
5653 "), E',\n ') AS attfdwoptions "
5654 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5655 "ON a.atttypid = t.oid "
5656 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5657 "AND a.attnum > 0::pg_catalog.int2 "
5658 "ORDER BY a.attrelid, a.attnum",
5659 tbinfo->dobj.catId.oid);
5661 else if (fout->remoteVersion >= 90100)
5664 * attcollation is new in 9.1. Since we only want to dump COLLATE
5665 * clauses for attributes whose collation is different from their
5666 * type's default, we use a CASE here to suppress uninteresting
5667 * attcollations cheaply.
5669 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5670 "a.attstattarget, a.attstorage, t.typstorage, "
5671 "a.attnotnull, a.atthasdef, a.attisdropped, "
5672 "a.attlen, a.attalign, a.attislocal, "
5673 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5674 "array_to_string(a.attoptions, ', ') AS attoptions, "
5675 "CASE WHEN a.attcollation <> t.typcollation "
5676 "THEN a.attcollation ELSE 0 END AS attcollation, "
5677 "NULL AS attfdwoptions "
5678 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5679 "ON a.atttypid = t.oid "
5680 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5681 "AND a.attnum > 0::pg_catalog.int2 "
5682 "ORDER BY a.attrelid, a.attnum",
5683 tbinfo->dobj.catId.oid);
5685 else if (fout->remoteVersion >= 90000)
5687 /* attoptions is new in 9.0 */
5688 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5689 "a.attstattarget, a.attstorage, t.typstorage, "
5690 "a.attnotnull, a.atthasdef, a.attisdropped, "
5691 "a.attlen, a.attalign, a.attislocal, "
5692 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5693 "array_to_string(a.attoptions, ', ') AS attoptions, "
5694 "0 AS attcollation, "
5695 "NULL AS attfdwoptions "
5696 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5697 "ON a.atttypid = t.oid "
5698 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5699 "AND a.attnum > 0::pg_catalog.int2 "
5700 "ORDER BY a.attrelid, a.attnum",
5701 tbinfo->dobj.catId.oid);
5703 else if (fout->remoteVersion >= 70300)
5705 /* need left join here to not fail on dropped columns ... */
5706 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5707 "a.attstattarget, a.attstorage, t.typstorage, "
5708 "a.attnotnull, a.atthasdef, a.attisdropped, "
5709 "a.attlen, a.attalign, a.attislocal, "
5710 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5711 "'' AS attoptions, 0 AS attcollation, "
5712 "NULL AS attfdwoptions "
5713 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5714 "ON a.atttypid = t.oid "
5715 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5716 "AND a.attnum > 0::pg_catalog.int2 "
5717 "ORDER BY a.attrelid, a.attnum",
5718 tbinfo->dobj.catId.oid);
5720 else if (fout->remoteVersion >= 70100)
5723 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5724 * we don't dump it because we can't tell whether it's been
5725 * explicitly set or was just a default.
5727 * attislocal doesn't exist before 7.3, either; in older databases
5728 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5730 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5731 "-1 AS attstattarget, a.attstorage, "
5732 "t.typstorage, a.attnotnull, a.atthasdef, "
5733 "false AS attisdropped, a.attlen, "
5734 "a.attalign, true AS attislocal, "
5735 "format_type(t.oid,a.atttypmod) AS atttypname, "
5736 "'' AS attoptions, 0 AS attcollation, "
5737 "NULL AS attfdwoptions "
5738 "FROM pg_attribute a LEFT JOIN pg_type t "
5739 "ON a.atttypid = t.oid "
5740 "WHERE a.attrelid = '%u'::oid "
5741 "AND a.attnum > 0::int2 "
5742 "ORDER BY a.attrelid, a.attnum",
5743 tbinfo->dobj.catId.oid);
5747 /* format_type not available before 7.1 */
5748 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5749 "-1 AS attstattarget, "
5750 "attstorage, attstorage AS typstorage, "
5751 "attnotnull, atthasdef, false AS attisdropped, "
5752 "attlen, attalign, "
5753 "true AS attislocal, "
5754 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5755 "'' AS attoptions, 0 AS attcollation, "
5756 "NULL AS attfdwoptions "
5757 "FROM pg_attribute a "
5758 "WHERE attrelid = '%u'::oid "
5759 "AND attnum > 0::int2 "
5760 "ORDER BY attrelid, attnum",
5761 tbinfo->dobj.catId.oid);
5764 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5766 ntups = PQntuples(res);
5768 i_attnum = PQfnumber(res, "attnum");
5769 i_attname = PQfnumber(res, "attname");
5770 i_atttypname = PQfnumber(res, "atttypname");
5771 i_atttypmod = PQfnumber(res, "atttypmod");
5772 i_attstattarget = PQfnumber(res, "attstattarget");
5773 i_attstorage = PQfnumber(res, "attstorage");
5774 i_typstorage = PQfnumber(res, "typstorage");
5775 i_attnotnull = PQfnumber(res, "attnotnull");
5776 i_atthasdef = PQfnumber(res, "atthasdef");
5777 i_attisdropped = PQfnumber(res, "attisdropped");
5778 i_attlen = PQfnumber(res, "attlen");
5779 i_attalign = PQfnumber(res, "attalign");
5780 i_attislocal = PQfnumber(res, "attislocal");
5781 i_attoptions = PQfnumber(res, "attoptions");
5782 i_attcollation = PQfnumber(res, "attcollation");
5783 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5785 tbinfo->numatts = ntups;
5786 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5787 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5788 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5789 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5790 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5791 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5792 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5793 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5794 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5795 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5796 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5797 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5798 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5799 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5800 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5801 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5802 hasdefaults = false;
5804 for (j = 0; j < ntups; j++)
5806 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5808 "invalid column numbering in table \"%s\"\n",
5810 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5811 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5812 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5813 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5814 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5815 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5816 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5817 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5818 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5819 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5820 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5821 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5822 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5823 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5824 tbinfo->attrdefs[j] = NULL; /* fix below */
5825 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5827 /* these flags will be set in flagInhAttrs() */
5828 tbinfo->inhNotNull[j] = false;
5834 * Get info about column defaults
5838 AttrDefInfo *attrdefs;
5842 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5845 resetPQExpBuffer(q);
5846 if (fout->remoteVersion >= 70300)
5848 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5849 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5850 "FROM pg_catalog.pg_attrdef "
5851 "WHERE adrelid = '%u'::pg_catalog.oid",
5852 tbinfo->dobj.catId.oid);
5854 else if (fout->remoteVersion >= 70200)
5856 /* 7.2 did not have OIDs in pg_attrdef */
5857 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5858 "pg_get_expr(adbin, adrelid) AS adsrc "
5860 "WHERE adrelid = '%u'::oid",
5861 tbinfo->dobj.catId.oid);
5863 else if (fout->remoteVersion >= 70100)
5865 /* no pg_get_expr, so must rely on adsrc */
5866 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5868 "WHERE adrelid = '%u'::oid",
5869 tbinfo->dobj.catId.oid);
5873 /* no pg_get_expr, no tableoid either */
5874 appendPQExpBuffer(q, "SELECT "
5875 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5876 "oid, adnum, adsrc "
5878 "WHERE adrelid = '%u'::oid",
5879 tbinfo->dobj.catId.oid);
5881 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5883 numDefaults = PQntuples(res);
5884 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5886 for (j = 0; j < numDefaults; j++)
5890 adnum = atoi(PQgetvalue(res, j, 2));
5892 if (adnum <= 0 || adnum > ntups)
5894 "invalid adnum value %d for table \"%s\"\n",
5895 adnum, tbinfo->dobj.name);
5898 * dropped columns shouldn't have defaults, but just in case,
5901 if (tbinfo->attisdropped[adnum - 1])
5904 attrdefs[j].dobj.objType = DO_ATTRDEF;
5905 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5906 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5907 AssignDumpId(&attrdefs[j].dobj);
5908 attrdefs[j].adtable = tbinfo;
5909 attrdefs[j].adnum = adnum;
5910 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5912 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5913 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5915 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5918 * Defaults on a VIEW must always be dumped as separate ALTER
5919 * TABLE commands. Defaults on regular tables are dumped as
5920 * part of the CREATE TABLE if possible, which it won't be
5921 * if the column is not going to be emitted explicitly.
5923 if (tbinfo->relkind == RELKIND_VIEW)
5925 attrdefs[j].separate = true;
5926 /* needed in case pre-7.3 DB: */
5927 addObjectDependency(&attrdefs[j].dobj,
5928 tbinfo->dobj.dumpId);
5930 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5932 /* column will be suppressed, print default separately */
5933 attrdefs[j].separate = true;
5934 /* needed in case pre-7.3 DB: */
5935 addObjectDependency(&attrdefs[j].dobj,
5936 tbinfo->dobj.dumpId);
5940 attrdefs[j].separate = false;
5942 * Mark the default as needing to appear before the table,
5943 * so that any dependencies it has must be emitted before
5944 * the CREATE TABLE. If this is not possible, we'll
5945 * change to "separate" mode while sorting dependencies.
5947 addObjectDependency(&tbinfo->dobj,
5948 attrdefs[j].dobj.dumpId);
5951 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5957 * Get info about table CHECK constraints
5959 if (tbinfo->ncheck > 0)
5961 ConstraintInfo *constrs;
5965 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5968 resetPQExpBuffer(q);
5969 if (fout->remoteVersion >= 90200)
5972 * conisonly and convalidated are new in 9.2 (actually, the latter
5973 * is there in 9.1, but it wasn't ever false for check constraints
5976 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5977 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5978 "conislocal, convalidated, conisonly "
5979 "FROM pg_catalog.pg_constraint "
5980 "WHERE conrelid = '%u'::pg_catalog.oid "
5981 " AND contype = 'c' "
5983 tbinfo->dobj.catId.oid);
5985 else if (fout->remoteVersion >= 80400)
5987 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5988 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5989 "conislocal, true AS convalidated, "
5990 "false as conisonly "
5991 "FROM pg_catalog.pg_constraint "
5992 "WHERE conrelid = '%u'::pg_catalog.oid "
5993 " AND contype = 'c' "
5995 tbinfo->dobj.catId.oid);
5997 else if (fout->remoteVersion >= 70400)
5999 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6000 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6001 "true AS conislocal, true AS convalidated, "
6002 "false as conisonly "
6003 "FROM pg_catalog.pg_constraint "
6004 "WHERE conrelid = '%u'::pg_catalog.oid "
6005 " AND contype = 'c' "
6007 tbinfo->dobj.catId.oid);
6009 else if (fout->remoteVersion >= 70300)
6011 /* no pg_get_constraintdef, must use consrc */
6012 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6013 "'CHECK (' || consrc || ')' AS consrc, "
6014 "true AS conislocal, true AS convalidated, "
6015 "false as conisonly "
6016 "FROM pg_catalog.pg_constraint "
6017 "WHERE conrelid = '%u'::pg_catalog.oid "
6018 " AND contype = 'c' "
6020 tbinfo->dobj.catId.oid);
6022 else if (fout->remoteVersion >= 70200)
6024 /* 7.2 did not have OIDs in pg_relcheck */
6025 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6026 "rcname AS conname, "
6027 "'CHECK (' || rcsrc || ')' AS consrc, "
6028 "true AS conislocal, true AS convalidated, "
6029 "false as conisonly "
6031 "WHERE rcrelid = '%u'::oid "
6033 tbinfo->dobj.catId.oid);
6035 else if (fout->remoteVersion >= 70100)
6037 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6038 "rcname AS conname, "
6039 "'CHECK (' || rcsrc || ')' AS consrc, "
6040 "true AS conislocal, true AS convalidated, "
6041 "false as conisonly "
6043 "WHERE rcrelid = '%u'::oid "
6045 tbinfo->dobj.catId.oid);
6049 /* no tableoid in 7.0 */
6050 appendPQExpBuffer(q, "SELECT "
6051 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6052 "oid, rcname AS conname, "
6053 "'CHECK (' || rcsrc || ')' AS consrc, "
6054 "true AS conislocal, true AS convalidated, "
6055 "false as conisonly "
6057 "WHERE rcrelid = '%u'::oid "
6059 tbinfo->dobj.catId.oid);
6061 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6063 numConstrs = PQntuples(res);
6064 if (numConstrs != tbinfo->ncheck)
6066 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6067 "expected %d check constraints on table \"%s\" but found %d\n",
6069 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6070 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6074 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6075 tbinfo->checkexprs = constrs;
6077 for (j = 0; j < numConstrs; j++)
6079 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6080 bool isonly = PQgetvalue(res, j, 6)[0] == 't';
6082 constrs[j].dobj.objType = DO_CONSTRAINT;
6083 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6084 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6085 AssignDumpId(&constrs[j].dobj);
6086 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6087 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6088 constrs[j].contable = tbinfo;
6089 constrs[j].condomain = NULL;
6090 constrs[j].contype = 'c';
6091 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6092 constrs[j].confrelid = InvalidOid;
6093 constrs[j].conindex = 0;
6094 constrs[j].condeferrable = false;
6095 constrs[j].condeferred = false;
6096 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6097 constrs[j].conisonly = isonly;
6099 * An unvalidated constraint needs to be dumped separately, so
6100 * that potentially-violating existing data is loaded before
6101 * the constraint. An ONLY constraint needs to be dumped
6104 constrs[j].separate = !validated || isonly;
6106 constrs[j].dobj.dump = tbinfo->dobj.dump;
6109 * Mark the constraint as needing to appear before the table
6110 * --- this is so that any other dependencies of the
6111 * constraint will be emitted before we try to create the
6112 * table. If the constraint is to be dumped separately, it will be
6113 * dumped after data is loaded anyway, so don't do it. (There's
6114 * an automatic dependency in the opposite direction anyway, so
6115 * don't need to add one manually here.)
6117 if (!constrs[j].separate)
6118 addObjectDependency(&tbinfo->dobj,
6119 constrs[j].dobj.dumpId);
6122 * If the constraint is inherited, this will be detected later
6123 * (in pre-8.4 databases). We also detect later if the
6124 * constraint must be split out from the table definition.
6131 destroyPQExpBuffer(q);
6135 * Test whether a column should be printed as part of table's CREATE TABLE.
6136 * Column number is zero-based.
6138 * Normally this is always true, but it's false for dropped columns, as well
6139 * as those that were inherited without any local definition. (If we print
6140 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6141 * However, in binary_upgrade mode, we must print all such columns anyway and
6142 * fix the attislocal/attisdropped state later, so as to keep control of the
6143 * physical column order.
6145 * This function exists because there are scattered nonobvious places that
6146 * must be kept in sync with this decision.
6149 shouldPrintColumn(TableInfo *tbinfo, int colno)
6153 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6159 * read all text search parsers in the system catalogs and return them
6160 * in the TSParserInfo* structure
6162 * numTSParsers is set to the number of parsers read in
6165 getTSParsers(Archive *fout, int *numTSParsers)
6171 TSParserInfo *prsinfo;
6182 /* Before 8.3, there is no built-in text search support */
6183 if (fout->remoteVersion < 80300)
6189 query = createPQExpBuffer();
6192 * find all text search objects, including builtin ones; we filter out
6193 * system-defined objects at dump-out time.
6196 /* Make sure we are in proper schema */
6197 selectSourceSchema(fout, "pg_catalog");
6199 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6200 "prsstart::oid, prstoken::oid, "
6201 "prsend::oid, prsheadline::oid, prslextype::oid "
6202 "FROM pg_ts_parser");
6204 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6206 ntups = PQntuples(res);
6207 *numTSParsers = ntups;
6209 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6211 i_tableoid = PQfnumber(res, "tableoid");
6212 i_oid = PQfnumber(res, "oid");
6213 i_prsname = PQfnumber(res, "prsname");
6214 i_prsnamespace = PQfnumber(res, "prsnamespace");
6215 i_prsstart = PQfnumber(res, "prsstart");
6216 i_prstoken = PQfnumber(res, "prstoken");
6217 i_prsend = PQfnumber(res, "prsend");
6218 i_prsheadline = PQfnumber(res, "prsheadline");
6219 i_prslextype = PQfnumber(res, "prslextype");
6221 for (i = 0; i < ntups; i++)
6223 prsinfo[i].dobj.objType = DO_TSPARSER;
6224 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6225 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6226 AssignDumpId(&prsinfo[i].dobj);
6227 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6228 prsinfo[i].dobj.namespace =
6230 atooid(PQgetvalue(res, i, i_prsnamespace)),
6231 prsinfo[i].dobj.catId.oid);
6232 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6233 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6234 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6235 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6236 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6238 /* Decide whether we want to dump it */
6239 selectDumpableObject(&(prsinfo[i].dobj));
6244 destroyPQExpBuffer(query);
6250 * getTSDictionaries:
6251 * read all text search dictionaries in the system catalogs and return them
6252 * in the TSDictInfo* structure
6254 * numTSDicts is set to the number of dictionaries read in
6257 getTSDictionaries(Archive *fout, int *numTSDicts)
6263 TSDictInfo *dictinfo;
6267 int i_dictnamespace;
6270 int i_dictinitoption;
6272 /* Before 8.3, there is no built-in text search support */
6273 if (fout->remoteVersion < 80300)
6279 query = createPQExpBuffer();
6281 /* Make sure we are in proper schema */
6282 selectSourceSchema(fout, "pg_catalog");
6284 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6285 "dictnamespace, (%s dictowner) AS rolname, "
6286 "dicttemplate, dictinitoption "
6290 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6292 ntups = PQntuples(res);
6293 *numTSDicts = ntups;
6295 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6297 i_tableoid = PQfnumber(res, "tableoid");
6298 i_oid = PQfnumber(res, "oid");
6299 i_dictname = PQfnumber(res, "dictname");
6300 i_dictnamespace = PQfnumber(res, "dictnamespace");
6301 i_rolname = PQfnumber(res, "rolname");
6302 i_dictinitoption = PQfnumber(res, "dictinitoption");
6303 i_dicttemplate = PQfnumber(res, "dicttemplate");
6305 for (i = 0; i < ntups; i++)
6307 dictinfo[i].dobj.objType = DO_TSDICT;
6308 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6309 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6310 AssignDumpId(&dictinfo[i].dobj);
6311 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6312 dictinfo[i].dobj.namespace =
6314 atooid(PQgetvalue(res, i, i_dictnamespace)),
6315 dictinfo[i].dobj.catId.oid);
6316 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6317 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6318 if (PQgetisnull(res, i, i_dictinitoption))
6319 dictinfo[i].dictinitoption = NULL;
6321 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6323 /* Decide whether we want to dump it */
6324 selectDumpableObject(&(dictinfo[i].dobj));
6329 destroyPQExpBuffer(query);
6336 * read all text search templates in the system catalogs and return them
6337 * in the TSTemplateInfo* structure
6339 * numTSTemplates is set to the number of templates read in
6342 getTSTemplates(Archive *fout, int *numTSTemplates)
6348 TSTemplateInfo *tmplinfo;
6352 int i_tmplnamespace;
6356 /* Before 8.3, there is no built-in text search support */
6357 if (fout->remoteVersion < 80300)
6359 *numTSTemplates = 0;
6363 query = createPQExpBuffer();
6365 /* Make sure we are in proper schema */
6366 selectSourceSchema(fout, "pg_catalog");
6368 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6369 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6370 "FROM pg_ts_template");
6372 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6374 ntups = PQntuples(res);
6375 *numTSTemplates = ntups;
6377 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6379 i_tableoid = PQfnumber(res, "tableoid");
6380 i_oid = PQfnumber(res, "oid");
6381 i_tmplname = PQfnumber(res, "tmplname");
6382 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6383 i_tmplinit = PQfnumber(res, "tmplinit");
6384 i_tmpllexize = PQfnumber(res, "tmpllexize");
6386 for (i = 0; i < ntups; i++)
6388 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6389 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6390 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6391 AssignDumpId(&tmplinfo[i].dobj);
6392 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6393 tmplinfo[i].dobj.namespace =
6395 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6396 tmplinfo[i].dobj.catId.oid);
6397 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6398 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6400 /* Decide whether we want to dump it */
6401 selectDumpableObject(&(tmplinfo[i].dobj));
6406 destroyPQExpBuffer(query);
6412 * getTSConfigurations:
6413 * read all text search configurations in the system catalogs and return
6414 * them in the TSConfigInfo* structure
6416 * numTSConfigs is set to the number of configurations read in
6419 getTSConfigurations(Archive *fout, int *numTSConfigs)
6425 TSConfigInfo *cfginfo;
6433 /* Before 8.3, there is no built-in text search support */
6434 if (fout->remoteVersion < 80300)
6440 query = createPQExpBuffer();
6442 /* Make sure we are in proper schema */
6443 selectSourceSchema(fout, "pg_catalog");
6445 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6446 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6447 "FROM pg_ts_config",
6450 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6452 ntups = PQntuples(res);
6453 *numTSConfigs = ntups;
6455 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6457 i_tableoid = PQfnumber(res, "tableoid");
6458 i_oid = PQfnumber(res, "oid");
6459 i_cfgname = PQfnumber(res, "cfgname");
6460 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6461 i_rolname = PQfnumber(res, "rolname");
6462 i_cfgparser = PQfnumber(res, "cfgparser");
6464 for (i = 0; i < ntups; i++)
6466 cfginfo[i].dobj.objType = DO_TSCONFIG;
6467 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6468 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6469 AssignDumpId(&cfginfo[i].dobj);
6470 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6471 cfginfo[i].dobj.namespace =
6473 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6474 cfginfo[i].dobj.catId.oid);
6475 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6476 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6478 /* Decide whether we want to dump it */
6479 selectDumpableObject(&(cfginfo[i].dobj));
6484 destroyPQExpBuffer(query);
6490 * getForeignDataWrappers:
6491 * read all foreign-data wrappers in the system catalogs and return
6492 * them in the FdwInfo* structure
6494 * numForeignDataWrappers is set to the number of fdws read in
6497 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6502 PQExpBuffer query = createPQExpBuffer();
6513 /* Before 8.4, there are no foreign-data wrappers */
6514 if (fout->remoteVersion < 80400)
6516 *numForeignDataWrappers = 0;
6520 /* Make sure we are in proper schema */
6521 selectSourceSchema(fout, "pg_catalog");
6523 if (fout->remoteVersion >= 90100)
6525 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6526 "(%s fdwowner) AS rolname, "
6527 "fdwhandler::pg_catalog.regproc, "
6528 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6529 "array_to_string(ARRAY("
6530 "SELECT quote_ident(option_name) || ' ' || "
6531 "quote_literal(option_value) "
6532 "FROM pg_options_to_table(fdwoptions) "
6533 "ORDER BY option_name"
6534 "), E',\n ') AS fdwoptions "
6535 "FROM pg_foreign_data_wrapper",
6540 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6541 "(%s fdwowner) AS rolname, "
6542 "'-' AS fdwhandler, "
6543 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6544 "array_to_string(ARRAY("
6545 "SELECT quote_ident(option_name) || ' ' || "
6546 "quote_literal(option_value) "
6547 "FROM pg_options_to_table(fdwoptions) "
6548 "ORDER BY option_name"
6549 "), E',\n ') AS fdwoptions "
6550 "FROM pg_foreign_data_wrapper",
6554 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6556 ntups = PQntuples(res);
6557 *numForeignDataWrappers = ntups;
6559 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6561 i_tableoid = PQfnumber(res, "tableoid");
6562 i_oid = PQfnumber(res, "oid");
6563 i_fdwname = PQfnumber(res, "fdwname");
6564 i_rolname = PQfnumber(res, "rolname");
6565 i_fdwhandler = PQfnumber(res, "fdwhandler");
6566 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6567 i_fdwacl = PQfnumber(res, "fdwacl");
6568 i_fdwoptions = PQfnumber(res, "fdwoptions");
6570 for (i = 0; i < ntups; i++)
6572 fdwinfo[i].dobj.objType = DO_FDW;
6573 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6574 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6575 AssignDumpId(&fdwinfo[i].dobj);
6576 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6577 fdwinfo[i].dobj.namespace = NULL;
6578 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6579 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6580 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6581 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6582 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6584 /* Decide whether we want to dump it */
6585 selectDumpableObject(&(fdwinfo[i].dobj));
6590 destroyPQExpBuffer(query);
6596 * getForeignServers:
6597 * read all foreign servers in the system catalogs and return
6598 * them in the ForeignServerInfo * structure
6600 * numForeignServers is set to the number of servers read in
6603 getForeignServers(Archive *fout, int *numForeignServers)
6608 PQExpBuffer query = createPQExpBuffer();
6609 ForeignServerInfo *srvinfo;
6620 /* Before 8.4, there are no foreign servers */
6621 if (fout->remoteVersion < 80400)
6623 *numForeignServers = 0;
6627 /* Make sure we are in proper schema */
6628 selectSourceSchema(fout,"pg_catalog");
6630 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6631 "(%s srvowner) AS rolname, "
6632 "srvfdw, srvtype, srvversion, srvacl,"
6633 "array_to_string(ARRAY("
6634 "SELECT quote_ident(option_name) || ' ' || "
6635 "quote_literal(option_value) "
6636 "FROM pg_options_to_table(srvoptions) "
6637 "ORDER BY option_name"
6638 "), E',\n ') AS srvoptions "
6639 "FROM pg_foreign_server",
6642 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6644 ntups = PQntuples(res);
6645 *numForeignServers = ntups;
6647 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6649 i_tableoid = PQfnumber(res, "tableoid");
6650 i_oid = PQfnumber(res, "oid");
6651 i_srvname = PQfnumber(res, "srvname");
6652 i_rolname = PQfnumber(res, "rolname");
6653 i_srvfdw = PQfnumber(res, "srvfdw");
6654 i_srvtype = PQfnumber(res, "srvtype");
6655 i_srvversion = PQfnumber(res, "srvversion");
6656 i_srvacl = PQfnumber(res, "srvacl");
6657 i_srvoptions = PQfnumber(res, "srvoptions");
6659 for (i = 0; i < ntups; i++)
6661 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6662 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6663 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6664 AssignDumpId(&srvinfo[i].dobj);
6665 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6666 srvinfo[i].dobj.namespace = NULL;
6667 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6668 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6669 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6670 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6671 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6672 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6674 /* Decide whether we want to dump it */
6675 selectDumpableObject(&(srvinfo[i].dobj));
6680 destroyPQExpBuffer(query);
6687 * read all default ACL information in the system catalogs and return
6688 * them in the DefaultACLInfo structure
6690 * numDefaultACLs is set to the number of ACLs read in
6693 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6695 DefaultACLInfo *daclinfo;
6701 int i_defaclnamespace;
6702 int i_defaclobjtype;
6707 if (fout->remoteVersion < 90000)
6709 *numDefaultACLs = 0;
6713 query = createPQExpBuffer();
6715 /* Make sure we are in proper schema */
6716 selectSourceSchema(fout, "pg_catalog");
6718 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6719 "(%s defaclrole) AS defaclrole, "
6723 "FROM pg_default_acl",
6726 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6728 ntups = PQntuples(res);
6729 *numDefaultACLs = ntups;
6731 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6733 i_oid = PQfnumber(res, "oid");
6734 i_tableoid = PQfnumber(res, "tableoid");
6735 i_defaclrole = PQfnumber(res, "defaclrole");
6736 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6737 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6738 i_defaclacl = PQfnumber(res, "defaclacl");
6740 for (i = 0; i < ntups; i++)
6742 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6744 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6745 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6746 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6747 AssignDumpId(&daclinfo[i].dobj);
6748 /* cheesy ... is it worth coming up with a better object name? */
6749 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6751 if (nspid != InvalidOid)
6752 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6753 daclinfo[i].dobj.catId.oid);
6755 daclinfo[i].dobj.namespace = NULL;
6757 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6758 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6759 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6761 /* Decide whether we want to dump it */
6762 selectDumpableDefaultACL(&(daclinfo[i]));
6767 destroyPQExpBuffer(query);
6775 * This routine is used to dump any comments associated with the
6776 * object handed to this routine. The routine takes a constant character
6777 * string for the target part of the comment-creation command, plus
6778 * the namespace and owner of the object (for labeling the ArchiveEntry),
6779 * plus catalog ID and subid which are the lookup key for pg_description,
6780 * plus the dump ID for the object (for setting a dependency).
6781 * If a matching pg_description entry is found, it is dumped.
6783 * Note: although this routine takes a dumpId for dependency purposes,
6784 * that purpose is just to mark the dependency in the emitted dump file
6785 * for possible future use by pg_restore. We do NOT use it for determining
6786 * ordering of the comment in the dump file, because this routine is called
6787 * after dependency sorting occurs. This routine should be called just after
6788 * calling ArchiveEntry() for the specified object.
6791 dumpComment(Archive *fout, const char *target,
6792 const char *namespace, const char *owner,
6793 CatalogId catalogId, int subid, DumpId dumpId)
6795 CommentItem *comments;
6798 /* Comments are schema not data ... except blob comments are data */
6799 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6810 /* Search for comments associated with catalogId, using table */
6811 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6814 /* Is there one matching the subid? */
6815 while (ncomments > 0)
6817 if (comments->objsubid == subid)
6823 /* If a comment exists, build COMMENT ON statement */
6826 PQExpBuffer query = createPQExpBuffer();
6828 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6829 appendStringLiteralAH(query, comments->descr, fout);
6830 appendPQExpBuffer(query, ";\n");
6833 * We mark comments as SECTION_NONE because they really belong in the
6834 * same section as their parent, whether that is pre-data or
6837 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6838 target, namespace, NULL, owner,
6839 false, "COMMENT", SECTION_NONE,
6840 query->data, "", NULL,
6844 destroyPQExpBuffer(query);
6849 * dumpTableComment --
6851 * As above, but dump comments for both the specified table (or view)
6855 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6856 const char *reltypename)
6858 CommentItem *comments;
6863 /* Comments are SCHEMA not data */
6867 /* Search for comments associated with relation, using table */
6868 ncomments = findComments(fout,
6869 tbinfo->dobj.catId.tableoid,
6870 tbinfo->dobj.catId.oid,
6873 /* If comments exist, build COMMENT ON statements */
6877 query = createPQExpBuffer();
6878 target = createPQExpBuffer();
6880 while (ncomments > 0)
6882 const char *descr = comments->descr;
6883 int objsubid = comments->objsubid;
6887 resetPQExpBuffer(target);
6888 appendPQExpBuffer(target, "%s %s", reltypename,
6889 fmtId(tbinfo->dobj.name));
6891 resetPQExpBuffer(query);
6892 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6893 appendStringLiteralAH(query, descr, fout);
6894 appendPQExpBuffer(query, ";\n");
6896 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6898 tbinfo->dobj.namespace->dobj.name,
6899 NULL, tbinfo->rolname,
6900 false, "COMMENT", SECTION_NONE,
6901 query->data, "", NULL,
6902 &(tbinfo->dobj.dumpId), 1,
6905 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6907 resetPQExpBuffer(target);
6908 appendPQExpBuffer(target, "COLUMN %s.",
6909 fmtId(tbinfo->dobj.name));
6910 appendPQExpBuffer(target, "%s",
6911 fmtId(tbinfo->attnames[objsubid - 1]));
6913 resetPQExpBuffer(query);
6914 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6915 appendStringLiteralAH(query, descr, fout);
6916 appendPQExpBuffer(query, ";\n");
6918 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6920 tbinfo->dobj.namespace->dobj.name,
6921 NULL, tbinfo->rolname,
6922 false, "COMMENT", SECTION_NONE,
6923 query->data, "", NULL,
6924 &(tbinfo->dobj.dumpId), 1,
6932 destroyPQExpBuffer(query);
6933 destroyPQExpBuffer(target);
6939 * Find the comment(s), if any, associated with the given object. All the
6940 * objsubid values associated with the given classoid/objoid are found with
6944 findComments(Archive *fout, Oid classoid, Oid objoid,
6945 CommentItem **items)
6947 /* static storage for table of comments */
6948 static CommentItem *comments = NULL;
6949 static int ncomments = -1;
6951 CommentItem *middle = NULL;
6956 /* Get comments if we didn't already */
6958 ncomments = collectComments(fout, &comments);
6961 * Pre-7.2, pg_description does not contain classoid, so collectComments
6962 * just stores a zero. If there's a collision on object OID, well, you
6963 * get duplicate comments.
6965 if (fout->remoteVersion < 70200)
6969 * Do binary search to find some item matching the object.
6972 high = &comments[ncomments - 1];
6975 middle = low + (high - low) / 2;
6977 if (classoid < middle->classoid)
6979 else if (classoid > middle->classoid)
6981 else if (objoid < middle->objoid)
6983 else if (objoid > middle->objoid)
6986 break; /* found a match */
6989 if (low > high) /* no matches */
6996 * Now determine how many items match the object. The search loop
6997 * invariant still holds: only items between low and high inclusive could
7001 while (middle > low)
7003 if (classoid != middle[-1].classoid ||
7004 objoid != middle[-1].objoid)
7013 while (middle <= high)
7015 if (classoid != middle->classoid ||
7016 objoid != middle->objoid)
7026 * collectComments --
7028 * Construct a table of all comments available for database objects.
7029 * We used to do per-object queries for the comments, but it's much faster
7030 * to pull them all over at once, and on most databases the memory cost
7033 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7036 collectComments(Archive *fout, CommentItem **items)
7046 CommentItem *comments;
7049 * Note we do NOT change source schema here; preserve the caller's
7053 query = createPQExpBuffer();
7055 if (fout->remoteVersion >= 70300)
7057 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7058 "FROM pg_catalog.pg_description "
7059 "ORDER BY classoid, objoid, objsubid");
7061 else if (fout->remoteVersion >= 70200)
7063 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7064 "FROM pg_description "
7065 "ORDER BY classoid, objoid, objsubid");
7069 /* Note: this will fail to find attribute comments in pre-7.2... */
7070 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7071 "FROM pg_description "
7075 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7077 /* Construct lookup table containing OIDs in numeric form */
7079 i_description = PQfnumber(res, "description");
7080 i_classoid = PQfnumber(res, "classoid");
7081 i_objoid = PQfnumber(res, "objoid");
7082 i_objsubid = PQfnumber(res, "objsubid");
7084 ntups = PQntuples(res);
7086 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7088 for (i = 0; i < ntups; i++)
7090 comments[i].descr = PQgetvalue(res, i, i_description);
7091 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7092 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7093 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7096 /* Do NOT free the PGresult since we are keeping pointers into it */
7097 destroyPQExpBuffer(query);
7104 * dumpDumpableObject
7106 * This routine and its subsidiaries are responsible for creating
7107 * ArchiveEntries (TOC objects) for each object to be dumped.
7110 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7115 switch (dobj->objType)
7120 case DO_FK_CONSTRAINT:
7122 skip = !(dumpSections & DUMP_POST_DATA);
7125 skip = !(dumpSections & DUMP_DATA);
7128 skip = !(dumpSections & DUMP_PRE_DATA);
7134 switch (dobj->objType)
7137 dumpNamespace(fout, (NamespaceInfo *) dobj);
7140 dumpExtension(fout, (ExtensionInfo *) dobj);
7143 dumpType(fout, (TypeInfo *) dobj);
7146 dumpShellType(fout, (ShellTypeInfo *) dobj);
7149 dumpFunc(fout, (FuncInfo *) dobj);
7152 dumpAgg(fout, (AggInfo *) dobj);
7155 dumpOpr(fout, (OprInfo *) dobj);
7158 dumpOpclass(fout, (OpclassInfo *) dobj);
7161 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7164 dumpCollation(fout, (CollInfo *) dobj);
7167 dumpConversion(fout, (ConvInfo *) dobj);
7170 dumpTable(fout, (TableInfo *) dobj);
7173 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7176 dumpIndex(fout, (IndxInfo *) dobj);
7179 dumpRule(fout, (RuleInfo *) dobj);
7182 dumpTrigger(fout, (TriggerInfo *) dobj);
7185 dumpConstraint(fout, (ConstraintInfo *) dobj);
7187 case DO_FK_CONSTRAINT:
7188 dumpConstraint(fout, (ConstraintInfo *) dobj);
7191 dumpProcLang(fout, (ProcLangInfo *) dobj);
7194 dumpCast(fout, (CastInfo *) dobj);
7197 dumpTableData(fout, (TableDataInfo *) dobj);
7200 /* table rowtypes and array types are never dumped separately */
7203 dumpTSParser(fout, (TSParserInfo *) dobj);
7206 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7209 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7212 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7215 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7217 case DO_FOREIGN_SERVER:
7218 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7220 case DO_DEFAULT_ACL:
7221 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7224 dumpBlob(fout, (BlobInfo *) dobj);
7227 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7228 dobj->name, NULL, NULL, "",
7229 false, "BLOBS", SECTION_DATA,
7231 dobj->dependencies, dobj->nDeps,
7239 * writes out to fout the queries to recreate a user-defined namespace
7242 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7249 /* Skip if not to be dumped */
7250 if (!nspinfo->dobj.dump || dataOnly)
7253 /* don't dump dummy namespace from pre-7.3 source */
7254 if (strlen(nspinfo->dobj.name) == 0)
7257 q = createPQExpBuffer();
7258 delq = createPQExpBuffer();
7259 labelq = createPQExpBuffer();
7261 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7263 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7265 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7267 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7270 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7272 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7276 false, "SCHEMA", SECTION_PRE_DATA,
7277 q->data, delq->data, NULL,
7278 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7281 /* Dump Schema Comments and Security Labels */
7282 dumpComment(fout, labelq->data,
7283 NULL, nspinfo->rolname,
7284 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7285 dumpSecLabel(fout, labelq->data,
7286 NULL, nspinfo->rolname,
7287 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7289 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7290 qnspname, NULL, nspinfo->dobj.name, NULL,
7291 nspinfo->rolname, nspinfo->nspacl);
7295 destroyPQExpBuffer(q);
7296 destroyPQExpBuffer(delq);
7297 destroyPQExpBuffer(labelq);
7302 * writes out to fout the queries to recreate an extension
7305 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7312 /* Skip if not to be dumped */
7313 if (!extinfo->dobj.dump || dataOnly)
7316 q = createPQExpBuffer();
7317 delq = createPQExpBuffer();
7318 labelq = createPQExpBuffer();
7320 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7322 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7324 if (!binary_upgrade)
7327 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7328 * problem if the extension already exists in the target database;
7329 * this is essential for installed-by-default extensions such as
7332 * In binary-upgrade mode, that doesn't work well, so instead we skip
7333 * built-in extensions based on their OIDs; see
7334 * selectDumpableExtension.
7336 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7337 qextname, fmtId(extinfo->namespace));
7344 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7345 appendPQExpBuffer(q,
7346 "SELECT binary_upgrade.create_empty_extension(");
7347 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7348 appendPQExpBuffer(q, ", ");
7349 appendStringLiteralAH(q, extinfo->namespace, fout);
7350 appendPQExpBuffer(q, ", ");
7351 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7352 appendStringLiteralAH(q, extinfo->extversion, fout);
7353 appendPQExpBuffer(q, ", ");
7356 * Note that we're pushing extconfig (an OID array) back into
7357 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7358 * preserved in binary upgrade.
7360 if (strlen(extinfo->extconfig) > 2)
7361 appendStringLiteralAH(q, extinfo->extconfig, fout);
7363 appendPQExpBuffer(q, "NULL");
7364 appendPQExpBuffer(q, ", ");
7365 if (strlen(extinfo->extcondition) > 2)
7366 appendStringLiteralAH(q, extinfo->extcondition, fout);
7368 appendPQExpBuffer(q, "NULL");
7369 appendPQExpBuffer(q, ", ");
7370 appendPQExpBuffer(q, "ARRAY[");
7372 for (i = 0; i < extinfo->dobj.nDeps; i++)
7374 DumpableObject *extobj;
7376 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7377 if (extobj && extobj->objType == DO_EXTENSION)
7380 appendPQExpBuffer(q, ",");
7381 appendStringLiteralAH(q, extobj->name, fout);
7384 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7385 appendPQExpBuffer(q, ");\n");
7388 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7390 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7394 false, "EXTENSION", SECTION_PRE_DATA,
7395 q->data, delq->data, NULL,
7396 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7399 /* Dump Extension Comments and Security Labels */
7400 dumpComment(fout, labelq->data,
7402 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7403 dumpSecLabel(fout, labelq->data,
7405 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7409 destroyPQExpBuffer(q);
7410 destroyPQExpBuffer(delq);
7411 destroyPQExpBuffer(labelq);
7416 * writes out to fout the queries to recreate a user-defined type
7419 dumpType(Archive *fout, TypeInfo *tyinfo)
7421 /* Skip if not to be dumped */
7422 if (!tyinfo->dobj.dump || dataOnly)
7425 /* Dump out in proper style */
7426 if (tyinfo->typtype == TYPTYPE_BASE)
7427 dumpBaseType(fout, tyinfo);
7428 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7429 dumpDomain(fout, tyinfo);
7430 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7431 dumpCompositeType(fout, tyinfo);
7432 else if (tyinfo->typtype == TYPTYPE_ENUM)
7433 dumpEnumType(fout, tyinfo);
7434 else if (tyinfo->typtype == TYPTYPE_RANGE)
7435 dumpRangeType(fout, tyinfo);
7437 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7443 * writes out to fout the queries to recreate a user-defined enum type
7446 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7448 PQExpBuffer q = createPQExpBuffer();
7449 PQExpBuffer delq = createPQExpBuffer();
7450 PQExpBuffer labelq = createPQExpBuffer();
7451 PQExpBuffer query = createPQExpBuffer();
7458 /* Set proper schema search path */
7459 selectSourceSchema(fout, "pg_catalog");
7461 if (fout->remoteVersion >= 90100)
7462 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7463 "FROM pg_catalog.pg_enum "
7464 "WHERE enumtypid = '%u'"
7465 "ORDER BY enumsortorder",
7466 tyinfo->dobj.catId.oid);
7468 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7469 "FROM pg_catalog.pg_enum "
7470 "WHERE enumtypid = '%u'"
7472 tyinfo->dobj.catId.oid);
7474 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7476 num = PQntuples(res);
7479 * DROP must be fully qualified in case same name appears in pg_catalog.
7480 * CASCADE shouldn't be required here as for normal types since the I/O
7481 * functions are generic and do not get dropped.
7483 appendPQExpBuffer(delq, "DROP TYPE %s.",
7484 fmtId(tyinfo->dobj.namespace->dobj.name));
7485 appendPQExpBuffer(delq, "%s;\n",
7486 fmtId(tyinfo->dobj.name));
7489 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7490 tyinfo->dobj.catId.oid);
7492 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7493 fmtId(tyinfo->dobj.name));
7495 if (!binary_upgrade)
7497 /* Labels with server-assigned oids */
7498 for (i = 0; i < num; i++)
7500 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7502 appendPQExpBuffer(q, ",");
7503 appendPQExpBuffer(q, "\n ");
7504 appendStringLiteralAH(q, label, fout);
7508 appendPQExpBuffer(q, "\n);\n");
7512 /* Labels with dump-assigned (preserved) oids */
7513 for (i = 0; i < num; i++)
7515 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7516 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7519 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7520 appendPQExpBuffer(q,
7521 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7523 appendPQExpBuffer(q, "ALTER TYPE %s.",
7524 fmtId(tyinfo->dobj.namespace->dobj.name));
7525 appendPQExpBuffer(q, "%s ADD VALUE ",
7526 fmtId(tyinfo->dobj.name));
7527 appendStringLiteralAH(q, label, fout);
7528 appendPQExpBuffer(q, ";\n\n");
7532 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7535 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7537 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7539 tyinfo->dobj.namespace->dobj.name,
7541 tyinfo->rolname, false,
7542 "TYPE", SECTION_PRE_DATA,
7543 q->data, delq->data, NULL,
7544 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7547 /* Dump Type Comments and Security Labels */
7548 dumpComment(fout, labelq->data,
7549 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7550 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7551 dumpSecLabel(fout, labelq->data,
7552 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7553 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7556 destroyPQExpBuffer(q);
7557 destroyPQExpBuffer(delq);
7558 destroyPQExpBuffer(labelq);
7559 destroyPQExpBuffer(query);
7564 * writes out to fout the queries to recreate a user-defined range type
7567 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7569 PQExpBuffer q = createPQExpBuffer();
7570 PQExpBuffer delq = createPQExpBuffer();
7571 PQExpBuffer labelq = createPQExpBuffer();
7572 PQExpBuffer query = createPQExpBuffer();
7578 * select appropriate schema to ensure names in CREATE are properly
7581 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7583 appendPQExpBuffer(query,
7584 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7585 "opc.opcname AS opcname, "
7586 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7587 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7589 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7590 " ELSE rngcollation END AS collation, "
7591 "rngcanonical, rngsubdiff "
7592 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7593 " pg_catalog.pg_opclass opc "
7594 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7596 tyinfo->dobj.catId.oid);
7598 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7601 * DROP must be fully qualified in case same name appears in pg_catalog.
7602 * CASCADE shouldn't be required here as for normal types since the I/O
7603 * functions are generic and do not get dropped.
7605 appendPQExpBuffer(delq, "DROP TYPE %s.",
7606 fmtId(tyinfo->dobj.namespace->dobj.name));
7607 appendPQExpBuffer(delq, "%s;\n",
7608 fmtId(tyinfo->dobj.name));
7611 binary_upgrade_set_type_oids_by_type_oid(fout,
7612 q, tyinfo->dobj.catId.oid);
7614 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7615 fmtId(tyinfo->dobj.name));
7617 appendPQExpBuffer(q, "\n subtype = %s",
7618 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7620 /* print subtype_opclass only if not default for subtype */
7621 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7623 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7624 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7626 /* always schema-qualify, don't try to be smart */
7627 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7629 appendPQExpBuffer(q, "%s", fmtId(opcname));
7632 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7633 if (OidIsValid(collationOid))
7635 CollInfo *coll = findCollationByOid(collationOid);
7639 /* always schema-qualify, don't try to be smart */
7640 appendPQExpBuffer(q, ",\n collation = %s.",
7641 fmtId(coll->dobj.namespace->dobj.name));
7642 appendPQExpBuffer(q, "%s",
7643 fmtId(coll->dobj.name));
7647 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7648 if (strcmp(procname, "-") != 0)
7649 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7651 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7652 if (strcmp(procname, "-") != 0)
7653 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7655 appendPQExpBuffer(q, "\n);\n");
7657 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7660 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7662 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7664 tyinfo->dobj.namespace->dobj.name,
7666 tyinfo->rolname, false,
7667 "TYPE", SECTION_PRE_DATA,
7668 q->data, delq->data, NULL,
7669 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7672 /* Dump Type Comments and Security Labels */
7673 dumpComment(fout, labelq->data,
7674 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7675 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7676 dumpSecLabel(fout, labelq->data,
7677 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7678 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7681 destroyPQExpBuffer(q);
7682 destroyPQExpBuffer(delq);
7683 destroyPQExpBuffer(labelq);
7684 destroyPQExpBuffer(query);
7689 * writes out to fout the queries to recreate a user-defined base type
7692 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7694 PQExpBuffer q = createPQExpBuffer();
7695 PQExpBuffer delq = createPQExpBuffer();
7696 PQExpBuffer labelq = createPQExpBuffer();
7697 PQExpBuffer query = createPQExpBuffer();
7713 char *typispreferred;
7718 char *typcollatable;
7720 bool typdefault_is_literal = false;
7722 /* Set proper schema search path so regproc references list correctly */
7723 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7725 /* Fetch type-specific details */
7726 if (fout->remoteVersion >= 90100)
7728 appendPQExpBuffer(query, "SELECT typlen, "
7729 "typinput, typoutput, typreceive, typsend, "
7730 "typmodin, typmodout, typanalyze, "
7731 "typreceive::pg_catalog.oid AS typreceiveoid, "
7732 "typsend::pg_catalog.oid AS typsendoid, "
7733 "typmodin::pg_catalog.oid AS typmodinoid, "
7734 "typmodout::pg_catalog.oid AS typmodoutoid, "
7735 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7736 "typcategory, typispreferred, "
7737 "typdelim, typbyval, typalign, typstorage, "
7738 "(typcollation <> 0) AS typcollatable, "
7739 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7740 "FROM pg_catalog.pg_type "
7741 "WHERE oid = '%u'::pg_catalog.oid",
7742 tyinfo->dobj.catId.oid);
7744 else if (fout->remoteVersion >= 80400)
7746 appendPQExpBuffer(query, "SELECT typlen, "
7747 "typinput, typoutput, typreceive, typsend, "
7748 "typmodin, typmodout, typanalyze, "
7749 "typreceive::pg_catalog.oid AS typreceiveoid, "
7750 "typsend::pg_catalog.oid AS typsendoid, "
7751 "typmodin::pg_catalog.oid AS typmodinoid, "
7752 "typmodout::pg_catalog.oid AS typmodoutoid, "
7753 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7754 "typcategory, typispreferred, "
7755 "typdelim, typbyval, typalign, typstorage, "
7756 "false AS typcollatable, "
7757 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7758 "FROM pg_catalog.pg_type "
7759 "WHERE oid = '%u'::pg_catalog.oid",
7760 tyinfo->dobj.catId.oid);
7762 else if (fout->remoteVersion >= 80300)
7764 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7765 appendPQExpBuffer(query, "SELECT typlen, "
7766 "typinput, typoutput, typreceive, typsend, "
7767 "typmodin, typmodout, typanalyze, "
7768 "typreceive::pg_catalog.oid AS typreceiveoid, "
7769 "typsend::pg_catalog.oid AS typsendoid, "
7770 "typmodin::pg_catalog.oid AS typmodinoid, "
7771 "typmodout::pg_catalog.oid AS typmodoutoid, "
7772 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7773 "'U' AS typcategory, false AS typispreferred, "
7774 "typdelim, typbyval, typalign, typstorage, "
7775 "false AS typcollatable, "
7776 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7777 "FROM pg_catalog.pg_type "
7778 "WHERE oid = '%u'::pg_catalog.oid",
7779 tyinfo->dobj.catId.oid);
7781 else if (fout->remoteVersion >= 80000)
7783 appendPQExpBuffer(query, "SELECT typlen, "
7784 "typinput, typoutput, typreceive, typsend, "
7785 "'-' AS typmodin, '-' AS typmodout, "
7787 "typreceive::pg_catalog.oid AS typreceiveoid, "
7788 "typsend::pg_catalog.oid AS typsendoid, "
7789 "0 AS typmodinoid, 0 AS typmodoutoid, "
7790 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7791 "'U' AS typcategory, false AS typispreferred, "
7792 "typdelim, typbyval, typalign, typstorage, "
7793 "false AS typcollatable, "
7794 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7795 "FROM pg_catalog.pg_type "
7796 "WHERE oid = '%u'::pg_catalog.oid",
7797 tyinfo->dobj.catId.oid);
7799 else if (fout->remoteVersion >= 70400)
7801 appendPQExpBuffer(query, "SELECT typlen, "
7802 "typinput, typoutput, typreceive, typsend, "
7803 "'-' AS typmodin, '-' AS typmodout, "
7804 "'-' AS typanalyze, "
7805 "typreceive::pg_catalog.oid AS typreceiveoid, "
7806 "typsend::pg_catalog.oid AS typsendoid, "
7807 "0 AS typmodinoid, 0 AS typmodoutoid, "
7808 "0 AS typanalyzeoid, "
7809 "'U' AS typcategory, false AS typispreferred, "
7810 "typdelim, typbyval, typalign, typstorage, "
7811 "false AS typcollatable, "
7812 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7813 "FROM pg_catalog.pg_type "
7814 "WHERE oid = '%u'::pg_catalog.oid",
7815 tyinfo->dobj.catId.oid);
7817 else if (fout->remoteVersion >= 70300)
7819 appendPQExpBuffer(query, "SELECT typlen, "
7820 "typinput, typoutput, "
7821 "'-' AS typreceive, '-' AS typsend, "
7822 "'-' AS typmodin, '-' AS typmodout, "
7823 "'-' AS typanalyze, "
7824 "0 AS typreceiveoid, 0 AS typsendoid, "
7825 "0 AS typmodinoid, 0 AS typmodoutoid, "
7826 "0 AS typanalyzeoid, "
7827 "'U' AS typcategory, false AS typispreferred, "
7828 "typdelim, typbyval, typalign, typstorage, "
7829 "false AS typcollatable, "
7830 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7831 "FROM pg_catalog.pg_type "
7832 "WHERE oid = '%u'::pg_catalog.oid",
7833 tyinfo->dobj.catId.oid);
7835 else if (fout->remoteVersion >= 70200)
7838 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7839 * ignore them because they are not right.
7841 appendPQExpBuffer(query, "SELECT typlen, "
7842 "typinput, typoutput, "
7843 "'-' AS typreceive, '-' AS typsend, "
7844 "'-' AS typmodin, '-' AS typmodout, "
7845 "'-' AS typanalyze, "
7846 "0 AS typreceiveoid, 0 AS typsendoid, "
7847 "0 AS typmodinoid, 0 AS typmodoutoid, "
7848 "0 AS typanalyzeoid, "
7849 "'U' AS typcategory, false AS typispreferred, "
7850 "typdelim, typbyval, typalign, typstorage, "
7851 "false AS typcollatable, "
7852 "NULL AS typdefaultbin, typdefault "
7854 "WHERE oid = '%u'::oid",
7855 tyinfo->dobj.catId.oid);
7857 else if (fout->remoteVersion >= 70100)
7860 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7863 appendPQExpBuffer(query, "SELECT typlen, "
7864 "typinput, typoutput, "
7865 "'-' AS typreceive, '-' AS typsend, "
7866 "'-' AS typmodin, '-' AS typmodout, "
7867 "'-' AS typanalyze, "
7868 "0 AS typreceiveoid, 0 AS typsendoid, "
7869 "0 AS typmodinoid, 0 AS typmodoutoid, "
7870 "0 AS typanalyzeoid, "
7871 "'U' AS typcategory, false AS typispreferred, "
7872 "typdelim, typbyval, typalign, typstorage, "
7873 "false AS typcollatable, "
7874 "NULL AS typdefaultbin, NULL AS typdefault "
7876 "WHERE oid = '%u'::oid",
7877 tyinfo->dobj.catId.oid);
7881 appendPQExpBuffer(query, "SELECT typlen, "
7882 "typinput, typoutput, "
7883 "'-' AS typreceive, '-' AS typsend, "
7884 "'-' AS typmodin, '-' AS typmodout, "
7885 "'-' AS typanalyze, "
7886 "0 AS typreceiveoid, 0 AS typsendoid, "
7887 "0 AS typmodinoid, 0 AS typmodoutoid, "
7888 "0 AS typanalyzeoid, "
7889 "'U' AS typcategory, false AS typispreferred, "
7890 "typdelim, typbyval, typalign, "
7891 "'p'::char AS typstorage, "
7892 "false AS typcollatable, "
7893 "NULL AS typdefaultbin, NULL AS typdefault "
7895 "WHERE oid = '%u'::oid",
7896 tyinfo->dobj.catId.oid);
7899 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7901 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7902 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7903 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7904 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7905 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7906 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7907 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7908 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7909 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7910 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7911 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7912 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7913 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7914 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7915 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7916 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7917 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7918 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7919 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7920 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7921 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7922 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7923 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7925 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7926 typdefault_is_literal = true; /* it needs quotes */
7932 * DROP must be fully qualified in case same name appears in pg_catalog.
7933 * The reason we include CASCADE is that the circular dependency between
7934 * the type and its I/O functions makes it impossible to drop the type any
7937 appendPQExpBuffer(delq, "DROP TYPE %s.",
7938 fmtId(tyinfo->dobj.namespace->dobj.name));
7939 appendPQExpBuffer(delq, "%s CASCADE;\n",
7940 fmtId(tyinfo->dobj.name));
7942 /* We might already have a shell type, but setting pg_type_oid is harmless */
7944 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7945 tyinfo->dobj.catId.oid);
7947 appendPQExpBuffer(q,
7948 "CREATE TYPE %s (\n"
7949 " INTERNALLENGTH = %s",
7950 fmtId(tyinfo->dobj.name),
7951 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7953 if (fout->remoteVersion >= 70300)
7955 /* regproc result is correctly quoted as of 7.3 */
7956 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7957 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7958 if (OidIsValid(typreceiveoid))
7959 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7960 if (OidIsValid(typsendoid))
7961 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7962 if (OidIsValid(typmodinoid))
7963 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7964 if (OidIsValid(typmodoutoid))
7965 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7966 if (OidIsValid(typanalyzeoid))
7967 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7971 /* regproc delivers an unquoted name before 7.3 */
7972 /* cannot combine these because fmtId uses static result area */
7973 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7974 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7975 /* receive/send/typmodin/typmodout/analyze need not be printed */
7978 if (strcmp(typcollatable, "t") == 0)
7979 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7981 if (typdefault != NULL)
7983 appendPQExpBuffer(q, ",\n DEFAULT = ");
7984 if (typdefault_is_literal)
7985 appendStringLiteralAH(q, typdefault, fout);
7987 appendPQExpBufferStr(q, typdefault);
7990 if (OidIsValid(tyinfo->typelem))
7994 /* reselect schema in case changed by function dump */
7995 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7996 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7997 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8001 if (strcmp(typcategory, "U") != 0)
8003 appendPQExpBuffer(q, ",\n CATEGORY = ");
8004 appendStringLiteralAH(q, typcategory, fout);
8007 if (strcmp(typispreferred, "t") == 0)
8008 appendPQExpBuffer(q, ",\n PREFERRED = true");
8010 if (typdelim && strcmp(typdelim, ",") != 0)
8012 appendPQExpBuffer(q, ",\n DELIMITER = ");
8013 appendStringLiteralAH(q, typdelim, fout);
8016 if (strcmp(typalign, "c") == 0)
8017 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8018 else if (strcmp(typalign, "s") == 0)
8019 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8020 else if (strcmp(typalign, "i") == 0)
8021 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8022 else if (strcmp(typalign, "d") == 0)
8023 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8025 if (strcmp(typstorage, "p") == 0)
8026 appendPQExpBuffer(q, ",\n STORAGE = plain");
8027 else if (strcmp(typstorage, "e") == 0)
8028 appendPQExpBuffer(q, ",\n STORAGE = external");
8029 else if (strcmp(typstorage, "x") == 0)
8030 appendPQExpBuffer(q, ",\n STORAGE = extended");
8031 else if (strcmp(typstorage, "m") == 0)
8032 appendPQExpBuffer(q, ",\n STORAGE = main");
8034 if (strcmp(typbyval, "t") == 0)
8035 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8037 appendPQExpBuffer(q, "\n);\n");
8039 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8042 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8044 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8046 tyinfo->dobj.namespace->dobj.name,
8048 tyinfo->rolname, false,
8049 "TYPE", SECTION_PRE_DATA,
8050 q->data, delq->data, NULL,
8051 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8054 /* Dump Type Comments and Security Labels */
8055 dumpComment(fout, labelq->data,
8056 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8057 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8058 dumpSecLabel(fout, labelq->data,
8059 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8060 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8063 destroyPQExpBuffer(q);
8064 destroyPQExpBuffer(delq);
8065 destroyPQExpBuffer(labelq);
8066 destroyPQExpBuffer(query);
8071 * writes out to fout the queries to recreate a user-defined domain
8074 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8076 PQExpBuffer q = createPQExpBuffer();
8077 PQExpBuffer delq = createPQExpBuffer();
8078 PQExpBuffer labelq = createPQExpBuffer();
8079 PQExpBuffer query = createPQExpBuffer();
8086 bool typdefault_is_literal = false;
8088 /* Set proper schema search path so type references list correctly */
8089 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8091 /* Fetch domain specific details */
8092 if (fout->remoteVersion >= 90100)
8094 /* typcollation is new in 9.1 */
8095 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8096 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8097 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8099 "CASE WHEN t.typcollation <> u.typcollation "
8100 "THEN t.typcollation ELSE 0 END AS typcollation "
8101 "FROM pg_catalog.pg_type t "
8102 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8103 "WHERE t.oid = '%u'::pg_catalog.oid",
8104 tyinfo->dobj.catId.oid);
8108 /* We assume here that remoteVersion must be at least 70300 */
8109 appendPQExpBuffer(query, "SELECT typnotnull, "
8110 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8111 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8112 "typdefault, 0 AS typcollation "
8113 "FROM pg_catalog.pg_type "
8114 "WHERE oid = '%u'::pg_catalog.oid",
8115 tyinfo->dobj.catId.oid);
8118 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8120 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8121 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8122 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8123 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8124 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8126 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8127 typdefault_is_literal = true; /* it needs quotes */
8131 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8134 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8135 tyinfo->dobj.catId.oid);
8137 appendPQExpBuffer(q,
8138 "CREATE DOMAIN %s AS %s",
8139 fmtId(tyinfo->dobj.name),
8142 /* Print collation only if different from base type's collation */
8143 if (OidIsValid(typcollation))
8147 coll = findCollationByOid(typcollation);
8150 /* always schema-qualify, don't try to be smart */
8151 appendPQExpBuffer(q, " COLLATE %s.",
8152 fmtId(coll->dobj.namespace->dobj.name));
8153 appendPQExpBuffer(q, "%s",
8154 fmtId(coll->dobj.name));
8158 if (typnotnull[0] == 't')
8159 appendPQExpBuffer(q, " NOT NULL");
8161 if (typdefault != NULL)
8163 appendPQExpBuffer(q, " DEFAULT ");
8164 if (typdefault_is_literal)
8165 appendStringLiteralAH(q, typdefault, fout);
8167 appendPQExpBufferStr(q, typdefault);
8173 * Add any CHECK constraints for the domain
8175 for (i = 0; i < tyinfo->nDomChecks; i++)
8177 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8179 if (!domcheck->separate)
8180 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8181 fmtId(domcheck->dobj.name), domcheck->condef);
8184 appendPQExpBuffer(q, ";\n");
8187 * DROP must be fully qualified in case same name appears in pg_catalog
8189 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8190 fmtId(tyinfo->dobj.namespace->dobj.name));
8191 appendPQExpBuffer(delq, "%s;\n",
8192 fmtId(tyinfo->dobj.name));
8194 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8197 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8199 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8201 tyinfo->dobj.namespace->dobj.name,
8203 tyinfo->rolname, false,
8204 "DOMAIN", SECTION_PRE_DATA,
8205 q->data, delq->data, NULL,
8206 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8209 /* Dump Domain Comments and Security Labels */
8210 dumpComment(fout, labelq->data,
8211 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8212 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8213 dumpSecLabel(fout, labelq->data,
8214 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8215 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8217 destroyPQExpBuffer(q);
8218 destroyPQExpBuffer(delq);
8219 destroyPQExpBuffer(labelq);
8220 destroyPQExpBuffer(query);
8225 * writes out to fout the queries to recreate a user-defined stand-alone
8229 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8231 PQExpBuffer q = createPQExpBuffer();
8232 PQExpBuffer dropped = createPQExpBuffer();
8233 PQExpBuffer delq = createPQExpBuffer();
8234 PQExpBuffer labelq = createPQExpBuffer();
8235 PQExpBuffer query = createPQExpBuffer();
8248 /* Set proper schema search path so type references list correctly */
8249 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8251 /* Fetch type specific details */
8252 if (fout->remoteVersion >= 90100)
8255 * attcollation is new in 9.1. Since we only want to dump COLLATE
8256 * clauses for attributes whose collation is different from their
8257 * type's default, we use a CASE here to suppress uninteresting
8258 * attcollations cheaply. atttypid will be 0 for dropped columns;
8259 * collation does not matter for those.
8261 appendPQExpBuffer(query, "SELECT a.attname, "
8262 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8263 "a.attlen, a.attalign, a.attisdropped, "
8264 "CASE WHEN a.attcollation <> at.typcollation "
8265 "THEN a.attcollation ELSE 0 END AS attcollation, "
8267 "FROM pg_catalog.pg_type ct "
8268 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8269 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8270 "WHERE ct.oid = '%u'::pg_catalog.oid "
8271 "ORDER BY a.attnum ",
8272 tyinfo->dobj.catId.oid);
8277 * We assume here that remoteVersion must be at least 70300. Since
8278 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8281 appendPQExpBuffer(query, "SELECT a.attname, "
8282 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8283 "a.attlen, a.attalign, a.attisdropped, "
8284 "0 AS attcollation, "
8286 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8287 "WHERE ct.oid = '%u'::pg_catalog.oid "
8288 "AND a.attrelid = ct.typrelid "
8289 "ORDER BY a.attnum ",
8290 tyinfo->dobj.catId.oid);
8293 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8295 ntups = PQntuples(res);
8297 i_attname = PQfnumber(res, "attname");
8298 i_atttypdefn = PQfnumber(res, "atttypdefn");
8299 i_attlen = PQfnumber(res, "attlen");
8300 i_attalign = PQfnumber(res, "attalign");
8301 i_attisdropped = PQfnumber(res, "attisdropped");
8302 i_attcollation = PQfnumber(res, "attcollation");
8303 i_typrelid = PQfnumber(res, "typrelid");
8307 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8309 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8310 tyinfo->dobj.catId.oid);
8311 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8314 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8315 fmtId(tyinfo->dobj.name));
8318 for (i = 0; i < ntups; i++)
8327 attname = PQgetvalue(res, i, i_attname);
8328 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8329 attlen = PQgetvalue(res, i, i_attlen);
8330 attalign = PQgetvalue(res, i, i_attalign);
8331 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8332 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8334 if (attisdropped && !binary_upgrade)
8337 /* Format properly if not first attr */
8338 if (actual_atts++ > 0)
8339 appendPQExpBuffer(q, ",");
8340 appendPQExpBuffer(q, "\n\t");
8344 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8346 /* Add collation if not default for the column type */
8347 if (OidIsValid(attcollation))
8351 coll = findCollationByOid(attcollation);
8354 /* always schema-qualify, don't try to be smart */
8355 appendPQExpBuffer(q, " COLLATE %s.",
8356 fmtId(coll->dobj.namespace->dobj.name));
8357 appendPQExpBuffer(q, "%s",
8358 fmtId(coll->dobj.name));
8365 * This is a dropped attribute and we're in binary_upgrade mode.
8366 * Insert a placeholder for it in the CREATE TYPE command, and set
8367 * length and alignment with direct UPDATE to the catalogs
8368 * afterwards. See similar code in dumpTableSchema().
8370 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8372 /* stash separately for insertion after the CREATE TYPE */
8373 appendPQExpBuffer(dropped,
8374 "\n-- For binary upgrade, recreate dropped column.\n");
8375 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8377 "attalign = '%s', attbyval = false\n"
8378 "WHERE attname = ", attlen, attalign);
8379 appendStringLiteralAH(dropped, attname, fout);
8380 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8381 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8382 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8384 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8385 fmtId(tyinfo->dobj.name));
8386 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8390 appendPQExpBuffer(q, "\n);\n");
8391 appendPQExpBufferStr(q, dropped->data);
8394 * DROP must be fully qualified in case same name appears in pg_catalog
8396 appendPQExpBuffer(delq, "DROP TYPE %s.",
8397 fmtId(tyinfo->dobj.namespace->dobj.name));
8398 appendPQExpBuffer(delq, "%s;\n",
8399 fmtId(tyinfo->dobj.name));
8401 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8404 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8406 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8408 tyinfo->dobj.namespace->dobj.name,
8410 tyinfo->rolname, false,
8411 "TYPE", SECTION_PRE_DATA,
8412 q->data, delq->data, NULL,
8413 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8417 /* Dump Type Comments and Security Labels */
8418 dumpComment(fout, labelq->data,
8419 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8420 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8421 dumpSecLabel(fout, labelq->data,
8422 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8423 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8426 destroyPQExpBuffer(q);
8427 destroyPQExpBuffer(dropped);
8428 destroyPQExpBuffer(delq);
8429 destroyPQExpBuffer(labelq);
8430 destroyPQExpBuffer(query);
8432 /* Dump any per-column comments */
8433 dumpCompositeTypeColComments(fout, tyinfo);
8437 * dumpCompositeTypeColComments
8438 * writes out to fout the queries to recreate comments on the columns of
8439 * a user-defined stand-alone composite type
8442 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8444 CommentItem *comments;
8455 query = createPQExpBuffer();
8457 /* We assume here that remoteVersion must be at least 70300 */
8458 appendPQExpBuffer(query,
8459 "SELECT c.tableoid, a.attname, a.attnum "
8460 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8461 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8462 " AND NOT a.attisdropped "
8463 "ORDER BY a.attnum ",
8466 /* Fetch column attnames */
8467 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8469 ntups = PQntuples(res);
8473 destroyPQExpBuffer(query);
8477 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8479 /* Search for comments associated with type's pg_class OID */
8480 ncomments = findComments(fout,
8485 /* If no comments exist, we're done */
8489 destroyPQExpBuffer(query);
8493 /* Build COMMENT ON statements */
8494 target = createPQExpBuffer();
8496 i_attnum = PQfnumber(res, "attnum");
8497 i_attname = PQfnumber(res, "attname");
8498 while (ncomments > 0)
8500 const char *attname;
8503 for (i = 0; i < ntups; i++)
8505 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8507 attname = PQgetvalue(res, i, i_attname);
8511 if (attname) /* just in case we don't find it */
8513 const char *descr = comments->descr;
8515 resetPQExpBuffer(target);
8516 appendPQExpBuffer(target, "COLUMN %s.",
8517 fmtId(tyinfo->dobj.name));
8518 appendPQExpBuffer(target, "%s",
8521 resetPQExpBuffer(query);
8522 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8523 appendStringLiteralAH(query, descr, fout);
8524 appendPQExpBuffer(query, ";\n");
8526 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8528 tyinfo->dobj.namespace->dobj.name,
8529 NULL, tyinfo->rolname,
8530 false, "COMMENT", SECTION_NONE,
8531 query->data, "", NULL,
8532 &(tyinfo->dobj.dumpId), 1,
8541 destroyPQExpBuffer(query);
8542 destroyPQExpBuffer(target);
8547 * writes out to fout the queries to create a shell type
8549 * We dump a shell definition in advance of the I/O functions for the type.
8552 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8556 /* Skip if not to be dumped */
8557 if (!stinfo->dobj.dump || dataOnly)
8560 q = createPQExpBuffer();
8563 * Note the lack of a DROP command for the shell type; any required DROP
8564 * is driven off the base type entry, instead. This interacts with
8565 * _printTocEntry()'s use of the presence of a DROP command to decide
8566 * whether an entry needs an ALTER OWNER command. We don't want to alter
8567 * the shell type's owner immediately on creation; that should happen only
8568 * after it's filled in, otherwise the backend complains.
8572 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8573 stinfo->baseType->dobj.catId.oid);
8575 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8576 fmtId(stinfo->dobj.name));
8578 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8580 stinfo->dobj.namespace->dobj.name,
8582 stinfo->baseType->rolname, false,
8583 "SHELL TYPE", SECTION_PRE_DATA,
8585 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8588 destroyPQExpBuffer(q);
8592 * Determine whether we want to dump definitions for procedural languages.
8593 * Since the languages themselves don't have schemas, we can't rely on
8594 * the normal schema-based selection mechanism. We choose to dump them
8595 * whenever neither --schema nor --table was given. (Before 8.1, we used
8596 * the dump flag of the PL's call handler function, but in 8.1 this will
8597 * probably always be false since call handlers are created in pg_catalog.)
8599 * For some backwards compatibility with the older behavior, we forcibly
8600 * dump a PL if its handler function (and validator if any) are in a
8601 * dumpable namespace. That case is not checked here.
8603 * Also, if the PL belongs to an extension, we do not use this heuristic.
8604 * That case isn't checked here either.
8607 shouldDumpProcLangs(void)
8609 if (!include_everything)
8611 /* And they're schema not data */
8619 * writes out to fout the queries to recreate a user-defined
8620 * procedural language
8623 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8632 FuncInfo *inlineInfo = NULL;
8633 FuncInfo *validatorInfo = NULL;
8635 /* Skip if not to be dumped */
8636 if (!plang->dobj.dump || dataOnly)
8640 * Try to find the support function(s). It is not an error if we don't
8641 * find them --- if the functions are in the pg_catalog schema, as is
8642 * standard in 8.1 and up, then we won't have loaded them. (In this case
8643 * we will emit a parameterless CREATE LANGUAGE command, which will
8644 * require PL template knowledge in the backend to reload.)
8647 funcInfo = findFuncByOid(plang->lanplcallfoid);
8648 if (funcInfo != NULL && !funcInfo->dobj.dump)
8649 funcInfo = NULL; /* treat not-dumped same as not-found */
8651 if (OidIsValid(plang->laninline))
8653 inlineInfo = findFuncByOid(plang->laninline);
8654 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8658 if (OidIsValid(plang->lanvalidator))
8660 validatorInfo = findFuncByOid(plang->lanvalidator);
8661 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8662 validatorInfo = NULL;
8666 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8667 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8670 * However, for a language that belongs to an extension, we must not use
8671 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8672 * told to (via dobj.dump). Generally the support functions will belong
8673 * to the same extension and so have the same dump flags ... if they
8674 * don't, this might not work terribly nicely.
8676 useParams = (funcInfo != NULL &&
8677 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8678 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8680 if (!plang->dobj.ext_member)
8682 if (!useParams && !shouldDumpProcLangs())
8686 defqry = createPQExpBuffer();
8687 delqry = createPQExpBuffer();
8688 labelq = createPQExpBuffer();
8690 qlanname = pg_strdup(fmtId(plang->dobj.name));
8693 * If dumping a HANDLER clause, treat the language as being in the handler
8694 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8695 * it doesn't really have a schema.
8698 lanschema = funcInfo->dobj.namespace->dobj.name;
8702 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8707 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8708 plang->lanpltrusted ? "TRUSTED " : "",
8710 appendPQExpBuffer(defqry, " HANDLER %s",
8711 fmtId(funcInfo->dobj.name));
8712 if (OidIsValid(plang->laninline))
8714 appendPQExpBuffer(defqry, " INLINE ");
8715 /* Cope with possibility that inline is in different schema */
8716 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8717 appendPQExpBuffer(defqry, "%s.",
8718 fmtId(inlineInfo->dobj.namespace->dobj.name));
8719 appendPQExpBuffer(defqry, "%s",
8720 fmtId(inlineInfo->dobj.name));
8722 if (OidIsValid(plang->lanvalidator))
8724 appendPQExpBuffer(defqry, " VALIDATOR ");
8725 /* Cope with possibility that validator is in different schema */
8726 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8727 appendPQExpBuffer(defqry, "%s.",
8728 fmtId(validatorInfo->dobj.namespace->dobj.name));
8729 appendPQExpBuffer(defqry, "%s",
8730 fmtId(validatorInfo->dobj.name));
8736 * If not dumping parameters, then use CREATE OR REPLACE so that the
8737 * command will not fail if the language is preinstalled in the target
8738 * database. We restrict the use of REPLACE to this case so as to
8739 * eliminate the risk of replacing a language with incompatible
8740 * parameter settings: this command will only succeed at all if there
8741 * is a pg_pltemplate entry, and if there is one, the existing entry
8742 * must match it too.
8744 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8747 appendPQExpBuffer(defqry, ";\n");
8749 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8752 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8754 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8756 lanschema, NULL, plang->lanowner,
8757 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8758 defqry->data, delqry->data, NULL,
8759 plang->dobj.dependencies, plang->dobj.nDeps,
8762 /* Dump Proc Lang Comments and Security Labels */
8763 dumpComment(fout, labelq->data,
8765 plang->dobj.catId, 0, plang->dobj.dumpId);
8766 dumpSecLabel(fout, labelq->data,
8768 plang->dobj.catId, 0, plang->dobj.dumpId);
8770 if (plang->lanpltrusted)
8771 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8772 qlanname, NULL, plang->dobj.name,
8774 plang->lanowner, plang->lanacl);
8778 destroyPQExpBuffer(defqry);
8779 destroyPQExpBuffer(delqry);
8780 destroyPQExpBuffer(labelq);
8784 * format_function_arguments: generate function name and argument list
8786 * This is used when we can rely on pg_get_function_arguments to format
8787 * the argument list.
8790 format_function_arguments(FuncInfo *finfo, char *funcargs)
8794 initPQExpBuffer(&fn);
8795 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8800 * format_function_arguments_old: generate function name and argument list
8802 * The argument type names are qualified if needed. The function name
8803 * is never qualified.
8805 * This is used only with pre-8.4 servers, so we aren't expecting to see
8806 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8808 * Any or all of allargtypes, argmodes, argnames may be NULL.
8811 format_function_arguments_old(Archive *fout,
8812 FuncInfo *finfo, int nallargs,
8820 initPQExpBuffer(&fn);
8821 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8822 for (j = 0; j < nallargs; j++)
8826 const char *argmode;
8827 const char *argname;
8829 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8830 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8834 switch (argmodes[j][0])
8839 case PROARGMODE_OUT:
8842 case PROARGMODE_INOUT:
8846 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8854 argname = argnames ? argnames[j] : (char *) NULL;
8855 if (argname && argname[0] == '\0')
8858 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8859 (j > 0) ? ", " : "",
8861 argname ? fmtId(argname) : "",
8866 appendPQExpBuffer(&fn, ")");
8871 * format_function_signature: generate function name and argument list
8873 * This is like format_function_arguments_old except that only a minimal
8874 * list of input argument types is generated; this is sufficient to
8875 * reference the function, but not to define it.
8877 * If honor_quotes is false then the function name is never quoted.
8878 * This is appropriate for use in TOC tags, but not in SQL commands.
8881 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8886 initPQExpBuffer(&fn);
8888 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8890 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8891 for (j = 0; j < finfo->nargs; j++)
8895 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8898 appendPQExpBuffer(&fn, "%s%s",
8899 (j > 0) ? ", " : "",
8903 appendPQExpBuffer(&fn, ")");
8910 * dump out one function
8913 dumpFunc(Archive *fout, FuncInfo *finfo)
8921 char *funcsig; /* identity signature */
8922 char *funcfullsig; /* full signature */
8930 char *proallargtypes;
8944 char **allargtypes = NULL;
8945 char **argmodes = NULL;
8946 char **argnames = NULL;
8947 char **configitems = NULL;
8948 int nconfigitems = 0;
8951 /* Skip if not to be dumped */
8952 if (!finfo->dobj.dump || dataOnly)
8955 query = createPQExpBuffer();
8956 q = createPQExpBuffer();
8957 delqry = createPQExpBuffer();
8958 labelq = createPQExpBuffer();
8959 asPart = createPQExpBuffer();
8961 /* Set proper schema search path so type references list correctly */
8962 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8964 /* Fetch function-specific details */
8965 if (fout->remoteVersion >= 90200)
8968 * proleakproof was added at v9.2
8970 appendPQExpBuffer(query,
8971 "SELECT proretset, prosrc, probin, "
8972 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8973 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8974 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8975 "proiswindow, provolatile, proisstrict, prosecdef, "
8976 "proleakproof, proconfig, procost, prorows, "
8977 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8978 "FROM pg_catalog.pg_proc "
8979 "WHERE oid = '%u'::pg_catalog.oid",
8980 finfo->dobj.catId.oid);
8982 else if (fout->remoteVersion >= 80400)
8985 * In 8.4 and up we rely on pg_get_function_arguments and
8986 * pg_get_function_result instead of examining proallargtypes etc.
8988 appendPQExpBuffer(query,
8989 "SELECT proretset, prosrc, probin, "
8990 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8991 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8992 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8993 "proiswindow, provolatile, proisstrict, prosecdef, "
8994 "false AS proleakproof, "
8995 " proconfig, procost, prorows, "
8996 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8997 "FROM pg_catalog.pg_proc "
8998 "WHERE oid = '%u'::pg_catalog.oid",
8999 finfo->dobj.catId.oid);
9001 else if (fout->remoteVersion >= 80300)
9003 appendPQExpBuffer(query,
9004 "SELECT proretset, prosrc, probin, "
9005 "proallargtypes, proargmodes, proargnames, "
9006 "false AS proiswindow, "
9007 "provolatile, proisstrict, prosecdef, "
9008 "false AS proleakproof, "
9009 "proconfig, procost, prorows, "
9010 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9011 "FROM pg_catalog.pg_proc "
9012 "WHERE oid = '%u'::pg_catalog.oid",
9013 finfo->dobj.catId.oid);
9015 else if (fout->remoteVersion >= 80100)
9017 appendPQExpBuffer(query,
9018 "SELECT proretset, prosrc, probin, "
9019 "proallargtypes, proargmodes, proargnames, "
9020 "false AS proiswindow, "
9021 "provolatile, proisstrict, prosecdef, "
9022 "false AS proleakproof, "
9023 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9024 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9025 "FROM pg_catalog.pg_proc "
9026 "WHERE oid = '%u'::pg_catalog.oid",
9027 finfo->dobj.catId.oid);
9029 else if (fout->remoteVersion >= 80000)
9031 appendPQExpBuffer(query,
9032 "SELECT proretset, prosrc, probin, "
9033 "null AS proallargtypes, "
9034 "null AS proargmodes, "
9036 "false AS proiswindow, "
9037 "provolatile, proisstrict, prosecdef, "
9038 "false AS proleakproof, "
9039 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9040 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9041 "FROM pg_catalog.pg_proc "
9042 "WHERE oid = '%u'::pg_catalog.oid",
9043 finfo->dobj.catId.oid);
9045 else if (fout->remoteVersion >= 70300)
9047 appendPQExpBuffer(query,
9048 "SELECT proretset, prosrc, probin, "
9049 "null AS proallargtypes, "
9050 "null AS proargmodes, "
9051 "null AS proargnames, "
9052 "false AS proiswindow, "
9053 "provolatile, proisstrict, prosecdef, "
9054 "false AS proleakproof, "
9055 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9056 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9057 "FROM pg_catalog.pg_proc "
9058 "WHERE oid = '%u'::pg_catalog.oid",
9059 finfo->dobj.catId.oid);
9061 else if (fout->remoteVersion >= 70100)
9063 appendPQExpBuffer(query,
9064 "SELECT proretset, prosrc, probin, "
9065 "null AS proallargtypes, "
9066 "null AS proargmodes, "
9067 "null AS proargnames, "
9068 "false AS proiswindow, "
9069 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9071 "false AS prosecdef, "
9072 "false AS proleakproof, "
9073 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9074 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9076 "WHERE oid = '%u'::oid",
9077 finfo->dobj.catId.oid);
9081 appendPQExpBuffer(query,
9082 "SELECT proretset, prosrc, probin, "
9083 "null AS proallargtypes, "
9084 "null AS proargmodes, "
9085 "null AS proargnames, "
9086 "false AS proiswindow, "
9087 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9088 "false AS proisstrict, "
9089 "false AS prosecdef, "
9090 "false AS proleakproof, "
9091 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9092 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9094 "WHERE oid = '%u'::oid",
9095 finfo->dobj.catId.oid);
9098 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9100 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9101 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9102 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9103 if (fout->remoteVersion >= 80400)
9105 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9106 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9107 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9108 proallargtypes = proargmodes = proargnames = NULL;
9112 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9113 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9114 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9115 funcargs = funciargs = funcresult = NULL;
9117 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9118 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9119 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9120 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9121 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9122 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9123 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9124 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9125 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9128 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9129 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9130 * versions would set it to "-". There are no known cases in which prosrc
9131 * is unused, so the tests below for "-" are probably useless.
9133 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9135 appendPQExpBuffer(asPart, "AS ");
9136 appendStringLiteralAH(asPart, probin, fout);
9137 if (strcmp(prosrc, "-") != 0)
9139 appendPQExpBuffer(asPart, ", ");
9142 * where we have bin, use dollar quoting if allowed and src
9143 * contains quote or backslash; else use regular quoting.
9145 if (disable_dollar_quoting ||
9146 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9147 appendStringLiteralAH(asPart, prosrc, fout);
9149 appendStringLiteralDQ(asPart, prosrc, NULL);
9154 if (strcmp(prosrc, "-") != 0)
9156 appendPQExpBuffer(asPart, "AS ");
9157 /* with no bin, dollar quote src unconditionally if allowed */
9158 if (disable_dollar_quoting)
9159 appendStringLiteralAH(asPart, prosrc, fout);
9161 appendStringLiteralDQ(asPart, prosrc, NULL);
9165 nallargs = finfo->nargs; /* unless we learn different from allargs */
9167 if (proallargtypes && *proallargtypes)
9171 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9172 nitems < finfo->nargs)
9174 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9183 if (proargmodes && *proargmodes)
9187 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9190 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9197 if (proargnames && *proargnames)
9201 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9204 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9211 if (proconfig && *proconfig)
9213 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9215 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9225 /* 8.4 or later; we rely on server-side code for most of the work */
9226 funcfullsig = format_function_arguments(finfo, funcargs);
9227 funcsig = format_function_arguments(finfo, funciargs);
9231 /* pre-8.4, do it ourselves */
9232 funcsig = format_function_arguments_old(fout,
9233 finfo, nallargs, allargtypes,
9234 argmodes, argnames);
9235 funcfullsig = funcsig;
9238 funcsig_tag = format_function_signature(fout, finfo, false);
9241 * DROP must be fully qualified in case same name appears in pg_catalog
9243 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9244 fmtId(finfo->dobj.namespace->dobj.name),
9247 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9249 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9252 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9254 appendPQExpBuffer(q, "RETURNS %s%s",
9255 (proretset[0] == 't') ? "SETOF " : "",
9260 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9262 if (proiswindow[0] == 't')
9263 appendPQExpBuffer(q, " WINDOW");
9265 if (provolatile[0] != PROVOLATILE_VOLATILE)
9267 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9268 appendPQExpBuffer(q, " IMMUTABLE");
9269 else if (provolatile[0] == PROVOLATILE_STABLE)
9270 appendPQExpBuffer(q, " STABLE");
9271 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9272 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9276 if (proisstrict[0] == 't')
9277 appendPQExpBuffer(q, " STRICT");
9279 if (prosecdef[0] == 't')
9280 appendPQExpBuffer(q, " SECURITY DEFINER");
9282 if (proleakproof[0] == 't')
9283 appendPQExpBuffer(q, " LEAKPROOF");
9286 * COST and ROWS are emitted only if present and not default, so as not to
9287 * break backwards-compatibility of the dump without need. Keep this code
9288 * in sync with the defaults in functioncmds.c.
9290 if (strcmp(procost, "0") != 0)
9292 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9294 /* default cost is 1 */
9295 if (strcmp(procost, "1") != 0)
9296 appendPQExpBuffer(q, " COST %s", procost);
9300 /* default cost is 100 */
9301 if (strcmp(procost, "100") != 0)
9302 appendPQExpBuffer(q, " COST %s", procost);
9305 if (proretset[0] == 't' &&
9306 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9307 appendPQExpBuffer(q, " ROWS %s", prorows);
9309 for (i = 0; i < nconfigitems; i++)
9311 /* we feel free to scribble on configitems[] here */
9312 char *configitem = configitems[i];
9315 pos = strchr(configitem, '=');
9319 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9322 * Some GUC variable names are 'LIST' type and hence must not be
9325 if (pg_strcasecmp(configitem, "DateStyle") == 0
9326 || pg_strcasecmp(configitem, "search_path") == 0)
9327 appendPQExpBuffer(q, "%s", pos);
9329 appendStringLiteralAH(q, pos, fout);
9332 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9334 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9337 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9339 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9341 finfo->dobj.namespace->dobj.name,
9343 finfo->rolname, false,
9344 "FUNCTION", SECTION_PRE_DATA,
9345 q->data, delqry->data, NULL,
9346 finfo->dobj.dependencies, finfo->dobj.nDeps,
9349 /* Dump Function Comments and Security Labels */
9350 dumpComment(fout, labelq->data,
9351 finfo->dobj.namespace->dobj.name, finfo->rolname,
9352 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9353 dumpSecLabel(fout, labelq->data,
9354 finfo->dobj.namespace->dobj.name, finfo->rolname,
9355 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9357 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9358 funcsig, NULL, funcsig_tag,
9359 finfo->dobj.namespace->dobj.name,
9360 finfo->rolname, finfo->proacl);
9364 destroyPQExpBuffer(query);
9365 destroyPQExpBuffer(q);
9366 destroyPQExpBuffer(delqry);
9367 destroyPQExpBuffer(labelq);
9368 destroyPQExpBuffer(asPart);
9383 * Dump a user-defined cast
9386 dumpCast(Archive *fout, CastInfo *cast)
9391 FuncInfo *funcInfo = NULL;
9393 /* Skip if not to be dumped */
9394 if (!cast->dobj.dump || dataOnly)
9397 /* Cannot dump if we don't have the cast function's info */
9398 if (OidIsValid(cast->castfunc))
9400 funcInfo = findFuncByOid(cast->castfunc);
9401 if (funcInfo == NULL)
9406 * As per discussion we dump casts if one or more of the underlying
9407 * objects (the conversion function and the two data types) are not
9408 * builtin AND if all of the non-builtin objects are included in the dump.
9409 * Builtin meaning, the namespace name does not start with "pg_".
9411 * However, for a cast that belongs to an extension, we must not use this
9412 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9414 if (!cast->dobj.ext_member)
9416 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9417 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9419 if (sourceInfo == NULL || targetInfo == NULL)
9423 * Skip this cast if all objects are from pg_
9425 if ((funcInfo == NULL ||
9426 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9427 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9428 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9432 * Skip cast if function isn't from pg_ and is not to be dumped.
9435 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9436 !funcInfo->dobj.dump)
9440 * Same for the source type
9442 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9443 !sourceInfo->dobj.dump)
9447 * and the target type.
9449 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9450 !targetInfo->dobj.dump)
9454 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9455 selectSourceSchema(fout, "pg_catalog");
9457 defqry = createPQExpBuffer();
9458 delqry = createPQExpBuffer();
9459 labelq = createPQExpBuffer();
9461 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9462 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9463 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9465 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9466 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9467 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9469 switch (cast->castmethod)
9471 case COERCION_METHOD_BINARY:
9472 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9474 case COERCION_METHOD_INOUT:
9475 appendPQExpBuffer(defqry, "WITH INOUT");
9477 case COERCION_METHOD_FUNCTION:
9480 char *fsig = format_function_signature(fout, funcInfo, true);
9483 * Always qualify the function name, in case it is not in
9484 * pg_catalog schema (format_function_signature won't qualify it).
9486 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9487 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9491 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9494 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9497 if (cast->castcontext == 'a')
9498 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9499 else if (cast->castcontext == 'i')
9500 appendPQExpBuffer(defqry, " AS IMPLICIT");
9501 appendPQExpBuffer(defqry, ";\n");
9503 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9504 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9505 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9508 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9510 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9512 "pg_catalog", NULL, "",
9513 false, "CAST", SECTION_PRE_DATA,
9514 defqry->data, delqry->data, NULL,
9515 cast->dobj.dependencies, cast->dobj.nDeps,
9518 /* Dump Cast Comments */
9519 dumpComment(fout, labelq->data,
9521 cast->dobj.catId, 0, cast->dobj.dumpId);
9523 destroyPQExpBuffer(defqry);
9524 destroyPQExpBuffer(delqry);
9525 destroyPQExpBuffer(labelq);
9530 * write out a single operator definition
9533 dumpOpr(Archive *fout, OprInfo *oprinfo)
9540 PQExpBuffer details;
9564 /* Skip if not to be dumped */
9565 if (!oprinfo->dobj.dump || dataOnly)
9569 * some operators are invalid because they were the result of user
9570 * defining operators before commutators exist
9572 if (!OidIsValid(oprinfo->oprcode))
9575 query = createPQExpBuffer();
9576 q = createPQExpBuffer();
9577 delq = createPQExpBuffer();
9578 labelq = createPQExpBuffer();
9579 oprid = createPQExpBuffer();
9580 details = createPQExpBuffer();
9582 /* Make sure we are in proper schema so regoperator works correctly */
9583 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9585 if (fout->remoteVersion >= 80300)
9587 appendPQExpBuffer(query, "SELECT oprkind, "
9588 "oprcode::pg_catalog.regprocedure, "
9589 "oprleft::pg_catalog.regtype, "
9590 "oprright::pg_catalog.regtype, "
9591 "oprcom::pg_catalog.regoperator, "
9592 "oprnegate::pg_catalog.regoperator, "
9593 "oprrest::pg_catalog.regprocedure, "
9594 "oprjoin::pg_catalog.regprocedure, "
9595 "oprcanmerge, oprcanhash "
9596 "FROM pg_catalog.pg_operator "
9597 "WHERE oid = '%u'::pg_catalog.oid",
9598 oprinfo->dobj.catId.oid);
9600 else if (fout->remoteVersion >= 70300)
9602 appendPQExpBuffer(query, "SELECT oprkind, "
9603 "oprcode::pg_catalog.regprocedure, "
9604 "oprleft::pg_catalog.regtype, "
9605 "oprright::pg_catalog.regtype, "
9606 "oprcom::pg_catalog.regoperator, "
9607 "oprnegate::pg_catalog.regoperator, "
9608 "oprrest::pg_catalog.regprocedure, "
9609 "oprjoin::pg_catalog.regprocedure, "
9610 "(oprlsortop != 0) AS oprcanmerge, "
9612 "FROM pg_catalog.pg_operator "
9613 "WHERE oid = '%u'::pg_catalog.oid",
9614 oprinfo->dobj.catId.oid);
9616 else if (fout->remoteVersion >= 70100)
9618 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9619 "CASE WHEN oprleft = 0 THEN '-' "
9620 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9621 "CASE WHEN oprright = 0 THEN '-' "
9622 "ELSE format_type(oprright, NULL) END AS oprright, "
9623 "oprcom, oprnegate, oprrest, oprjoin, "
9624 "(oprlsortop != 0) AS oprcanmerge, "
9627 "WHERE oid = '%u'::oid",
9628 oprinfo->dobj.catId.oid);
9632 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9633 "CASE WHEN oprleft = 0 THEN '-'::name "
9634 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9635 "CASE WHEN oprright = 0 THEN '-'::name "
9636 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9637 "oprcom, oprnegate, oprrest, oprjoin, "
9638 "(oprlsortop != 0) AS oprcanmerge, "
9641 "WHERE oid = '%u'::oid",
9642 oprinfo->dobj.catId.oid);
9645 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9647 i_oprkind = PQfnumber(res, "oprkind");
9648 i_oprcode = PQfnumber(res, "oprcode");
9649 i_oprleft = PQfnumber(res, "oprleft");
9650 i_oprright = PQfnumber(res, "oprright");
9651 i_oprcom = PQfnumber(res, "oprcom");
9652 i_oprnegate = PQfnumber(res, "oprnegate");
9653 i_oprrest = PQfnumber(res, "oprrest");
9654 i_oprjoin = PQfnumber(res, "oprjoin");
9655 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9656 i_oprcanhash = PQfnumber(res, "oprcanhash");
9658 oprkind = PQgetvalue(res, 0, i_oprkind);
9659 oprcode = PQgetvalue(res, 0, i_oprcode);
9660 oprleft = PQgetvalue(res, 0, i_oprleft);
9661 oprright = PQgetvalue(res, 0, i_oprright);
9662 oprcom = PQgetvalue(res, 0, i_oprcom);
9663 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9664 oprrest = PQgetvalue(res, 0, i_oprrest);
9665 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9666 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9667 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9669 appendPQExpBuffer(details, " PROCEDURE = %s",
9670 convertRegProcReference(fout, oprcode));
9672 appendPQExpBuffer(oprid, "%s (",
9673 oprinfo->dobj.name);
9676 * right unary means there's a left arg and left unary means there's a
9679 if (strcmp(oprkind, "r") == 0 ||
9680 strcmp(oprkind, "b") == 0)
9682 if (fout->remoteVersion >= 70100)
9685 name = fmtId(oprleft);
9686 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9687 appendPQExpBuffer(oprid, "%s", name);
9690 appendPQExpBuffer(oprid, "NONE");
9692 if (strcmp(oprkind, "l") == 0 ||
9693 strcmp(oprkind, "b") == 0)
9695 if (fout->remoteVersion >= 70100)
9698 name = fmtId(oprright);
9699 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9700 appendPQExpBuffer(oprid, ", %s)", name);
9703 appendPQExpBuffer(oprid, ", NONE)");
9705 name = convertOperatorReference(fout, oprcom);
9707 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9709 name = convertOperatorReference(fout, oprnegate);
9711 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9713 if (strcmp(oprcanmerge, "t") == 0)
9714 appendPQExpBuffer(details, ",\n MERGES");
9716 if (strcmp(oprcanhash, "t") == 0)
9717 appendPQExpBuffer(details, ",\n HASHES");
9719 name = convertRegProcReference(fout, oprrest);
9721 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9723 name = convertRegProcReference(fout, oprjoin);
9725 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9728 * DROP must be fully qualified in case same name appears in pg_catalog
9730 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9731 fmtId(oprinfo->dobj.namespace->dobj.name),
9734 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9735 oprinfo->dobj.name, details->data);
9737 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9740 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9742 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9744 oprinfo->dobj.namespace->dobj.name,
9747 false, "OPERATOR", SECTION_PRE_DATA,
9748 q->data, delq->data, NULL,
9749 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9752 /* Dump Operator Comments */
9753 dumpComment(fout, labelq->data,
9754 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9755 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9759 destroyPQExpBuffer(query);
9760 destroyPQExpBuffer(q);
9761 destroyPQExpBuffer(delq);
9762 destroyPQExpBuffer(labelq);
9763 destroyPQExpBuffer(oprid);
9764 destroyPQExpBuffer(details);
9768 * Convert a function reference obtained from pg_operator
9770 * Returns what to print, or NULL if function references is InvalidOid
9772 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9773 * argument-types part. In prior versions, the input is a REGPROC display.
9776 convertRegProcReference(Archive *fout, const char *proc)
9778 /* In all cases "-" means a null reference */
9779 if (strcmp(proc, "-") == 0)
9782 if (fout->remoteVersion >= 70300)
9788 name = pg_strdup(proc);
9789 /* find non-double-quoted left paren */
9791 for (paren = name; *paren; paren++)
9793 if (*paren == '(' && !inquote)
9804 /* REGPROC before 7.3 does not quote its result */
9809 * Convert an operator cross-reference obtained from pg_operator
9811 * Returns what to print, or NULL to print nothing
9813 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9814 * argument-types part, and add OPERATOR() decoration if the name is
9815 * schema-qualified. In older versions, the input is just a numeric OID,
9816 * which we search our operator list for.
9819 convertOperatorReference(Archive *fout, const char *opr)
9823 /* In all cases "0" means a null reference */
9824 if (strcmp(opr, "0") == 0)
9827 if (fout->remoteVersion >= 70300)
9835 name = pg_strdup(opr);
9836 /* find non-double-quoted left paren, and check for non-quoted dot */
9839 for (ptr = name; *ptr; ptr++)
9843 else if (*ptr == '.' && !inquote)
9845 else if (*ptr == '(' && !inquote)
9851 /* If not schema-qualified, don't need to add OPERATOR() */
9854 oname = pg_malloc(strlen(name) + 11);
9855 sprintf(oname, "OPERATOR(%s)", name);
9860 oprInfo = findOprByOid(atooid(opr));
9861 if (oprInfo == NULL)
9863 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9867 return oprInfo->dobj.name;
9871 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9873 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9874 * argument lists of these functions are predetermined. Note that the
9875 * caller should ensure we are in the proper schema, because the results
9876 * are search path dependent!
9879 convertTSFunction(Archive *fout, Oid funcOid)
9885 snprintf(query, sizeof(query),
9886 "SELECT '%u'::pg_catalog.regproc", funcOid);
9887 res = ExecuteSqlQueryForSingleRow(fout, query);
9889 result = pg_strdup(PQgetvalue(res, 0, 0));
9899 * write out a single operator class definition
9902 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9914 int i_opcfamilyname;
9921 int i_sortfamilynsp;
9924 int i_amproclefttype;
9925 int i_amprocrighttype;
9930 char *opcfamilyname;
9937 char *sortfamilynsp;
9940 char *amproclefttype;
9941 char *amprocrighttype;
9945 /* Skip if not to be dumped */
9946 if (!opcinfo->dobj.dump || dataOnly)
9950 * XXX currently we do not implement dumping of operator classes from
9951 * pre-7.3 databases. This could be done but it seems not worth the
9954 if (fout->remoteVersion < 70300)
9957 query = createPQExpBuffer();
9958 q = createPQExpBuffer();
9959 delq = createPQExpBuffer();
9960 labelq = createPQExpBuffer();
9962 /* Make sure we are in proper schema so regoperator works correctly */
9963 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9965 /* Get additional fields from the pg_opclass row */
9966 if (fout->remoteVersion >= 80300)
9968 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9969 "opckeytype::pg_catalog.regtype, "
9970 "opcdefault, opcfamily, "
9971 "opfname AS opcfamilyname, "
9972 "nspname AS opcfamilynsp, "
9973 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9974 "FROM pg_catalog.pg_opclass c "
9975 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9976 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9977 "WHERE c.oid = '%u'::pg_catalog.oid",
9978 opcinfo->dobj.catId.oid);
9982 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9983 "opckeytype::pg_catalog.regtype, "
9984 "opcdefault, NULL AS opcfamily, "
9985 "NULL AS opcfamilyname, "
9986 "NULL AS opcfamilynsp, "
9987 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9988 "FROM pg_catalog.pg_opclass "
9989 "WHERE oid = '%u'::pg_catalog.oid",
9990 opcinfo->dobj.catId.oid);
9993 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9995 i_opcintype = PQfnumber(res, "opcintype");
9996 i_opckeytype = PQfnumber(res, "opckeytype");
9997 i_opcdefault = PQfnumber(res, "opcdefault");
9998 i_opcfamily = PQfnumber(res, "opcfamily");
9999 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10000 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10001 i_amname = PQfnumber(res, "amname");
10003 opcintype = PQgetvalue(res, 0, i_opcintype);
10004 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10005 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10006 /* opcfamily will still be needed after we PQclear res */
10007 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10008 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10009 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10010 /* amname will still be needed after we PQclear res */
10011 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10014 * DROP must be fully qualified in case same name appears in pg_catalog
10016 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10017 fmtId(opcinfo->dobj.namespace->dobj.name));
10018 appendPQExpBuffer(delq, ".%s",
10019 fmtId(opcinfo->dobj.name));
10020 appendPQExpBuffer(delq, " USING %s;\n",
10023 /* Build the fixed portion of the CREATE command */
10024 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10025 fmtId(opcinfo->dobj.name));
10026 if (strcmp(opcdefault, "t") == 0)
10027 appendPQExpBuffer(q, "DEFAULT ");
10028 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10031 if (strlen(opcfamilyname) > 0 &&
10032 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10033 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10035 appendPQExpBuffer(q, " FAMILY ");
10036 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10037 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10038 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10040 appendPQExpBuffer(q, " AS\n ");
10044 if (strcmp(opckeytype, "-") != 0)
10046 appendPQExpBuffer(q, "STORAGE %s",
10054 * Now fetch and print the OPERATOR entries (pg_amop rows).
10056 * Print only those opfamily members that are tied to the opclass by
10057 * pg_depend entries.
10059 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10060 * older server's opclass in which it is used. This is to avoid
10061 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10062 * older server and then reload into that old version. This can go away
10063 * once 8.3 is so old as to not be of interest to anyone.
10065 resetPQExpBuffer(query);
10067 if (fout->remoteVersion >= 90100)
10069 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10070 "amopopr::pg_catalog.regoperator, "
10071 "opfname AS sortfamily, "
10072 "nspname AS sortfamilynsp "
10073 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10074 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10075 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10076 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10077 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10078 "AND refobjid = '%u'::pg_catalog.oid "
10079 "AND amopfamily = '%s'::pg_catalog.oid "
10080 "ORDER BY amopstrategy",
10081 opcinfo->dobj.catId.oid,
10084 else if (fout->remoteVersion >= 80400)
10086 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10087 "amopopr::pg_catalog.regoperator, "
10088 "NULL AS sortfamily, "
10089 "NULL AS sortfamilynsp "
10090 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10091 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10092 "AND refobjid = '%u'::pg_catalog.oid "
10093 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10094 "AND objid = ao.oid "
10095 "ORDER BY amopstrategy",
10096 opcinfo->dobj.catId.oid);
10098 else if (fout->remoteVersion >= 80300)
10100 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10101 "amopopr::pg_catalog.regoperator, "
10102 "NULL AS sortfamily, "
10103 "NULL AS sortfamilynsp "
10104 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10105 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10106 "AND refobjid = '%u'::pg_catalog.oid "
10107 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10108 "AND objid = ao.oid "
10109 "ORDER BY amopstrategy",
10110 opcinfo->dobj.catId.oid);
10115 * Here, we print all entries since there are no opfamilies and hence
10116 * no loose operators to worry about.
10118 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10119 "amopopr::pg_catalog.regoperator, "
10120 "NULL AS sortfamily, "
10121 "NULL AS sortfamilynsp "
10122 "FROM pg_catalog.pg_amop "
10123 "WHERE amopclaid = '%u'::pg_catalog.oid "
10124 "ORDER BY amopstrategy",
10125 opcinfo->dobj.catId.oid);
10128 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10130 ntups = PQntuples(res);
10132 i_amopstrategy = PQfnumber(res, "amopstrategy");
10133 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10134 i_amopopr = PQfnumber(res, "amopopr");
10135 i_sortfamily = PQfnumber(res, "sortfamily");
10136 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10138 for (i = 0; i < ntups; i++)
10140 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10141 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10142 amopopr = PQgetvalue(res, i, i_amopopr);
10143 sortfamily = PQgetvalue(res, i, i_sortfamily);
10144 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10147 appendPQExpBuffer(q, " ,\n ");
10149 appendPQExpBuffer(q, "OPERATOR %s %s",
10150 amopstrategy, amopopr);
10152 if (strlen(sortfamily) > 0)
10154 appendPQExpBuffer(q, " FOR ORDER BY ");
10155 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10156 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10157 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10160 if (strcmp(amopreqcheck, "t") == 0)
10161 appendPQExpBuffer(q, " RECHECK");
10169 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10171 * Print only those opfamily members that are tied to the opclass by
10172 * pg_depend entries.
10174 * We print the amproclefttype/amprocrighttype even though in most cases
10175 * the backend could deduce the right values, because of the corner case
10176 * of a btree sort support function for a cross-type comparison. That's
10177 * only allowed in 9.2 and later, but for simplicity print them in all
10178 * versions that have the columns.
10180 resetPQExpBuffer(query);
10182 if (fout->remoteVersion >= 80300)
10184 appendPQExpBuffer(query, "SELECT amprocnum, "
10185 "amproc::pg_catalog.regprocedure, "
10186 "amproclefttype::pg_catalog.regtype, "
10187 "amprocrighttype::pg_catalog.regtype "
10188 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10189 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10190 "AND refobjid = '%u'::pg_catalog.oid "
10191 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10192 "AND objid = ap.oid "
10193 "ORDER BY amprocnum",
10194 opcinfo->dobj.catId.oid);
10198 appendPQExpBuffer(query, "SELECT amprocnum, "
10199 "amproc::pg_catalog.regprocedure, "
10200 "'' AS amproclefttype, "
10201 "'' AS amprocrighttype "
10202 "FROM pg_catalog.pg_amproc "
10203 "WHERE amopclaid = '%u'::pg_catalog.oid "
10204 "ORDER BY amprocnum",
10205 opcinfo->dobj.catId.oid);
10208 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10210 ntups = PQntuples(res);
10212 i_amprocnum = PQfnumber(res, "amprocnum");
10213 i_amproc = PQfnumber(res, "amproc");
10214 i_amproclefttype = PQfnumber(res, "amproclefttype");
10215 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10217 for (i = 0; i < ntups; i++)
10219 amprocnum = PQgetvalue(res, i, i_amprocnum);
10220 amproc = PQgetvalue(res, i, i_amproc);
10221 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10222 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10225 appendPQExpBuffer(q, " ,\n ");
10227 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10229 if (*amproclefttype && *amprocrighttype)
10230 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10232 appendPQExpBuffer(q, " %s", amproc);
10239 appendPQExpBuffer(q, ";\n");
10241 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10242 fmtId(opcinfo->dobj.name));
10243 appendPQExpBuffer(labelq, " USING %s",
10246 if (binary_upgrade)
10247 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10249 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10250 opcinfo->dobj.name,
10251 opcinfo->dobj.namespace->dobj.name,
10254 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10255 q->data, delq->data, NULL,
10256 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10259 /* Dump Operator Class Comments */
10260 dumpComment(fout, labelq->data,
10261 NULL, opcinfo->rolname,
10262 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10265 destroyPQExpBuffer(query);
10266 destroyPQExpBuffer(q);
10267 destroyPQExpBuffer(delq);
10268 destroyPQExpBuffer(labelq);
10273 * write out a single operator family definition
10275 * Note: this also dumps any "loose" operator members that aren't bound to a
10276 * specific opclass within the opfamily.
10279 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10284 PQExpBuffer labelq;
10287 PGresult *res_procs;
10290 int i_amopstrategy;
10291 int i_amopreqcheck;
10294 int i_sortfamilynsp;
10297 int i_amproclefttype;
10298 int i_amprocrighttype;
10300 char *amopstrategy;
10301 char *amopreqcheck;
10304 char *sortfamilynsp;
10307 char *amproclefttype;
10308 char *amprocrighttype;
10312 /* Skip if not to be dumped */
10313 if (!opfinfo->dobj.dump || dataOnly)
10317 * We want to dump the opfamily only if (1) it contains "loose" operators
10318 * or functions, or (2) it contains an opclass with a different name or
10319 * owner. Otherwise it's sufficient to let it be created during creation
10320 * of the contained opclass, and not dumping it improves portability of
10321 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10325 query = createPQExpBuffer();
10326 q = createPQExpBuffer();
10327 delq = createPQExpBuffer();
10328 labelq = createPQExpBuffer();
10330 /* Make sure we are in proper schema so regoperator works correctly */
10331 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10334 * Fetch only those opfamily members that are tied directly to the
10335 * opfamily by pg_depend entries.
10337 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10338 * older server's opclass in which it is used. This is to avoid
10339 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10340 * older server and then reload into that old version. This can go away
10341 * once 8.3 is so old as to not be of interest to anyone.
10343 if (fout->remoteVersion >= 90100)
10345 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10346 "amopopr::pg_catalog.regoperator, "
10347 "opfname AS sortfamily, "
10348 "nspname AS sortfamilynsp "
10349 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10350 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10351 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10352 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10353 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10354 "AND refobjid = '%u'::pg_catalog.oid "
10355 "AND amopfamily = '%u'::pg_catalog.oid "
10356 "ORDER BY amopstrategy",
10357 opfinfo->dobj.catId.oid,
10358 opfinfo->dobj.catId.oid);
10360 else if (fout->remoteVersion >= 80400)
10362 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10363 "amopopr::pg_catalog.regoperator, "
10364 "NULL AS sortfamily, "
10365 "NULL AS sortfamilynsp "
10366 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10367 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10368 "AND refobjid = '%u'::pg_catalog.oid "
10369 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10370 "AND objid = ao.oid "
10371 "ORDER BY amopstrategy",
10372 opfinfo->dobj.catId.oid);
10376 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10377 "amopopr::pg_catalog.regoperator, "
10378 "NULL AS sortfamily, "
10379 "NULL AS sortfamilynsp "
10380 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10381 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10382 "AND refobjid = '%u'::pg_catalog.oid "
10383 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10384 "AND objid = ao.oid "
10385 "ORDER BY amopstrategy",
10386 opfinfo->dobj.catId.oid);
10389 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10391 resetPQExpBuffer(query);
10393 appendPQExpBuffer(query, "SELECT amprocnum, "
10394 "amproc::pg_catalog.regprocedure, "
10395 "amproclefttype::pg_catalog.regtype, "
10396 "amprocrighttype::pg_catalog.regtype "
10397 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10398 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10399 "AND refobjid = '%u'::pg_catalog.oid "
10400 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10401 "AND objid = ap.oid "
10402 "ORDER BY amprocnum",
10403 opfinfo->dobj.catId.oid);
10405 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10407 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10409 /* No loose members, so check contained opclasses */
10410 resetPQExpBuffer(query);
10412 appendPQExpBuffer(query, "SELECT 1 "
10413 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10414 "WHERE f.oid = '%u'::pg_catalog.oid "
10415 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10416 "AND refobjid = f.oid "
10417 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10418 "AND objid = c.oid "
10419 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10421 opfinfo->dobj.catId.oid);
10423 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10425 if (PQntuples(res) == 0)
10427 /* no need to dump it, so bail out */
10430 PQclear(res_procs);
10431 destroyPQExpBuffer(query);
10432 destroyPQExpBuffer(q);
10433 destroyPQExpBuffer(delq);
10434 destroyPQExpBuffer(labelq);
10441 /* Get additional fields from the pg_opfamily row */
10442 resetPQExpBuffer(query);
10444 appendPQExpBuffer(query, "SELECT "
10445 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10446 "FROM pg_catalog.pg_opfamily "
10447 "WHERE oid = '%u'::pg_catalog.oid",
10448 opfinfo->dobj.catId.oid);
10450 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10452 i_amname = PQfnumber(res, "amname");
10454 /* amname will still be needed after we PQclear res */
10455 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10458 * DROP must be fully qualified in case same name appears in pg_catalog
10460 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10461 fmtId(opfinfo->dobj.namespace->dobj.name));
10462 appendPQExpBuffer(delq, ".%s",
10463 fmtId(opfinfo->dobj.name));
10464 appendPQExpBuffer(delq, " USING %s;\n",
10467 /* Build the fixed portion of the CREATE command */
10468 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10469 fmtId(opfinfo->dobj.name));
10470 appendPQExpBuffer(q, " USING %s;\n",
10475 /* Do we need an ALTER to add loose members? */
10476 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10478 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10479 fmtId(opfinfo->dobj.name));
10480 appendPQExpBuffer(q, " USING %s ADD\n ",
10486 * Now fetch and print the OPERATOR entries (pg_amop rows).
10488 ntups = PQntuples(res_ops);
10490 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10491 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10492 i_amopopr = PQfnumber(res_ops, "amopopr");
10493 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10494 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10496 for (i = 0; i < ntups; i++)
10498 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10499 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10500 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10501 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10502 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10505 appendPQExpBuffer(q, " ,\n ");
10507 appendPQExpBuffer(q, "OPERATOR %s %s",
10508 amopstrategy, amopopr);
10510 if (strlen(sortfamily) > 0)
10512 appendPQExpBuffer(q, " FOR ORDER BY ");
10513 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10514 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10515 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10518 if (strcmp(amopreqcheck, "t") == 0)
10519 appendPQExpBuffer(q, " RECHECK");
10525 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10527 ntups = PQntuples(res_procs);
10529 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10530 i_amproc = PQfnumber(res_procs, "amproc");
10531 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10532 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10534 for (i = 0; i < ntups; i++)
10536 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10537 amproc = PQgetvalue(res_procs, i, i_amproc);
10538 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10539 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10542 appendPQExpBuffer(q, " ,\n ");
10544 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10545 amprocnum, amproclefttype, amprocrighttype,
10551 appendPQExpBuffer(q, ";\n");
10554 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10555 fmtId(opfinfo->dobj.name));
10556 appendPQExpBuffer(labelq, " USING %s",
10559 if (binary_upgrade)
10560 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10562 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10563 opfinfo->dobj.name,
10564 opfinfo->dobj.namespace->dobj.name,
10567 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10568 q->data, delq->data, NULL,
10569 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10572 /* Dump Operator Family Comments */
10573 dumpComment(fout, labelq->data,
10574 NULL, opfinfo->rolname,
10575 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10579 PQclear(res_procs);
10580 destroyPQExpBuffer(query);
10581 destroyPQExpBuffer(q);
10582 destroyPQExpBuffer(delq);
10583 destroyPQExpBuffer(labelq);
10588 * write out a single collation definition
10591 dumpCollation(Archive *fout, CollInfo *collinfo)
10596 PQExpBuffer labelq;
10600 const char *collcollate;
10601 const char *collctype;
10603 /* Skip if not to be dumped */
10604 if (!collinfo->dobj.dump || dataOnly)
10607 query = createPQExpBuffer();
10608 q = createPQExpBuffer();
10609 delq = createPQExpBuffer();
10610 labelq = createPQExpBuffer();
10612 /* Make sure we are in proper schema */
10613 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10615 /* Get conversion-specific details */
10616 appendPQExpBuffer(query, "SELECT "
10619 "FROM pg_catalog.pg_collation c "
10620 "WHERE c.oid = '%u'::pg_catalog.oid",
10621 collinfo->dobj.catId.oid);
10623 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10625 i_collcollate = PQfnumber(res, "collcollate");
10626 i_collctype = PQfnumber(res, "collctype");
10628 collcollate = PQgetvalue(res, 0, i_collcollate);
10629 collctype = PQgetvalue(res, 0, i_collctype);
10632 * DROP must be fully qualified in case same name appears in pg_catalog
10634 appendPQExpBuffer(delq, "DROP COLLATION %s",
10635 fmtId(collinfo->dobj.namespace->dobj.name));
10636 appendPQExpBuffer(delq, ".%s;\n",
10637 fmtId(collinfo->dobj.name));
10639 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10640 fmtId(collinfo->dobj.name));
10641 appendStringLiteralAH(q, collcollate, fout);
10642 appendPQExpBuffer(q, ", lc_ctype = ");
10643 appendStringLiteralAH(q, collctype, fout);
10644 appendPQExpBuffer(q, ");\n");
10646 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10648 if (binary_upgrade)
10649 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10651 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10652 collinfo->dobj.name,
10653 collinfo->dobj.namespace->dobj.name,
10656 false, "COLLATION", SECTION_PRE_DATA,
10657 q->data, delq->data, NULL,
10658 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10661 /* Dump Collation Comments */
10662 dumpComment(fout, labelq->data,
10663 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10664 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10668 destroyPQExpBuffer(query);
10669 destroyPQExpBuffer(q);
10670 destroyPQExpBuffer(delq);
10671 destroyPQExpBuffer(labelq);
10676 * write out a single conversion definition
10679 dumpConversion(Archive *fout, ConvInfo *convinfo)
10684 PQExpBuffer labelq;
10686 int i_conforencoding;
10687 int i_contoencoding;
10690 const char *conforencoding;
10691 const char *contoencoding;
10692 const char *conproc;
10695 /* Skip if not to be dumped */
10696 if (!convinfo->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(fout, convinfo->dobj.namespace->dobj.name);
10707 /* Get conversion-specific details */
10708 appendPQExpBuffer(query, "SELECT "
10709 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10710 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10711 "conproc, condefault "
10712 "FROM pg_catalog.pg_conversion c "
10713 "WHERE c.oid = '%u'::pg_catalog.oid",
10714 convinfo->dobj.catId.oid);
10716 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10718 i_conforencoding = PQfnumber(res, "conforencoding");
10719 i_contoencoding = PQfnumber(res, "contoencoding");
10720 i_conproc = PQfnumber(res, "conproc");
10721 i_condefault = PQfnumber(res, "condefault");
10723 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10724 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10725 conproc = PQgetvalue(res, 0, i_conproc);
10726 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10729 * DROP must be fully qualified in case same name appears in pg_catalog
10731 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10732 fmtId(convinfo->dobj.namespace->dobj.name));
10733 appendPQExpBuffer(delq, ".%s;\n",
10734 fmtId(convinfo->dobj.name));
10736 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10737 (condefault) ? "DEFAULT " : "",
10738 fmtId(convinfo->dobj.name));
10739 appendStringLiteralAH(q, conforencoding, fout);
10740 appendPQExpBuffer(q, " TO ");
10741 appendStringLiteralAH(q, contoencoding, fout);
10742 /* regproc is automatically quoted in 7.3 and above */
10743 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10745 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10747 if (binary_upgrade)
10748 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10750 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10751 convinfo->dobj.name,
10752 convinfo->dobj.namespace->dobj.name,
10755 false, "CONVERSION", SECTION_PRE_DATA,
10756 q->data, delq->data, NULL,
10757 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10760 /* Dump Conversion Comments */
10761 dumpComment(fout, labelq->data,
10762 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10763 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10767 destroyPQExpBuffer(query);
10768 destroyPQExpBuffer(q);
10769 destroyPQExpBuffer(delq);
10770 destroyPQExpBuffer(labelq);
10774 * format_aggregate_signature: generate aggregate name and argument list
10776 * The argument type names are qualified if needed. The aggregate name
10777 * is never qualified.
10780 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10782 PQExpBufferData buf;
10785 initPQExpBuffer(&buf);
10787 appendPQExpBuffer(&buf, "%s",
10788 fmtId(agginfo->aggfn.dobj.name));
10790 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10792 if (agginfo->aggfn.nargs == 0)
10793 appendPQExpBuffer(&buf, "(*)");
10796 appendPQExpBuffer(&buf, "(");
10797 for (j = 0; j < agginfo->aggfn.nargs; j++)
10801 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10804 appendPQExpBuffer(&buf, "%s%s",
10805 (j > 0) ? ", " : "",
10809 appendPQExpBuffer(&buf, ")");
10816 * write out a single aggregate definition
10819 dumpAgg(Archive *fout, AggInfo *agginfo)
10824 PQExpBuffer labelq;
10825 PQExpBuffer details;
10832 int i_aggtranstype;
10835 const char *aggtransfn;
10836 const char *aggfinalfn;
10837 const char *aggsortop;
10838 const char *aggtranstype;
10839 const char *agginitval;
10842 /* Skip if not to be dumped */
10843 if (!agginfo->aggfn.dobj.dump || dataOnly)
10846 query = createPQExpBuffer();
10847 q = createPQExpBuffer();
10848 delq = createPQExpBuffer();
10849 labelq = createPQExpBuffer();
10850 details = createPQExpBuffer();
10852 /* Make sure we are in proper schema */
10853 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10855 /* Get aggregate-specific details */
10856 if (fout->remoteVersion >= 80100)
10858 appendPQExpBuffer(query, "SELECT aggtransfn, "
10859 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10860 "aggsortop::pg_catalog.regoperator, "
10862 "'t'::boolean AS convertok "
10863 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10864 "WHERE a.aggfnoid = p.oid "
10865 "AND p.oid = '%u'::pg_catalog.oid",
10866 agginfo->aggfn.dobj.catId.oid);
10868 else if (fout->remoteVersion >= 70300)
10870 appendPQExpBuffer(query, "SELECT aggtransfn, "
10871 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10874 "'t'::boolean AS convertok "
10875 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10876 "WHERE a.aggfnoid = p.oid "
10877 "AND p.oid = '%u'::pg_catalog.oid",
10878 agginfo->aggfn.dobj.catId.oid);
10880 else if (fout->remoteVersion >= 70100)
10882 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10883 "format_type(aggtranstype, NULL) AS aggtranstype, "
10886 "'t'::boolean AS convertok "
10887 "FROM pg_aggregate "
10888 "WHERE oid = '%u'::oid",
10889 agginfo->aggfn.dobj.catId.oid);
10893 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10895 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10897 "agginitval1 AS agginitval, "
10898 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10899 "FROM pg_aggregate "
10900 "WHERE oid = '%u'::oid",
10901 agginfo->aggfn.dobj.catId.oid);
10904 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10906 i_aggtransfn = PQfnumber(res, "aggtransfn");
10907 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10908 i_aggsortop = PQfnumber(res, "aggsortop");
10909 i_aggtranstype = PQfnumber(res, "aggtranstype");
10910 i_agginitval = PQfnumber(res, "agginitval");
10911 i_convertok = PQfnumber(res, "convertok");
10913 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10914 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10915 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10916 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10917 agginitval = PQgetvalue(res, 0, i_agginitval);
10918 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10920 aggsig = format_aggregate_signature(agginfo, fout, true);
10921 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10925 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10930 if (fout->remoteVersion >= 70300)
10932 /* If using 7.3's regproc or regtype, data is already quoted */
10933 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10937 else if (fout->remoteVersion >= 70100)
10939 /* format_type quotes, regproc does not */
10940 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10946 /* need quotes all around */
10947 appendPQExpBuffer(details, " SFUNC = %s,\n",
10948 fmtId(aggtransfn));
10949 appendPQExpBuffer(details, " STYPE = %s",
10950 fmtId(aggtranstype));
10953 if (!PQgetisnull(res, 0, i_agginitval))
10955 appendPQExpBuffer(details, ",\n INITCOND = ");
10956 appendStringLiteralAH(details, agginitval, fout);
10959 if (strcmp(aggfinalfn, "-") != 0)
10961 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
10965 aggsortop = convertOperatorReference(fout, aggsortop);
10968 appendPQExpBuffer(details, ",\n SORTOP = %s",
10973 * DROP must be fully qualified in case same name appears in pg_catalog
10975 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10976 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10979 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10980 aggsig, details->data);
10982 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10984 if (binary_upgrade)
10985 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10987 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10989 agginfo->aggfn.dobj.namespace->dobj.name,
10991 agginfo->aggfn.rolname,
10992 false, "AGGREGATE", SECTION_PRE_DATA,
10993 q->data, delq->data, NULL,
10994 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10997 /* Dump Aggregate Comments */
10998 dumpComment(fout, labelq->data,
10999 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11000 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11001 dumpSecLabel(fout, labelq->data,
11002 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11003 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11006 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11007 * command look like a function's GRANT; in particular this affects the
11008 * syntax for zero-argument aggregates.
11013 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11014 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11016 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11018 aggsig, NULL, aggsig_tag,
11019 agginfo->aggfn.dobj.namespace->dobj.name,
11020 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11027 destroyPQExpBuffer(query);
11028 destroyPQExpBuffer(q);
11029 destroyPQExpBuffer(delq);
11030 destroyPQExpBuffer(labelq);
11031 destroyPQExpBuffer(details);
11036 * write out a single text search parser
11039 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11043 PQExpBuffer labelq;
11045 /* Skip if not to be dumped */
11046 if (!prsinfo->dobj.dump || dataOnly)
11049 q = createPQExpBuffer();
11050 delq = createPQExpBuffer();
11051 labelq = createPQExpBuffer();
11053 /* Make sure we are in proper schema */
11054 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11056 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11057 fmtId(prsinfo->dobj.name));
11059 appendPQExpBuffer(q, " START = %s,\n",
11060 convertTSFunction(fout, prsinfo->prsstart));
11061 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11062 convertTSFunction(fout, prsinfo->prstoken));
11063 appendPQExpBuffer(q, " END = %s,\n",
11064 convertTSFunction(fout, prsinfo->prsend));
11065 if (prsinfo->prsheadline != InvalidOid)
11066 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11067 convertTSFunction(fout, prsinfo->prsheadline));
11068 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11069 convertTSFunction(fout, prsinfo->prslextype));
11072 * DROP must be fully qualified in case same name appears in pg_catalog
11074 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11075 fmtId(prsinfo->dobj.namespace->dobj.name));
11076 appendPQExpBuffer(delq, ".%s;\n",
11077 fmtId(prsinfo->dobj.name));
11079 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11080 fmtId(prsinfo->dobj.name));
11082 if (binary_upgrade)
11083 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11085 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11086 prsinfo->dobj.name,
11087 prsinfo->dobj.namespace->dobj.name,
11090 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11091 q->data, delq->data, NULL,
11092 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11095 /* Dump Parser Comments */
11096 dumpComment(fout, labelq->data,
11098 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11100 destroyPQExpBuffer(q);
11101 destroyPQExpBuffer(delq);
11102 destroyPQExpBuffer(labelq);
11107 * write out a single text search dictionary
11110 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11114 PQExpBuffer labelq;
11120 /* Skip if not to be dumped */
11121 if (!dictinfo->dobj.dump || dataOnly)
11124 q = createPQExpBuffer();
11125 delq = createPQExpBuffer();
11126 labelq = createPQExpBuffer();
11127 query = createPQExpBuffer();
11129 /* Fetch name and namespace of the dictionary's template */
11130 selectSourceSchema(fout, "pg_catalog");
11131 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11132 "FROM pg_ts_template p, pg_namespace n "
11133 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11134 dictinfo->dicttemplate);
11135 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11136 nspname = PQgetvalue(res, 0, 0);
11137 tmplname = PQgetvalue(res, 0, 1);
11139 /* Make sure we are in proper schema */
11140 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11142 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11143 fmtId(dictinfo->dobj.name));
11145 appendPQExpBuffer(q, " TEMPLATE = ");
11146 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11147 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11148 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11152 /* the dictinitoption can be dumped straight into the command */
11153 if (dictinfo->dictinitoption)
11154 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11156 appendPQExpBuffer(q, " );\n");
11159 * DROP must be fully qualified in case same name appears in pg_catalog
11161 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11162 fmtId(dictinfo->dobj.namespace->dobj.name));
11163 appendPQExpBuffer(delq, ".%s;\n",
11164 fmtId(dictinfo->dobj.name));
11166 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11167 fmtId(dictinfo->dobj.name));
11169 if (binary_upgrade)
11170 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11172 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11173 dictinfo->dobj.name,
11174 dictinfo->dobj.namespace->dobj.name,
11177 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11178 q->data, delq->data, NULL,
11179 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11182 /* Dump Dictionary Comments */
11183 dumpComment(fout, labelq->data,
11184 NULL, dictinfo->rolname,
11185 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11187 destroyPQExpBuffer(q);
11188 destroyPQExpBuffer(delq);
11189 destroyPQExpBuffer(labelq);
11190 destroyPQExpBuffer(query);
11195 * write out a single text search template
11198 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11202 PQExpBuffer labelq;
11204 /* Skip if not to be dumped */
11205 if (!tmplinfo->dobj.dump || dataOnly)
11208 q = createPQExpBuffer();
11209 delq = createPQExpBuffer();
11210 labelq = createPQExpBuffer();
11212 /* Make sure we are in proper schema */
11213 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11215 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11216 fmtId(tmplinfo->dobj.name));
11218 if (tmplinfo->tmplinit != InvalidOid)
11219 appendPQExpBuffer(q, " INIT = %s,\n",
11220 convertTSFunction(fout, tmplinfo->tmplinit));
11221 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11222 convertTSFunction(fout, tmplinfo->tmpllexize));
11225 * DROP must be fully qualified in case same name appears in pg_catalog
11227 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11228 fmtId(tmplinfo->dobj.namespace->dobj.name));
11229 appendPQExpBuffer(delq, ".%s;\n",
11230 fmtId(tmplinfo->dobj.name));
11232 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11233 fmtId(tmplinfo->dobj.name));
11235 if (binary_upgrade)
11236 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11238 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11239 tmplinfo->dobj.name,
11240 tmplinfo->dobj.namespace->dobj.name,
11243 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11244 q->data, delq->data, NULL,
11245 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11248 /* Dump Template Comments */
11249 dumpComment(fout, labelq->data,
11251 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11253 destroyPQExpBuffer(q);
11254 destroyPQExpBuffer(delq);
11255 destroyPQExpBuffer(labelq);
11260 * write out a single text search configuration
11263 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11267 PQExpBuffer labelq;
11277 /* Skip if not to be dumped */
11278 if (!cfginfo->dobj.dump || dataOnly)
11281 q = createPQExpBuffer();
11282 delq = createPQExpBuffer();
11283 labelq = createPQExpBuffer();
11284 query = createPQExpBuffer();
11286 /* Fetch name and namespace of the config's parser */
11287 selectSourceSchema(fout, "pg_catalog");
11288 appendPQExpBuffer(query, "SELECT nspname, prsname "
11289 "FROM pg_ts_parser p, pg_namespace n "
11290 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11291 cfginfo->cfgparser);
11292 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11293 nspname = PQgetvalue(res, 0, 0);
11294 prsname = PQgetvalue(res, 0, 1);
11296 /* Make sure we are in proper schema */
11297 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11299 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11300 fmtId(cfginfo->dobj.name));
11302 appendPQExpBuffer(q, " PARSER = ");
11303 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11304 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11305 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11309 resetPQExpBuffer(query);
11310 appendPQExpBuffer(query,
11312 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11313 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11314 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11315 "FROM pg_catalog.pg_ts_config_map AS m \n"
11316 "WHERE m.mapcfg = '%u' \n"
11317 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11318 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11320 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11321 ntups = PQntuples(res);
11323 i_tokenname = PQfnumber(res, "tokenname");
11324 i_dictname = PQfnumber(res, "dictname");
11326 for (i = 0; i < ntups; i++)
11328 char *tokenname = PQgetvalue(res, i, i_tokenname);
11329 char *dictname = PQgetvalue(res, i, i_dictname);
11332 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11334 /* starting a new token type, so start a new command */
11336 appendPQExpBuffer(q, ";\n");
11337 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11338 fmtId(cfginfo->dobj.name));
11339 /* tokenname needs quoting, dictname does NOT */
11340 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11341 fmtId(tokenname), dictname);
11344 appendPQExpBuffer(q, ", %s", dictname);
11348 appendPQExpBuffer(q, ";\n");
11353 * DROP must be fully qualified in case same name appears in pg_catalog
11355 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11356 fmtId(cfginfo->dobj.namespace->dobj.name));
11357 appendPQExpBuffer(delq, ".%s;\n",
11358 fmtId(cfginfo->dobj.name));
11360 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11361 fmtId(cfginfo->dobj.name));
11363 if (binary_upgrade)
11364 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11366 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11367 cfginfo->dobj.name,
11368 cfginfo->dobj.namespace->dobj.name,
11371 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11372 q->data, delq->data, NULL,
11373 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11376 /* Dump Configuration Comments */
11377 dumpComment(fout, labelq->data,
11378 NULL, cfginfo->rolname,
11379 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11381 destroyPQExpBuffer(q);
11382 destroyPQExpBuffer(delq);
11383 destroyPQExpBuffer(labelq);
11384 destroyPQExpBuffer(query);
11388 * dumpForeignDataWrapper
11389 * write out a single foreign-data wrapper definition
11392 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11396 PQExpBuffer labelq;
11399 /* Skip if not to be dumped */
11400 if (!fdwinfo->dobj.dump || dataOnly)
11404 * FDWs that belong to an extension are dumped based on their "dump"
11405 * field. Otherwise omit them if we are only dumping some specific object.
11407 if (!fdwinfo->dobj.ext_member)
11408 if (!include_everything)
11411 q = createPQExpBuffer();
11412 delq = createPQExpBuffer();
11413 labelq = createPQExpBuffer();
11415 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11417 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11420 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11421 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11423 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11424 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11426 if (strlen(fdwinfo->fdwoptions) > 0)
11427 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11429 appendPQExpBuffer(q, ";\n");
11431 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11434 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11437 if (binary_upgrade)
11438 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11440 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11441 fdwinfo->dobj.name,
11445 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11446 q->data, delq->data, NULL,
11447 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11450 /* Handle the ACL */
11451 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11452 "FOREIGN DATA WRAPPER",
11453 qfdwname, NULL, fdwinfo->dobj.name,
11454 NULL, fdwinfo->rolname,
11457 /* Dump Foreign Data Wrapper Comments */
11458 dumpComment(fout, labelq->data,
11459 NULL, fdwinfo->rolname,
11460 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11464 destroyPQExpBuffer(q);
11465 destroyPQExpBuffer(delq);
11466 destroyPQExpBuffer(labelq);
11470 * dumpForeignServer
11471 * write out a foreign server definition
11474 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11478 PQExpBuffer labelq;
11484 /* Skip if not to be dumped */
11485 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11488 q = createPQExpBuffer();
11489 delq = createPQExpBuffer();
11490 labelq = createPQExpBuffer();
11491 query = createPQExpBuffer();
11493 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11495 /* look up the foreign-data wrapper */
11496 selectSourceSchema(fout, "pg_catalog");
11497 appendPQExpBuffer(query, "SELECT fdwname "
11498 "FROM pg_foreign_data_wrapper w "
11499 "WHERE w.oid = '%u'",
11501 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11502 fdwname = PQgetvalue(res, 0, 0);
11504 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11505 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11507 appendPQExpBuffer(q, " TYPE ");
11508 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11510 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11512 appendPQExpBuffer(q, " VERSION ");
11513 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11516 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11517 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11519 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11520 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11522 appendPQExpBuffer(q, ";\n");
11524 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11527 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11529 if (binary_upgrade)
11530 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11532 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11533 srvinfo->dobj.name,
11537 false, "SERVER", SECTION_PRE_DATA,
11538 q->data, delq->data, NULL,
11539 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11542 /* Handle the ACL */
11543 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11545 qsrvname, NULL, srvinfo->dobj.name,
11546 NULL, srvinfo->rolname,
11549 /* Dump user mappings */
11550 dumpUserMappings(fout,
11551 srvinfo->dobj.name, NULL,
11553 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11555 /* Dump Foreign Server Comments */
11556 dumpComment(fout, labelq->data,
11557 NULL, srvinfo->rolname,
11558 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11562 destroyPQExpBuffer(q);
11563 destroyPQExpBuffer(delq);
11564 destroyPQExpBuffer(labelq);
11570 * This routine is used to dump any user mappings associated with the
11571 * server handed to this routine. Should be called after ArchiveEntry()
11575 dumpUserMappings(Archive *fout,
11576 const char *servername, const char *namespace,
11578 CatalogId catalogId, DumpId dumpId)
11590 q = createPQExpBuffer();
11591 tag = createPQExpBuffer();
11592 delq = createPQExpBuffer();
11593 query = createPQExpBuffer();
11596 * We read from the publicly accessible view pg_user_mappings, so as not
11597 * to fail if run by a non-superuser. Note that the view will show
11598 * umoptions as null if the user hasn't got privileges for the associated
11599 * server; this means that pg_dump will dump such a mapping, but with no
11600 * OPTIONS clause. A possible alternative is to skip such mappings
11601 * altogether, but it's not clear that that's an improvement.
11603 selectSourceSchema(fout, "pg_catalog");
11605 appendPQExpBuffer(query,
11607 "array_to_string(ARRAY("
11608 "SELECT quote_ident(option_name) || ' ' || "
11609 "quote_literal(option_value) "
11610 "FROM pg_options_to_table(umoptions) "
11611 "ORDER BY option_name"
11612 "), E',\n ') AS umoptions "
11613 "FROM pg_user_mappings "
11614 "WHERE srvid = '%u' "
11615 "ORDER BY usename",
11618 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11620 ntups = PQntuples(res);
11621 i_usename = PQfnumber(res, "usename");
11622 i_umoptions = PQfnumber(res, "umoptions");
11624 for (i = 0; i < ntups; i++)
11629 usename = PQgetvalue(res, i, i_usename);
11630 umoptions = PQgetvalue(res, i, i_umoptions);
11632 resetPQExpBuffer(q);
11633 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11634 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11636 if (umoptions && strlen(umoptions) > 0)
11637 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11639 appendPQExpBuffer(q, ";\n");
11641 resetPQExpBuffer(delq);
11642 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11643 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11645 resetPQExpBuffer(tag);
11646 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11647 usename, servername);
11649 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11654 "USER MAPPING", SECTION_PRE_DATA,
11655 q->data, delq->data, NULL,
11662 destroyPQExpBuffer(query);
11663 destroyPQExpBuffer(delq);
11664 destroyPQExpBuffer(q);
11668 * Write out default privileges information
11671 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11677 /* Skip if not to be dumped */
11678 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11681 q = createPQExpBuffer();
11682 tag = createPQExpBuffer();
11684 switch (daclinfo->defaclobjtype)
11686 case DEFACLOBJ_RELATION:
11689 case DEFACLOBJ_SEQUENCE:
11690 type = "SEQUENCES";
11692 case DEFACLOBJ_FUNCTION:
11693 type = "FUNCTIONS";
11696 /* shouldn't get here */
11697 exit_horribly(NULL,
11698 "unknown object type (%d) in default privileges\n",
11699 (int) daclinfo->defaclobjtype);
11700 type = ""; /* keep compiler quiet */
11703 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11705 /* build the actual command(s) for this tuple */
11706 if (!buildDefaultACLCommands(type,
11707 daclinfo->dobj.namespace != NULL ?
11708 daclinfo->dobj.namespace->dobj.name : NULL,
11709 daclinfo->defaclacl,
11710 daclinfo->defaclrole,
11711 fout->remoteVersion,
11713 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11714 daclinfo->defaclacl);
11716 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11718 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11720 daclinfo->defaclrole,
11721 false, "DEFAULT ACL", SECTION_NONE,
11723 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11726 destroyPQExpBuffer(tag);
11727 destroyPQExpBuffer(q);
11731 * Write out grant/revoke information
11733 * 'objCatId' is the catalog ID of the underlying object.
11734 * 'objDumpId' is the dump ID of the underlying object.
11735 * 'type' must be one of
11736 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11737 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11738 * 'name' is the formatted name of the object. Must be quoted etc. already.
11739 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11740 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11741 * 'nspname' is the namespace the object is in (NULL if none).
11742 * 'owner' is the owner, NULL if there is no owner (for languages).
11743 * 'acls' is the string read out of the fooacl system catalog field;
11744 * it will be parsed here.
11748 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11749 const char *type, const char *name, const char *subname,
11750 const char *tag, const char *nspname, const char *owner,
11755 /* Do nothing if ACL dump is not enabled */
11759 /* --data-only skips ACLs *except* BLOB ACLs */
11760 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11763 sql = createPQExpBuffer();
11765 if (!buildACLCommands(name, subname, type, acls, owner,
11766 "", fout->remoteVersion, sql))
11767 exit_horribly(NULL,
11768 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11772 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11775 owner ? owner : "",
11776 false, "ACL", SECTION_NONE,
11777 sql->data, "", NULL,
11781 destroyPQExpBuffer(sql);
11787 * This routine is used to dump any security labels associated with the
11788 * object handed to this routine. The routine takes a constant character
11789 * string for the target part of the security-label command, plus
11790 * the namespace and owner of the object (for labeling the ArchiveEntry),
11791 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11792 * plus the dump ID for the object (for setting a dependency).
11793 * If a matching pg_seclabel entry is found, it is dumped.
11795 * Note: although this routine takes a dumpId for dependency purposes,
11796 * that purpose is just to mark the dependency in the emitted dump file
11797 * for possible future use by pg_restore. We do NOT use it for determining
11798 * ordering of the label in the dump file, because this routine is called
11799 * after dependency sorting occurs. This routine should be called just after
11800 * calling ArchiveEntry() for the specified object.
11803 dumpSecLabel(Archive *fout, const char *target,
11804 const char *namespace, const char *owner,
11805 CatalogId catalogId, int subid, DumpId dumpId)
11807 SecLabelItem *labels;
11812 /* do nothing, if --no-security-labels is supplied */
11813 if (no_security_labels)
11816 /* Comments are schema not data ... except blob comments are data */
11817 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11828 /* Search for security labels associated with catalogId, using table */
11829 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11831 query = createPQExpBuffer();
11833 for (i = 0; i < nlabels; i++)
11836 * Ignore label entries for which the subid doesn't match.
11838 if (labels[i].objsubid != subid)
11841 appendPQExpBuffer(query,
11842 "SECURITY LABEL FOR %s ON %s IS ",
11843 fmtId(labels[i].provider), target);
11844 appendStringLiteralAH(query, labels[i].label, fout);
11845 appendPQExpBuffer(query, ";\n");
11848 if (query->len > 0)
11850 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11851 target, namespace, NULL, owner,
11852 false, "SECURITY LABEL", SECTION_NONE,
11853 query->data, "", NULL,
11857 destroyPQExpBuffer(query);
11861 * dumpTableSecLabel
11863 * As above, but dump security label for both the specified table (or view)
11867 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11869 SecLabelItem *labels;
11873 PQExpBuffer target;
11875 /* do nothing, if --no-security-labels is supplied */
11876 if (no_security_labels)
11879 /* SecLabel are SCHEMA not data */
11883 /* Search for comments associated with relation, using table */
11884 nlabels = findSecLabels(fout,
11885 tbinfo->dobj.catId.tableoid,
11886 tbinfo->dobj.catId.oid,
11889 /* If security labels exist, build SECURITY LABEL statements */
11893 query = createPQExpBuffer();
11894 target = createPQExpBuffer();
11896 for (i = 0; i < nlabels; i++)
11898 const char *colname;
11899 const char *provider = labels[i].provider;
11900 const char *label = labels[i].label;
11901 int objsubid = labels[i].objsubid;
11903 resetPQExpBuffer(target);
11906 appendPQExpBuffer(target, "%s %s", reltypename,
11907 fmtId(tbinfo->dobj.name));
11911 colname = getAttrName(objsubid, tbinfo);
11912 /* first fmtId result must be consumed before calling it again */
11913 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11914 appendPQExpBuffer(target, ".%s", fmtId(colname));
11916 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11917 fmtId(provider), target->data);
11918 appendStringLiteralAH(query, label, fout);
11919 appendPQExpBuffer(query, ";\n");
11921 if (query->len > 0)
11923 resetPQExpBuffer(target);
11924 appendPQExpBuffer(target, "%s %s", reltypename,
11925 fmtId(tbinfo->dobj.name));
11926 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11928 tbinfo->dobj.namespace->dobj.name,
11929 NULL, tbinfo->rolname,
11930 false, "SECURITY LABEL", SECTION_NONE,
11931 query->data, "", NULL,
11932 &(tbinfo->dobj.dumpId), 1,
11935 destroyPQExpBuffer(query);
11936 destroyPQExpBuffer(target);
11942 * Find the security label(s), if any, associated with the given object.
11943 * All the objsubid values associated with the given classoid/objoid are
11944 * found with one search.
11947 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11949 /* static storage for table of security labels */
11950 static SecLabelItem *labels = NULL;
11951 static int nlabels = -1;
11953 SecLabelItem *middle = NULL;
11955 SecLabelItem *high;
11958 /* Get security labels if we didn't already */
11960 nlabels = collectSecLabels(fout, &labels);
11962 if (nlabels <= 0) /* no labels, so no match is possible */
11969 * Do binary search to find some item matching the object.
11972 high = &labels[nlabels - 1];
11973 while (low <= high)
11975 middle = low + (high - low) / 2;
11977 if (classoid < middle->classoid)
11979 else if (classoid > middle->classoid)
11981 else if (objoid < middle->objoid)
11983 else if (objoid > middle->objoid)
11986 break; /* found a match */
11989 if (low > high) /* no matches */
11996 * Now determine how many items match the object. The search loop
11997 * invariant still holds: only items between low and high inclusive could
12001 while (middle > low)
12003 if (classoid != middle[-1].classoid ||
12004 objoid != middle[-1].objoid)
12013 while (middle <= high)
12015 if (classoid != middle->classoid ||
12016 objoid != middle->objoid)
12028 * Construct a table of all security labels available for database objects.
12029 * It's much faster to pull them all at once.
12031 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12034 collectSecLabels(Archive *fout, SecLabelItem **items)
12045 SecLabelItem *labels;
12047 query = createPQExpBuffer();
12049 appendPQExpBuffer(query,
12050 "SELECT label, provider, classoid, objoid, objsubid "
12051 "FROM pg_catalog.pg_seclabel "
12052 "ORDER BY classoid, objoid, objsubid");
12054 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12056 /* Construct lookup table containing OIDs in numeric form */
12057 i_label = PQfnumber(res, "label");
12058 i_provider = PQfnumber(res, "provider");
12059 i_classoid = PQfnumber(res, "classoid");
12060 i_objoid = PQfnumber(res, "objoid");
12061 i_objsubid = PQfnumber(res, "objsubid");
12063 ntups = PQntuples(res);
12065 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12067 for (i = 0; i < ntups; i++)
12069 labels[i].label = PQgetvalue(res, i, i_label);
12070 labels[i].provider = PQgetvalue(res, i, i_provider);
12071 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12072 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12073 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12076 /* Do NOT free the PGresult since we are keeping pointers into it */
12077 destroyPQExpBuffer(query);
12085 * write out to fout the declarations (not data) of a user-defined table
12088 dumpTable(Archive *fout, TableInfo *tbinfo)
12090 if (tbinfo->dobj.dump)
12094 if (tbinfo->relkind == RELKIND_SEQUENCE)
12095 dumpSequence(fout, tbinfo);
12096 else if (!dataOnly)
12097 dumpTableSchema(fout, tbinfo);
12099 /* Handle the ACL here */
12100 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12101 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12102 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12104 namecopy, NULL, tbinfo->dobj.name,
12105 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12109 * Handle column ACLs, if any. Note: we pull these with a separate
12110 * query rather than trying to fetch them during getTableAttrs, so
12111 * that we won't miss ACLs on system columns.
12113 if (fout->remoteVersion >= 80400)
12115 PQExpBuffer query = createPQExpBuffer();
12119 appendPQExpBuffer(query,
12120 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12121 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12123 tbinfo->dobj.catId.oid);
12124 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12126 for (i = 0; i < PQntuples(res); i++)
12128 char *attname = PQgetvalue(res, i, 0);
12129 char *attacl = PQgetvalue(res, i, 1);
12133 attnamecopy = pg_strdup(fmtId(attname));
12134 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12135 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12136 /* Column's GRANT type is always TABLE */
12137 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12138 namecopy, attnamecopy, acltag,
12139 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12145 destroyPQExpBuffer(query);
12154 * write the declaration (not data) of one user-defined table or view
12157 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12159 PQExpBuffer query = createPQExpBuffer();
12160 PQExpBuffer q = createPQExpBuffer();
12161 PQExpBuffer delq = createPQExpBuffer();
12162 PQExpBuffer labelq = createPQExpBuffer();
12165 TableInfo **parents;
12166 int actual_atts; /* number of attrs in this CREATE statment */
12167 const char *reltypename;
12174 /* Make sure we are in proper schema */
12175 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12177 if (binary_upgrade)
12178 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12179 tbinfo->dobj.catId.oid);
12181 /* Is it a table or a view? */
12182 if (tbinfo->relkind == RELKIND_VIEW)
12186 reltypename = "VIEW";
12188 /* Fetch the view definition */
12189 if (fout->remoteVersion >= 70300)
12191 /* Beginning in 7.3, viewname is not unique; rely on OID */
12192 appendPQExpBuffer(query,
12193 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12194 tbinfo->dobj.catId.oid);
12198 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12199 "FROM pg_views WHERE viewname = ");
12200 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12201 appendPQExpBuffer(query, ";");
12204 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12206 if (PQntuples(res) != 1)
12208 if (PQntuples(res) < 1)
12209 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12210 tbinfo->dobj.name);
12212 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12213 tbinfo->dobj.name);
12216 viewdef = PQgetvalue(res, 0, 0);
12218 if (strlen(viewdef) == 0)
12219 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12220 tbinfo->dobj.name);
12223 * DROP must be fully qualified in case same name appears in
12226 appendPQExpBuffer(delq, "DROP VIEW %s.",
12227 fmtId(tbinfo->dobj.namespace->dobj.name));
12228 appendPQExpBuffer(delq, "%s;\n",
12229 fmtId(tbinfo->dobj.name));
12231 if (binary_upgrade)
12232 binary_upgrade_set_pg_class_oids(fout, q,
12233 tbinfo->dobj.catId.oid, false);
12235 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12236 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12237 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12238 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12240 appendPQExpBuffer(labelq, "VIEW %s",
12241 fmtId(tbinfo->dobj.name));
12247 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12252 reltypename = "FOREIGN TABLE";
12254 /* retrieve name of foreign server and generic options */
12255 appendPQExpBuffer(query,
12256 "SELECT fs.srvname, "
12257 "pg_catalog.array_to_string(ARRAY("
12258 "SELECT pg_catalog.quote_ident(option_name) || "
12259 "' ' || pg_catalog.quote_literal(option_value) "
12260 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12261 "ORDER BY option_name"
12262 "), E',\n ') AS ftoptions "
12263 "FROM pg_catalog.pg_foreign_table ft "
12264 "JOIN pg_catalog.pg_foreign_server fs "
12265 "ON (fs.oid = ft.ftserver) "
12266 "WHERE ft.ftrelid = '%u'",
12267 tbinfo->dobj.catId.oid);
12268 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12269 i_srvname = PQfnumber(res, "srvname");
12270 i_ftoptions = PQfnumber(res, "ftoptions");
12271 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12272 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12277 reltypename = "TABLE";
12281 numParents = tbinfo->numParents;
12282 parents = tbinfo->parents;
12285 * DROP must be fully qualified in case same name appears in
12288 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12289 fmtId(tbinfo->dobj.namespace->dobj.name));
12290 appendPQExpBuffer(delq, "%s;\n",
12291 fmtId(tbinfo->dobj.name));
12293 appendPQExpBuffer(labelq, "%s %s", reltypename,
12294 fmtId(tbinfo->dobj.name));
12296 if (binary_upgrade)
12297 binary_upgrade_set_pg_class_oids(fout, q,
12298 tbinfo->dobj.catId.oid, false);
12300 appendPQExpBuffer(q, "CREATE %s%s %s",
12301 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12304 fmtId(tbinfo->dobj.name));
12307 * Attach to type, if reloftype; except in case of a binary upgrade,
12308 * we dump the table normally and attach it to the type afterward.
12310 if (tbinfo->reloftype && !binary_upgrade)
12311 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12313 /* Dump the attributes */
12315 for (j = 0; j < tbinfo->numatts; j++)
12318 * Normally, dump if it's locally defined in this table, and not
12319 * dropped. But for binary upgrade, we'll dump all the columns,
12320 * and then fix up the dropped and nonlocal cases below.
12322 if (shouldPrintColumn(tbinfo, j))
12325 * Default value --- suppress if to be printed separately.
12327 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12328 !tbinfo->attrdefs[j]->separate);
12331 * Not Null constraint --- suppress if inherited, except in
12332 * binary-upgrade case where that won't work.
12334 bool has_notnull = (tbinfo->notnull[j] &&
12335 (!tbinfo->inhNotNull[j] ||
12338 /* Skip column if fully defined by reloftype */
12339 if (tbinfo->reloftype &&
12340 !has_default && !has_notnull && !binary_upgrade)
12343 /* Format properly if not first attr */
12344 if (actual_atts == 0)
12345 appendPQExpBuffer(q, " (");
12347 appendPQExpBuffer(q, ",");
12348 appendPQExpBuffer(q, "\n ");
12351 /* Attribute name */
12352 appendPQExpBuffer(q, "%s ",
12353 fmtId(tbinfo->attnames[j]));
12355 if (tbinfo->attisdropped[j])
12358 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12359 * so we will not have gotten a valid type name; insert
12360 * INTEGER as a stopgap. We'll clean things up later.
12362 appendPQExpBuffer(q, "INTEGER /* dummy */");
12363 /* Skip all the rest, too */
12367 /* Attribute type */
12368 if (tbinfo->reloftype && !binary_upgrade)
12370 appendPQExpBuffer(q, "WITH OPTIONS");
12372 else if (fout->remoteVersion >= 70100)
12374 appendPQExpBuffer(q, "%s",
12375 tbinfo->atttypnames[j]);
12379 /* If no format_type, fake it */
12380 appendPQExpBuffer(q, "%s",
12381 myFormatType(tbinfo->atttypnames[j],
12382 tbinfo->atttypmod[j]));
12385 /* Add collation if not default for the type */
12386 if (OidIsValid(tbinfo->attcollation[j]))
12390 coll = findCollationByOid(tbinfo->attcollation[j]);
12393 /* always schema-qualify, don't try to be smart */
12394 appendPQExpBuffer(q, " COLLATE %s.",
12395 fmtId(coll->dobj.namespace->dobj.name));
12396 appendPQExpBuffer(q, "%s",
12397 fmtId(coll->dobj.name));
12402 appendPQExpBuffer(q, " DEFAULT %s",
12403 tbinfo->attrdefs[j]->adef_expr);
12406 appendPQExpBuffer(q, " NOT NULL");
12411 * Add non-inherited CHECK constraints, if any.
12413 for (j = 0; j < tbinfo->ncheck; j++)
12415 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12417 if (constr->separate || !constr->conislocal)
12420 if (actual_atts == 0)
12421 appendPQExpBuffer(q, " (\n ");
12423 appendPQExpBuffer(q, ",\n ");
12425 appendPQExpBuffer(q, "CONSTRAINT %s ",
12426 fmtId(constr->dobj.name));
12427 appendPQExpBuffer(q, "%s", constr->condef);
12433 appendPQExpBuffer(q, "\n)");
12434 else if (!(tbinfo->reloftype && !binary_upgrade))
12437 * We must have a parenthesized attribute list, even though empty,
12438 * when not using the OF TYPE syntax.
12440 appendPQExpBuffer(q, " (\n)");
12443 if (numParents > 0 && !binary_upgrade)
12445 appendPQExpBuffer(q, "\nINHERITS (");
12446 for (k = 0; k < numParents; k++)
12448 TableInfo *parentRel = parents[k];
12451 appendPQExpBuffer(q, ", ");
12452 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12453 appendPQExpBuffer(q, "%s.",
12454 fmtId(parentRel->dobj.namespace->dobj.name));
12455 appendPQExpBuffer(q, "%s",
12456 fmtId(parentRel->dobj.name));
12458 appendPQExpBuffer(q, ")");
12461 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12462 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12464 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12465 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12467 bool addcomma = false;
12469 appendPQExpBuffer(q, "\nWITH (");
12470 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12473 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12475 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12477 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12478 tbinfo->toast_reloptions);
12480 appendPQExpBuffer(q, ")");
12483 /* Dump generic options if any */
12484 if (ftoptions && ftoptions[0])
12485 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12487 appendPQExpBuffer(q, ";\n");
12490 * To create binary-compatible heap files, we have to ensure the same
12491 * physical column order, including dropped columns, as in the
12492 * original. Therefore, we create dropped columns above and drop them
12493 * here, also updating their attlen/attalign values so that the
12494 * dropped column can be skipped properly. (We do not bother with
12495 * restoring the original attbyval setting.) Also, inheritance
12496 * relationships are set up by doing ALTER INHERIT rather than using
12497 * an INHERITS clause --- the latter would possibly mess up the column
12498 * order. That also means we have to take care about setting
12499 * attislocal correctly, plus fix up any inherited CHECK constraints.
12500 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12502 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12504 for (j = 0; j < tbinfo->numatts; j++)
12506 if (tbinfo->attisdropped[j])
12508 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12509 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12510 "SET attlen = %d, "
12511 "attalign = '%c', attbyval = false\n"
12512 "WHERE attname = ",
12514 tbinfo->attalign[j]);
12515 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12516 appendPQExpBuffer(q, "\n AND attrelid = ");
12517 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12518 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12520 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12521 fmtId(tbinfo->dobj.name));
12522 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12523 fmtId(tbinfo->attnames[j]));
12525 else if (!tbinfo->attislocal[j])
12527 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12528 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12529 "SET attislocal = false\n"
12530 "WHERE attname = ");
12531 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12532 appendPQExpBuffer(q, "\n AND attrelid = ");
12533 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12534 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12538 for (k = 0; k < tbinfo->ncheck; k++)
12540 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12542 if (constr->separate || constr->conislocal)
12545 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12546 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12547 fmtId(tbinfo->dobj.name));
12548 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12549 fmtId(constr->dobj.name));
12550 appendPQExpBuffer(q, "%s;\n", constr->condef);
12551 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12552 "SET conislocal = false\n"
12553 "WHERE contype = 'c' AND conname = ");
12554 appendStringLiteralAH(q, constr->dobj.name, fout);
12555 appendPQExpBuffer(q, "\n AND conrelid = ");
12556 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12557 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12560 if (numParents > 0)
12562 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12563 for (k = 0; k < numParents; k++)
12565 TableInfo *parentRel = parents[k];
12567 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12568 fmtId(tbinfo->dobj.name));
12569 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12570 appendPQExpBuffer(q, "%s.",
12571 fmtId(parentRel->dobj.namespace->dobj.name));
12572 appendPQExpBuffer(q, "%s;\n",
12573 fmtId(parentRel->dobj.name));
12577 if (tbinfo->reloftype)
12579 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12580 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12581 fmtId(tbinfo->dobj.name),
12582 tbinfo->reloftype);
12585 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12586 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12587 "SET relfrozenxid = '%u'\n"
12589 tbinfo->frozenxid);
12590 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12591 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12593 if (tbinfo->toast_oid)
12595 /* We preserve the toast oids, so we can use it during restore */
12596 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12597 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12598 "SET relfrozenxid = '%u'\n"
12599 "WHERE oid = '%u';\n",
12600 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12605 * Dump additional per-column properties that we can't handle in the
12606 * main CREATE TABLE command.
12608 for (j = 0; j < tbinfo->numatts; j++)
12610 /* None of this applies to dropped columns */
12611 if (tbinfo->attisdropped[j])
12615 * If we didn't dump the column definition explicitly above, and
12616 * it is NOT NULL and did not inherit that property from a parent,
12617 * we have to mark it separately.
12619 if (!shouldPrintColumn(tbinfo, j) &&
12620 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12622 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12623 fmtId(tbinfo->dobj.name));
12624 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12625 fmtId(tbinfo->attnames[j]));
12629 * Dump per-column statistics information. We only issue an ALTER
12630 * TABLE statement if the attstattarget entry for this column is
12631 * non-negative (i.e. it's not the default value)
12633 if (tbinfo->attstattarget[j] >= 0)
12635 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12636 fmtId(tbinfo->dobj.name));
12637 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12638 fmtId(tbinfo->attnames[j]));
12639 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12640 tbinfo->attstattarget[j]);
12644 * Dump per-column storage information. The statement is only
12645 * dumped if the storage has been changed from the type's default.
12647 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12649 switch (tbinfo->attstorage[j])
12655 storage = "EXTERNAL";
12661 storage = "EXTENDED";
12668 * Only dump the statement if it's a storage type we recognize
12670 if (storage != NULL)
12672 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12673 fmtId(tbinfo->dobj.name));
12674 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12675 fmtId(tbinfo->attnames[j]));
12676 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12682 * Dump per-column attributes.
12684 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12686 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12687 fmtId(tbinfo->dobj.name));
12688 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12689 fmtId(tbinfo->attnames[j]));
12690 appendPQExpBuffer(q, "SET (%s);\n",
12691 tbinfo->attoptions[j]);
12695 * Dump per-column fdw options.
12697 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12698 tbinfo->attfdwoptions[j] &&
12699 tbinfo->attfdwoptions[j][0] != '\0')
12701 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12702 fmtId(tbinfo->dobj.name));
12703 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12704 fmtId(tbinfo->attnames[j]));
12705 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12706 tbinfo->attfdwoptions[j]);
12711 if (binary_upgrade)
12712 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12714 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12716 tbinfo->dobj.namespace->dobj.name,
12717 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12719 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12720 reltypename, SECTION_PRE_DATA,
12721 q->data, delq->data, NULL,
12722 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12726 /* Dump Table Comments */
12727 dumpTableComment(fout, tbinfo, reltypename);
12729 /* Dump Table Security Labels */
12730 dumpTableSecLabel(fout, tbinfo, reltypename);
12732 /* Dump comments on inlined table constraints */
12733 for (j = 0; j < tbinfo->ncheck; j++)
12735 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12737 if (constr->separate || !constr->conislocal)
12740 dumpTableConstraintComment(fout, constr);
12743 destroyPQExpBuffer(query);
12744 destroyPQExpBuffer(q);
12745 destroyPQExpBuffer(delq);
12746 destroyPQExpBuffer(labelq);
12750 * dumpAttrDef --- dump an attribute's default-value declaration
12753 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12755 TableInfo *tbinfo = adinfo->adtable;
12756 int adnum = adinfo->adnum;
12760 /* Skip if table definition not to be dumped */
12761 if (!tbinfo->dobj.dump || dataOnly)
12764 /* Skip if not "separate"; it was dumped in the table's definition */
12765 if (!adinfo->separate)
12768 q = createPQExpBuffer();
12769 delq = createPQExpBuffer();
12771 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12772 fmtId(tbinfo->dobj.name));
12773 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12774 fmtId(tbinfo->attnames[adnum - 1]),
12775 adinfo->adef_expr);
12778 * DROP must be fully qualified in case same name appears in pg_catalog
12780 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12781 fmtId(tbinfo->dobj.namespace->dobj.name));
12782 appendPQExpBuffer(delq, "%s ",
12783 fmtId(tbinfo->dobj.name));
12784 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12785 fmtId(tbinfo->attnames[adnum - 1]));
12787 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12788 tbinfo->attnames[adnum - 1],
12789 tbinfo->dobj.namespace->dobj.name,
12792 false, "DEFAULT", SECTION_PRE_DATA,
12793 q->data, delq->data, NULL,
12794 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12797 destroyPQExpBuffer(q);
12798 destroyPQExpBuffer(delq);
12802 * getAttrName: extract the correct name for an attribute
12804 * The array tblInfo->attnames[] only provides names of user attributes;
12805 * if a system attribute number is supplied, we have to fake it.
12806 * We also do a little bit of bounds checking for safety's sake.
12808 static const char *
12809 getAttrName(int attrnum, TableInfo *tblInfo)
12811 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12812 return tblInfo->attnames[attrnum - 1];
12815 case SelfItemPointerAttributeNumber:
12817 case ObjectIdAttributeNumber:
12819 case MinTransactionIdAttributeNumber:
12821 case MinCommandIdAttributeNumber:
12823 case MaxTransactionIdAttributeNumber:
12825 case MaxCommandIdAttributeNumber:
12827 case TableOidAttributeNumber:
12830 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12831 attrnum, tblInfo->dobj.name);
12832 return NULL; /* keep compiler quiet */
12837 * write out to fout a user-defined index
12840 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12842 TableInfo *tbinfo = indxinfo->indextable;
12845 PQExpBuffer labelq;
12850 q = createPQExpBuffer();
12851 delq = createPQExpBuffer();
12852 labelq = createPQExpBuffer();
12854 appendPQExpBuffer(labelq, "INDEX %s",
12855 fmtId(indxinfo->dobj.name));
12858 * If there's an associated constraint, don't dump the index per se, but
12859 * do dump any comment for it. (This is safe because dependency ordering
12860 * will have ensured the constraint is emitted first.)
12862 if (indxinfo->indexconstraint == 0)
12864 if (binary_upgrade)
12865 binary_upgrade_set_pg_class_oids(fout, q,
12866 indxinfo->dobj.catId.oid, true);
12868 /* Plain secondary index */
12869 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12871 /* If the index is clustered, we need to record that. */
12872 if (indxinfo->indisclustered)
12874 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12875 fmtId(tbinfo->dobj.name));
12876 appendPQExpBuffer(q, " ON %s;\n",
12877 fmtId(indxinfo->dobj.name));
12881 * DROP must be fully qualified in case same name appears in
12884 appendPQExpBuffer(delq, "DROP INDEX %s.",
12885 fmtId(tbinfo->dobj.namespace->dobj.name));
12886 appendPQExpBuffer(delq, "%s;\n",
12887 fmtId(indxinfo->dobj.name));
12889 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12890 indxinfo->dobj.name,
12891 tbinfo->dobj.namespace->dobj.name,
12892 indxinfo->tablespace,
12893 tbinfo->rolname, false,
12894 "INDEX", SECTION_POST_DATA,
12895 q->data, delq->data, NULL,
12896 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12900 /* Dump Index Comments */
12901 dumpComment(fout, labelq->data,
12902 tbinfo->dobj.namespace->dobj.name,
12904 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12906 destroyPQExpBuffer(q);
12907 destroyPQExpBuffer(delq);
12908 destroyPQExpBuffer(labelq);
12913 * write out to fout a user-defined constraint
12916 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12918 TableInfo *tbinfo = coninfo->contable;
12922 /* Skip if not to be dumped */
12923 if (!coninfo->dobj.dump || dataOnly)
12926 q = createPQExpBuffer();
12927 delq = createPQExpBuffer();
12929 if (coninfo->contype == 'p' ||
12930 coninfo->contype == 'u' ||
12931 coninfo->contype == 'x')
12933 /* Index-related constraint */
12934 IndxInfo *indxinfo;
12937 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12939 if (indxinfo == NULL)
12940 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12941 coninfo->dobj.name);
12943 if (binary_upgrade)
12944 binary_upgrade_set_pg_class_oids(fout, q,
12945 indxinfo->dobj.catId.oid, true);
12947 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12948 fmtId(tbinfo->dobj.name));
12949 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12950 fmtId(coninfo->dobj.name));
12952 if (coninfo->condef)
12954 /* pg_get_constraintdef should have provided everything */
12955 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12959 appendPQExpBuffer(q, "%s (",
12960 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12961 for (k = 0; k < indxinfo->indnkeys; k++)
12963 int indkey = (int) indxinfo->indkeys[k];
12964 const char *attname;
12966 if (indkey == InvalidAttrNumber)
12968 attname = getAttrName(indkey, tbinfo);
12970 appendPQExpBuffer(q, "%s%s",
12971 (k == 0) ? "" : ", ",
12975 appendPQExpBuffer(q, ")");
12977 if (indxinfo->options && strlen(indxinfo->options) > 0)
12978 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12980 if (coninfo->condeferrable)
12982 appendPQExpBuffer(q, " DEFERRABLE");
12983 if (coninfo->condeferred)
12984 appendPQExpBuffer(q, " INITIALLY DEFERRED");
12987 appendPQExpBuffer(q, ";\n");
12990 /* If the index is clustered, we need to record that. */
12991 if (indxinfo->indisclustered)
12993 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12994 fmtId(tbinfo->dobj.name));
12995 appendPQExpBuffer(q, " ON %s;\n",
12996 fmtId(indxinfo->dobj.name));
13000 * DROP must be fully qualified in case same name appears in
13003 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13004 fmtId(tbinfo->dobj.namespace->dobj.name));
13005 appendPQExpBuffer(delq, "%s ",
13006 fmtId(tbinfo->dobj.name));
13007 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13008 fmtId(coninfo->dobj.name));
13010 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13011 coninfo->dobj.name,
13012 tbinfo->dobj.namespace->dobj.name,
13013 indxinfo->tablespace,
13014 tbinfo->rolname, false,
13015 "CONSTRAINT", SECTION_POST_DATA,
13016 q->data, delq->data, NULL,
13017 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13020 else if (coninfo->contype == 'f')
13023 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13024 * current table data is not processed
13026 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13027 fmtId(tbinfo->dobj.name));
13028 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13029 fmtId(coninfo->dobj.name),
13033 * DROP must be fully qualified in case same name appears in
13036 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13037 fmtId(tbinfo->dobj.namespace->dobj.name));
13038 appendPQExpBuffer(delq, "%s ",
13039 fmtId(tbinfo->dobj.name));
13040 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13041 fmtId(coninfo->dobj.name));
13043 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13044 coninfo->dobj.name,
13045 tbinfo->dobj.namespace->dobj.name,
13047 tbinfo->rolname, false,
13048 "FK CONSTRAINT", SECTION_POST_DATA,
13049 q->data, delq->data, NULL,
13050 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13053 else if (coninfo->contype == 'c' && tbinfo)
13055 /* CHECK constraint on a table */
13057 /* Ignore if not to be dumped separately */
13058 if (coninfo->separate)
13060 /* add ONLY if we do not want it to propagate to children */
13061 appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13062 coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13063 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13064 fmtId(coninfo->dobj.name),
13068 * DROP must be fully qualified in case same name appears in
13071 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13072 fmtId(tbinfo->dobj.namespace->dobj.name));
13073 appendPQExpBuffer(delq, "%s ",
13074 fmtId(tbinfo->dobj.name));
13075 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13076 fmtId(coninfo->dobj.name));
13078 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13079 coninfo->dobj.name,
13080 tbinfo->dobj.namespace->dobj.name,
13082 tbinfo->rolname, false,
13083 "CHECK CONSTRAINT", SECTION_POST_DATA,
13084 q->data, delq->data, NULL,
13085 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13089 else if (coninfo->contype == 'c' && tbinfo == NULL)
13091 /* CHECK constraint on a domain */
13092 TypeInfo *tyinfo = coninfo->condomain;
13094 /* Ignore if not to be dumped separately */
13095 if (coninfo->separate)
13097 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13098 fmtId(tyinfo->dobj.name));
13099 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13100 fmtId(coninfo->dobj.name),
13104 * DROP must be fully qualified in case same name appears in
13107 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13108 fmtId(tyinfo->dobj.namespace->dobj.name));
13109 appendPQExpBuffer(delq, "%s ",
13110 fmtId(tyinfo->dobj.name));
13111 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13112 fmtId(coninfo->dobj.name));
13114 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13115 coninfo->dobj.name,
13116 tyinfo->dobj.namespace->dobj.name,
13118 tyinfo->rolname, false,
13119 "CHECK CONSTRAINT", SECTION_POST_DATA,
13120 q->data, delq->data, NULL,
13121 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13127 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13131 /* Dump Constraint Comments --- only works for table constraints */
13132 if (tbinfo && coninfo->separate)
13133 dumpTableConstraintComment(fout, coninfo);
13135 destroyPQExpBuffer(q);
13136 destroyPQExpBuffer(delq);
13140 * dumpTableConstraintComment --- dump a constraint's comment if any
13142 * This is split out because we need the function in two different places
13143 * depending on whether the constraint is dumped as part of CREATE TABLE
13144 * or as a separate ALTER command.
13147 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13149 TableInfo *tbinfo = coninfo->contable;
13150 PQExpBuffer labelq = createPQExpBuffer();
13152 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13153 fmtId(coninfo->dobj.name));
13154 appendPQExpBuffer(labelq, "ON %s",
13155 fmtId(tbinfo->dobj.name));
13156 dumpComment(fout, labelq->data,
13157 tbinfo->dobj.namespace->dobj.name,
13159 coninfo->dobj.catId, 0,
13160 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13162 destroyPQExpBuffer(labelq);
13166 * findLastBuiltInOid -
13167 * find the last built in oid
13169 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13170 * pg_database entry for the current database
13173 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13177 PQExpBuffer query = createPQExpBuffer();
13179 resetPQExpBuffer(query);
13180 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13181 appendStringLiteralAH(query, dbname, fout);
13183 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13184 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13186 destroyPQExpBuffer(query);
13191 * findLastBuiltInOid -
13192 * find the last built in oid
13194 * For 7.0, we do this by assuming that the last thing that initdb does is to
13195 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13196 * initdb won't be changing anymore, it'll do.
13199 findLastBuiltinOid_V70(Archive *fout)
13204 res = ExecuteSqlQueryForSingleRow(fout,
13205 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13206 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13212 dumpSequence(Archive *fout, TableInfo *tbinfo)
13225 PQExpBuffer query = createPQExpBuffer();
13226 PQExpBuffer delqry = createPQExpBuffer();
13227 PQExpBuffer labelq = createPQExpBuffer();
13229 /* Make sure we are in proper schema */
13230 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13232 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13233 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13235 if (fout->remoteVersion >= 80400)
13237 appendPQExpBuffer(query,
13238 "SELECT sequence_name, "
13239 "start_value, last_value, increment_by, "
13240 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13241 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13243 "END AS max_value, "
13244 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13245 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13247 "END AS min_value, "
13248 "cache_value, is_cycled, is_called from %s",
13250 fmtId(tbinfo->dobj.name));
13254 appendPQExpBuffer(query,
13255 "SELECT sequence_name, "
13256 "0 AS start_value, last_value, increment_by, "
13257 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13258 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13260 "END AS max_value, "
13261 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13262 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13264 "END AS min_value, "
13265 "cache_value, is_cycled, is_called from %s",
13267 fmtId(tbinfo->dobj.name));
13270 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13272 if (PQntuples(res) != 1)
13274 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13275 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13277 tbinfo->dobj.name, PQntuples(res));
13281 /* Disable this check: it fails if sequence has been renamed */
13283 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13285 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13286 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13291 startv = PQgetvalue(res, 0, 1);
13292 last = PQgetvalue(res, 0, 2);
13293 incby = PQgetvalue(res, 0, 3);
13294 if (!PQgetisnull(res, 0, 4))
13295 maxv = PQgetvalue(res, 0, 4);
13296 if (!PQgetisnull(res, 0, 5))
13297 minv = PQgetvalue(res, 0, 5);
13298 cache = PQgetvalue(res, 0, 6);
13299 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13300 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13303 * The logic we use for restoring sequences is as follows:
13305 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13306 * last_val for start if called is false, else use min_val for start_val).
13307 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13308 * BY command for it.
13310 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13315 * DROP must be fully qualified in case same name appears in
13318 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13319 fmtId(tbinfo->dobj.namespace->dobj.name));
13320 appendPQExpBuffer(delqry, "%s;\n",
13321 fmtId(tbinfo->dobj.name));
13323 resetPQExpBuffer(query);
13325 if (binary_upgrade)
13327 binary_upgrade_set_pg_class_oids(fout, query,
13328 tbinfo->dobj.catId.oid, false);
13329 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13330 tbinfo->dobj.catId.oid);
13333 appendPQExpBuffer(query,
13334 "CREATE SEQUENCE %s\n",
13335 fmtId(tbinfo->dobj.name));
13337 if (fout->remoteVersion >= 80400)
13338 appendPQExpBuffer(query, " START WITH %s\n", startv);
13342 * Versions before 8.4 did not remember the true start value. If
13343 * is_called is false then the sequence has never been incremented
13344 * so we can use last_val. Otherwise punt and let it default.
13347 appendPQExpBuffer(query, " START WITH %s\n", last);
13350 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13353 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13355 appendPQExpBuffer(query, " NO MINVALUE\n");
13358 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13360 appendPQExpBuffer(query, " NO MAXVALUE\n");
13362 appendPQExpBuffer(query,
13364 cache, (cycled ? "\n CYCLE" : ""));
13366 appendPQExpBuffer(query, ";\n");
13368 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13370 /* binary_upgrade: no need to clear TOAST table oid */
13372 if (binary_upgrade)
13373 binary_upgrade_extension_member(query, &tbinfo->dobj,
13376 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13378 tbinfo->dobj.namespace->dobj.name,
13381 false, "SEQUENCE", SECTION_PRE_DATA,
13382 query->data, delqry->data, NULL,
13383 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13387 * If the sequence is owned by a table column, emit the ALTER for it
13388 * as a separate TOC entry immediately following the sequence's own
13389 * entry. It's OK to do this rather than using full sorting logic,
13390 * because the dependency that tells us it's owned will have forced
13391 * the table to be created first. We can't just include the ALTER in
13392 * the TOC entry because it will fail if we haven't reassigned the
13393 * sequence owner to match the table's owner.
13395 * We need not schema-qualify the table reference because both
13396 * sequence and table must be in the same schema.
13398 if (OidIsValid(tbinfo->owning_tab))
13400 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13402 if (owning_tab && owning_tab->dobj.dump)
13404 resetPQExpBuffer(query);
13405 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13406 fmtId(tbinfo->dobj.name));
13407 appendPQExpBuffer(query, " OWNED BY %s",
13408 fmtId(owning_tab->dobj.name));
13409 appendPQExpBuffer(query, ".%s;\n",
13410 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13412 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13414 tbinfo->dobj.namespace->dobj.name,
13417 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13418 query->data, "", NULL,
13419 &(tbinfo->dobj.dumpId), 1,
13424 /* Dump Sequence Comments and Security Labels */
13425 dumpComment(fout, labelq->data,
13426 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13427 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13428 dumpSecLabel(fout, labelq->data,
13429 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13430 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13435 resetPQExpBuffer(query);
13436 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13437 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13438 appendPQExpBuffer(query, ", %s, %s);\n",
13439 last, (called ? "true" : "false"));
13441 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13443 tbinfo->dobj.namespace->dobj.name,
13446 false, "SEQUENCE SET", SECTION_PRE_DATA,
13447 query->data, "", NULL,
13448 &(tbinfo->dobj.dumpId), 1,
13454 destroyPQExpBuffer(query);
13455 destroyPQExpBuffer(delqry);
13456 destroyPQExpBuffer(labelq);
13460 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13462 TableInfo *tbinfo = tginfo->tgtable;
13464 PQExpBuffer delqry;
13465 PQExpBuffer labelq;
13474 query = createPQExpBuffer();
13475 delqry = createPQExpBuffer();
13476 labelq = createPQExpBuffer();
13479 * DROP must be fully qualified in case same name appears in pg_catalog
13481 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13482 fmtId(tginfo->dobj.name));
13483 appendPQExpBuffer(delqry, "ON %s.",
13484 fmtId(tbinfo->dobj.namespace->dobj.name));
13485 appendPQExpBuffer(delqry, "%s;\n",
13486 fmtId(tbinfo->dobj.name));
13490 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13494 if (tginfo->tgisconstraint)
13496 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13497 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13501 appendPQExpBuffer(query, "CREATE TRIGGER ");
13502 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13504 appendPQExpBuffer(query, "\n ");
13507 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13508 appendPQExpBuffer(query, "BEFORE");
13509 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13510 appendPQExpBuffer(query, "AFTER");
13511 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13512 appendPQExpBuffer(query, "INSTEAD OF");
13515 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13520 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13522 appendPQExpBuffer(query, " INSERT");
13525 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13528 appendPQExpBuffer(query, " OR DELETE");
13530 appendPQExpBuffer(query, " DELETE");
13533 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13536 appendPQExpBuffer(query, " OR UPDATE");
13538 appendPQExpBuffer(query, " UPDATE");
13541 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13544 appendPQExpBuffer(query, " OR TRUNCATE");
13546 appendPQExpBuffer(query, " TRUNCATE");
13549 appendPQExpBuffer(query, " ON %s\n",
13550 fmtId(tbinfo->dobj.name));
13552 if (tginfo->tgisconstraint)
13554 if (OidIsValid(tginfo->tgconstrrelid))
13556 /* If we are using regclass, name is already quoted */
13557 if (fout->remoteVersion >= 70300)
13558 appendPQExpBuffer(query, " FROM %s\n ",
13559 tginfo->tgconstrrelname);
13561 appendPQExpBuffer(query, " FROM %s\n ",
13562 fmtId(tginfo->tgconstrrelname));
13564 if (!tginfo->tgdeferrable)
13565 appendPQExpBuffer(query, "NOT ");
13566 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13567 if (tginfo->tginitdeferred)
13568 appendPQExpBuffer(query, "DEFERRED\n");
13570 appendPQExpBuffer(query, "IMMEDIATE\n");
13573 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13574 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13576 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13578 /* In 7.3, result of regproc is already quoted */
13579 if (fout->remoteVersion >= 70300)
13580 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13583 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13584 fmtId(tginfo->tgfname));
13586 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13589 for (findx = 0; findx < tginfo->tgnargs; findx++)
13591 /* find the embedded null that terminates this trigger argument */
13592 size_t tlen = strlen(p);
13594 if (p + tlen >= tgargs + lentgargs)
13596 /* hm, not found before end of bytea value... */
13597 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13600 tbinfo->dobj.name);
13605 appendPQExpBuffer(query, ", ");
13606 appendStringLiteralAH(query, p, fout);
13610 appendPQExpBuffer(query, ");\n");
13613 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13615 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13616 fmtId(tbinfo->dobj.name));
13617 switch (tginfo->tgenabled)
13621 appendPQExpBuffer(query, "DISABLE");
13624 appendPQExpBuffer(query, "ENABLE ALWAYS");
13627 appendPQExpBuffer(query, "ENABLE REPLICA");
13630 appendPQExpBuffer(query, "ENABLE");
13633 appendPQExpBuffer(query, " TRIGGER %s;\n",
13634 fmtId(tginfo->dobj.name));
13637 appendPQExpBuffer(labelq, "TRIGGER %s ",
13638 fmtId(tginfo->dobj.name));
13639 appendPQExpBuffer(labelq, "ON %s",
13640 fmtId(tbinfo->dobj.name));
13642 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13644 tbinfo->dobj.namespace->dobj.name,
13646 tbinfo->rolname, false,
13647 "TRIGGER", SECTION_POST_DATA,
13648 query->data, delqry->data, NULL,
13649 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13652 dumpComment(fout, labelq->data,
13653 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13654 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13656 destroyPQExpBuffer(query);
13657 destroyPQExpBuffer(delqry);
13658 destroyPQExpBuffer(labelq);
13666 dumpRule(Archive *fout, RuleInfo *rinfo)
13668 TableInfo *tbinfo = rinfo->ruletable;
13671 PQExpBuffer delcmd;
13672 PQExpBuffer labelq;
13675 /* Skip if not to be dumped */
13676 if (!rinfo->dobj.dump || dataOnly)
13680 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13681 * we do not want to dump it as a separate object.
13683 if (!rinfo->separate)
13687 * Make sure we are in proper schema.
13689 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13691 query = createPQExpBuffer();
13692 cmd = createPQExpBuffer();
13693 delcmd = createPQExpBuffer();
13694 labelq = createPQExpBuffer();
13696 if (fout->remoteVersion >= 70300)
13698 appendPQExpBuffer(query,
13699 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13700 rinfo->dobj.catId.oid);
13704 /* Rule name was unique before 7.3 ... */
13705 appendPQExpBuffer(query,
13706 "SELECT pg_get_ruledef('%s') AS definition",
13710 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13712 if (PQntuples(res) != 1)
13714 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13715 rinfo->dobj.name, tbinfo->dobj.name);
13719 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13722 * Add the command to alter the rules replication firing semantics if it
13723 * differs from the default.
13725 if (rinfo->ev_enabled != 'O')
13727 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13728 fmtId(tbinfo->dobj.namespace->dobj.name));
13729 appendPQExpBuffer(cmd, "%s ",
13730 fmtId(tbinfo->dobj.name));
13731 switch (rinfo->ev_enabled)
13734 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13735 fmtId(rinfo->dobj.name));
13738 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13739 fmtId(rinfo->dobj.name));
13742 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13743 fmtId(rinfo->dobj.name));
13749 * DROP must be fully qualified in case same name appears in pg_catalog
13751 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13752 fmtId(rinfo->dobj.name));
13753 appendPQExpBuffer(delcmd, "ON %s.",
13754 fmtId(tbinfo->dobj.namespace->dobj.name));
13755 appendPQExpBuffer(delcmd, "%s;\n",
13756 fmtId(tbinfo->dobj.name));
13758 appendPQExpBuffer(labelq, "RULE %s",
13759 fmtId(rinfo->dobj.name));
13760 appendPQExpBuffer(labelq, " ON %s",
13761 fmtId(tbinfo->dobj.name));
13763 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13765 tbinfo->dobj.namespace->dobj.name,
13767 tbinfo->rolname, false,
13768 "RULE", SECTION_POST_DATA,
13769 cmd->data, delcmd->data, NULL,
13770 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13773 /* Dump rule comments */
13774 dumpComment(fout, labelq->data,
13775 tbinfo->dobj.namespace->dobj.name,
13777 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13781 destroyPQExpBuffer(query);
13782 destroyPQExpBuffer(cmd);
13783 destroyPQExpBuffer(delcmd);
13784 destroyPQExpBuffer(labelq);
13788 * getExtensionMembership --- obtain extension membership data
13791 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13802 DumpableObject *dobj,
13805 /* Nothing to do if no extensions */
13806 if (numExtensions == 0)
13809 /* Make sure we are in proper schema */
13810 selectSourceSchema(fout, "pg_catalog");
13812 query = createPQExpBuffer();
13814 /* refclassid constraint is redundant but may speed the search */
13815 appendPQExpBuffer(query, "SELECT "
13816 "classid, objid, refclassid, refobjid "
13818 "WHERE refclassid = 'pg_extension'::regclass "
13819 "AND deptype = 'e' "
13822 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13824 ntups = PQntuples(res);
13826 i_classid = PQfnumber(res, "classid");
13827 i_objid = PQfnumber(res, "objid");
13828 i_refclassid = PQfnumber(res, "refclassid");
13829 i_refobjid = PQfnumber(res, "refobjid");
13832 * Since we ordered the SELECT by referenced ID, we can expect that
13833 * multiple entries for the same extension will appear together; this
13834 * saves on searches.
13838 for (i = 0; i < ntups; i++)
13841 CatalogId refobjId;
13843 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13844 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13845 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13846 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13848 if (refdobj == NULL ||
13849 refdobj->catId.tableoid != refobjId.tableoid ||
13850 refdobj->catId.oid != refobjId.oid)
13851 refdobj = findObjectByCatalogId(refobjId);
13854 * Failure to find objects mentioned in pg_depend is not unexpected,
13855 * since for example we don't collect info about TOAST tables.
13857 if (refdobj == NULL)
13860 fprintf(stderr, "no referenced object %u %u\n",
13861 refobjId.tableoid, refobjId.oid);
13866 dobj = findObjectByCatalogId(objId);
13871 fprintf(stderr, "no referencing object %u %u\n",
13872 objId.tableoid, objId.oid);
13877 /* Record dependency so that getDependencies needn't repeat this */
13878 addObjectDependency(dobj, refdobj->dumpId);
13880 dobj->ext_member = true;
13883 * Normally, mark the member object as not to be dumped. But in
13884 * binary upgrades, we still dump the members individually, since the
13885 * idea is to exactly reproduce the database contents rather than
13886 * replace the extension contents with something different.
13888 if (!binary_upgrade)
13889 dobj->dump = false;
13891 dobj->dump = refdobj->dump;
13897 * Now identify extension configuration tables and create TableDataInfo
13898 * objects for them, ensuring their data will be dumped even though the
13899 * tables themselves won't be.
13901 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13902 * user data in a configuration table is treated like schema data. This
13903 * seems appropriate since system data in a config table would get
13904 * reloaded by CREATE EXTENSION.
13906 for (i = 0; i < numExtensions; i++)
13908 ExtensionInfo *curext = &(extinfo[i]);
13909 char *extconfig = curext->extconfig;
13910 char *extcondition = curext->extcondition;
13911 char **extconfigarray = NULL;
13912 char **extconditionarray = NULL;
13914 int nconditionitems;
13916 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13917 if (!curext->dobj.dump)
13920 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13921 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13922 nconfigitems == nconditionitems)
13926 for (j = 0; j < nconfigitems; j++)
13928 TableInfo *configtbl;
13930 configtbl = findTableByOid(atooid(extconfigarray[j]));
13931 if (configtbl == NULL)
13935 * Note: config tables are dumped without OIDs regardless
13936 * of the --oids setting. This is because row filtering
13937 * conditions aren't compatible with dumping OIDs.
13939 makeTableDataInfo(configtbl, false);
13940 if (configtbl->dataObj != NULL)
13942 if (strlen(extconditionarray[j]) > 0)
13943 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13947 if (extconfigarray)
13948 free(extconfigarray);
13949 if (extconditionarray)
13950 free(extconditionarray);
13953 destroyPQExpBuffer(query);
13957 * getDependencies --- obtain available dependency data
13960 getDependencies(Archive *fout)
13971 DumpableObject *dobj,
13974 /* No dependency info available before 7.3 */
13975 if (fout->remoteVersion < 70300)
13979 write_msg(NULL, "reading dependency data\n");
13981 /* Make sure we are in proper schema */
13982 selectSourceSchema(fout, "pg_catalog");
13984 query = createPQExpBuffer();
13987 * PIN dependencies aren't interesting, and EXTENSION dependencies were
13988 * already processed by getExtensionMembership.
13990 appendPQExpBuffer(query, "SELECT "
13991 "classid, objid, refclassid, refobjid, deptype "
13993 "WHERE deptype != 'p' AND deptype != 'e' "
13996 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13998 ntups = PQntuples(res);
14000 i_classid = PQfnumber(res, "classid");
14001 i_objid = PQfnumber(res, "objid");
14002 i_refclassid = PQfnumber(res, "refclassid");
14003 i_refobjid = PQfnumber(res, "refobjid");
14004 i_deptype = PQfnumber(res, "deptype");
14007 * Since we ordered the SELECT by referencing ID, we can expect that
14008 * multiple entries for the same object will appear together; this saves
14013 for (i = 0; i < ntups; i++)
14016 CatalogId refobjId;
14019 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14020 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14021 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14022 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14023 deptype = *(PQgetvalue(res, i, i_deptype));
14025 if (dobj == NULL ||
14026 dobj->catId.tableoid != objId.tableoid ||
14027 dobj->catId.oid != objId.oid)
14028 dobj = findObjectByCatalogId(objId);
14031 * Failure to find objects mentioned in pg_depend is not unexpected,
14032 * since for example we don't collect info about TOAST tables.
14037 fprintf(stderr, "no referencing object %u %u\n",
14038 objId.tableoid, objId.oid);
14043 refdobj = findObjectByCatalogId(refobjId);
14045 if (refdobj == NULL)
14048 fprintf(stderr, "no referenced object %u %u\n",
14049 refobjId.tableoid, refobjId.oid);
14055 * Ordinarily, table rowtypes have implicit dependencies on their
14056 * tables. However, for a composite type the implicit dependency goes
14057 * the other way in pg_depend; which is the right thing for DROP but
14058 * it doesn't produce the dependency ordering we need. So in that one
14059 * case, we reverse the direction of the dependency.
14061 if (deptype == 'i' &&
14062 dobj->objType == DO_TABLE &&
14063 refdobj->objType == DO_TYPE)
14064 addObjectDependency(refdobj, dobj->dumpId);
14067 addObjectDependency(dobj, refdobj->dumpId);
14072 destroyPQExpBuffer(query);
14077 * selectSourceSchema - make the specified schema the active search path
14078 * in the source database.
14080 * NB: pg_catalog is explicitly searched after the specified schema;
14081 * so user names are only qualified if they are cross-schema references,
14082 * and system names are only qualified if they conflict with a user name
14083 * in the current schema.
14085 * Whenever the selected schema is not pg_catalog, be careful to qualify
14086 * references to system catalogs and types in our emitted commands!
14089 selectSourceSchema(Archive *fout, const char *schemaName)
14091 static char *curSchemaName = NULL;
14094 /* Not relevant if fetching from pre-7.3 DB */
14095 if (fout->remoteVersion < 70300)
14097 /* Ignore null schema names */
14098 if (schemaName == NULL || *schemaName == '\0')
14100 /* Optimize away repeated selection of same schema */
14101 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14104 query = createPQExpBuffer();
14105 appendPQExpBuffer(query, "SET search_path = %s",
14106 fmtId(schemaName));
14107 if (strcmp(schemaName, "pg_catalog") != 0)
14108 appendPQExpBuffer(query, ", pg_catalog");
14110 ExecuteSqlStatement(fout, query->data);
14112 destroyPQExpBuffer(query);
14114 free(curSchemaName);
14115 curSchemaName = pg_strdup(schemaName);
14119 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14122 * NB: in 7.3 and up the result may depend on the currently-selected
14123 * schema; this is why we don't try to cache the names.
14126 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14134 if ((opts & zeroAsOpaque) != 0)
14135 return pg_strdup(g_opaque_type);
14136 else if ((opts & zeroAsAny) != 0)
14137 return pg_strdup("'any'");
14138 else if ((opts & zeroAsStar) != 0)
14139 return pg_strdup("*");
14140 else if ((opts & zeroAsNone) != 0)
14141 return pg_strdup("NONE");
14144 query = createPQExpBuffer();
14145 if (fout->remoteVersion >= 70300)
14147 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14150 else if (fout->remoteVersion >= 70100)
14152 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14157 appendPQExpBuffer(query, "SELECT typname "
14159 "WHERE oid = '%u'::oid",
14163 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14165 if (fout->remoteVersion >= 70100)
14167 /* already quoted */
14168 result = pg_strdup(PQgetvalue(res, 0, 0));
14172 /* may need to quote it */
14173 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14177 destroyPQExpBuffer(query);
14183 * myFormatType --- local implementation of format_type for use with 7.0.
14186 myFormatType(const char *typname, int32 typmod)
14189 bool isarray = false;
14190 PQExpBuffer buf = createPQExpBuffer();
14192 /* Handle array types */
14193 if (typname[0] == '_')
14199 /* Show lengths on bpchar and varchar */
14200 if (strcmp(typname, "bpchar") == 0)
14202 int len = (typmod - VARHDRSZ);
14204 appendPQExpBuffer(buf, "character");
14206 appendPQExpBuffer(buf, "(%d)",
14207 typmod - VARHDRSZ);
14209 else if (strcmp(typname, "varchar") == 0)
14211 appendPQExpBuffer(buf, "character varying");
14213 appendPQExpBuffer(buf, "(%d)",
14214 typmod - VARHDRSZ);
14216 else if (strcmp(typname, "numeric") == 0)
14218 appendPQExpBuffer(buf, "numeric");
14225 tmp_typmod = typmod - VARHDRSZ;
14226 precision = (tmp_typmod >> 16) & 0xffff;
14227 scale = tmp_typmod & 0xffff;
14228 appendPQExpBuffer(buf, "(%d,%d)",
14234 * char is an internal single-byte data type; Let's make sure we force it
14235 * through with quotes. - thomas 1998-12-13
14237 else if (strcmp(typname, "char") == 0)
14238 appendPQExpBuffer(buf, "\"char\"");
14240 appendPQExpBuffer(buf, "%s", fmtId(typname));
14242 /* Append array qualifier for array types */
14244 appendPQExpBuffer(buf, "[]");
14246 result = pg_strdup(buf->data);
14247 destroyPQExpBuffer(buf);
14253 * fmtQualifiedId - convert a qualified name to the proper format for
14254 * the source database.
14256 * Like fmtId, use the result before calling again.
14258 static const char *
14259 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14261 static PQExpBuffer id_return = NULL;
14263 if (id_return) /* first time through? */
14264 resetPQExpBuffer(id_return);
14266 id_return = createPQExpBuffer();
14268 /* Suppress schema name if fetching from pre-7.3 DB */
14269 if (fout->remoteVersion >= 70300 && schema && *schema)
14271 appendPQExpBuffer(id_return, "%s.",
14274 appendPQExpBuffer(id_return, "%s",
14277 return id_return->data;
14281 * Return a column list clause for the given relation.
14283 * Special case: if there are no undropped columns in the relation, return
14284 * "", not an invalid "()" column list.
14286 static const char *
14287 fmtCopyColumnList(const TableInfo *ti)
14289 static PQExpBuffer q = NULL;
14290 int numatts = ti->numatts;
14291 char **attnames = ti->attnames;
14292 bool *attisdropped = ti->attisdropped;
14296 if (q) /* first time through? */
14297 resetPQExpBuffer(q);
14299 q = createPQExpBuffer();
14301 appendPQExpBuffer(q, "(");
14303 for (i = 0; i < numatts; i++)
14305 if (attisdropped[i])
14308 appendPQExpBuffer(q, ", ");
14309 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14314 return ""; /* no undropped columns */
14316 appendPQExpBuffer(q, ")");
14321 * Execute an SQL query and verify that we got exactly one row back.
14324 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14329 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14331 /* Expecting a single result only */
14332 ntups = PQntuples(res);
14334 exit_horribly(NULL,
14335 ngettext("query returned %d row instead of one: %s\n",
14336 "query returned %d rows instead of one: %s\n",