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 /* flags for various command-line long options */
133 static int binary_upgrade = 0;
134 static int disable_dollar_quoting = 0;
135 static int dump_inserts = 0;
136 static int column_inserts = 0;
137 static int no_security_labels = 0;
138 static int no_unlogged_table_data = 0;
139 static int serializable_deferrable = 0;
142 static void help(const char *progname);
143 static void setup_connection(Archive *AH, const char *dumpencoding,
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(Archive *fout,
147 SimpleStringList *patterns,
148 SimpleOidList *oids);
149 static void expand_table_name_patterns(Archive *fout,
150 SimpleStringList *patterns,
151 SimpleOidList *oids);
152 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
153 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
154 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
155 static void dumpComment(Archive *fout, const char *target,
156 const char *namespace, const char *owner,
157 CatalogId catalogId, int subid, DumpId dumpId);
158 static int findComments(Archive *fout, Oid classoid, Oid objoid,
159 CommentItem **items);
160 static int collectComments(Archive *fout, CommentItem **items);
161 static void dumpSecLabel(Archive *fout, const char *target,
162 const char *namespace, const char *owner,
163 CatalogId catalogId, int subid, DumpId dumpId);
164 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
165 SecLabelItem **items);
166 static int collectSecLabels(Archive *fout, SecLabelItem **items);
167 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
168 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
169 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
170 static void dumpType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
175 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
177 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
178 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
179 static void dumpFunc(Archive *fout, FuncInfo *finfo);
180 static void dumpCast(Archive *fout, CastInfo *cast);
181 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *convinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpTable(Archive *fout, TableInfo *tbinfo);
190 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
191 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
192 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
193 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
194 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
195 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
196 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
197 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
198 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
199 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
200 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
201 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
202 static void dumpUserMappings(Archive *fout,
203 const char *servername, const char *namespace,
204 const char *owner, CatalogId catalogId, DumpId dumpId);
205 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
207 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
208 const char *type, const char *name, const char *subname,
209 const char *tag, const char *nspname, const char *owner,
212 static void getDependencies(Archive *fout);
213 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
214 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
215 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
216 static void getTableDataFKConstraints(void);
217 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
218 static char *format_function_arguments_old(Archive *fout,
219 FuncInfo *finfo, int nallargs,
223 static char *format_function_signature(Archive *fout,
224 FuncInfo *finfo, bool honor_quotes);
225 static const char *convertRegProcReference(Archive *fout,
227 static const char *convertOperatorReference(Archive *fout, const char *opr);
228 static const char *convertTSFunction(Archive *fout, Oid funcOid);
229 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
230 static Oid findLastBuiltinOid_V70(Archive *fout);
231 static void selectSourceSchema(Archive *fout, const char *schemaName);
232 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
233 static char *myFormatType(const char *typname, int32 typmod);
234 static const char *fmtQualifiedId(Archive *fout,
235 const char *schema, const char *id);
236 static void getBlobs(Archive *fout);
237 static void dumpBlob(Archive *fout, BlobInfo *binfo);
238 static int dumpBlobs(Archive *fout, void *arg);
239 static void dumpDatabase(Archive *AH);
240 static void dumpEncoding(Archive *AH);
241 static void dumpStdStrings(Archive *AH);
242 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
243 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
244 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
245 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
246 static void binary_upgrade_set_pg_class_oids(Archive *fout,
247 PQExpBuffer upgrade_buffer,
248 Oid pg_class_oid, bool is_index);
249 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
250 DumpableObject *dobj,
251 const char *objlabel);
252 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
253 static const char *fmtCopyColumnList(const TableInfo *ti);
254 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
258 main(int argc, char **argv)
261 const char *filename = NULL;
262 const char *format = "p";
263 const char *dbname = NULL;
264 const char *pghost = NULL;
265 const char *pgport = NULL;
266 const char *username = NULL;
267 const char *dumpencoding = NULL;
271 DumpableObject **dobjs;
274 enum trivalue prompt_password = TRI_DEFAULT;
275 int compressLevel = -1;
278 int outputCreateDB = 0;
279 bool outputBlobs = false;
280 int outputNoOwner = 0;
281 char *outputSuperuser = NULL;
282 char *use_role = NULL;
285 RestoreOptions *ropt;
286 ArchiveFormat archiveFormat = archUnknown;
287 ArchiveMode archiveMode;
288 Archive *fout; /* the script file */
290 static int disable_triggers = 0;
291 static int outputNoTablespaces = 0;
292 static int use_setsessauth = 0;
294 static struct option long_options[] = {
295 {"data-only", no_argument, NULL, 'a'},
296 {"blobs", no_argument, NULL, 'b'},
297 {"clean", no_argument, NULL, 'c'},
298 {"create", no_argument, NULL, 'C'},
299 {"file", required_argument, NULL, 'f'},
300 {"format", required_argument, NULL, 'F'},
301 {"host", required_argument, NULL, 'h'},
302 {"ignore-version", no_argument, NULL, 'i'},
303 {"no-reconnect", no_argument, NULL, 'R'},
304 {"oids", no_argument, NULL, 'o'},
305 {"no-owner", no_argument, NULL, 'O'},
306 {"port", required_argument, NULL, 'p'},
307 {"schema", required_argument, NULL, 'n'},
308 {"exclude-schema", required_argument, NULL, 'N'},
309 {"schema-only", no_argument, NULL, 's'},
310 {"superuser", required_argument, NULL, 'S'},
311 {"table", required_argument, NULL, 't'},
312 {"exclude-table", required_argument, NULL, 'T'},
313 {"no-password", no_argument, NULL, 'w'},
314 {"password", no_argument, NULL, 'W'},
315 {"username", required_argument, NULL, 'U'},
316 {"verbose", no_argument, NULL, 'v'},
317 {"no-privileges", no_argument, NULL, 'x'},
318 {"no-acl", no_argument, NULL, 'x'},
319 {"compress", required_argument, NULL, 'Z'},
320 {"encoding", required_argument, NULL, 'E'},
321 {"help", no_argument, NULL, '?'},
322 {"version", no_argument, NULL, 'V'},
325 * the following options don't have an equivalent short option letter
327 {"attribute-inserts", no_argument, &column_inserts, 1},
328 {"binary-upgrade", no_argument, &binary_upgrade, 1},
329 {"column-inserts", no_argument, &column_inserts, 1},
330 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
331 {"disable-triggers", no_argument, &disable_triggers, 1},
332 {"exclude-table-data", required_argument, NULL, 4},
333 {"inserts", no_argument, &dump_inserts, 1},
334 {"lock-wait-timeout", required_argument, NULL, 2},
335 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
336 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
337 {"role", required_argument, NULL, 3},
338 {"section", required_argument, NULL, 5},
339 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
340 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
341 {"no-security-labels", no_argument, &no_security_labels, 1},
342 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
347 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
351 strcpy(g_comment_start, "-- ");
352 g_comment_end[0] = '\0';
353 strcpy(g_opaque_type, "opaque");
355 dataOnly = schemaOnly = false;
356 dumpSections = DUMP_UNSECTIONED;
357 lockWaitTimeout = NULL;
359 progname = get_progname(argv[0]);
361 /* Set default options based on progname */
362 if (strcmp(progname, "pg_backup") == 0)
367 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
372 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
374 puts("pg_dump (PostgreSQL) " PG_VERSION);
379 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
380 long_options, &optindex)) != -1)
384 case 'a': /* Dump data only */
388 case 'b': /* Dump blobs */
392 case 'c': /* clean (i.e., drop) schema prior to create */
396 case 'C': /* Create DB */
400 case 'E': /* Dump encoding */
401 dumpencoding = optarg;
412 case 'h': /* server host */
417 /* ignored, deprecated option */
420 case 'n': /* include schema(s) */
421 simple_string_list_append(&schema_include_patterns, optarg);
422 include_everything = false;
425 case 'N': /* exclude schema(s) */
426 simple_string_list_append(&schema_exclude_patterns, optarg);
429 case 'o': /* Dump oids */
433 case 'O': /* Don't reconnect to match owner */
437 case 'p': /* server port */
442 /* no-op, still accepted for backwards compatibility */
445 case 's': /* dump schema only */
449 case 'S': /* Username for superuser in plain text output */
450 outputSuperuser = pg_strdup(optarg);
453 case 't': /* include table(s) */
454 simple_string_list_append(&table_include_patterns, optarg);
455 include_everything = false;
458 case 'T': /* exclude table(s) */
459 simple_string_list_append(&table_exclude_patterns, optarg);
466 case 'v': /* verbose */
471 prompt_password = TRI_NO;
475 prompt_password = TRI_YES;
478 case 'x': /* skip ACL dump */
482 case 'Z': /* Compression Level */
483 compressLevel = atoi(optarg);
487 /* This covers the long options. */
490 case 2: /* lock-wait-timeout */
491 lockWaitTimeout = optarg;
494 case 3: /* SET ROLE */
498 case 4: /* exclude table(s) data */
499 simple_string_list_append(&tabledata_exclude_patterns, optarg);
502 case 5: /* section */
503 set_dump_section(optarg, &dumpSections);
507 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
512 /* Get database name from command line */
514 dbname = argv[optind++];
516 /* Complain if any arguments remain */
519 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
520 progname, argv[optind]);
521 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
526 /* --column-inserts implies --inserts */
530 if (dataOnly && schemaOnly)
531 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
533 if (dataOnly && outputClean)
534 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
536 if (dump_inserts && oids)
538 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
539 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
543 /* Identify archive format to emit */
544 archiveFormat = parseArchiveFormat(format, &archiveMode);
546 /* archiveFormat specific setup */
547 if (archiveFormat == archNull)
550 /* Custom and directory formats are compressed by default, others not */
551 if (compressLevel == -1)
553 if (archiveFormat == archCustom || archiveFormat == archDirectory)
554 compressLevel = Z_DEFAULT_COMPRESSION;
559 /* Open the output file */
560 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
562 /* Register the cleanup hook */
563 on_exit_close_archive(fout);
566 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
568 /* Let the archiver know how noisy to be */
569 fout->verbose = g_verbose;
571 my_version = parse_version(PG_VERSION);
573 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
576 * We allow the server to be back to 7.0, and up to any minor release of
577 * our own major version. (See also version check in pg_dumpall.c.)
579 fout->minRemoteVersion = 70000;
580 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
583 * Open the database using the Archiver, so it knows about it. Errors mean
586 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
587 setup_connection(fout, dumpencoding, use_role);
590 * Disable security label support if server version < v9.1.x (prevents
591 * access to nonexistent pg_seclabel catalog)
593 if (fout->remoteVersion < 90100)
594 no_security_labels = 1;
597 * Start transaction-snapshot mode transaction to dump consistent data.
599 ExecuteSqlStatement(fout, "BEGIN");
600 if (fout->remoteVersion >= 90100)
602 if (serializable_deferrable)
603 ExecuteSqlStatement(fout,
604 "SET TRANSACTION ISOLATION LEVEL "
605 "SERIALIZABLE, READ ONLY, DEFERRABLE");
607 ExecuteSqlStatement(fout,
608 "SET TRANSACTION ISOLATION LEVEL "
612 ExecuteSqlStatement(fout,
613 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
615 /* Select the appropriate subquery to convert user IDs to names */
616 if (fout->remoteVersion >= 80100)
617 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
618 else if (fout->remoteVersion >= 70300)
619 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
621 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
623 /* Find the last built-in OID, if needed */
624 if (fout->remoteVersion < 70300)
626 if (fout->remoteVersion >= 70100)
627 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
628 PQdb(GetConnection(fout)));
630 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
632 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
635 /* Expand schema selection patterns into OID lists */
636 if (schema_include_patterns.head != NULL)
638 expand_schema_name_patterns(fout, &schema_include_patterns,
639 &schema_include_oids);
640 if (schema_include_oids.head == NULL)
641 exit_horribly(NULL, "No matching schemas were found\n");
643 expand_schema_name_patterns(fout, &schema_exclude_patterns,
644 &schema_exclude_oids);
645 /* non-matching exclusion patterns aren't an error */
647 /* Expand table selection patterns into OID lists */
648 if (table_include_patterns.head != NULL)
650 expand_table_name_patterns(fout, &table_include_patterns,
651 &table_include_oids);
652 if (table_include_oids.head == NULL)
653 exit_horribly(NULL, "No matching tables were found\n");
655 expand_table_name_patterns(fout, &table_exclude_patterns,
656 &table_exclude_oids);
658 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
659 &tabledata_exclude_oids);
661 /* non-matching exclusion patterns aren't an error */
664 * Dumping blobs is now default unless we saw an inclusion switch or -s
665 * ... but even if we did see one of these, -b turns it back on.
667 if (include_everything && !schemaOnly)
671 * Now scan the database and create DumpableObject structs for all the
672 * objects we intend to dump.
674 tblinfo = getSchemaData(fout, &numTables);
676 if (fout->remoteVersion < 80400)
677 guessConstraintInheritance(tblinfo, numTables);
681 getTableData(tblinfo, numTables, oids);
683 getTableDataFKConstraints();
690 * Collect dependency data to assist in ordering the objects.
692 getDependencies(fout);
695 * Sort the objects into a safe dump order (no forward references).
697 * In 7.3 or later, we can rely on dependency information to help us
698 * determine a safe order, so the initial sort is mostly for cosmetic
699 * purposes: we sort by name to ensure that logically identical schemas
700 * will dump identically. Before 7.3 we don't have dependencies and we
701 * use OID ordering as an (unreliable) guide to creation order.
703 getDumpableObjects(&dobjs, &numObjs);
705 if (fout->remoteVersion >= 70300)
706 sortDumpableObjectsByTypeName(dobjs, numObjs);
708 sortDumpableObjectsByTypeOid(dobjs, numObjs);
710 sortDumpableObjects(dobjs, numObjs);
713 * Create archive TOC entries for all the objects to be dumped, in a safe
717 /* First the special ENCODING and STDSTRINGS entries. */
719 dumpStdStrings(fout);
721 /* The database item is always next, unless we don't want it at all */
722 if (include_everything && !dataOnly)
725 /* Now the rearrangeable objects. */
726 for (i = 0; i < numObjs; i++)
727 dumpDumpableObject(fout, dobjs[i]);
730 * Set up options info to ensure we dump what we want.
732 ropt = NewRestoreOptions();
733 ropt->filename = filename;
734 ropt->dropSchema = outputClean;
735 ropt->dataOnly = dataOnly;
736 ropt->schemaOnly = schemaOnly;
737 ropt->dumpSections = dumpSections;
738 ropt->aclsSkip = aclsSkip;
739 ropt->superuser = outputSuperuser;
740 ropt->createDB = outputCreateDB;
741 ropt->noOwner = outputNoOwner;
742 ropt->noTablespace = outputNoTablespaces;
743 ropt->disable_triggers = disable_triggers;
744 ropt->use_setsessauth = use_setsessauth;
746 if (compressLevel == -1)
747 ropt->compression = 0;
749 ropt->compression = compressLevel;
751 ropt->suppressDumpWarnings = true; /* We've already shown them */
753 SetArchiveRestoreOptions(fout, ropt);
756 * And finally we can do the actual output.
758 * Note: for non-plain-text output formats, the output file is written
759 * inside CloseArchive(). This is, um, bizarre; but not worth changing
763 RestoreArchive(fout);
772 help(const char *progname)
774 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
775 printf(_("Usage:\n"));
776 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
778 printf(_("\nGeneral options:\n"));
779 printf(_(" -f, --file=FILENAME output file or directory name\n"));
780 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
781 " plain text (default))\n"));
782 printf(_(" -v, --verbose verbose mode\n"));
783 printf(_(" -V, --version output version information, then exit\n"));
784 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
785 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
786 printf(_(" -?, --help show this help, then exit\n"));
788 printf(_("\nOptions controlling the output content:\n"));
789 printf(_(" -a, --data-only dump only the data, not the schema\n"));
790 printf(_(" -b, --blobs include large objects in dump\n"));
791 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
792 printf(_(" -C, --create include commands to create database in dump\n"));
793 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
794 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
795 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
796 printf(_(" -o, --oids include OIDs in dump\n"));
797 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
798 " plain-text format\n"));
799 printf(_(" -s, --schema-only dump only the schema, no data\n"));
800 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
801 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
802 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
803 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
804 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
805 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
806 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
807 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
808 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
809 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
810 printf(_(" --no-security-labels do not dump security label assignments\n"));
811 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
812 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
813 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
814 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
815 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
816 printf(_(" --use-set-session-authorization\n"
817 " use SET SESSION AUTHORIZATION commands instead of\n"
818 " ALTER OWNER commands to set ownership\n"));
820 printf(_("\nConnection options:\n"));
821 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
822 printf(_(" -p, --port=PORT database server port number\n"));
823 printf(_(" -U, --username=NAME connect as specified database user\n"));
824 printf(_(" -w, --no-password never prompt for password\n"));
825 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
826 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
828 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
829 "variable value is used.\n\n"));
830 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
834 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
836 PGconn *conn = GetConnection(AH);
837 const char *std_strings;
839 /* Set the client encoding if requested */
842 if (PQsetClientEncoding(conn, dumpencoding) < 0)
843 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
848 * Get the active encoding and the standard_conforming_strings setting, so
849 * we know how to escape strings.
851 AH->encoding = PQclientEncoding(conn);
853 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
854 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
856 /* Set the role if requested */
857 if (use_role && AH->remoteVersion >= 80100)
859 PQExpBuffer query = createPQExpBuffer();
861 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
862 ExecuteSqlStatement(AH, query->data);
863 destroyPQExpBuffer(query);
866 /* Set the datestyle to ISO to ensure the dump's portability */
867 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
869 /* Likewise, avoid using sql_standard intervalstyle */
870 if (AH->remoteVersion >= 80400)
871 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
874 * If supported, set extra_float_digits so that we can dump float data
875 * exactly (given correctly implemented float I/O code, anyway)
877 if (AH->remoteVersion >= 90000)
878 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
879 else if (AH->remoteVersion >= 70400)
880 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
883 * If synchronized scanning is supported, disable it, to prevent
884 * unpredictable changes in row ordering across a dump and reload.
886 if (AH->remoteVersion >= 80300)
887 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
890 * Disable timeouts if supported.
892 if (AH->remoteVersion >= 70300)
893 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
896 * Quote all identifiers, if requested.
898 if (quote_all_identifiers && AH->remoteVersion >= 90100)
899 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
903 parseArchiveFormat(const char *format, ArchiveMode *mode)
905 ArchiveFormat archiveFormat;
907 *mode = archModeWrite;
909 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
911 /* This is used by pg_dumpall, and is not documented */
912 archiveFormat = archNull;
913 *mode = archModeAppend;
915 else if (pg_strcasecmp(format, "c") == 0)
916 archiveFormat = archCustom;
917 else if (pg_strcasecmp(format, "custom") == 0)
918 archiveFormat = archCustom;
919 else if (pg_strcasecmp(format, "d") == 0)
920 archiveFormat = archDirectory;
921 else if (pg_strcasecmp(format, "directory") == 0)
922 archiveFormat = archDirectory;
923 else if (pg_strcasecmp(format, "p") == 0)
924 archiveFormat = archNull;
925 else if (pg_strcasecmp(format, "plain") == 0)
926 archiveFormat = archNull;
927 else if (pg_strcasecmp(format, "t") == 0)
928 archiveFormat = archTar;
929 else if (pg_strcasecmp(format, "tar") == 0)
930 archiveFormat = archTar;
932 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
933 return archiveFormat;
937 * Find the OIDs of all schemas matching the given list of patterns,
938 * and append them to the given OID list.
941 expand_schema_name_patterns(Archive *fout,
942 SimpleStringList *patterns,
947 SimpleStringListCell *cell;
950 if (patterns->head == NULL)
951 return; /* nothing to do */
953 if (fout->remoteVersion < 70300)
954 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
956 query = createPQExpBuffer();
959 * We use UNION ALL rather than UNION; this might sometimes result in
960 * duplicate entries in the OID list, but we don't care.
963 for (cell = patterns->head; cell; cell = cell->next)
965 if (cell != patterns->head)
966 appendPQExpBuffer(query, "UNION ALL\n");
967 appendPQExpBuffer(query,
968 "SELECT oid FROM pg_catalog.pg_namespace n\n");
969 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
970 false, NULL, "n.nspname", NULL, NULL);
973 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
975 for (i = 0; i < PQntuples(res); i++)
977 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
981 destroyPQExpBuffer(query);
985 * Find the OIDs of all tables matching the given list of patterns,
986 * and append them to the given OID list.
989 expand_table_name_patterns(Archive *fout,
990 SimpleStringList *patterns, SimpleOidList *oids)
994 SimpleStringListCell *cell;
997 if (patterns->head == NULL)
998 return; /* nothing to do */
1000 query = createPQExpBuffer();
1003 * We use UNION ALL rather than UNION; this might sometimes result in
1004 * duplicate entries in the OID list, but we don't care.
1007 for (cell = patterns->head; cell; cell = cell->next)
1009 if (cell != patterns->head)
1010 appendPQExpBuffer(query, "UNION ALL\n");
1011 appendPQExpBuffer(query,
1013 "\nFROM pg_catalog.pg_class c"
1014 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1015 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1016 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1017 RELKIND_FOREIGN_TABLE);
1018 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1019 false, "n.nspname", "c.relname", NULL,
1020 "pg_catalog.pg_table_is_visible(c.oid)");
1023 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1025 for (i = 0; i < PQntuples(res); i++)
1027 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1031 destroyPQExpBuffer(query);
1035 * selectDumpableNamespace: policy-setting subroutine
1036 * Mark a namespace as to be dumped or not
1039 selectDumpableNamespace(NamespaceInfo *nsinfo)
1042 * If specific tables are being dumped, do not dump any complete
1043 * namespaces. If specific namespaces are being dumped, dump just those
1044 * namespaces. Otherwise, dump all non-system namespaces.
1046 if (table_include_oids.head != NULL)
1047 nsinfo->dobj.dump = false;
1048 else if (schema_include_oids.head != NULL)
1049 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1050 nsinfo->dobj.catId.oid);
1051 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1052 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1053 nsinfo->dobj.dump = false;
1055 nsinfo->dobj.dump = true;
1058 * In any case, a namespace can be excluded by an exclusion switch
1060 if (nsinfo->dobj.dump &&
1061 simple_oid_list_member(&schema_exclude_oids,
1062 nsinfo->dobj.catId.oid))
1063 nsinfo->dobj.dump = false;
1067 * selectDumpableTable: policy-setting subroutine
1068 * Mark a table as to be dumped or not
1071 selectDumpableTable(TableInfo *tbinfo)
1074 * If specific tables are being dumped, dump just those tables; else, dump
1075 * according to the parent namespace's dump flag.
1077 if (table_include_oids.head != NULL)
1078 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1079 tbinfo->dobj.catId.oid);
1081 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1084 * In any case, a table can be excluded by an exclusion switch
1086 if (tbinfo->dobj.dump &&
1087 simple_oid_list_member(&table_exclude_oids,
1088 tbinfo->dobj.catId.oid))
1089 tbinfo->dobj.dump = false;
1093 * selectDumpableType: policy-setting subroutine
1094 * Mark a type as to be dumped or not
1096 * If it's a table's rowtype or an autogenerated array type, we also apply a
1097 * special type code to facilitate sorting into the desired order. (We don't
1098 * want to consider those to be ordinary types because that would bring tables
1099 * up into the datatype part of the dump order.) We still set the object's
1100 * dump flag; that's not going to cause the dummy type to be dumped, but we
1101 * need it so that casts involving such types will be dumped correctly -- see
1102 * dumpCast. This means the flag should be set the same as for the underlying
1103 * object (the table or base type).
1106 selectDumpableType(TypeInfo *tyinfo)
1108 /* skip complex types, except for standalone composite types */
1109 if (OidIsValid(tyinfo->typrelid) &&
1110 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1112 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1114 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1115 if (tytable != NULL)
1116 tyinfo->dobj.dump = tytable->dobj.dump;
1118 tyinfo->dobj.dump = false;
1122 /* skip auto-generated array types */
1123 if (tyinfo->isArray)
1125 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1128 * Fall through to set the dump flag; we assume that the subsequent
1129 * rules will do the same thing as they would for the array's base
1130 * type. (We cannot reliably look up the base type here, since
1131 * getTypes may not have processed it yet.)
1135 /* dump only types in dumpable namespaces */
1136 if (!tyinfo->dobj.namespace->dobj.dump)
1137 tyinfo->dobj.dump = false;
1139 /* skip undefined placeholder types */
1140 else if (!tyinfo->isDefined)
1141 tyinfo->dobj.dump = false;
1144 tyinfo->dobj.dump = true;
1148 * selectDumpableDefaultACL: policy-setting subroutine
1149 * Mark a default ACL as to be dumped or not
1151 * For per-schema default ACLs, dump if the schema is to be dumped.
1152 * Otherwise dump if we are dumping "everything". Note that dataOnly
1153 * and aclsSkip are checked separately.
1156 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1158 if (dinfo->dobj.namespace)
1159 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1161 dinfo->dobj.dump = include_everything;
1165 * selectDumpableExtension: policy-setting subroutine
1166 * Mark an extension as to be dumped or not
1168 * Normally, we dump all extensions, or none of them if include_everything
1169 * is false (i.e., a --schema or --table switch was given). However, in
1170 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1171 * assume those will already be installed in the target database. We identify
1172 * such extensions by their having OIDs in the range reserved for initdb.
1175 selectDumpableExtension(ExtensionInfo *extinfo)
1177 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1178 extinfo->dobj.dump = false;
1180 extinfo->dobj.dump = include_everything;
1184 * selectDumpableObject: policy-setting subroutine
1185 * Mark a generic dumpable object as to be dumped or not
1187 * Use this only for object types without a special-case routine above.
1190 selectDumpableObject(DumpableObject *dobj)
1193 * Default policy is to dump if parent namespace is dumpable, or always
1194 * for non-namespace-associated items.
1196 if (dobj->namespace)
1197 dobj->dump = dobj->namespace->dobj.dump;
1203 * Dump a table's contents for loading using the COPY command
1204 * - this routine is called by the Archiver when it wants the table
1209 dumpTableData_copy(Archive *fout, void *dcontext)
1211 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1212 TableInfo *tbinfo = tdinfo->tdtable;
1213 const char *classname = tbinfo->dobj.name;
1214 const bool hasoids = tbinfo->hasoids;
1215 const bool oids = tdinfo->oids;
1216 PQExpBuffer q = createPQExpBuffer();
1217 PGconn *conn = GetConnection(fout);
1221 const char *column_list;
1224 write_msg(NULL, "dumping contents of table %s\n", classname);
1227 * Make sure we are in proper schema. We will qualify the table name
1228 * below anyway (in case its name conflicts with a pg_catalog table); but
1229 * this ensures reproducible results in case the table contains regproc,
1230 * regclass, etc columns.
1232 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1235 * If possible, specify the column list explicitly so that we have no
1236 * possibility of retrieving data in the wrong column order. (The default
1237 * column ordering of COPY will not be what we want in certain corner
1238 * cases involving ADD COLUMN and inheritance.)
1240 if (fout->remoteVersion >= 70300)
1241 column_list = fmtCopyColumnList(tbinfo);
1243 column_list = ""; /* can't select columns in COPY */
1245 if (oids && hasoids)
1247 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1248 fmtQualifiedId(fout,
1249 tbinfo->dobj.namespace->dobj.name,
1253 else if (tdinfo->filtercond)
1255 /* Note: this syntax is only supported in 8.2 and up */
1256 appendPQExpBufferStr(q, "COPY (SELECT ");
1257 /* klugery to get rid of parens in column list */
1258 if (strlen(column_list) > 2)
1260 appendPQExpBufferStr(q, column_list + 1);
1261 q->data[q->len - 1] = ' ';
1264 appendPQExpBufferStr(q, "* ");
1265 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1266 fmtQualifiedId(fout,
1267 tbinfo->dobj.namespace->dobj.name,
1269 tdinfo->filtercond);
1273 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1274 fmtQualifiedId(fout,
1275 tbinfo->dobj.namespace->dobj.name,
1279 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1284 ret = PQgetCopyData(conn, ©buf, 0);
1287 break; /* done or error */
1291 WriteData(fout, copybuf, ret);
1298 * There was considerable discussion in late July, 2000 regarding
1299 * slowing down pg_dump when backing up large tables. Users with both
1300 * slow & fast (multi-processor) machines experienced performance
1301 * degradation when doing a backup.
1303 * Initial attempts based on sleeping for a number of ms for each ms
1304 * of work were deemed too complex, then a simple 'sleep in each loop'
1305 * implementation was suggested. The latter failed because the loop
1306 * was too tight. Finally, the following was implemented:
1308 * If throttle is non-zero, then
1309 * See how long since the last sleep.
1310 * Work out how long to sleep (based on ratio).
1311 * If sleep is more than 100ms, then
1317 * where the throttle value was the number of ms to sleep per ms of
1318 * work. The calculation was done in each loop.
1320 * Most of the hard work is done in the backend, and this solution
1321 * still did not work particularly well: on slow machines, the ratio
1322 * was 50:1, and on medium paced machines, 1:1, and on fast
1323 * multi-processor machines, it had little or no effect, for reasons
1324 * that were unclear.
1326 * Further discussion ensued, and the proposal was dropped.
1328 * For those people who want this feature, it can be implemented using
1329 * gettimeofday in each loop, calculating the time since last sleep,
1330 * multiplying that by the sleep ratio, then if the result is more
1331 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1332 * function to sleep for a subsecond period ie.
1334 * select(0, NULL, NULL, NULL, &tvi);
1336 * This will return after the interval specified in the structure tvi.
1337 * Finally, call gettimeofday again to save the 'last sleep time'.
1341 archprintf(fout, "\\.\n\n\n");
1345 /* copy data transfer failed */
1346 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1347 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1348 write_msg(NULL, "The command was: %s\n", q->data);
1352 /* Check command status and return to normal libpq state */
1353 res = PQgetResult(conn);
1354 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1356 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1357 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1358 write_msg(NULL, "The command was: %s\n", q->data);
1363 destroyPQExpBuffer(q);
1368 * Dump table data using INSERT commands.
1370 * Caution: when we restore from an archive file direct to database, the
1371 * INSERT commands emitted by this function have to be parsed by
1372 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1373 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1376 dumpTableData_insert(Archive *fout, void *dcontext)
1378 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1379 TableInfo *tbinfo = tdinfo->tdtable;
1380 const char *classname = tbinfo->dobj.name;
1381 PQExpBuffer q = createPQExpBuffer();
1388 * Make sure we are in proper schema. We will qualify the table name
1389 * below anyway (in case its name conflicts with a pg_catalog table); but
1390 * this ensures reproducible results in case the table contains regproc,
1391 * regclass, etc columns.
1393 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1395 if (fout->remoteVersion >= 70100)
1397 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1398 "SELECT * FROM ONLY %s",
1399 fmtQualifiedId(fout,
1400 tbinfo->dobj.namespace->dobj.name,
1405 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1407 fmtQualifiedId(fout,
1408 tbinfo->dobj.namespace->dobj.name,
1411 if (tdinfo->filtercond)
1412 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1414 ExecuteSqlStatement(fout, q->data);
1418 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1420 nfields = PQnfields(res);
1421 for (tuple = 0; tuple < PQntuples(res); tuple++)
1423 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1426 /* corner case for zero-column table */
1427 archprintf(fout, "DEFAULT VALUES;\n");
1432 resetPQExpBuffer(q);
1433 appendPQExpBuffer(q, "(");
1434 for (field = 0; field < nfields; field++)
1437 appendPQExpBuffer(q, ", ");
1438 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1440 appendPQExpBuffer(q, ") ");
1441 archputs(q->data, fout);
1443 archprintf(fout, "VALUES (");
1444 for (field = 0; field < nfields; field++)
1447 archprintf(fout, ", ");
1448 if (PQgetisnull(res, tuple, field))
1450 archprintf(fout, "NULL");
1454 /* XXX This code is partially duplicated in ruleutils.c */
1455 switch (PQftype(res, field))
1466 * These types are printed without quotes unless
1467 * they contain values that aren't accepted by the
1468 * scanner unquoted (e.g., 'NaN'). Note that
1469 * strtod() and friends might accept NaN, so we
1470 * can't use that to test.
1472 * In reality we only need to defend against
1473 * infinity and NaN, so we need not get too crazy
1474 * about pattern matching here.
1476 const char *s = PQgetvalue(res, tuple, field);
1478 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1479 archprintf(fout, "%s", s);
1481 archprintf(fout, "'%s'", s);
1487 archprintf(fout, "B'%s'",
1488 PQgetvalue(res, tuple, field));
1492 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1493 archprintf(fout, "true");
1495 archprintf(fout, "false");
1499 /* All other types are printed as string literals. */
1500 resetPQExpBuffer(q);
1501 appendStringLiteralAH(q,
1502 PQgetvalue(res, tuple, field),
1504 archputs(q->data, fout);
1508 archprintf(fout, ");\n");
1511 if (PQntuples(res) <= 0)
1519 archprintf(fout, "\n\n");
1521 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1523 destroyPQExpBuffer(q);
1530 * dump the contents of a single table
1532 * Actually, this just makes an ArchiveEntry for the table contents.
1535 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1537 TableInfo *tbinfo = tdinfo->tdtable;
1538 PQExpBuffer copyBuf = createPQExpBuffer();
1539 DataDumperPtr dumpFn;
1544 /* Dump/restore using COPY */
1545 dumpFn = dumpTableData_copy;
1546 /* must use 2 steps here 'cause fmtId is nonreentrant */
1547 appendPQExpBuffer(copyBuf, "COPY %s ",
1548 fmtId(tbinfo->dobj.name));
1549 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1550 fmtCopyColumnList(tbinfo),
1551 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1552 copyStmt = copyBuf->data;
1556 /* Restore using INSERT */
1557 dumpFn = dumpTableData_insert;
1561 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1562 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1563 NULL, tbinfo->rolname,
1564 false, "TABLE DATA", SECTION_DATA,
1566 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1569 destroyPQExpBuffer(copyBuf);
1574 * set up dumpable objects representing the contents of tables
1577 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1581 for (i = 0; i < numTables; i++)
1583 if (tblinfo[i].dobj.dump)
1584 makeTableDataInfo(&(tblinfo[i]), oids);
1589 * Make a dumpable object for the data of this specific table
1591 * Note: we make a TableDataInfo if and only if we are going to dump the
1592 * table data; the "dump" flag in such objects isn't used.
1595 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1597 TableDataInfo *tdinfo;
1600 * Nothing to do if we already decided to dump the table. This will
1601 * happen for "config" tables.
1603 if (tbinfo->dataObj != NULL)
1606 /* Skip VIEWs (no data to dump) */
1607 if (tbinfo->relkind == RELKIND_VIEW)
1609 /* Skip SEQUENCEs (handled elsewhere) */
1610 if (tbinfo->relkind == RELKIND_SEQUENCE)
1612 /* Skip FOREIGN TABLEs (no data to dump) */
1613 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1616 /* Don't dump data in unlogged tables, if so requested */
1617 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1618 no_unlogged_table_data)
1621 /* Check that the data is not explicitly excluded */
1622 if (simple_oid_list_member(&tabledata_exclude_oids,
1623 tbinfo->dobj.catId.oid))
1626 /* OK, let's dump it */
1627 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1629 tdinfo->dobj.objType = DO_TABLE_DATA;
1632 * Note: use tableoid 0 so that this object won't be mistaken for
1633 * something that pg_depend entries apply to.
1635 tdinfo->dobj.catId.tableoid = 0;
1636 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1637 AssignDumpId(&tdinfo->dobj);
1638 tdinfo->dobj.name = tbinfo->dobj.name;
1639 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1640 tdinfo->tdtable = tbinfo;
1641 tdinfo->oids = oids;
1642 tdinfo->filtercond = NULL; /* might get set later */
1643 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1645 tbinfo->dataObj = tdinfo;
1649 * getTableDataFKConstraints -
1650 * add dump-order dependencies reflecting foreign key constraints
1652 * This code is executed only in a data-only dump --- in schema+data dumps
1653 * we handle foreign key issues by not creating the FK constraints until
1654 * after the data is loaded. In a data-only dump, however, we want to
1655 * order the table data objects in such a way that a table's referenced
1656 * tables are restored first. (In the presence of circular references or
1657 * self-references this may be impossible; we'll detect and complain about
1658 * that during the dependency sorting step.)
1661 getTableDataFKConstraints(void)
1663 DumpableObject **dobjs;
1667 /* Search through all the dumpable objects for FK constraints */
1668 getDumpableObjects(&dobjs, &numObjs);
1669 for (i = 0; i < numObjs; i++)
1671 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1673 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1676 /* Not interesting unless both tables are to be dumped */
1677 if (cinfo->contable == NULL ||
1678 cinfo->contable->dataObj == NULL)
1680 ftable = findTableByOid(cinfo->confrelid);
1681 if (ftable == NULL ||
1682 ftable->dataObj == NULL)
1686 * Okay, make referencing table's TABLE_DATA object depend on the
1687 * referenced table's TABLE_DATA object.
1689 addObjectDependency(&cinfo->contable->dataObj->dobj,
1690 ftable->dataObj->dobj.dumpId);
1698 * guessConstraintInheritance:
1699 * In pre-8.4 databases, we can't tell for certain which constraints
1700 * are inherited. We assume a CHECK constraint is inherited if its name
1701 * matches the name of any constraint in the parent. Originally this code
1702 * tried to compare the expression texts, but that can fail for various
1703 * reasons --- for example, if the parent and child tables are in different
1704 * schemas, reverse-listing of function calls may produce different text
1705 * (schema-qualified or not) depending on search path.
1707 * In 8.4 and up we can rely on the conislocal field to decide which
1708 * constraints must be dumped; much safer.
1710 * This function assumes all conislocal flags were initialized to TRUE.
1711 * It clears the flag on anything that seems to be inherited.
1714 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1720 for (i = 0; i < numTables; i++)
1722 TableInfo *tbinfo = &(tblinfo[i]);
1724 TableInfo **parents;
1727 /* Sequences and views never have parents */
1728 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1729 tbinfo->relkind == RELKIND_VIEW)
1732 /* Don't bother computing anything for non-target tables, either */
1733 if (!tbinfo->dobj.dump)
1736 numParents = tbinfo->numParents;
1737 parents = tbinfo->parents;
1739 if (numParents == 0)
1740 continue; /* nothing to see here, move along */
1742 /* scan for inherited CHECK constraints */
1743 for (j = 0; j < tbinfo->ncheck; j++)
1745 ConstraintInfo *constr;
1747 constr = &(tbinfo->checkexprs[j]);
1749 for (k = 0; k < numParents; k++)
1753 parent = parents[k];
1754 for (l = 0; l < parent->ncheck; l++)
1756 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1758 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1760 constr->conislocal = false;
1764 if (!constr->conislocal)
1774 * dump the database definition
1777 dumpDatabase(Archive *fout)
1779 PQExpBuffer dbQry = createPQExpBuffer();
1780 PQExpBuffer delQry = createPQExpBuffer();
1781 PQExpBuffer creaQry = createPQExpBuffer();
1782 PGconn *conn = GetConnection(fout);
1794 const char *datname,
1802 datname = PQdb(conn);
1805 write_msg(NULL, "saving database definition\n");
1807 /* Make sure we are in proper schema */
1808 selectSourceSchema(fout, "pg_catalog");
1810 /* Get the database owner and parameters from pg_database */
1811 if (fout->remoteVersion >= 80400)
1813 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1814 "(%s datdba) AS dba, "
1815 "pg_encoding_to_char(encoding) AS encoding, "
1816 "datcollate, datctype, datfrozenxid, "
1817 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1818 "shobj_description(oid, 'pg_database') AS description "
1823 appendStringLiteralAH(dbQry, datname, fout);
1825 else if (fout->remoteVersion >= 80200)
1827 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1828 "(%s datdba) AS dba, "
1829 "pg_encoding_to_char(encoding) AS encoding, "
1830 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1831 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1832 "shobj_description(oid, 'pg_database') AS description "
1837 appendStringLiteralAH(dbQry, datname, fout);
1839 else if (fout->remoteVersion >= 80000)
1841 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1842 "(%s datdba) AS dba, "
1843 "pg_encoding_to_char(encoding) AS encoding, "
1844 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1845 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1849 appendStringLiteralAH(dbQry, datname, fout);
1851 else if (fout->remoteVersion >= 70100)
1853 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1854 "(%s datdba) AS dba, "
1855 "pg_encoding_to_char(encoding) AS encoding, "
1856 "NULL AS datcollate, NULL AS datctype, "
1857 "0 AS datfrozenxid, "
1858 "NULL AS tablespace "
1862 appendStringLiteralAH(dbQry, datname, fout);
1866 appendPQExpBuffer(dbQry, "SELECT "
1867 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1869 "(%s datdba) AS dba, "
1870 "pg_encoding_to_char(encoding) AS encoding, "
1871 "NULL AS datcollate, NULL AS datctype, "
1872 "0 AS datfrozenxid, "
1873 "NULL AS tablespace "
1877 appendStringLiteralAH(dbQry, datname, fout);
1880 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1882 i_tableoid = PQfnumber(res, "tableoid");
1883 i_oid = PQfnumber(res, "oid");
1884 i_dba = PQfnumber(res, "dba");
1885 i_encoding = PQfnumber(res, "encoding");
1886 i_collate = PQfnumber(res, "datcollate");
1887 i_ctype = PQfnumber(res, "datctype");
1888 i_frozenxid = PQfnumber(res, "datfrozenxid");
1889 i_tablespace = PQfnumber(res, "tablespace");
1891 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1892 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1893 dba = PQgetvalue(res, 0, i_dba);
1894 encoding = PQgetvalue(res, 0, i_encoding);
1895 collate = PQgetvalue(res, 0, i_collate);
1896 ctype = PQgetvalue(res, 0, i_ctype);
1897 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1898 tablespace = PQgetvalue(res, 0, i_tablespace);
1900 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1902 if (strlen(encoding) > 0)
1904 appendPQExpBuffer(creaQry, " ENCODING = ");
1905 appendStringLiteralAH(creaQry, encoding, fout);
1907 if (strlen(collate) > 0)
1909 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1910 appendStringLiteralAH(creaQry, collate, fout);
1912 if (strlen(ctype) > 0)
1914 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1915 appendStringLiteralAH(creaQry, ctype, fout);
1917 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1918 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1920 appendPQExpBuffer(creaQry, ";\n");
1924 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1925 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1926 "SET datfrozenxid = '%u'\n"
1929 appendStringLiteralAH(creaQry, datname, fout);
1930 appendPQExpBuffer(creaQry, ";\n");
1934 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1937 dbDumpId = createDumpId();
1940 dbCatId, /* catalog ID */
1941 dbDumpId, /* dump ID */
1943 NULL, /* Namespace */
1944 NULL, /* Tablespace */
1946 false, /* with oids */
1947 "DATABASE", /* Desc */
1948 SECTION_PRE_DATA, /* Section */
1949 creaQry->data, /* Create */
1950 delQry->data, /* Del */
1955 NULL); /* Dumper Arg */
1958 * pg_largeobject and pg_largeobject_metadata come from the old system
1959 * intact, so set their relfrozenxids.
1964 PQExpBuffer loFrozenQry = createPQExpBuffer();
1965 PQExpBuffer loOutQry = createPQExpBuffer();
1971 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1972 "FROM pg_catalog.pg_class\n"
1973 "WHERE oid = %u;\n",
1974 LargeObjectRelationId);
1976 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1978 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1980 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
1981 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1982 "SET relfrozenxid = '%u'\n"
1983 "WHERE oid = %u;\n",
1984 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1985 LargeObjectRelationId);
1986 ArchiveEntry(fout, nilCatalogId, createDumpId(),
1987 "pg_largeobject", NULL, NULL, "",
1988 false, "pg_largeobject", SECTION_PRE_DATA,
1989 loOutQry->data, "", NULL,
1996 * pg_largeobject_metadata
1998 if (fout->remoteVersion >= 90000)
2000 resetPQExpBuffer(loFrozenQry);
2001 resetPQExpBuffer(loOutQry);
2003 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2004 "FROM pg_catalog.pg_class\n"
2005 "WHERE oid = %u;\n",
2006 LargeObjectMetadataRelationId);
2008 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2010 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2012 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2013 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2014 "SET relfrozenxid = '%u'\n"
2015 "WHERE oid = %u;\n",
2016 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2017 LargeObjectMetadataRelationId);
2018 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2019 "pg_largeobject_metadata", NULL, NULL, "",
2020 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2021 loOutQry->data, "", NULL,
2028 destroyPQExpBuffer(loFrozenQry);
2029 destroyPQExpBuffer(loOutQry);
2032 /* Dump DB comment if any */
2033 if (fout->remoteVersion >= 80200)
2036 * 8.2 keeps comments on shared objects in a shared table, so we
2037 * cannot use the dumpComment used for other database objects.
2039 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2041 if (comment && strlen(comment))
2043 resetPQExpBuffer(dbQry);
2046 * Generates warning when loaded into a differently-named
2049 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2050 appendStringLiteralAH(dbQry, comment, fout);
2051 appendPQExpBuffer(dbQry, ";\n");
2053 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2054 dba, false, "COMMENT", SECTION_NONE,
2055 dbQry->data, "", NULL,
2056 &dbDumpId, 1, NULL, NULL);
2061 resetPQExpBuffer(dbQry);
2062 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2063 dumpComment(fout, dbQry->data, NULL, "",
2064 dbCatId, 0, dbDumpId);
2069 /* Dump shared security label. */
2070 if (!no_security_labels && fout->remoteVersion >= 90200)
2072 PQExpBuffer seclabelQry = createPQExpBuffer();
2074 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2075 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2076 resetPQExpBuffer(seclabelQry);
2077 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2078 if (strlen(seclabelQry->data))
2079 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2080 dba, false, "SECURITY LABEL", SECTION_NONE,
2081 seclabelQry->data, "", NULL,
2082 &dbDumpId, 1, NULL, NULL);
2083 destroyPQExpBuffer(seclabelQry);
2086 destroyPQExpBuffer(dbQry);
2087 destroyPQExpBuffer(delQry);
2088 destroyPQExpBuffer(creaQry);
2093 * dumpEncoding: put the correct encoding into the archive
2096 dumpEncoding(Archive *AH)
2098 const char *encname = pg_encoding_to_char(AH->encoding);
2099 PQExpBuffer qry = createPQExpBuffer();
2102 write_msg(NULL, "saving encoding = %s\n", encname);
2104 appendPQExpBuffer(qry, "SET client_encoding = ");
2105 appendStringLiteralAH(qry, encname, AH);
2106 appendPQExpBuffer(qry, ";\n");
2108 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2109 "ENCODING", NULL, NULL, "",
2110 false, "ENCODING", SECTION_PRE_DATA,
2111 qry->data, "", NULL,
2115 destroyPQExpBuffer(qry);
2120 * dumpStdStrings: put the correct escape string behavior into the archive
2123 dumpStdStrings(Archive *AH)
2125 const char *stdstrings = AH->std_strings ? "on" : "off";
2126 PQExpBuffer qry = createPQExpBuffer();
2129 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2132 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2135 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2136 "STDSTRINGS", NULL, NULL, "",
2137 false, "STDSTRINGS", SECTION_PRE_DATA,
2138 qry->data, "", NULL,
2142 destroyPQExpBuffer(qry);
2148 * Collect schema-level data about large objects
2151 getBlobs(Archive *fout)
2153 PQExpBuffer blobQry = createPQExpBuffer();
2155 DumpableObject *bdata;
2160 /* Verbose message */
2162 write_msg(NULL, "reading large objects\n");
2164 /* Make sure we are in proper schema */
2165 selectSourceSchema(fout, "pg_catalog");
2167 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2168 if (fout->remoteVersion >= 90000)
2169 appendPQExpBuffer(blobQry,
2170 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2171 " FROM pg_largeobject_metadata",
2173 else if (fout->remoteVersion >= 70100)
2174 appendPQExpBuffer(blobQry,
2175 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2176 " FROM pg_largeobject");
2178 appendPQExpBuffer(blobQry,
2179 "SELECT oid, NULL::oid, NULL::oid"
2180 " FROM pg_class WHERE relkind = 'l'");
2182 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2184 ntups = PQntuples(res);
2188 * Each large object has its own BLOB archive entry.
2190 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2192 for (i = 0; i < ntups; i++)
2194 binfo[i].dobj.objType = DO_BLOB;
2195 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2196 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2197 AssignDumpId(&binfo[i].dobj);
2199 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2200 if (!PQgetisnull(res, i, 1))
2201 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2203 binfo[i].rolname = "";
2204 if (!PQgetisnull(res, i, 2))
2205 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2207 binfo[i].blobacl = NULL;
2211 * If we have any large objects, a "BLOBS" archive entry is needed.
2212 * This is just a placeholder for sorting; it carries no data now.
2214 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2215 bdata->objType = DO_BLOB_DATA;
2216 bdata->catId = nilCatalogId;
2217 AssignDumpId(bdata);
2218 bdata->name = pg_strdup("BLOBS");
2222 destroyPQExpBuffer(blobQry);
2228 * dump the definition (metadata) of the given large object
2231 dumpBlob(Archive *fout, BlobInfo *binfo)
2233 PQExpBuffer cquery = createPQExpBuffer();
2234 PQExpBuffer dquery = createPQExpBuffer();
2236 appendPQExpBuffer(cquery,
2237 "SELECT pg_catalog.lo_create('%s');\n",
2240 appendPQExpBuffer(dquery,
2241 "SELECT pg_catalog.lo_unlink('%s');\n",
2244 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2247 binfo->rolname, false,
2248 "BLOB", SECTION_PRE_DATA,
2249 cquery->data, dquery->data, NULL,
2250 binfo->dobj.dependencies, binfo->dobj.nDeps,
2253 /* set up tag for comment and/or ACL */
2254 resetPQExpBuffer(cquery);
2255 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2257 /* Dump comment if any */
2258 dumpComment(fout, cquery->data,
2259 NULL, binfo->rolname,
2260 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2262 /* Dump security label if any */
2263 dumpSecLabel(fout, cquery->data,
2264 NULL, binfo->rolname,
2265 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2267 /* Dump ACL if any */
2269 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2270 binfo->dobj.name, NULL, cquery->data,
2271 NULL, binfo->rolname, binfo->blobacl);
2273 destroyPQExpBuffer(cquery);
2274 destroyPQExpBuffer(dquery);
2279 * dump the data contents of all large objects
2282 dumpBlobs(Archive *fout, void *arg)
2284 const char *blobQry;
2285 const char *blobFetchQry;
2286 PGconn *conn = GetConnection(fout);
2288 char buf[LOBBUFSIZE];
2294 write_msg(NULL, "saving large objects\n");
2296 /* Make sure we are in proper schema */
2297 selectSourceSchema(fout, "pg_catalog");
2300 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2301 * the already-in-memory dumpable objects instead...
2303 if (fout->remoteVersion >= 90000)
2304 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2305 else if (fout->remoteVersion >= 70100)
2306 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2308 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2310 ExecuteSqlStatement(fout, blobQry);
2312 /* Command to fetch from cursor */
2313 blobFetchQry = "FETCH 1000 IN bloboid";
2318 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2320 /* Process the tuples, if any */
2321 ntups = PQntuples(res);
2322 for (i = 0; i < ntups; i++)
2327 blobOid = atooid(PQgetvalue(res, i, 0));
2329 loFd = lo_open(conn, blobOid, INV_READ);
2331 exit_horribly(NULL, "could not open large object %u: %s",
2332 blobOid, PQerrorMessage(conn));
2334 StartBlob(fout, blobOid);
2336 /* Now read it in chunks, sending data to archive */
2339 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2341 exit_horribly(NULL, "error reading large object %u: %s",
2342 blobOid, PQerrorMessage(conn));
2344 WriteData(fout, buf, cnt);
2347 lo_close(conn, loFd);
2349 EndBlob(fout, blobOid);
2353 } while (ntups > 0);
2359 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2360 PQExpBuffer upgrade_buffer,
2363 PQExpBuffer upgrade_query = createPQExpBuffer();
2364 PGresult *upgrade_res;
2365 Oid pg_type_array_oid;
2367 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2368 appendPQExpBuffer(upgrade_buffer,
2369 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2372 /* we only support old >= 8.3 for binary upgrades */
2373 appendPQExpBuffer(upgrade_query,
2375 "FROM pg_catalog.pg_type "
2376 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2379 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2381 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2383 if (OidIsValid(pg_type_array_oid))
2385 appendPQExpBuffer(upgrade_buffer,
2386 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2387 appendPQExpBuffer(upgrade_buffer,
2388 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2392 PQclear(upgrade_res);
2393 destroyPQExpBuffer(upgrade_query);
2397 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2398 PQExpBuffer upgrade_buffer,
2401 PQExpBuffer upgrade_query = createPQExpBuffer();
2402 PGresult *upgrade_res;
2404 bool toast_set = false;
2406 /* we only support old >= 8.3 for binary upgrades */
2407 appendPQExpBuffer(upgrade_query,
2408 "SELECT c.reltype AS crel, t.reltype AS trel "
2409 "FROM pg_catalog.pg_class c "
2410 "LEFT JOIN pg_catalog.pg_class t ON "
2411 " (c.reltoastrelid = t.oid) "
2412 "WHERE c.oid = '%u'::pg_catalog.oid;",
2415 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2417 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2419 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2422 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2424 /* Toast tables do not have pg_type array rows */
2425 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2426 PQfnumber(upgrade_res, "trel")));
2428 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2429 appendPQExpBuffer(upgrade_buffer,
2430 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2436 PQclear(upgrade_res);
2437 destroyPQExpBuffer(upgrade_query);
2443 binary_upgrade_set_pg_class_oids(Archive *fout,
2444 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2447 PQExpBuffer upgrade_query = createPQExpBuffer();
2448 PGresult *upgrade_res;
2449 Oid pg_class_reltoastrelid;
2450 Oid pg_class_reltoastidxid;
2452 appendPQExpBuffer(upgrade_query,
2453 "SELECT c.reltoastrelid, t.reltoastidxid "
2454 "FROM pg_catalog.pg_class c LEFT JOIN "
2455 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2456 "WHERE c.oid = '%u'::pg_catalog.oid;",
2459 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2461 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2462 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2464 appendPQExpBuffer(upgrade_buffer,
2465 "\n-- For binary upgrade, must preserve pg_class oids\n");
2469 appendPQExpBuffer(upgrade_buffer,
2470 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2472 /* only tables have toast tables, not indexes */
2473 if (OidIsValid(pg_class_reltoastrelid))
2476 * One complexity is that the table definition might not require
2477 * the creation of a TOAST table, and the TOAST table might have
2478 * been created long after table creation, when the table was
2479 * loaded with wide data. By setting the TOAST oid we force
2480 * creation of the TOAST heap and TOAST index by the backend so we
2481 * can cleanly copy the files during binary upgrade.
2484 appendPQExpBuffer(upgrade_buffer,
2485 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2486 pg_class_reltoastrelid);
2488 /* every toast table has an index */
2489 appendPQExpBuffer(upgrade_buffer,
2490 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2491 pg_class_reltoastidxid);
2495 appendPQExpBuffer(upgrade_buffer,
2496 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2499 appendPQExpBuffer(upgrade_buffer, "\n");
2501 PQclear(upgrade_res);
2502 destroyPQExpBuffer(upgrade_query);
2506 * If the DumpableObject is a member of an extension, add a suitable
2507 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2510 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2511 DumpableObject *dobj,
2512 const char *objlabel)
2514 DumpableObject *extobj = NULL;
2517 if (!dobj->ext_member)
2521 * Find the parent extension. We could avoid this search if we wanted to
2522 * add a link field to DumpableObject, but the space costs of that would
2523 * be considerable. We assume that member objects could only have a
2524 * direct dependency on their own extension, not any others.
2526 for (i = 0; i < dobj->nDeps; i++)
2528 extobj = findObjectByDumpId(dobj->dependencies[i]);
2529 if (extobj && extobj->objType == DO_EXTENSION)
2534 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2536 appendPQExpBuffer(upgrade_buffer,
2537 "\n-- For binary upgrade, handle extension membership the hard way\n");
2538 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2539 fmtId(extobj->name),
2545 * read all namespaces in the system catalogs and return them in the
2546 * NamespaceInfo* structure
2548 * numNamespaces is set to the number of namespaces read in
2551 getNamespaces(Archive *fout, int *numNamespaces)
2557 NamespaceInfo *nsinfo;
2565 * Before 7.3, there are no real namespaces; create two dummy entries, one
2566 * for user stuff and one for system stuff.
2568 if (fout->remoteVersion < 70300)
2570 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2572 nsinfo[0].dobj.objType = DO_NAMESPACE;
2573 nsinfo[0].dobj.catId.tableoid = 0;
2574 nsinfo[0].dobj.catId.oid = 0;
2575 AssignDumpId(&nsinfo[0].dobj);
2576 nsinfo[0].dobj.name = pg_strdup("public");
2577 nsinfo[0].rolname = pg_strdup("");
2578 nsinfo[0].nspacl = pg_strdup("");
2580 selectDumpableNamespace(&nsinfo[0]);
2582 nsinfo[1].dobj.objType = DO_NAMESPACE;
2583 nsinfo[1].dobj.catId.tableoid = 0;
2584 nsinfo[1].dobj.catId.oid = 1;
2585 AssignDumpId(&nsinfo[1].dobj);
2586 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2587 nsinfo[1].rolname = pg_strdup("");
2588 nsinfo[1].nspacl = pg_strdup("");
2590 selectDumpableNamespace(&nsinfo[1]);
2597 query = createPQExpBuffer();
2599 /* Make sure we are in proper schema */
2600 selectSourceSchema(fout, "pg_catalog");
2603 * we fetch all namespaces including system ones, so that every object we
2604 * read in can be linked to a containing namespace.
2606 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2607 "(%s nspowner) AS rolname, "
2608 "nspacl FROM pg_namespace",
2611 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2613 ntups = PQntuples(res);
2615 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2617 i_tableoid = PQfnumber(res, "tableoid");
2618 i_oid = PQfnumber(res, "oid");
2619 i_nspname = PQfnumber(res, "nspname");
2620 i_rolname = PQfnumber(res, "rolname");
2621 i_nspacl = PQfnumber(res, "nspacl");
2623 for (i = 0; i < ntups; i++)
2625 nsinfo[i].dobj.objType = DO_NAMESPACE;
2626 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2627 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2628 AssignDumpId(&nsinfo[i].dobj);
2629 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2630 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2631 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2633 /* Decide whether to dump this namespace */
2634 selectDumpableNamespace(&nsinfo[i]);
2636 if (strlen(nsinfo[i].rolname) == 0)
2637 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2638 nsinfo[i].dobj.name);
2642 destroyPQExpBuffer(query);
2644 *numNamespaces = ntups;
2651 * given a namespace OID and an object OID, look up the info read by
2654 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2655 * a system object or not. In 7.3 and later there is no guessing, and we
2656 * don't use objoid at all.
2658 static NamespaceInfo *
2659 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2661 NamespaceInfo *nsinfo;
2663 if (fout->remoteVersion >= 70300)
2665 nsinfo = findNamespaceByOid(nsoid);
2669 /* This code depends on the dummy objects set up by getNamespaces. */
2672 if (objoid > g_last_builtin_oid)
2673 i = 0; /* user object */
2675 i = 1; /* system object */
2676 nsinfo = findNamespaceByOid(i);
2680 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2687 * read all extensions in the system catalogs and return them in the
2688 * ExtensionInfo* structure
2690 * numExtensions is set to the number of extensions read in
2693 getExtensions(Archive *fout, int *numExtensions)
2699 ExtensionInfo *extinfo;
2704 int i_extrelocatable;
2710 * Before 9.1, there are no extensions.
2712 if (fout->remoteVersion < 90100)
2718 query = createPQExpBuffer();
2720 /* Make sure we are in proper schema */
2721 selectSourceSchema(fout, "pg_catalog");
2723 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2724 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2725 "FROM pg_extension x "
2726 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2728 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2730 ntups = PQntuples(res);
2732 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2734 i_tableoid = PQfnumber(res, "tableoid");
2735 i_oid = PQfnumber(res, "oid");
2736 i_extname = PQfnumber(res, "extname");
2737 i_nspname = PQfnumber(res, "nspname");
2738 i_extrelocatable = PQfnumber(res, "extrelocatable");
2739 i_extversion = PQfnumber(res, "extversion");
2740 i_extconfig = PQfnumber(res, "extconfig");
2741 i_extcondition = PQfnumber(res, "extcondition");
2743 for (i = 0; i < ntups; i++)
2745 extinfo[i].dobj.objType = DO_EXTENSION;
2746 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2747 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2748 AssignDumpId(&extinfo[i].dobj);
2749 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2750 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2751 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2752 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2753 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2754 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2756 /* Decide whether we want to dump it */
2757 selectDumpableExtension(&(extinfo[i]));
2761 destroyPQExpBuffer(query);
2763 *numExtensions = ntups;
2770 * read all types in the system catalogs and return them in the
2771 * TypeInfo* structure
2773 * numTypes is set to the number of types read in
2775 * NB: this must run after getFuncs() because we assume we can do
2779 getTypes(Archive *fout, int *numTypes)
2784 PQExpBuffer query = createPQExpBuffer();
2786 ShellTypeInfo *stinfo;
2802 * we include even the built-in types because those may be used as array
2803 * elements by user-defined types
2805 * we filter out the built-in types when we dump out the types
2807 * same approach for undefined (shell) types and array types
2809 * Note: as of 8.3 we can reliably detect whether a type is an
2810 * auto-generated array type by checking the element type's typarray.
2811 * (Before that the test is capable of generating false positives.) We
2812 * still check for name beginning with '_', though, so as to avoid the
2813 * cost of the subselect probe for all standard types. This would have to
2814 * be revisited if the backend ever allows renaming of array types.
2817 /* Make sure we are in proper schema */
2818 selectSourceSchema(fout, "pg_catalog");
2820 if (fout->remoteVersion >= 80300)
2822 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2824 "(%s typowner) AS rolname, "
2825 "typinput::oid AS typinput, "
2826 "typoutput::oid AS typoutput, typelem, typrelid, "
2827 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2828 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2829 "typtype, typisdefined, "
2830 "typname[0] = '_' AND typelem != 0 AND "
2831 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2835 else if (fout->remoteVersion >= 70300)
2837 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2839 "(%s typowner) AS rolname, "
2840 "typinput::oid AS typinput, "
2841 "typoutput::oid AS typoutput, typelem, typrelid, "
2842 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2843 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2844 "typtype, typisdefined, "
2845 "typname[0] = '_' AND typelem != 0 AS isarray "
2849 else if (fout->remoteVersion >= 70100)
2851 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2852 "0::oid AS typnamespace, "
2853 "(%s typowner) AS rolname, "
2854 "typinput::oid AS typinput, "
2855 "typoutput::oid AS typoutput, typelem, typrelid, "
2856 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2857 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2858 "typtype, typisdefined, "
2859 "typname[0] = '_' AND typelem != 0 AS isarray "
2865 appendPQExpBuffer(query, "SELECT "
2866 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2868 "0::oid AS typnamespace, "
2869 "(%s typowner) AS rolname, "
2870 "typinput::oid AS typinput, "
2871 "typoutput::oid AS typoutput, typelem, typrelid, "
2872 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2873 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2874 "typtype, typisdefined, "
2875 "typname[0] = '_' AND typelem != 0 AS isarray "
2880 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2882 ntups = PQntuples(res);
2884 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2886 i_tableoid = PQfnumber(res, "tableoid");
2887 i_oid = PQfnumber(res, "oid");
2888 i_typname = PQfnumber(res, "typname");
2889 i_typnamespace = PQfnumber(res, "typnamespace");
2890 i_rolname = PQfnumber(res, "rolname");
2891 i_typinput = PQfnumber(res, "typinput");
2892 i_typoutput = PQfnumber(res, "typoutput");
2893 i_typelem = PQfnumber(res, "typelem");
2894 i_typrelid = PQfnumber(res, "typrelid");
2895 i_typrelkind = PQfnumber(res, "typrelkind");
2896 i_typtype = PQfnumber(res, "typtype");
2897 i_typisdefined = PQfnumber(res, "typisdefined");
2898 i_isarray = PQfnumber(res, "isarray");
2900 for (i = 0; i < ntups; i++)
2902 tyinfo[i].dobj.objType = DO_TYPE;
2903 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2904 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2905 AssignDumpId(&tyinfo[i].dobj);
2906 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2907 tyinfo[i].dobj.namespace =
2909 atooid(PQgetvalue(res, i, i_typnamespace)),
2910 tyinfo[i].dobj.catId.oid);
2911 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2912 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2913 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2914 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2915 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2916 tyinfo[i].shellType = NULL;
2918 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2919 tyinfo[i].isDefined = true;
2921 tyinfo[i].isDefined = false;
2923 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2924 tyinfo[i].isArray = true;
2926 tyinfo[i].isArray = false;
2928 /* Decide whether we want to dump it */
2929 selectDumpableType(&tyinfo[i]);
2932 * If it's a domain, fetch info about its constraints, if any
2934 tyinfo[i].nDomChecks = 0;
2935 tyinfo[i].domChecks = NULL;
2936 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2937 getDomainConstraints(fout, &(tyinfo[i]));
2940 * If it's a base type, make a DumpableObject representing a shell
2941 * definition of the type. We will need to dump that ahead of the I/O
2942 * functions for the type. Similarly, range types need a shell
2943 * definition in case they have a canonicalize function.
2945 * Note: the shell type doesn't have a catId. You might think it
2946 * should copy the base type's catId, but then it might capture the
2947 * pg_depend entries for the type, which we don't want.
2949 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2950 tyinfo[i].typtype == TYPTYPE_RANGE))
2952 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2953 stinfo->dobj.objType = DO_SHELL_TYPE;
2954 stinfo->dobj.catId = nilCatalogId;
2955 AssignDumpId(&stinfo->dobj);
2956 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2957 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2958 stinfo->baseType = &(tyinfo[i]);
2959 tyinfo[i].shellType = stinfo;
2962 * Initially mark the shell type as not to be dumped. We'll only
2963 * dump it if the I/O or canonicalize functions need to be dumped;
2964 * this is taken care of while sorting dependencies.
2966 stinfo->dobj.dump = false;
2969 * However, if dumping from pre-7.3, there will be no dependency
2970 * info so we have to fake it here. We only need to worry about
2971 * typinput and typoutput since the other functions only exist
2974 if (fout->remoteVersion < 70300)
2980 typinput = atooid(PQgetvalue(res, i, i_typinput));
2981 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
2983 funcInfo = findFuncByOid(typinput);
2984 if (funcInfo && funcInfo->dobj.dump)
2986 /* base type depends on function */
2987 addObjectDependency(&tyinfo[i].dobj,
2988 funcInfo->dobj.dumpId);
2989 /* function depends on shell type */
2990 addObjectDependency(&funcInfo->dobj,
2991 stinfo->dobj.dumpId);
2992 /* mark shell type as to be dumped */
2993 stinfo->dobj.dump = true;
2996 funcInfo = findFuncByOid(typoutput);
2997 if (funcInfo && funcInfo->dobj.dump)
2999 /* base type depends on function */
3000 addObjectDependency(&tyinfo[i].dobj,
3001 funcInfo->dobj.dumpId);
3002 /* function depends on shell type */
3003 addObjectDependency(&funcInfo->dobj,
3004 stinfo->dobj.dumpId);
3005 /* mark shell type as to be dumped */
3006 stinfo->dobj.dump = true;
3011 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3012 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3013 tyinfo[i].dobj.name);
3020 destroyPQExpBuffer(query);
3027 * read all operators in the system catalogs and return them in the
3028 * OprInfo* structure
3030 * numOprs is set to the number of operators read in
3033 getOperators(Archive *fout, int *numOprs)
3038 PQExpBuffer query = createPQExpBuffer();
3049 * find all operators, including builtin operators; we filter out
3050 * system-defined operators at dump-out time.
3053 /* Make sure we are in proper schema */
3054 selectSourceSchema(fout, "pg_catalog");
3056 if (fout->remoteVersion >= 70300)
3058 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3060 "(%s oprowner) AS rolname, "
3062 "oprcode::oid AS oprcode "
3066 else if (fout->remoteVersion >= 70100)
3068 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3069 "0::oid AS oprnamespace, "
3070 "(%s oprowner) AS rolname, "
3072 "oprcode::oid AS oprcode "
3078 appendPQExpBuffer(query, "SELECT "
3079 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3081 "0::oid AS oprnamespace, "
3082 "(%s oprowner) AS rolname, "
3084 "oprcode::oid AS oprcode "
3089 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3091 ntups = PQntuples(res);
3094 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3096 i_tableoid = PQfnumber(res, "tableoid");
3097 i_oid = PQfnumber(res, "oid");
3098 i_oprname = PQfnumber(res, "oprname");
3099 i_oprnamespace = PQfnumber(res, "oprnamespace");
3100 i_rolname = PQfnumber(res, "rolname");
3101 i_oprkind = PQfnumber(res, "oprkind");
3102 i_oprcode = PQfnumber(res, "oprcode");
3104 for (i = 0; i < ntups; i++)
3106 oprinfo[i].dobj.objType = DO_OPERATOR;
3107 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3108 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3109 AssignDumpId(&oprinfo[i].dobj);
3110 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3111 oprinfo[i].dobj.namespace =
3113 atooid(PQgetvalue(res, i, i_oprnamespace)),
3114 oprinfo[i].dobj.catId.oid);
3115 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3116 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3117 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3119 /* Decide whether we want to dump it */
3120 selectDumpableObject(&(oprinfo[i].dobj));
3122 if (strlen(oprinfo[i].rolname) == 0)
3123 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3124 oprinfo[i].dobj.name);
3129 destroyPQExpBuffer(query);
3136 * read all collations in the system catalogs and return them in the
3137 * CollInfo* structure
3139 * numCollations is set to the number of collations read in
3142 getCollations(Archive *fout, int *numCollations)
3152 int i_collnamespace;
3155 /* Collations didn't exist pre-9.1 */
3156 if (fout->remoteVersion < 90100)
3162 query = createPQExpBuffer();
3165 * find all collations, including builtin collations; we filter out
3166 * system-defined collations at dump-out time.
3169 /* Make sure we are in proper schema */
3170 selectSourceSchema(fout, "pg_catalog");
3172 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3174 "(%s collowner) AS rolname "
3175 "FROM pg_collation",
3178 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3180 ntups = PQntuples(res);
3181 *numCollations = ntups;
3183 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3185 i_tableoid = PQfnumber(res, "tableoid");
3186 i_oid = PQfnumber(res, "oid");
3187 i_collname = PQfnumber(res, "collname");
3188 i_collnamespace = PQfnumber(res, "collnamespace");
3189 i_rolname = PQfnumber(res, "rolname");
3191 for (i = 0; i < ntups; i++)
3193 collinfo[i].dobj.objType = DO_COLLATION;
3194 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3195 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3196 AssignDumpId(&collinfo[i].dobj);
3197 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3198 collinfo[i].dobj.namespace =
3200 atooid(PQgetvalue(res, i, i_collnamespace)),
3201 collinfo[i].dobj.catId.oid);
3202 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3204 /* Decide whether we want to dump it */
3205 selectDumpableObject(&(collinfo[i].dobj));
3210 destroyPQExpBuffer(query);
3217 * read all conversions in the system catalogs and return them in the
3218 * ConvInfo* structure
3220 * numConversions is set to the number of conversions read in
3223 getConversions(Archive *fout, int *numConversions)
3228 PQExpBuffer query = createPQExpBuffer();
3236 /* Conversions didn't exist pre-7.3 */
3237 if (fout->remoteVersion < 70300)
3239 *numConversions = 0;
3244 * find all conversions, including builtin conversions; we filter out
3245 * system-defined conversions at dump-out time.
3248 /* Make sure we are in proper schema */
3249 selectSourceSchema(fout, "pg_catalog");
3251 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3253 "(%s conowner) AS rolname "
3254 "FROM pg_conversion",
3257 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3259 ntups = PQntuples(res);
3260 *numConversions = ntups;
3262 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3264 i_tableoid = PQfnumber(res, "tableoid");
3265 i_oid = PQfnumber(res, "oid");
3266 i_conname = PQfnumber(res, "conname");
3267 i_connamespace = PQfnumber(res, "connamespace");
3268 i_rolname = PQfnumber(res, "rolname");
3270 for (i = 0; i < ntups; i++)
3272 convinfo[i].dobj.objType = DO_CONVERSION;
3273 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3274 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3275 AssignDumpId(&convinfo[i].dobj);
3276 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3277 convinfo[i].dobj.namespace =
3279 atooid(PQgetvalue(res, i, i_connamespace)),
3280 convinfo[i].dobj.catId.oid);
3281 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3283 /* Decide whether we want to dump it */
3284 selectDumpableObject(&(convinfo[i].dobj));
3289 destroyPQExpBuffer(query);
3296 * read all opclasses in the system catalogs and return them in the
3297 * OpclassInfo* structure
3299 * numOpclasses is set to the number of opclasses read in
3302 getOpclasses(Archive *fout, int *numOpclasses)
3307 PQExpBuffer query = createPQExpBuffer();
3308 OpclassInfo *opcinfo;
3316 * find all opclasses, including builtin opclasses; we filter out
3317 * system-defined opclasses at dump-out time.
3320 /* Make sure we are in proper schema */
3321 selectSourceSchema(fout, "pg_catalog");
3323 if (fout->remoteVersion >= 70300)
3325 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3327 "(%s opcowner) AS rolname "
3331 else if (fout->remoteVersion >= 70100)
3333 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3334 "0::oid AS opcnamespace, "
3335 "''::name AS rolname "
3340 appendPQExpBuffer(query, "SELECT "
3341 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3343 "0::oid AS opcnamespace, "
3344 "''::name AS rolname "
3348 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3350 ntups = PQntuples(res);
3351 *numOpclasses = ntups;
3353 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3355 i_tableoid = PQfnumber(res, "tableoid");
3356 i_oid = PQfnumber(res, "oid");
3357 i_opcname = PQfnumber(res, "opcname");
3358 i_opcnamespace = PQfnumber(res, "opcnamespace");
3359 i_rolname = PQfnumber(res, "rolname");
3361 for (i = 0; i < ntups; i++)
3363 opcinfo[i].dobj.objType = DO_OPCLASS;
3364 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3365 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3366 AssignDumpId(&opcinfo[i].dobj);
3367 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3368 opcinfo[i].dobj.namespace =
3370 atooid(PQgetvalue(res, i, i_opcnamespace)),
3371 opcinfo[i].dobj.catId.oid);
3372 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3374 /* Decide whether we want to dump it */
3375 selectDumpableObject(&(opcinfo[i].dobj));
3377 if (fout->remoteVersion >= 70300)
3379 if (strlen(opcinfo[i].rolname) == 0)
3380 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3381 opcinfo[i].dobj.name);
3387 destroyPQExpBuffer(query);
3394 * read all opfamilies in the system catalogs and return them in the
3395 * OpfamilyInfo* structure
3397 * numOpfamilies is set to the number of opfamilies read in
3400 getOpfamilies(Archive *fout, int *numOpfamilies)
3406 OpfamilyInfo *opfinfo;
3413 /* Before 8.3, there is no separate concept of opfamilies */
3414 if (fout->remoteVersion < 80300)
3420 query = createPQExpBuffer();
3423 * find all opfamilies, including builtin opfamilies; we filter out
3424 * system-defined opfamilies at dump-out time.
3427 /* Make sure we are in proper schema */
3428 selectSourceSchema(fout, "pg_catalog");
3430 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3432 "(%s opfowner) AS rolname "
3436 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3438 ntups = PQntuples(res);
3439 *numOpfamilies = ntups;
3441 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3443 i_tableoid = PQfnumber(res, "tableoid");
3444 i_oid = PQfnumber(res, "oid");
3445 i_opfname = PQfnumber(res, "opfname");
3446 i_opfnamespace = PQfnumber(res, "opfnamespace");
3447 i_rolname = PQfnumber(res, "rolname");
3449 for (i = 0; i < ntups; i++)
3451 opfinfo[i].dobj.objType = DO_OPFAMILY;
3452 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3453 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3454 AssignDumpId(&opfinfo[i].dobj);
3455 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3456 opfinfo[i].dobj.namespace =
3458 atooid(PQgetvalue(res, i, i_opfnamespace)),
3459 opfinfo[i].dobj.catId.oid);
3460 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3462 /* Decide whether we want to dump it */
3463 selectDumpableObject(&(opfinfo[i].dobj));
3465 if (fout->remoteVersion >= 70300)
3467 if (strlen(opfinfo[i].rolname) == 0)
3468 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3469 opfinfo[i].dobj.name);
3475 destroyPQExpBuffer(query);
3482 * read all the user-defined aggregates in the system catalogs and
3483 * return them in the AggInfo* structure
3485 * numAggs is set to the number of aggregates read in
3488 getAggregates(Archive *fout, int *numAggs)
3493 PQExpBuffer query = createPQExpBuffer();
3504 /* Make sure we are in proper schema */
3505 selectSourceSchema(fout, "pg_catalog");
3508 * Find all user-defined aggregates. See comment in getFuncs() for the
3509 * rationale behind the filtering logic.
3512 if (fout->remoteVersion >= 80200)
3514 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3515 "pronamespace AS aggnamespace, "
3516 "pronargs, proargtypes, "
3517 "(%s proowner) AS rolname, "
3520 "WHERE proisagg AND ("
3522 "(SELECT oid FROM pg_namespace "
3523 "WHERE nspname = 'pg_catalog')",
3525 if (binary_upgrade && fout->remoteVersion >= 90100)
3526 appendPQExpBuffer(query,
3527 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3528 "classid = 'pg_proc'::regclass AND "
3529 "objid = p.oid AND "
3530 "refclassid = 'pg_extension'::regclass AND "
3532 appendPQExpBuffer(query, ")");
3534 else if (fout->remoteVersion >= 70300)
3536 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3537 "pronamespace AS aggnamespace, "
3538 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3540 "(%s proowner) AS rolname, "
3544 "AND pronamespace != "
3545 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3548 else if (fout->remoteVersion >= 70100)
3550 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3551 "0::oid AS aggnamespace, "
3552 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3553 "aggbasetype AS proargtypes, "
3554 "(%s aggowner) AS rolname, "
3556 "FROM pg_aggregate "
3557 "where oid > '%u'::oid",
3559 g_last_builtin_oid);
3563 appendPQExpBuffer(query, "SELECT "
3564 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3566 "0::oid AS aggnamespace, "
3567 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3568 "aggbasetype AS proargtypes, "
3569 "(%s aggowner) AS rolname, "
3571 "FROM pg_aggregate "
3572 "where oid > '%u'::oid",
3574 g_last_builtin_oid);
3577 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3579 ntups = PQntuples(res);
3582 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3584 i_tableoid = PQfnumber(res, "tableoid");
3585 i_oid = PQfnumber(res, "oid");
3586 i_aggname = PQfnumber(res, "aggname");
3587 i_aggnamespace = PQfnumber(res, "aggnamespace");
3588 i_pronargs = PQfnumber(res, "pronargs");
3589 i_proargtypes = PQfnumber(res, "proargtypes");
3590 i_rolname = PQfnumber(res, "rolname");
3591 i_aggacl = PQfnumber(res, "aggacl");
3593 for (i = 0; i < ntups; i++)
3595 agginfo[i].aggfn.dobj.objType = DO_AGG;
3596 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3597 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3598 AssignDumpId(&agginfo[i].aggfn.dobj);
3599 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3600 agginfo[i].aggfn.dobj.namespace =
3602 atooid(PQgetvalue(res, i, i_aggnamespace)),
3603 agginfo[i].aggfn.dobj.catId.oid);
3604 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3605 if (strlen(agginfo[i].aggfn.rolname) == 0)
3606 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3607 agginfo[i].aggfn.dobj.name);
3608 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3609 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3610 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3611 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3612 if (agginfo[i].aggfn.nargs == 0)
3613 agginfo[i].aggfn.argtypes = NULL;
3616 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3617 if (fout->remoteVersion >= 70300)
3618 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3619 agginfo[i].aggfn.argtypes,
3620 agginfo[i].aggfn.nargs);
3622 /* it's just aggbasetype */
3623 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3626 /* Decide whether we want to dump it */
3627 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3632 destroyPQExpBuffer(query);
3639 * read all the user-defined functions in the system catalogs and
3640 * return them in the FuncInfo* structure
3642 * numFuncs is set to the number of functions read in
3645 getFuncs(Archive *fout, int *numFuncs)
3650 PQExpBuffer query = createPQExpBuffer();
3663 /* Make sure we are in proper schema */
3664 selectSourceSchema(fout, "pg_catalog");
3667 * Find all user-defined functions. Normally we can exclude functions in
3668 * pg_catalog, which is worth doing since there are several thousand of
3669 * 'em. However, there are some extensions that create functions in
3670 * pg_catalog. In normal dumps we can still ignore those --- but in
3671 * binary-upgrade mode, we must dump the member objects of the extension,
3672 * so be sure to fetch any such functions.
3674 * Also, in 9.2 and up, exclude functions that are internally dependent on
3675 * something else, since presumably those will be created as a result of
3676 * creating the something else. This currently only acts to suppress
3677 * constructor functions for range types. Note that this is OK only
3678 * because the constructors don't have any dependencies the range type
3679 * doesn't have; otherwise we might not get creation ordering correct.
3682 if (fout->remoteVersion >= 70300)
3684 appendPQExpBuffer(query,
3685 "SELECT tableoid, oid, proname, prolang, "
3686 "pronargs, proargtypes, prorettype, proacl, "
3688 "(%s proowner) AS rolname "
3690 "WHERE NOT proisagg AND ("
3692 "(SELECT oid FROM pg_namespace "
3693 "WHERE nspname = 'pg_catalog')",
3695 if (fout->remoteVersion >= 90200)
3696 appendPQExpBuffer(query,
3697 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3698 "WHERE classid = 'pg_proc'::regclass AND "
3699 "objid = p.oid AND deptype = 'i')");
3700 if (binary_upgrade && fout->remoteVersion >= 90100)
3701 appendPQExpBuffer(query,
3702 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3703 "classid = 'pg_proc'::regclass AND "
3704 "objid = p.oid AND "
3705 "refclassid = 'pg_extension'::regclass AND "
3707 appendPQExpBuffer(query, ")");
3709 else if (fout->remoteVersion >= 70100)
3711 appendPQExpBuffer(query,
3712 "SELECT tableoid, oid, proname, prolang, "
3713 "pronargs, proargtypes, prorettype, "
3714 "'{=X}' AS proacl, "
3715 "0::oid AS pronamespace, "
3716 "(%s proowner) AS rolname "
3718 "WHERE pg_proc.oid > '%u'::oid",
3720 g_last_builtin_oid);
3724 appendPQExpBuffer(query,
3726 "(SELECT oid FROM pg_class "
3727 " WHERE relname = 'pg_proc') AS tableoid, "
3728 "oid, proname, prolang, "
3729 "pronargs, proargtypes, prorettype, "
3730 "'{=X}' AS proacl, "
3731 "0::oid AS pronamespace, "
3732 "(%s proowner) AS rolname "
3734 "where pg_proc.oid > '%u'::oid",
3736 g_last_builtin_oid);
3739 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3741 ntups = PQntuples(res);
3745 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3747 i_tableoid = PQfnumber(res, "tableoid");
3748 i_oid = PQfnumber(res, "oid");
3749 i_proname = PQfnumber(res, "proname");
3750 i_pronamespace = PQfnumber(res, "pronamespace");
3751 i_rolname = PQfnumber(res, "rolname");
3752 i_prolang = PQfnumber(res, "prolang");
3753 i_pronargs = PQfnumber(res, "pronargs");
3754 i_proargtypes = PQfnumber(res, "proargtypes");
3755 i_prorettype = PQfnumber(res, "prorettype");
3756 i_proacl = PQfnumber(res, "proacl");
3758 for (i = 0; i < ntups; i++)
3760 finfo[i].dobj.objType = DO_FUNC;
3761 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3762 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3763 AssignDumpId(&finfo[i].dobj);
3764 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3765 finfo[i].dobj.namespace =
3767 atooid(PQgetvalue(res, i, i_pronamespace)),
3768 finfo[i].dobj.catId.oid);
3769 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3770 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3771 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3772 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3773 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3774 if (finfo[i].nargs == 0)
3775 finfo[i].argtypes = NULL;
3778 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3779 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3780 finfo[i].argtypes, finfo[i].nargs);
3783 /* Decide whether we want to dump it */
3784 selectDumpableObject(&(finfo[i].dobj));
3786 if (strlen(finfo[i].rolname) == 0)
3788 "WARNING: owner of function \"%s\" appears to be invalid\n",
3789 finfo[i].dobj.name);
3794 destroyPQExpBuffer(query);
3801 * read all the user-defined tables (no indexes, no catalogs)
3802 * in the system catalogs return them in the TableInfo* structure
3804 * numTables is set to the number of tables read in
3807 getTables(Archive *fout, int *numTables)
3812 PQExpBuffer query = createPQExpBuffer();
3822 int i_relhastriggers;
3828 int i_toastfrozenxid;
3829 int i_relpersistence;
3832 int i_reltablespace;
3834 int i_toastreloptions;
3837 /* Make sure we are in proper schema */
3838 selectSourceSchema(fout, "pg_catalog");
3841 * Find all the tables and table-like objects.
3843 * We include system catalogs, so that we can work if a user table is
3844 * defined to inherit from a system catalog (pretty weird, but...)
3846 * We ignore relations that are not ordinary tables, sequences, views,
3847 * composite types, or foreign tables.
3849 * Composite-type table entries won't be dumped as such, but we have to
3850 * make a DumpableObject for them so that we can track dependencies of the
3851 * composite type (pg_depend entries for columns of the composite type
3852 * link to the pg_class entry not the pg_type entry).
3854 * Note: in this phase we should collect only a minimal amount of
3855 * information about each table, basically just enough to decide if it is
3856 * interesting. We must fetch all tables in this phase because otherwise
3857 * we cannot correctly identify inherited columns, owned sequences, etc.
3860 if (fout->remoteVersion >= 90100)
3863 * Left join to pick up dependency info linking sequences to their
3864 * owning column, if any (note this dependency is AUTO as of 8.2)
3866 appendPQExpBuffer(query,
3867 "SELECT c.tableoid, c.oid, c.relname, "
3868 "c.relacl, c.relkind, c.relnamespace, "
3869 "(%s c.relowner) AS rolname, "
3870 "c.relchecks, c.relhastriggers, "
3871 "c.relhasindex, c.relhasrules, c.relhasoids, "
3872 "c.relfrozenxid, tc.oid AS toid, "
3873 "tc.relfrozenxid AS tfrozenxid, "
3874 "c.relpersistence, "
3875 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3876 "d.refobjid AS owning_tab, "
3877 "d.refobjsubid AS owning_col, "
3878 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3879 "array_to_string(c.reloptions, ', ') AS reloptions, "
3880 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3882 "LEFT JOIN pg_depend d ON "
3883 "(c.relkind = '%c' AND "
3884 "d.classid = c.tableoid AND d.objid = c.oid AND "
3885 "d.objsubid = 0 AND "
3886 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3887 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3888 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3892 RELKIND_RELATION, RELKIND_SEQUENCE,
3893 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3894 RELKIND_FOREIGN_TABLE);
3896 else if (fout->remoteVersion >= 90000)
3899 * Left join to pick up dependency info linking sequences to their
3900 * owning column, if any (note this dependency is AUTO as of 8.2)
3902 appendPQExpBuffer(query,
3903 "SELECT c.tableoid, c.oid, c.relname, "
3904 "c.relacl, c.relkind, c.relnamespace, "
3905 "(%s c.relowner) AS rolname, "
3906 "c.relchecks, c.relhastriggers, "
3907 "c.relhasindex, c.relhasrules, c.relhasoids, "
3908 "c.relfrozenxid, tc.oid AS toid, "
3909 "tc.relfrozenxid AS tfrozenxid, "
3910 "'p' AS relpersistence, "
3911 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3912 "d.refobjid AS owning_tab, "
3913 "d.refobjsubid AS owning_col, "
3914 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3915 "array_to_string(c.reloptions, ', ') AS reloptions, "
3916 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3918 "LEFT JOIN pg_depend d ON "
3919 "(c.relkind = '%c' AND "
3920 "d.classid = c.tableoid AND d.objid = c.oid AND "
3921 "d.objsubid = 0 AND "
3922 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3923 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3924 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3928 RELKIND_RELATION, RELKIND_SEQUENCE,
3929 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3931 else if (fout->remoteVersion >= 80400)
3934 * Left join to pick up dependency info linking sequences to their
3935 * owning column, if any (note this dependency is AUTO as of 8.2)
3937 appendPQExpBuffer(query,
3938 "SELECT c.tableoid, c.oid, c.relname, "
3939 "c.relacl, c.relkind, c.relnamespace, "
3940 "(%s c.relowner) AS rolname, "
3941 "c.relchecks, c.relhastriggers, "
3942 "c.relhasindex, c.relhasrules, c.relhasoids, "
3943 "c.relfrozenxid, tc.oid AS toid, "
3944 "tc.relfrozenxid AS tfrozenxid, "
3945 "'p' AS relpersistence, "
3946 "NULL AS reloftype, "
3947 "d.refobjid AS owning_tab, "
3948 "d.refobjsubid AS owning_col, "
3949 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3950 "array_to_string(c.reloptions, ', ') AS reloptions, "
3951 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3953 "LEFT JOIN pg_depend d ON "
3954 "(c.relkind = '%c' AND "
3955 "d.classid = c.tableoid AND d.objid = c.oid AND "
3956 "d.objsubid = 0 AND "
3957 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3958 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3959 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3963 RELKIND_RELATION, RELKIND_SEQUENCE,
3964 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3966 else if (fout->remoteVersion >= 80200)
3969 * Left join to pick up dependency info linking sequences to their
3970 * owning column, if any (note this dependency is AUTO as of 8.2)
3972 appendPQExpBuffer(query,
3973 "SELECT c.tableoid, c.oid, c.relname, "
3974 "c.relacl, c.relkind, c.relnamespace, "
3975 "(%s c.relowner) AS rolname, "
3976 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
3977 "c.relhasindex, c.relhasrules, c.relhasoids, "
3978 "c.relfrozenxid, tc.oid AS toid, "
3979 "tc.relfrozenxid AS tfrozenxid, "
3980 "'p' AS relpersistence, "
3981 "NULL AS reloftype, "
3982 "d.refobjid AS owning_tab, "
3983 "d.refobjsubid AS owning_col, "
3984 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3985 "array_to_string(c.reloptions, ', ') AS reloptions, "
3986 "NULL AS toast_reloptions "
3988 "LEFT JOIN pg_depend d ON "
3989 "(c.relkind = '%c' AND "
3990 "d.classid = c.tableoid AND d.objid = c.oid AND "
3991 "d.objsubid = 0 AND "
3992 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3993 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3994 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3998 RELKIND_RELATION, RELKIND_SEQUENCE,
3999 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4001 else if (fout->remoteVersion >= 80000)
4004 * Left join to pick up dependency info linking sequences to their
4005 * owning column, if any
4007 appendPQExpBuffer(query,
4008 "SELECT c.tableoid, c.oid, relname, "
4009 "relacl, relkind, relnamespace, "
4010 "(%s relowner) AS rolname, "
4011 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4012 "relhasindex, relhasrules, relhasoids, "
4013 "0 AS relfrozenxid, "
4016 "'p' AS relpersistence, "
4017 "NULL AS reloftype, "
4018 "d.refobjid AS owning_tab, "
4019 "d.refobjsubid AS owning_col, "
4020 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4021 "NULL AS reloptions, "
4022 "NULL AS toast_reloptions "
4024 "LEFT JOIN pg_depend d ON "
4025 "(c.relkind = '%c' AND "
4026 "d.classid = c.tableoid AND d.objid = c.oid AND "
4027 "d.objsubid = 0 AND "
4028 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4029 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4033 RELKIND_RELATION, RELKIND_SEQUENCE,
4034 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4036 else if (fout->remoteVersion >= 70300)
4039 * Left join to pick up dependency info linking sequences to their
4040 * owning column, if any
4042 appendPQExpBuffer(query,
4043 "SELECT c.tableoid, c.oid, relname, "
4044 "relacl, relkind, relnamespace, "
4045 "(%s relowner) AS rolname, "
4046 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4047 "relhasindex, relhasrules, relhasoids, "
4048 "0 AS relfrozenxid, "
4051 "'p' AS relpersistence, "
4052 "NULL AS reloftype, "
4053 "d.refobjid AS owning_tab, "
4054 "d.refobjsubid AS owning_col, "
4055 "NULL AS reltablespace, "
4056 "NULL AS reloptions, "
4057 "NULL AS toast_reloptions "
4059 "LEFT JOIN pg_depend d ON "
4060 "(c.relkind = '%c' AND "
4061 "d.classid = c.tableoid AND d.objid = c.oid AND "
4062 "d.objsubid = 0 AND "
4063 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4064 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4068 RELKIND_RELATION, RELKIND_SEQUENCE,
4069 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4071 else if (fout->remoteVersion >= 70200)
4073 appendPQExpBuffer(query,
4074 "SELECT tableoid, oid, relname, relacl, relkind, "
4075 "0::oid AS relnamespace, "
4076 "(%s relowner) AS rolname, "
4077 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4078 "relhasindex, relhasrules, relhasoids, "
4079 "0 AS relfrozenxid, "
4082 "'p' AS relpersistence, "
4083 "NULL AS reloftype, "
4084 "NULL::oid AS owning_tab, "
4085 "NULL::int4 AS owning_col, "
4086 "NULL AS reltablespace, "
4087 "NULL AS reloptions, "
4088 "NULL AS toast_reloptions "
4090 "WHERE relkind IN ('%c', '%c', '%c') "
4093 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4095 else if (fout->remoteVersion >= 70100)
4097 /* all tables have oids in 7.1 */
4098 appendPQExpBuffer(query,
4099 "SELECT tableoid, oid, relname, relacl, relkind, "
4100 "0::oid AS relnamespace, "
4101 "(%s relowner) AS rolname, "
4102 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4103 "relhasindex, relhasrules, "
4104 "'t'::bool AS relhasoids, "
4105 "0 AS relfrozenxid, "
4108 "'p' AS relpersistence, "
4109 "NULL AS reloftype, "
4110 "NULL::oid AS owning_tab, "
4111 "NULL::int4 AS owning_col, "
4112 "NULL AS reltablespace, "
4113 "NULL AS reloptions, "
4114 "NULL AS toast_reloptions "
4116 "WHERE relkind IN ('%c', '%c', '%c') "
4119 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4124 * Before 7.1, view relkind was not set to 'v', so we must check if we
4125 * have a view by looking for a rule in pg_rewrite.
4127 appendPQExpBuffer(query,
4129 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4130 "oid, relname, relacl, "
4131 "CASE WHEN relhasrules and relkind = 'r' "
4132 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4133 " r.ev_class = c.oid AND r.ev_type = '1') "
4134 "THEN '%c'::\"char\" "
4135 "ELSE relkind END AS relkind,"
4136 "0::oid AS relnamespace, "
4137 "(%s relowner) AS rolname, "
4138 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4139 "relhasindex, relhasrules, "
4140 "'t'::bool AS relhasoids, "
4141 "0 as relfrozenxid, "
4144 "'p' AS relpersistence, "
4145 "NULL AS reloftype, "
4146 "NULL::oid AS owning_tab, "
4147 "NULL::int4 AS owning_col, "
4148 "NULL AS reltablespace, "
4149 "NULL AS reloptions, "
4150 "NULL AS toast_reloptions "
4152 "WHERE relkind IN ('%c', '%c') "
4156 RELKIND_RELATION, RELKIND_SEQUENCE);
4159 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4161 ntups = PQntuples(res);
4166 * Extract data from result and lock dumpable tables. We do the locking
4167 * before anything else, to minimize the window wherein a table could
4168 * disappear under us.
4170 * Note that we have to save info about all tables here, even when dumping
4171 * only one, because we don't yet know which tables might be inheritance
4172 * ancestors of the target table.
4174 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4176 i_reltableoid = PQfnumber(res, "tableoid");
4177 i_reloid = PQfnumber(res, "oid");
4178 i_relname = PQfnumber(res, "relname");
4179 i_relnamespace = PQfnumber(res, "relnamespace");
4180 i_relacl = PQfnumber(res, "relacl");
4181 i_relkind = PQfnumber(res, "relkind");
4182 i_rolname = PQfnumber(res, "rolname");
4183 i_relchecks = PQfnumber(res, "relchecks");
4184 i_relhastriggers = PQfnumber(res, "relhastriggers");
4185 i_relhasindex = PQfnumber(res, "relhasindex");
4186 i_relhasrules = PQfnumber(res, "relhasrules");
4187 i_relhasoids = PQfnumber(res, "relhasoids");
4188 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4189 i_toastoid = PQfnumber(res, "toid");
4190 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4191 i_relpersistence = PQfnumber(res, "relpersistence");
4192 i_owning_tab = PQfnumber(res, "owning_tab");
4193 i_owning_col = PQfnumber(res, "owning_col");
4194 i_reltablespace = PQfnumber(res, "reltablespace");
4195 i_reloptions = PQfnumber(res, "reloptions");
4196 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4197 i_reloftype = PQfnumber(res, "reloftype");
4199 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4202 * Arrange to fail instead of waiting forever for a table lock.
4204 * NB: this coding assumes that the only queries issued within the
4205 * following loop are LOCK TABLEs; else the timeout may be undesirably
4206 * applied to other things too.
4208 resetPQExpBuffer(query);
4209 appendPQExpBuffer(query, "SET statement_timeout = ");
4210 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4211 ExecuteSqlStatement(fout, query->data);
4214 for (i = 0; i < ntups; i++)
4216 tblinfo[i].dobj.objType = DO_TABLE;
4217 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4218 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4219 AssignDumpId(&tblinfo[i].dobj);
4220 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4221 tblinfo[i].dobj.namespace =
4223 atooid(PQgetvalue(res, i, i_relnamespace)),
4224 tblinfo[i].dobj.catId.oid);
4225 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4226 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4227 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4228 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4229 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4230 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4231 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4232 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4233 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4234 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4235 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4236 if (PQgetisnull(res, i, i_reloftype))
4237 tblinfo[i].reloftype = NULL;
4239 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4240 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4241 if (PQgetisnull(res, i, i_owning_tab))
4243 tblinfo[i].owning_tab = InvalidOid;
4244 tblinfo[i].owning_col = 0;
4248 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4249 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4251 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4252 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4253 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4255 /* other fields were zeroed above */
4258 * Decide whether we want to dump this table.
4260 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4261 tblinfo[i].dobj.dump = false;
4263 selectDumpableTable(&tblinfo[i]);
4264 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4267 * Read-lock target tables to make sure they aren't DROPPED or altered
4268 * in schema before we get around to dumping them.
4270 * Note that we don't explicitly lock parents of the target tables; we
4271 * assume our lock on the child is enough to prevent schema
4272 * alterations to parent tables.
4274 * NOTE: it'd be kinda nice to lock other relations too, not only
4275 * plain tables, but the backend doesn't presently allow that.
4277 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4279 resetPQExpBuffer(query);
4280 appendPQExpBuffer(query,
4281 "LOCK TABLE %s IN ACCESS SHARE MODE",
4282 fmtQualifiedId(fout,
4283 tblinfo[i].dobj.namespace->dobj.name,
4284 tblinfo[i].dobj.name));
4285 ExecuteSqlStatement(fout, query->data);
4288 /* Emit notice if join for owner failed */
4289 if (strlen(tblinfo[i].rolname) == 0)
4290 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4291 tblinfo[i].dobj.name);
4294 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4296 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4301 destroyPQExpBuffer(query);
4308 * identify owned sequences and mark them as dumpable if owning table is
4310 * We used to do this in getTables(), but it's better to do it after the
4311 * index used by findTableByOid() has been set up.
4314 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4319 * Force sequences that are "owned" by table columns to be dumped whenever
4320 * their owning table is being dumped.
4322 for (i = 0; i < numTables; i++)
4324 TableInfo *seqinfo = &tblinfo[i];
4325 TableInfo *owning_tab;
4327 if (!OidIsValid(seqinfo->owning_tab))
4328 continue; /* not an owned sequence */
4329 if (seqinfo->dobj.dump)
4330 continue; /* no need to search */
4331 owning_tab = findTableByOid(seqinfo->owning_tab);
4332 if (owning_tab && owning_tab->dobj.dump)
4334 seqinfo->interesting = true;
4335 seqinfo->dobj.dump = true;
4342 * read all the inheritance information
4343 * from the system catalogs return them in the InhInfo* structure
4345 * numInherits is set to the number of pairs read in
4348 getInherits(Archive *fout, int *numInherits)
4353 PQExpBuffer query = createPQExpBuffer();
4359 /* Make sure we are in proper schema */
4360 selectSourceSchema(fout, "pg_catalog");
4362 /* find all the inheritance information */
4364 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4366 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4368 ntups = PQntuples(res);
4370 *numInherits = ntups;
4372 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4374 i_inhrelid = PQfnumber(res, "inhrelid");
4375 i_inhparent = PQfnumber(res, "inhparent");
4377 for (i = 0; i < ntups; i++)
4379 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4380 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4385 destroyPQExpBuffer(query);
4392 * get information about every index on a dumpable table
4394 * Note: index data is not returned directly to the caller, but it
4395 * does get entered into the DumpableObject tables.
4398 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4402 PQExpBuffer query = createPQExpBuffer();
4405 ConstraintInfo *constrinfo;
4424 for (i = 0; i < numTables; i++)
4426 TableInfo *tbinfo = &tblinfo[i];
4428 /* Only plain tables have indexes */
4429 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4432 /* Ignore indexes of tables not to be dumped */
4433 if (!tbinfo->dobj.dump)
4437 write_msg(NULL, "reading indexes for table \"%s\"\n",
4440 /* Make sure we are in proper schema so indexdef is right */
4441 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4444 * The point of the messy-looking outer join is to find a constraint
4445 * that is related by an internal dependency link to the index. If we
4446 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4447 * assume an index won't have more than one internal dependency.
4449 * As of 9.0 we don't need to look at pg_depend but can check for a
4450 * match to pg_constraint.conindid. The check on conrelid is
4451 * redundant but useful because that column is indexed while conindid
4454 resetPQExpBuffer(query);
4455 if (fout->remoteVersion >= 90000)
4457 appendPQExpBuffer(query,
4458 "SELECT t.tableoid, t.oid, "
4459 "t.relname AS indexname, "
4460 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4461 "t.relnatts AS indnkeys, "
4462 "i.indkey, i.indisclustered, "
4463 "c.contype, c.conname, "
4464 "c.condeferrable, c.condeferred, "
4465 "c.tableoid AS contableoid, "
4467 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4468 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4469 "array_to_string(t.reloptions, ', ') AS options "
4470 "FROM pg_catalog.pg_index i "
4471 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4472 "LEFT JOIN pg_catalog.pg_constraint c "
4473 "ON (i.indrelid = c.conrelid AND "
4474 "i.indexrelid = c.conindid AND "
4475 "c.contype IN ('p','u','x')) "
4476 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4477 "ORDER BY indexname",
4478 tbinfo->dobj.catId.oid);
4480 else if (fout->remoteVersion >= 80200)
4482 appendPQExpBuffer(query,
4483 "SELECT t.tableoid, t.oid, "
4484 "t.relname AS indexname, "
4485 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4486 "t.relnatts AS indnkeys, "
4487 "i.indkey, i.indisclustered, "
4488 "c.contype, c.conname, "
4489 "c.condeferrable, c.condeferred, "
4490 "c.tableoid AS contableoid, "
4493 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4494 "array_to_string(t.reloptions, ', ') AS options "
4495 "FROM pg_catalog.pg_index i "
4496 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4497 "LEFT JOIN pg_catalog.pg_depend d "
4498 "ON (d.classid = t.tableoid "
4499 "AND d.objid = t.oid "
4500 "AND d.deptype = 'i') "
4501 "LEFT JOIN pg_catalog.pg_constraint c "
4502 "ON (d.refclassid = c.tableoid "
4503 "AND d.refobjid = c.oid) "
4504 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4505 "ORDER BY indexname",
4506 tbinfo->dobj.catId.oid);
4508 else if (fout->remoteVersion >= 80000)
4510 appendPQExpBuffer(query,
4511 "SELECT t.tableoid, t.oid, "
4512 "t.relname AS indexname, "
4513 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4514 "t.relnatts AS indnkeys, "
4515 "i.indkey, i.indisclustered, "
4516 "c.contype, c.conname, "
4517 "c.condeferrable, c.condeferred, "
4518 "c.tableoid AS contableoid, "
4521 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4523 "FROM pg_catalog.pg_index i "
4524 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4525 "LEFT JOIN pg_catalog.pg_depend d "
4526 "ON (d.classid = t.tableoid "
4527 "AND d.objid = t.oid "
4528 "AND d.deptype = 'i') "
4529 "LEFT JOIN pg_catalog.pg_constraint c "
4530 "ON (d.refclassid = c.tableoid "
4531 "AND d.refobjid = c.oid) "
4532 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4533 "ORDER BY indexname",
4534 tbinfo->dobj.catId.oid);
4536 else if (fout->remoteVersion >= 70300)
4538 appendPQExpBuffer(query,
4539 "SELECT t.tableoid, t.oid, "
4540 "t.relname AS indexname, "
4541 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4542 "t.relnatts AS indnkeys, "
4543 "i.indkey, i.indisclustered, "
4544 "c.contype, c.conname, "
4545 "c.condeferrable, c.condeferred, "
4546 "c.tableoid AS contableoid, "
4549 "NULL AS tablespace, "
4551 "FROM pg_catalog.pg_index i "
4552 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4553 "LEFT JOIN pg_catalog.pg_depend d "
4554 "ON (d.classid = t.tableoid "
4555 "AND d.objid = t.oid "
4556 "AND d.deptype = 'i') "
4557 "LEFT JOIN pg_catalog.pg_constraint c "
4558 "ON (d.refclassid = c.tableoid "
4559 "AND d.refobjid = c.oid) "
4560 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4561 "ORDER BY indexname",
4562 tbinfo->dobj.catId.oid);
4564 else if (fout->remoteVersion >= 70100)
4566 appendPQExpBuffer(query,
4567 "SELECT t.tableoid, t.oid, "
4568 "t.relname AS indexname, "
4569 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4570 "t.relnatts AS indnkeys, "
4571 "i.indkey, false AS indisclustered, "
4572 "CASE WHEN i.indisprimary THEN 'p'::char "
4573 "ELSE '0'::char END AS contype, "
4574 "t.relname AS conname, "
4575 "false AS condeferrable, "
4576 "false AS condeferred, "
4577 "0::oid AS contableoid, "
4580 "NULL AS tablespace, "
4582 "FROM pg_index i, pg_class t "
4583 "WHERE t.oid = i.indexrelid "
4584 "AND i.indrelid = '%u'::oid "
4585 "ORDER BY indexname",
4586 tbinfo->dobj.catId.oid);
4590 appendPQExpBuffer(query,
4592 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4594 "t.relname AS indexname, "
4595 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4596 "t.relnatts AS indnkeys, "
4597 "i.indkey, false AS indisclustered, "
4598 "CASE WHEN i.indisprimary THEN 'p'::char "
4599 "ELSE '0'::char END AS contype, "
4600 "t.relname AS conname, "
4601 "false AS condeferrable, "
4602 "false AS condeferred, "
4603 "0::oid AS contableoid, "
4606 "NULL AS tablespace, "
4608 "FROM pg_index i, pg_class t "
4609 "WHERE t.oid = i.indexrelid "
4610 "AND i.indrelid = '%u'::oid "
4611 "ORDER BY indexname",
4612 tbinfo->dobj.catId.oid);
4615 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4617 ntups = PQntuples(res);
4619 i_tableoid = PQfnumber(res, "tableoid");
4620 i_oid = PQfnumber(res, "oid");
4621 i_indexname = PQfnumber(res, "indexname");
4622 i_indexdef = PQfnumber(res, "indexdef");
4623 i_indnkeys = PQfnumber(res, "indnkeys");
4624 i_indkey = PQfnumber(res, "indkey");
4625 i_indisclustered = PQfnumber(res, "indisclustered");
4626 i_contype = PQfnumber(res, "contype");
4627 i_conname = PQfnumber(res, "conname");
4628 i_condeferrable = PQfnumber(res, "condeferrable");
4629 i_condeferred = PQfnumber(res, "condeferred");
4630 i_contableoid = PQfnumber(res, "contableoid");
4631 i_conoid = PQfnumber(res, "conoid");
4632 i_condef = PQfnumber(res, "condef");
4633 i_tablespace = PQfnumber(res, "tablespace");
4634 i_options = PQfnumber(res, "options");
4636 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4637 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4639 for (j = 0; j < ntups; j++)
4643 indxinfo[j].dobj.objType = DO_INDEX;
4644 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4645 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4646 AssignDumpId(&indxinfo[j].dobj);
4647 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4648 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4649 indxinfo[j].indextable = tbinfo;
4650 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4651 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4652 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4653 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4656 * In pre-7.4 releases, indkeys may contain more entries than
4657 * indnkeys says (since indnkeys will be 1 for a functional
4658 * index). We don't actually care about this case since we don't
4659 * examine indkeys except for indexes associated with PRIMARY and
4660 * UNIQUE constraints, which are never functional indexes. But we
4661 * have to allocate enough space to keep parseOidArray from
4664 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4665 parseOidArray(PQgetvalue(res, j, i_indkey),
4666 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4667 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4668 contype = *(PQgetvalue(res, j, i_contype));
4670 if (contype == 'p' || contype == 'u' || contype == 'x')
4673 * If we found a constraint matching the index, create an
4676 * In a pre-7.3 database, we take this path iff the index was
4677 * marked indisprimary.
4679 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4680 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4681 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4682 AssignDumpId(&constrinfo[j].dobj);
4683 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4684 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4685 constrinfo[j].contable = tbinfo;
4686 constrinfo[j].condomain = NULL;
4687 constrinfo[j].contype = contype;
4689 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4691 constrinfo[j].condef = NULL;
4692 constrinfo[j].confrelid = InvalidOid;
4693 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4694 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4695 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4696 constrinfo[j].conislocal = true;
4697 constrinfo[j].separate = true;
4699 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4701 /* If pre-7.3 DB, better make sure table comes first */
4702 addObjectDependency(&constrinfo[j].dobj,
4703 tbinfo->dobj.dumpId);
4707 /* Plain secondary index */
4708 indxinfo[j].indexconstraint = 0;
4715 destroyPQExpBuffer(query);
4721 * Get info about constraints on dumpable tables.
4723 * Currently handles foreign keys only.
4724 * Unique and primary key constraints are handled with indexes,
4725 * while check constraints are processed in getTableAttrs().
4728 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4732 ConstraintInfo *constrinfo;
4742 /* pg_constraint was created in 7.3, so nothing to do if older */
4743 if (fout->remoteVersion < 70300)
4746 query = createPQExpBuffer();
4748 for (i = 0; i < numTables; i++)
4750 TableInfo *tbinfo = &tblinfo[i];
4752 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4756 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4760 * select table schema to ensure constraint expr is qualified if
4763 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4765 resetPQExpBuffer(query);
4766 appendPQExpBuffer(query,
4767 "SELECT tableoid, oid, conname, confrelid, "
4768 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4769 "FROM pg_catalog.pg_constraint "
4770 "WHERE conrelid = '%u'::pg_catalog.oid "
4771 "AND contype = 'f'",
4772 tbinfo->dobj.catId.oid);
4773 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4775 ntups = PQntuples(res);
4777 i_contableoid = PQfnumber(res, "tableoid");
4778 i_conoid = PQfnumber(res, "oid");
4779 i_conname = PQfnumber(res, "conname");
4780 i_confrelid = PQfnumber(res, "confrelid");
4781 i_condef = PQfnumber(res, "condef");
4783 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4785 for (j = 0; j < ntups; j++)
4787 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4788 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4789 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4790 AssignDumpId(&constrinfo[j].dobj);
4791 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4792 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4793 constrinfo[j].contable = tbinfo;
4794 constrinfo[j].condomain = NULL;
4795 constrinfo[j].contype = 'f';
4796 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4797 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4798 constrinfo[j].conindex = 0;
4799 constrinfo[j].condeferrable = false;
4800 constrinfo[j].condeferred = false;
4801 constrinfo[j].conislocal = true;
4802 constrinfo[j].separate = true;
4808 destroyPQExpBuffer(query);
4812 * getDomainConstraints
4814 * Get info about constraints on a domain.
4817 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4820 ConstraintInfo *constrinfo;
4829 /* pg_constraint was created in 7.3, so nothing to do if older */
4830 if (fout->remoteVersion < 70300)
4834 * select appropriate schema to ensure names in constraint are properly
4837 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4839 query = createPQExpBuffer();
4841 if (fout->remoteVersion >= 90100)
4842 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4843 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4845 "FROM pg_catalog.pg_constraint "
4846 "WHERE contypid = '%u'::pg_catalog.oid "
4848 tyinfo->dobj.catId.oid);
4850 else if (fout->remoteVersion >= 70400)
4851 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4852 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4853 "true as convalidated "
4854 "FROM pg_catalog.pg_constraint "
4855 "WHERE contypid = '%u'::pg_catalog.oid "
4857 tyinfo->dobj.catId.oid);
4859 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4860 "'CHECK (' || consrc || ')' AS consrc, "
4861 "true as convalidated "
4862 "FROM pg_catalog.pg_constraint "
4863 "WHERE contypid = '%u'::pg_catalog.oid "
4865 tyinfo->dobj.catId.oid);
4867 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4869 ntups = PQntuples(res);
4871 i_tableoid = PQfnumber(res, "tableoid");
4872 i_oid = PQfnumber(res, "oid");
4873 i_conname = PQfnumber(res, "conname");
4874 i_consrc = PQfnumber(res, "consrc");
4876 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4878 tyinfo->nDomChecks = ntups;
4879 tyinfo->domChecks = constrinfo;
4881 for (i = 0; i < ntups; i++)
4883 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4885 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4886 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4887 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4888 AssignDumpId(&constrinfo[i].dobj);
4889 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4890 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4891 constrinfo[i].contable = NULL;
4892 constrinfo[i].condomain = tyinfo;
4893 constrinfo[i].contype = 'c';
4894 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4895 constrinfo[i].confrelid = InvalidOid;
4896 constrinfo[i].conindex = 0;
4897 constrinfo[i].condeferrable = false;
4898 constrinfo[i].condeferred = false;
4899 constrinfo[i].conislocal = true;
4901 constrinfo[i].separate = !validated;
4904 * Make the domain depend on the constraint, ensuring it won't be
4905 * output till any constraint dependencies are OK. If the constraint
4906 * has not been validated, it's going to be dumped after the domain
4907 * anyway, so this doesn't matter.
4910 addObjectDependency(&tyinfo->dobj,
4911 constrinfo[i].dobj.dumpId);
4916 destroyPQExpBuffer(query);
4921 * get basic information about every rule in the system
4923 * numRules is set to the number of rules read in
4926 getRules(Archive *fout, int *numRules)
4931 PQExpBuffer query = createPQExpBuffer();
4941 /* Make sure we are in proper schema */
4942 selectSourceSchema(fout, "pg_catalog");
4944 if (fout->remoteVersion >= 80300)
4946 appendPQExpBuffer(query, "SELECT "
4947 "tableoid, oid, rulename, "
4948 "ev_class AS ruletable, ev_type, is_instead, "
4953 else if (fout->remoteVersion >= 70100)
4955 appendPQExpBuffer(query, "SELECT "
4956 "tableoid, oid, rulename, "
4957 "ev_class AS ruletable, ev_type, is_instead, "
4958 "'O'::char AS ev_enabled "
4964 appendPQExpBuffer(query, "SELECT "
4965 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4967 "ev_class AS ruletable, ev_type, is_instead, "
4968 "'O'::char AS ev_enabled "
4973 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4975 ntups = PQntuples(res);
4979 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
4981 i_tableoid = PQfnumber(res, "tableoid");
4982 i_oid = PQfnumber(res, "oid");
4983 i_rulename = PQfnumber(res, "rulename");
4984 i_ruletable = PQfnumber(res, "ruletable");
4985 i_ev_type = PQfnumber(res, "ev_type");
4986 i_is_instead = PQfnumber(res, "is_instead");
4987 i_ev_enabled = PQfnumber(res, "ev_enabled");
4989 for (i = 0; i < ntups; i++)
4993 ruleinfo[i].dobj.objType = DO_RULE;
4994 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4995 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4996 AssignDumpId(&ruleinfo[i].dobj);
4997 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
4998 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
4999 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5000 if (ruleinfo[i].ruletable == NULL)
5001 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5002 ruletableoid, ruleinfo[i].dobj.catId.oid);
5003 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5004 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5005 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5006 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5007 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5008 if (ruleinfo[i].ruletable)
5011 * If the table is a view, force its ON SELECT rule to be sorted
5012 * before the view itself --- this ensures that any dependencies
5013 * for the rule affect the table's positioning. Other rules are
5014 * forced to appear after their table.
5016 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5017 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5019 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5020 ruleinfo[i].dobj.dumpId);
5021 /* We'll merge the rule into CREATE VIEW, if possible */
5022 ruleinfo[i].separate = false;
5026 addObjectDependency(&ruleinfo[i].dobj,
5027 ruleinfo[i].ruletable->dobj.dumpId);
5028 ruleinfo[i].separate = true;
5032 ruleinfo[i].separate = true;
5037 destroyPQExpBuffer(query);
5044 * get information about every trigger on a dumpable table
5046 * Note: trigger data is not returned directly to the caller, but it
5047 * does get entered into the DumpableObject tables.
5050 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5054 PQExpBuffer query = createPQExpBuffer();
5056 TriggerInfo *tginfo;
5074 for (i = 0; i < numTables; i++)
5076 TableInfo *tbinfo = &tblinfo[i];
5078 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5082 write_msg(NULL, "reading triggers for table \"%s\"\n",
5086 * select table schema to ensure regproc name is qualified if needed
5088 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5090 resetPQExpBuffer(query);
5091 if (fout->remoteVersion >= 90000)
5094 * NB: think not to use pretty=true in pg_get_triggerdef. It
5095 * could result in non-forward-compatible dumps of WHEN clauses
5096 * due to under-parenthesization.
5098 appendPQExpBuffer(query,
5100 "tgfoid::pg_catalog.regproc AS tgfname, "
5101 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5102 "tgenabled, tableoid, oid "
5103 "FROM pg_catalog.pg_trigger t "
5104 "WHERE tgrelid = '%u'::pg_catalog.oid "
5105 "AND NOT tgisinternal",
5106 tbinfo->dobj.catId.oid);
5108 else if (fout->remoteVersion >= 80300)
5111 * We ignore triggers that are tied to a foreign-key constraint
5113 appendPQExpBuffer(query,
5115 "tgfoid::pg_catalog.regproc AS tgfname, "
5116 "tgtype, tgnargs, tgargs, tgenabled, "
5117 "tgisconstraint, tgconstrname, tgdeferrable, "
5118 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5119 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5120 "FROM pg_catalog.pg_trigger t "
5121 "WHERE tgrelid = '%u'::pg_catalog.oid "
5122 "AND tgconstraint = 0",
5123 tbinfo->dobj.catId.oid);
5125 else if (fout->remoteVersion >= 70300)
5128 * We ignore triggers that are tied to a foreign-key constraint,
5129 * but in these versions we have to grovel through pg_constraint
5132 appendPQExpBuffer(query,
5134 "tgfoid::pg_catalog.regproc AS tgfname, "
5135 "tgtype, tgnargs, tgargs, tgenabled, "
5136 "tgisconstraint, tgconstrname, tgdeferrable, "
5137 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5138 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5139 "FROM pg_catalog.pg_trigger t "
5140 "WHERE tgrelid = '%u'::pg_catalog.oid "
5141 "AND (NOT tgisconstraint "
5143 " (SELECT 1 FROM pg_catalog.pg_depend d "
5144 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5145 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5146 tbinfo->dobj.catId.oid);
5148 else if (fout->remoteVersion >= 70100)
5150 appendPQExpBuffer(query,
5151 "SELECT tgname, tgfoid::regproc AS tgfname, "
5152 "tgtype, tgnargs, tgargs, tgenabled, "
5153 "tgisconstraint, tgconstrname, tgdeferrable, "
5154 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5155 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5156 " AS tgconstrrelname "
5158 "WHERE tgrelid = '%u'::oid",
5159 tbinfo->dobj.catId.oid);
5163 appendPQExpBuffer(query,
5164 "SELECT tgname, tgfoid::regproc AS tgfname, "
5165 "tgtype, tgnargs, tgargs, tgenabled, "
5166 "tgisconstraint, tgconstrname, tgdeferrable, "
5167 "tgconstrrelid, tginitdeferred, "
5168 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5170 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5171 " AS tgconstrrelname "
5173 "WHERE tgrelid = '%u'::oid",
5174 tbinfo->dobj.catId.oid);
5176 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5178 ntups = PQntuples(res);
5180 i_tableoid = PQfnumber(res, "tableoid");
5181 i_oid = PQfnumber(res, "oid");
5182 i_tgname = PQfnumber(res, "tgname");
5183 i_tgfname = PQfnumber(res, "tgfname");
5184 i_tgtype = PQfnumber(res, "tgtype");
5185 i_tgnargs = PQfnumber(res, "tgnargs");
5186 i_tgargs = PQfnumber(res, "tgargs");
5187 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5188 i_tgconstrname = PQfnumber(res, "tgconstrname");
5189 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5190 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5191 i_tgenabled = PQfnumber(res, "tgenabled");
5192 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5193 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5194 i_tgdef = PQfnumber(res, "tgdef");
5196 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5198 for (j = 0; j < ntups; j++)
5200 tginfo[j].dobj.objType = DO_TRIGGER;
5201 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5202 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5203 AssignDumpId(&tginfo[j].dobj);
5204 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5205 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5206 tginfo[j].tgtable = tbinfo;
5207 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5210 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5212 /* remaining fields are not valid if we have tgdef */
5213 tginfo[j].tgfname = NULL;
5214 tginfo[j].tgtype = 0;
5215 tginfo[j].tgnargs = 0;
5216 tginfo[j].tgargs = NULL;
5217 tginfo[j].tgisconstraint = false;
5218 tginfo[j].tgdeferrable = false;
5219 tginfo[j].tginitdeferred = false;
5220 tginfo[j].tgconstrname = NULL;
5221 tginfo[j].tgconstrrelid = InvalidOid;
5222 tginfo[j].tgconstrrelname = NULL;
5226 tginfo[j].tgdef = NULL;
5228 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5229 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5230 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5231 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5232 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5233 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5234 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5236 if (tginfo[j].tgisconstraint)
5238 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5239 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5240 if (OidIsValid(tginfo[j].tgconstrrelid))
5242 if (PQgetisnull(res, j, i_tgconstrrelname))
5243 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5244 tginfo[j].dobj.name,
5246 tginfo[j].tgconstrrelid);
5247 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5250 tginfo[j].tgconstrrelname = NULL;
5254 tginfo[j].tgconstrname = NULL;
5255 tginfo[j].tgconstrrelid = InvalidOid;
5256 tginfo[j].tgconstrrelname = NULL;
5264 destroyPQExpBuffer(query);
5269 * get basic information about every procedural language in the system
5271 * numProcLangs is set to the number of langs read in
5273 * NB: this must run after getFuncs() because we assume we can do
5277 getProcLangs(Archive *fout, int *numProcLangs)
5282 PQExpBuffer query = createPQExpBuffer();
5283 ProcLangInfo *planginfo;
5288 int i_lanplcallfoid;
5294 /* Make sure we are in proper schema */
5295 selectSourceSchema(fout, "pg_catalog");
5297 if (fout->remoteVersion >= 90000)
5299 /* pg_language has a laninline column */
5300 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5301 "lanname, lanpltrusted, lanplcallfoid, "
5302 "laninline, lanvalidator, lanacl, "
5303 "(%s lanowner) AS lanowner "
5309 else if (fout->remoteVersion >= 80300)
5311 /* pg_language has a lanowner column */
5312 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5313 "lanname, lanpltrusted, lanplcallfoid, "
5314 "lanvalidator, lanacl, "
5315 "(%s lanowner) AS lanowner "
5321 else if (fout->remoteVersion >= 80100)
5323 /* Languages are owned by the bootstrap superuser, OID 10 */
5324 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5325 "(%s '10') AS lanowner "
5331 else if (fout->remoteVersion >= 70400)
5333 /* Languages are owned by the bootstrap superuser, sysid 1 */
5334 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5335 "(%s '1') AS lanowner "
5341 else if (fout->remoteVersion >= 70100)
5343 /* No clear notion of an owner at all before 7.4 ... */
5344 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5350 appendPQExpBuffer(query, "SELECT "
5351 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5352 "oid, * FROM pg_language "
5357 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5359 ntups = PQntuples(res);
5361 *numProcLangs = ntups;
5363 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5365 i_tableoid = PQfnumber(res, "tableoid");
5366 i_oid = PQfnumber(res, "oid");
5367 i_lanname = PQfnumber(res, "lanname");
5368 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5369 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5370 /* these may fail and return -1: */
5371 i_laninline = PQfnumber(res, "laninline");
5372 i_lanvalidator = PQfnumber(res, "lanvalidator");
5373 i_lanacl = PQfnumber(res, "lanacl");
5374 i_lanowner = PQfnumber(res, "lanowner");
5376 for (i = 0; i < ntups; i++)
5378 planginfo[i].dobj.objType = DO_PROCLANG;
5379 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5380 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5381 AssignDumpId(&planginfo[i].dobj);
5383 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5384 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5385 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5386 if (i_laninline >= 0)
5387 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5389 planginfo[i].laninline = InvalidOid;
5390 if (i_lanvalidator >= 0)
5391 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5393 planginfo[i].lanvalidator = InvalidOid;
5395 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5397 planginfo[i].lanacl = pg_strdup("{=U}");
5398 if (i_lanowner >= 0)
5399 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5401 planginfo[i].lanowner = pg_strdup("");
5403 if (fout->remoteVersion < 70300)
5406 * We need to make a dependency to ensure the function will be
5407 * dumped first. (In 7.3 and later the regular dependency
5408 * mechanism will handle this for us.)
5410 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5413 addObjectDependency(&planginfo[i].dobj,
5414 funcInfo->dobj.dumpId);
5420 destroyPQExpBuffer(query);
5427 * get basic information about every cast in the system
5429 * numCasts is set to the number of casts read in
5432 getCasts(Archive *fout, int *numCasts)
5437 PQExpBuffer query = createPQExpBuffer();
5447 /* Make sure we are in proper schema */
5448 selectSourceSchema(fout, "pg_catalog");
5450 if (fout->remoteVersion >= 80400)
5452 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5453 "castsource, casttarget, castfunc, castcontext, "
5455 "FROM pg_cast ORDER BY 3,4");
5457 else if (fout->remoteVersion >= 70300)
5459 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5460 "castsource, casttarget, castfunc, castcontext, "
5461 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5462 "FROM pg_cast ORDER BY 3,4");
5466 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5467 "t1.oid AS castsource, t2.oid AS casttarget, "
5468 "p.oid AS castfunc, 'e' AS castcontext, "
5469 "'f' AS castmethod "
5470 "FROM pg_type t1, pg_type t2, pg_proc p "
5471 "WHERE p.pronargs = 1 AND "
5472 "p.proargtypes[0] = t1.oid AND "
5473 "p.prorettype = t2.oid AND p.proname = t2.typname "
5477 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5479 ntups = PQntuples(res);
5483 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5485 i_tableoid = PQfnumber(res, "tableoid");
5486 i_oid = PQfnumber(res, "oid");
5487 i_castsource = PQfnumber(res, "castsource");
5488 i_casttarget = PQfnumber(res, "casttarget");
5489 i_castfunc = PQfnumber(res, "castfunc");
5490 i_castcontext = PQfnumber(res, "castcontext");
5491 i_castmethod = PQfnumber(res, "castmethod");
5493 for (i = 0; i < ntups; i++)
5495 PQExpBufferData namebuf;
5496 TypeInfo *sTypeInfo;
5497 TypeInfo *tTypeInfo;
5499 castinfo[i].dobj.objType = DO_CAST;
5500 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5501 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5502 AssignDumpId(&castinfo[i].dobj);
5503 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5504 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5505 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5506 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5507 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5510 * Try to name cast as concatenation of typnames. This is only used
5511 * for purposes of sorting. If we fail to find either type, the name
5512 * will be an empty string.
5514 initPQExpBuffer(&namebuf);
5515 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5516 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5517 if (sTypeInfo && tTypeInfo)
5518 appendPQExpBuffer(&namebuf, "%s %s",
5519 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5520 castinfo[i].dobj.name = namebuf.data;
5522 if (OidIsValid(castinfo[i].castfunc))
5525 * We need to make a dependency to ensure the function will be
5526 * dumped first. (In 7.3 and later the regular dependency
5527 * mechanism will handle this for us.)
5531 funcInfo = findFuncByOid(castinfo[i].castfunc);
5533 addObjectDependency(&castinfo[i].dobj,
5534 funcInfo->dobj.dumpId);
5540 destroyPQExpBuffer(query);
5547 * for each interesting table, read info about its attributes
5548 * (names, types, default values, CHECK constraints, etc)
5550 * This is implemented in a very inefficient way right now, looping
5551 * through the tblinfo and doing a join per table to find the attrs and their
5552 * types. However, because we want type names and so forth to be named
5553 * relative to the schema of each table, we couldn't do it in just one
5554 * query. (Maybe one query per schema?)
5559 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5563 PQExpBuffer q = createPQExpBuffer();
5568 int i_attstattarget;
5579 int i_attfdwoptions;
5584 for (i = 0; i < numTables; i++)
5586 TableInfo *tbinfo = &tblinfo[i];
5588 /* Don't bother to collect info for sequences */
5589 if (tbinfo->relkind == RELKIND_SEQUENCE)
5592 /* Don't bother with uninteresting tables, either */
5593 if (!tbinfo->interesting)
5597 * Make sure we are in proper schema for this table; this allows
5598 * correct retrieval of formatted type names and default exprs
5600 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5602 /* find all the user attributes and their types */
5605 * we must read the attribute names in attribute number order! because
5606 * we will use the attnum to index into the attnames array later. We
5607 * actually ask to order by "attrelid, attnum" because (at least up to
5608 * 7.3) the planner is not smart enough to realize it needn't re-sort
5609 * the output of an indexscan on pg_attribute_relid_attnum_index.
5612 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5615 resetPQExpBuffer(q);
5617 if (fout->remoteVersion >= 90200)
5620 * attfdwoptions is new in 9.2.
5622 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5623 "a.attstattarget, a.attstorage, t.typstorage, "
5624 "a.attnotnull, a.atthasdef, a.attisdropped, "
5625 "a.attlen, a.attalign, a.attislocal, "
5626 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5627 "array_to_string(a.attoptions, ', ') AS attoptions, "
5628 "CASE WHEN a.attcollation <> t.typcollation "
5629 "THEN a.attcollation ELSE 0 END AS attcollation, "
5630 "pg_catalog.array_to_string(ARRAY("
5631 "SELECT pg_catalog.quote_ident(option_name) || "
5632 "' ' || pg_catalog.quote_literal(option_value) "
5633 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5634 "ORDER BY option_name"
5635 "), E',\n ') AS attfdwoptions "
5636 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5637 "ON a.atttypid = t.oid "
5638 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5639 "AND a.attnum > 0::pg_catalog.int2 "
5640 "ORDER BY a.attrelid, a.attnum",
5641 tbinfo->dobj.catId.oid);
5643 else if (fout->remoteVersion >= 90100)
5646 * attcollation is new in 9.1. Since we only want to dump COLLATE
5647 * clauses for attributes whose collation is different from their
5648 * type's default, we use a CASE here to suppress uninteresting
5649 * attcollations cheaply.
5651 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5652 "a.attstattarget, a.attstorage, t.typstorage, "
5653 "a.attnotnull, a.atthasdef, a.attisdropped, "
5654 "a.attlen, a.attalign, a.attislocal, "
5655 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5656 "array_to_string(a.attoptions, ', ') AS attoptions, "
5657 "CASE WHEN a.attcollation <> t.typcollation "
5658 "THEN a.attcollation ELSE 0 END AS attcollation, "
5659 "NULL AS attfdwoptions "
5660 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5661 "ON a.atttypid = t.oid "
5662 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5663 "AND a.attnum > 0::pg_catalog.int2 "
5664 "ORDER BY a.attrelid, a.attnum",
5665 tbinfo->dobj.catId.oid);
5667 else if (fout->remoteVersion >= 90000)
5669 /* attoptions is new in 9.0 */
5670 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5671 "a.attstattarget, a.attstorage, t.typstorage, "
5672 "a.attnotnull, a.atthasdef, a.attisdropped, "
5673 "a.attlen, a.attalign, a.attislocal, "
5674 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5675 "array_to_string(a.attoptions, ', ') AS attoptions, "
5676 "0 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 >= 70300)
5687 /* need left join here to not fail on dropped columns ... */
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 "'' AS attoptions, 0 AS attcollation, "
5694 "NULL AS attfdwoptions "
5695 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5696 "ON a.atttypid = t.oid "
5697 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5698 "AND a.attnum > 0::pg_catalog.int2 "
5699 "ORDER BY a.attrelid, a.attnum",
5700 tbinfo->dobj.catId.oid);
5702 else if (fout->remoteVersion >= 70100)
5705 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5706 * we don't dump it because we can't tell whether it's been
5707 * explicitly set or was just a default.
5709 * attislocal doesn't exist before 7.3, either; in older databases
5710 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5712 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5713 "-1 AS attstattarget, a.attstorage, "
5714 "t.typstorage, a.attnotnull, a.atthasdef, "
5715 "false AS attisdropped, a.attlen, "
5716 "a.attalign, true AS attislocal, "
5717 "format_type(t.oid,a.atttypmod) AS atttypname, "
5718 "'' AS attoptions, 0 AS attcollation, "
5719 "NULL AS attfdwoptions "
5720 "FROM pg_attribute a LEFT JOIN pg_type t "
5721 "ON a.atttypid = t.oid "
5722 "WHERE a.attrelid = '%u'::oid "
5723 "AND a.attnum > 0::int2 "
5724 "ORDER BY a.attrelid, a.attnum",
5725 tbinfo->dobj.catId.oid);
5729 /* format_type not available before 7.1 */
5730 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5731 "-1 AS attstattarget, "
5732 "attstorage, attstorage AS typstorage, "
5733 "attnotnull, atthasdef, false AS attisdropped, "
5734 "attlen, attalign, "
5735 "true AS attislocal, "
5736 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5737 "'' AS attoptions, 0 AS attcollation, "
5738 "NULL AS attfdwoptions "
5739 "FROM pg_attribute a "
5740 "WHERE attrelid = '%u'::oid "
5741 "AND attnum > 0::int2 "
5742 "ORDER BY attrelid, attnum",
5743 tbinfo->dobj.catId.oid);
5746 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5748 ntups = PQntuples(res);
5750 i_attnum = PQfnumber(res, "attnum");
5751 i_attname = PQfnumber(res, "attname");
5752 i_atttypname = PQfnumber(res, "atttypname");
5753 i_atttypmod = PQfnumber(res, "atttypmod");
5754 i_attstattarget = PQfnumber(res, "attstattarget");
5755 i_attstorage = PQfnumber(res, "attstorage");
5756 i_typstorage = PQfnumber(res, "typstorage");
5757 i_attnotnull = PQfnumber(res, "attnotnull");
5758 i_atthasdef = PQfnumber(res, "atthasdef");
5759 i_attisdropped = PQfnumber(res, "attisdropped");
5760 i_attlen = PQfnumber(res, "attlen");
5761 i_attalign = PQfnumber(res, "attalign");
5762 i_attislocal = PQfnumber(res, "attislocal");
5763 i_attoptions = PQfnumber(res, "attoptions");
5764 i_attcollation = PQfnumber(res, "attcollation");
5765 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5767 tbinfo->numatts = ntups;
5768 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5769 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5770 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5771 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5772 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5773 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5774 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5775 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5776 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5777 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5778 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5779 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5780 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5781 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5782 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5783 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5784 hasdefaults = false;
5786 for (j = 0; j < ntups; j++)
5788 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5790 "invalid column numbering in table \"%s\"\n",
5792 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5793 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5794 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5795 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5796 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5797 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5798 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5799 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5800 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5801 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5802 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5803 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5804 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5805 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5806 tbinfo->attrdefs[j] = NULL; /* fix below */
5807 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5809 /* these flags will be set in flagInhAttrs() */
5810 tbinfo->inhNotNull[j] = false;
5816 * Get info about column defaults
5820 AttrDefInfo *attrdefs;
5824 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5827 resetPQExpBuffer(q);
5828 if (fout->remoteVersion >= 70300)
5830 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5831 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5832 "FROM pg_catalog.pg_attrdef "
5833 "WHERE adrelid = '%u'::pg_catalog.oid",
5834 tbinfo->dobj.catId.oid);
5836 else if (fout->remoteVersion >= 70200)
5838 /* 7.2 did not have OIDs in pg_attrdef */
5839 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5840 "pg_get_expr(adbin, adrelid) AS adsrc "
5842 "WHERE adrelid = '%u'::oid",
5843 tbinfo->dobj.catId.oid);
5845 else if (fout->remoteVersion >= 70100)
5847 /* no pg_get_expr, so must rely on adsrc */
5848 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5850 "WHERE adrelid = '%u'::oid",
5851 tbinfo->dobj.catId.oid);
5855 /* no pg_get_expr, no tableoid either */
5856 appendPQExpBuffer(q, "SELECT "
5857 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5858 "oid, adnum, adsrc "
5860 "WHERE adrelid = '%u'::oid",
5861 tbinfo->dobj.catId.oid);
5863 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5865 numDefaults = PQntuples(res);
5866 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5868 for (j = 0; j < numDefaults; j++)
5872 adnum = atoi(PQgetvalue(res, j, 2));
5874 if (adnum <= 0 || adnum > ntups)
5876 "invalid adnum value %d for table \"%s\"\n",
5877 adnum, tbinfo->dobj.name);
5880 * dropped columns shouldn't have defaults, but just in case,
5883 if (tbinfo->attisdropped[adnum - 1])
5886 attrdefs[j].dobj.objType = DO_ATTRDEF;
5887 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5888 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5889 AssignDumpId(&attrdefs[j].dobj);
5890 attrdefs[j].adtable = tbinfo;
5891 attrdefs[j].adnum = adnum;
5892 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5894 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5895 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5897 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5900 * Defaults on a VIEW must always be dumped as separate ALTER
5901 * TABLE commands. Defaults on regular tables are dumped as
5902 * part of the CREATE TABLE if possible, which it won't be if
5903 * the column is not going to be emitted explicitly.
5905 if (tbinfo->relkind == RELKIND_VIEW)
5907 attrdefs[j].separate = true;
5908 /* needed in case pre-7.3 DB: */
5909 addObjectDependency(&attrdefs[j].dobj,
5910 tbinfo->dobj.dumpId);
5912 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5914 /* column will be suppressed, print default separately */
5915 attrdefs[j].separate = true;
5916 /* needed in case pre-7.3 DB: */
5917 addObjectDependency(&attrdefs[j].dobj,
5918 tbinfo->dobj.dumpId);
5922 attrdefs[j].separate = false;
5925 * Mark the default as needing to appear before the table,
5926 * so that any dependencies it has must be emitted before
5927 * the CREATE TABLE. If this is not possible, we'll
5928 * change to "separate" mode while sorting dependencies.
5930 addObjectDependency(&tbinfo->dobj,
5931 attrdefs[j].dobj.dumpId);
5934 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5940 * Get info about table CHECK constraints
5942 if (tbinfo->ncheck > 0)
5944 ConstraintInfo *constrs;
5948 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5951 resetPQExpBuffer(q);
5952 if (fout->remoteVersion >= 90200)
5955 * convalidated is new in 9.2 (actually, it is there in 9.1,
5956 * but it wasn't ever false for check constraints until 9.2).
5958 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5959 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5960 "conislocal, convalidated "
5961 "FROM pg_catalog.pg_constraint "
5962 "WHERE conrelid = '%u'::pg_catalog.oid "
5963 " AND contype = 'c' "
5965 tbinfo->dobj.catId.oid);
5967 else if (fout->remoteVersion >= 80400)
5969 /* conislocal is new in 8.4 */
5970 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5971 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5972 "conislocal, true AS convalidated "
5973 "FROM pg_catalog.pg_constraint "
5974 "WHERE conrelid = '%u'::pg_catalog.oid "
5975 " AND contype = 'c' "
5977 tbinfo->dobj.catId.oid);
5979 else if (fout->remoteVersion >= 70400)
5981 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5982 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5983 "true AS conislocal, true AS convalidated "
5984 "FROM pg_catalog.pg_constraint "
5985 "WHERE conrelid = '%u'::pg_catalog.oid "
5986 " AND contype = 'c' "
5988 tbinfo->dobj.catId.oid);
5990 else if (fout->remoteVersion >= 70300)
5992 /* no pg_get_constraintdef, must use consrc */
5993 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5994 "'CHECK (' || consrc || ')' AS consrc, "
5995 "true AS conislocal, true AS convalidated "
5996 "FROM pg_catalog.pg_constraint "
5997 "WHERE conrelid = '%u'::pg_catalog.oid "
5998 " AND contype = 'c' "
6000 tbinfo->dobj.catId.oid);
6002 else if (fout->remoteVersion >= 70200)
6004 /* 7.2 did not have OIDs in pg_relcheck */
6005 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6006 "rcname AS conname, "
6007 "'CHECK (' || rcsrc || ')' AS consrc, "
6008 "true AS conislocal, true AS convalidated "
6010 "WHERE rcrelid = '%u'::oid "
6012 tbinfo->dobj.catId.oid);
6014 else if (fout->remoteVersion >= 70100)
6016 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6017 "rcname AS conname, "
6018 "'CHECK (' || rcsrc || ')' AS consrc, "
6019 "true AS conislocal, true AS convalidated "
6021 "WHERE rcrelid = '%u'::oid "
6023 tbinfo->dobj.catId.oid);
6027 /* no tableoid in 7.0 */
6028 appendPQExpBuffer(q, "SELECT "
6029 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6030 "oid, rcname AS conname, "
6031 "'CHECK (' || rcsrc || ')' AS consrc, "
6032 "true AS conislocal, true AS convalidated "
6034 "WHERE rcrelid = '%u'::oid "
6036 tbinfo->dobj.catId.oid);
6038 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6040 numConstrs = PQntuples(res);
6041 if (numConstrs != tbinfo->ncheck)
6043 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6044 "expected %d check constraints on table \"%s\" but found %d\n",
6046 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6047 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6051 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6052 tbinfo->checkexprs = constrs;
6054 for (j = 0; j < numConstrs; j++)
6056 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6058 constrs[j].dobj.objType = DO_CONSTRAINT;
6059 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6060 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6061 AssignDumpId(&constrs[j].dobj);
6062 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6063 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6064 constrs[j].contable = tbinfo;
6065 constrs[j].condomain = NULL;
6066 constrs[j].contype = 'c';
6067 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6068 constrs[j].confrelid = InvalidOid;
6069 constrs[j].conindex = 0;
6070 constrs[j].condeferrable = false;
6071 constrs[j].condeferred = false;
6072 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6075 * An unvalidated constraint needs to be dumped separately, so
6076 * that potentially-violating existing data is loaded before
6079 constrs[j].separate = !validated;
6081 constrs[j].dobj.dump = tbinfo->dobj.dump;
6084 * Mark the constraint as needing to appear before the table
6085 * --- this is so that any other dependencies of the
6086 * constraint will be emitted before we try to create the
6087 * table. If the constraint is to be dumped separately, it
6088 * will be dumped after data is loaded anyway, so don't do it.
6089 * (There's an automatic dependency in the opposite direction
6090 * anyway, so don't need to add one manually here.)
6092 if (!constrs[j].separate)
6093 addObjectDependency(&tbinfo->dobj,
6094 constrs[j].dobj.dumpId);
6097 * If the constraint is inherited, this will be detected later
6098 * (in pre-8.4 databases). We also detect later if the
6099 * constraint must be split out from the table definition.
6106 destroyPQExpBuffer(q);
6110 * Test whether a column should be printed as part of table's CREATE TABLE.
6111 * Column number is zero-based.
6113 * Normally this is always true, but it's false for dropped columns, as well
6114 * as those that were inherited without any local definition. (If we print
6115 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6116 * However, in binary_upgrade mode, we must print all such columns anyway and
6117 * fix the attislocal/attisdropped state later, so as to keep control of the
6118 * physical column order.
6120 * This function exists because there are scattered nonobvious places that
6121 * must be kept in sync with this decision.
6124 shouldPrintColumn(TableInfo *tbinfo, int colno)
6128 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6134 * read all text search parsers in the system catalogs and return them
6135 * in the TSParserInfo* structure
6137 * numTSParsers is set to the number of parsers read in
6140 getTSParsers(Archive *fout, int *numTSParsers)
6146 TSParserInfo *prsinfo;
6157 /* Before 8.3, there is no built-in text search support */
6158 if (fout->remoteVersion < 80300)
6164 query = createPQExpBuffer();
6167 * find all text search objects, including builtin ones; we filter out
6168 * system-defined objects at dump-out time.
6171 /* Make sure we are in proper schema */
6172 selectSourceSchema(fout, "pg_catalog");
6174 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6175 "prsstart::oid, prstoken::oid, "
6176 "prsend::oid, prsheadline::oid, prslextype::oid "
6177 "FROM pg_ts_parser");
6179 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6181 ntups = PQntuples(res);
6182 *numTSParsers = ntups;
6184 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6186 i_tableoid = PQfnumber(res, "tableoid");
6187 i_oid = PQfnumber(res, "oid");
6188 i_prsname = PQfnumber(res, "prsname");
6189 i_prsnamespace = PQfnumber(res, "prsnamespace");
6190 i_prsstart = PQfnumber(res, "prsstart");
6191 i_prstoken = PQfnumber(res, "prstoken");
6192 i_prsend = PQfnumber(res, "prsend");
6193 i_prsheadline = PQfnumber(res, "prsheadline");
6194 i_prslextype = PQfnumber(res, "prslextype");
6196 for (i = 0; i < ntups; i++)
6198 prsinfo[i].dobj.objType = DO_TSPARSER;
6199 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6200 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6201 AssignDumpId(&prsinfo[i].dobj);
6202 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6203 prsinfo[i].dobj.namespace =
6205 atooid(PQgetvalue(res, i, i_prsnamespace)),
6206 prsinfo[i].dobj.catId.oid);
6207 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6208 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6209 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6210 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6211 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6213 /* Decide whether we want to dump it */
6214 selectDumpableObject(&(prsinfo[i].dobj));
6219 destroyPQExpBuffer(query);
6225 * getTSDictionaries:
6226 * read all text search dictionaries in the system catalogs and return them
6227 * in the TSDictInfo* structure
6229 * numTSDicts is set to the number of dictionaries read in
6232 getTSDictionaries(Archive *fout, int *numTSDicts)
6238 TSDictInfo *dictinfo;
6242 int i_dictnamespace;
6245 int i_dictinitoption;
6247 /* Before 8.3, there is no built-in text search support */
6248 if (fout->remoteVersion < 80300)
6254 query = createPQExpBuffer();
6256 /* Make sure we are in proper schema */
6257 selectSourceSchema(fout, "pg_catalog");
6259 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6260 "dictnamespace, (%s dictowner) AS rolname, "
6261 "dicttemplate, dictinitoption "
6265 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6267 ntups = PQntuples(res);
6268 *numTSDicts = ntups;
6270 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6272 i_tableoid = PQfnumber(res, "tableoid");
6273 i_oid = PQfnumber(res, "oid");
6274 i_dictname = PQfnumber(res, "dictname");
6275 i_dictnamespace = PQfnumber(res, "dictnamespace");
6276 i_rolname = PQfnumber(res, "rolname");
6277 i_dictinitoption = PQfnumber(res, "dictinitoption");
6278 i_dicttemplate = PQfnumber(res, "dicttemplate");
6280 for (i = 0; i < ntups; i++)
6282 dictinfo[i].dobj.objType = DO_TSDICT;
6283 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6284 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6285 AssignDumpId(&dictinfo[i].dobj);
6286 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6287 dictinfo[i].dobj.namespace =
6289 atooid(PQgetvalue(res, i, i_dictnamespace)),
6290 dictinfo[i].dobj.catId.oid);
6291 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6292 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6293 if (PQgetisnull(res, i, i_dictinitoption))
6294 dictinfo[i].dictinitoption = NULL;
6296 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6298 /* Decide whether we want to dump it */
6299 selectDumpableObject(&(dictinfo[i].dobj));
6304 destroyPQExpBuffer(query);
6311 * read all text search templates in the system catalogs and return them
6312 * in the TSTemplateInfo* structure
6314 * numTSTemplates is set to the number of templates read in
6317 getTSTemplates(Archive *fout, int *numTSTemplates)
6323 TSTemplateInfo *tmplinfo;
6327 int i_tmplnamespace;
6331 /* Before 8.3, there is no built-in text search support */
6332 if (fout->remoteVersion < 80300)
6334 *numTSTemplates = 0;
6338 query = createPQExpBuffer();
6340 /* Make sure we are in proper schema */
6341 selectSourceSchema(fout, "pg_catalog");
6343 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6344 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6345 "FROM pg_ts_template");
6347 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6349 ntups = PQntuples(res);
6350 *numTSTemplates = ntups;
6352 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6354 i_tableoid = PQfnumber(res, "tableoid");
6355 i_oid = PQfnumber(res, "oid");
6356 i_tmplname = PQfnumber(res, "tmplname");
6357 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6358 i_tmplinit = PQfnumber(res, "tmplinit");
6359 i_tmpllexize = PQfnumber(res, "tmpllexize");
6361 for (i = 0; i < ntups; i++)
6363 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6364 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6365 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6366 AssignDumpId(&tmplinfo[i].dobj);
6367 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6368 tmplinfo[i].dobj.namespace =
6370 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6371 tmplinfo[i].dobj.catId.oid);
6372 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6373 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6375 /* Decide whether we want to dump it */
6376 selectDumpableObject(&(tmplinfo[i].dobj));
6381 destroyPQExpBuffer(query);
6387 * getTSConfigurations:
6388 * read all text search configurations in the system catalogs and return
6389 * them in the TSConfigInfo* structure
6391 * numTSConfigs is set to the number of configurations read in
6394 getTSConfigurations(Archive *fout, int *numTSConfigs)
6400 TSConfigInfo *cfginfo;
6408 /* Before 8.3, there is no built-in text search support */
6409 if (fout->remoteVersion < 80300)
6415 query = createPQExpBuffer();
6417 /* Make sure we are in proper schema */
6418 selectSourceSchema(fout, "pg_catalog");
6420 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6421 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6422 "FROM pg_ts_config",
6425 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6427 ntups = PQntuples(res);
6428 *numTSConfigs = ntups;
6430 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6432 i_tableoid = PQfnumber(res, "tableoid");
6433 i_oid = PQfnumber(res, "oid");
6434 i_cfgname = PQfnumber(res, "cfgname");
6435 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6436 i_rolname = PQfnumber(res, "rolname");
6437 i_cfgparser = PQfnumber(res, "cfgparser");
6439 for (i = 0; i < ntups; i++)
6441 cfginfo[i].dobj.objType = DO_TSCONFIG;
6442 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6443 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6444 AssignDumpId(&cfginfo[i].dobj);
6445 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6446 cfginfo[i].dobj.namespace =
6448 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6449 cfginfo[i].dobj.catId.oid);
6450 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6451 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6453 /* Decide whether we want to dump it */
6454 selectDumpableObject(&(cfginfo[i].dobj));
6459 destroyPQExpBuffer(query);
6465 * getForeignDataWrappers:
6466 * read all foreign-data wrappers in the system catalogs and return
6467 * them in the FdwInfo* structure
6469 * numForeignDataWrappers is set to the number of fdws read in
6472 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6477 PQExpBuffer query = createPQExpBuffer();
6488 /* Before 8.4, there are no foreign-data wrappers */
6489 if (fout->remoteVersion < 80400)
6491 *numForeignDataWrappers = 0;
6495 /* Make sure we are in proper schema */
6496 selectSourceSchema(fout, "pg_catalog");
6498 if (fout->remoteVersion >= 90100)
6500 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6501 "(%s fdwowner) AS rolname, "
6502 "fdwhandler::pg_catalog.regproc, "
6503 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6504 "array_to_string(ARRAY("
6505 "SELECT quote_ident(option_name) || ' ' || "
6506 "quote_literal(option_value) "
6507 "FROM pg_options_to_table(fdwoptions) "
6508 "ORDER BY option_name"
6509 "), E',\n ') AS fdwoptions "
6510 "FROM pg_foreign_data_wrapper",
6515 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6516 "(%s fdwowner) AS rolname, "
6517 "'-' AS fdwhandler, "
6518 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6519 "array_to_string(ARRAY("
6520 "SELECT quote_ident(option_name) || ' ' || "
6521 "quote_literal(option_value) "
6522 "FROM pg_options_to_table(fdwoptions) "
6523 "ORDER BY option_name"
6524 "), E',\n ') AS fdwoptions "
6525 "FROM pg_foreign_data_wrapper",
6529 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6531 ntups = PQntuples(res);
6532 *numForeignDataWrappers = ntups;
6534 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6536 i_tableoid = PQfnumber(res, "tableoid");
6537 i_oid = PQfnumber(res, "oid");
6538 i_fdwname = PQfnumber(res, "fdwname");
6539 i_rolname = PQfnumber(res, "rolname");
6540 i_fdwhandler = PQfnumber(res, "fdwhandler");
6541 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6542 i_fdwacl = PQfnumber(res, "fdwacl");
6543 i_fdwoptions = PQfnumber(res, "fdwoptions");
6545 for (i = 0; i < ntups; i++)
6547 fdwinfo[i].dobj.objType = DO_FDW;
6548 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6549 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6550 AssignDumpId(&fdwinfo[i].dobj);
6551 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6552 fdwinfo[i].dobj.namespace = NULL;
6553 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6554 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6555 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6556 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6557 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6559 /* Decide whether we want to dump it */
6560 selectDumpableObject(&(fdwinfo[i].dobj));
6565 destroyPQExpBuffer(query);
6571 * getForeignServers:
6572 * read all foreign servers in the system catalogs and return
6573 * them in the ForeignServerInfo * structure
6575 * numForeignServers is set to the number of servers read in
6578 getForeignServers(Archive *fout, int *numForeignServers)
6583 PQExpBuffer query = createPQExpBuffer();
6584 ForeignServerInfo *srvinfo;
6595 /* Before 8.4, there are no foreign servers */
6596 if (fout->remoteVersion < 80400)
6598 *numForeignServers = 0;
6602 /* Make sure we are in proper schema */
6603 selectSourceSchema(fout, "pg_catalog");
6605 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6606 "(%s srvowner) AS rolname, "
6607 "srvfdw, srvtype, srvversion, srvacl,"
6608 "array_to_string(ARRAY("
6609 "SELECT quote_ident(option_name) || ' ' || "
6610 "quote_literal(option_value) "
6611 "FROM pg_options_to_table(srvoptions) "
6612 "ORDER BY option_name"
6613 "), E',\n ') AS srvoptions "
6614 "FROM pg_foreign_server",
6617 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6619 ntups = PQntuples(res);
6620 *numForeignServers = ntups;
6622 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6624 i_tableoid = PQfnumber(res, "tableoid");
6625 i_oid = PQfnumber(res, "oid");
6626 i_srvname = PQfnumber(res, "srvname");
6627 i_rolname = PQfnumber(res, "rolname");
6628 i_srvfdw = PQfnumber(res, "srvfdw");
6629 i_srvtype = PQfnumber(res, "srvtype");
6630 i_srvversion = PQfnumber(res, "srvversion");
6631 i_srvacl = PQfnumber(res, "srvacl");
6632 i_srvoptions = PQfnumber(res, "srvoptions");
6634 for (i = 0; i < ntups; i++)
6636 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6637 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6638 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6639 AssignDumpId(&srvinfo[i].dobj);
6640 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6641 srvinfo[i].dobj.namespace = NULL;
6642 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6643 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6644 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6645 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6646 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6647 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6649 /* Decide whether we want to dump it */
6650 selectDumpableObject(&(srvinfo[i].dobj));
6655 destroyPQExpBuffer(query);
6662 * read all default ACL information in the system catalogs and return
6663 * them in the DefaultACLInfo structure
6665 * numDefaultACLs is set to the number of ACLs read in
6668 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6670 DefaultACLInfo *daclinfo;
6676 int i_defaclnamespace;
6677 int i_defaclobjtype;
6682 if (fout->remoteVersion < 90000)
6684 *numDefaultACLs = 0;
6688 query = createPQExpBuffer();
6690 /* Make sure we are in proper schema */
6691 selectSourceSchema(fout, "pg_catalog");
6693 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6694 "(%s defaclrole) AS defaclrole, "
6698 "FROM pg_default_acl",
6701 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6703 ntups = PQntuples(res);
6704 *numDefaultACLs = ntups;
6706 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6708 i_oid = PQfnumber(res, "oid");
6709 i_tableoid = PQfnumber(res, "tableoid");
6710 i_defaclrole = PQfnumber(res, "defaclrole");
6711 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6712 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6713 i_defaclacl = PQfnumber(res, "defaclacl");
6715 for (i = 0; i < ntups; i++)
6717 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6719 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6720 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6721 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6722 AssignDumpId(&daclinfo[i].dobj);
6723 /* cheesy ... is it worth coming up with a better object name? */
6724 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6726 if (nspid != InvalidOid)
6727 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6728 daclinfo[i].dobj.catId.oid);
6730 daclinfo[i].dobj.namespace = NULL;
6732 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6733 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6734 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6736 /* Decide whether we want to dump it */
6737 selectDumpableDefaultACL(&(daclinfo[i]));
6742 destroyPQExpBuffer(query);
6750 * This routine is used to dump any comments associated with the
6751 * object handed to this routine. The routine takes a constant character
6752 * string for the target part of the comment-creation command, plus
6753 * the namespace and owner of the object (for labeling the ArchiveEntry),
6754 * plus catalog ID and subid which are the lookup key for pg_description,
6755 * plus the dump ID for the object (for setting a dependency).
6756 * If a matching pg_description entry is found, it is dumped.
6758 * Note: although this routine takes a dumpId for dependency purposes,
6759 * that purpose is just to mark the dependency in the emitted dump file
6760 * for possible future use by pg_restore. We do NOT use it for determining
6761 * ordering of the comment in the dump file, because this routine is called
6762 * after dependency sorting occurs. This routine should be called just after
6763 * calling ArchiveEntry() for the specified object.
6766 dumpComment(Archive *fout, const char *target,
6767 const char *namespace, const char *owner,
6768 CatalogId catalogId, int subid, DumpId dumpId)
6770 CommentItem *comments;
6773 /* Comments are schema not data ... except blob comments are data */
6774 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6785 /* Search for comments associated with catalogId, using table */
6786 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6789 /* Is there one matching the subid? */
6790 while (ncomments > 0)
6792 if (comments->objsubid == subid)
6798 /* If a comment exists, build COMMENT ON statement */
6801 PQExpBuffer query = createPQExpBuffer();
6803 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6804 appendStringLiteralAH(query, comments->descr, fout);
6805 appendPQExpBuffer(query, ";\n");
6808 * We mark comments as SECTION_NONE because they really belong in the
6809 * same section as their parent, whether that is pre-data or
6812 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6813 target, namespace, NULL, owner,
6814 false, "COMMENT", SECTION_NONE,
6815 query->data, "", NULL,
6819 destroyPQExpBuffer(query);
6824 * dumpTableComment --
6826 * As above, but dump comments for both the specified table (or view)
6830 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6831 const char *reltypename)
6833 CommentItem *comments;
6838 /* Comments are SCHEMA not data */
6842 /* Search for comments associated with relation, using table */
6843 ncomments = findComments(fout,
6844 tbinfo->dobj.catId.tableoid,
6845 tbinfo->dobj.catId.oid,
6848 /* If comments exist, build COMMENT ON statements */
6852 query = createPQExpBuffer();
6853 target = createPQExpBuffer();
6855 while (ncomments > 0)
6857 const char *descr = comments->descr;
6858 int objsubid = comments->objsubid;
6862 resetPQExpBuffer(target);
6863 appendPQExpBuffer(target, "%s %s", reltypename,
6864 fmtId(tbinfo->dobj.name));
6866 resetPQExpBuffer(query);
6867 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6868 appendStringLiteralAH(query, descr, fout);
6869 appendPQExpBuffer(query, ";\n");
6871 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6873 tbinfo->dobj.namespace->dobj.name,
6874 NULL, tbinfo->rolname,
6875 false, "COMMENT", SECTION_NONE,
6876 query->data, "", NULL,
6877 &(tbinfo->dobj.dumpId), 1,
6880 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6882 resetPQExpBuffer(target);
6883 appendPQExpBuffer(target, "COLUMN %s.",
6884 fmtId(tbinfo->dobj.name));
6885 appendPQExpBuffer(target, "%s",
6886 fmtId(tbinfo->attnames[objsubid - 1]));
6888 resetPQExpBuffer(query);
6889 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6890 appendStringLiteralAH(query, descr, fout);
6891 appendPQExpBuffer(query, ";\n");
6893 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6895 tbinfo->dobj.namespace->dobj.name,
6896 NULL, tbinfo->rolname,
6897 false, "COMMENT", SECTION_NONE,
6898 query->data, "", NULL,
6899 &(tbinfo->dobj.dumpId), 1,
6907 destroyPQExpBuffer(query);
6908 destroyPQExpBuffer(target);
6914 * Find the comment(s), if any, associated with the given object. All the
6915 * objsubid values associated with the given classoid/objoid are found with
6919 findComments(Archive *fout, Oid classoid, Oid objoid,
6920 CommentItem **items)
6922 /* static storage for table of comments */
6923 static CommentItem *comments = NULL;
6924 static int ncomments = -1;
6926 CommentItem *middle = NULL;
6931 /* Get comments if we didn't already */
6933 ncomments = collectComments(fout, &comments);
6936 * Pre-7.2, pg_description does not contain classoid, so collectComments
6937 * just stores a zero. If there's a collision on object OID, well, you
6938 * get duplicate comments.
6940 if (fout->remoteVersion < 70200)
6944 * Do binary search to find some item matching the object.
6947 high = &comments[ncomments - 1];
6950 middle = low + (high - low) / 2;
6952 if (classoid < middle->classoid)
6954 else if (classoid > middle->classoid)
6956 else if (objoid < middle->objoid)
6958 else if (objoid > middle->objoid)
6961 break; /* found a match */
6964 if (low > high) /* no matches */
6971 * Now determine how many items match the object. The search loop
6972 * invariant still holds: only items between low and high inclusive could
6976 while (middle > low)
6978 if (classoid != middle[-1].classoid ||
6979 objoid != middle[-1].objoid)
6988 while (middle <= high)
6990 if (classoid != middle->classoid ||
6991 objoid != middle->objoid)
7001 * collectComments --
7003 * Construct a table of all comments available for database objects.
7004 * We used to do per-object queries for the comments, but it's much faster
7005 * to pull them all over at once, and on most databases the memory cost
7008 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7011 collectComments(Archive *fout, CommentItem **items)
7021 CommentItem *comments;
7024 * Note we do NOT change source schema here; preserve the caller's
7028 query = createPQExpBuffer();
7030 if (fout->remoteVersion >= 70300)
7032 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7033 "FROM pg_catalog.pg_description "
7034 "ORDER BY classoid, objoid, objsubid");
7036 else if (fout->remoteVersion >= 70200)
7038 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7039 "FROM pg_description "
7040 "ORDER BY classoid, objoid, objsubid");
7044 /* Note: this will fail to find attribute comments in pre-7.2... */
7045 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7046 "FROM pg_description "
7050 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7052 /* Construct lookup table containing OIDs in numeric form */
7054 i_description = PQfnumber(res, "description");
7055 i_classoid = PQfnumber(res, "classoid");
7056 i_objoid = PQfnumber(res, "objoid");
7057 i_objsubid = PQfnumber(res, "objsubid");
7059 ntups = PQntuples(res);
7061 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7063 for (i = 0; i < ntups; i++)
7065 comments[i].descr = PQgetvalue(res, i, i_description);
7066 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7067 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7068 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7071 /* Do NOT free the PGresult since we are keeping pointers into it */
7072 destroyPQExpBuffer(query);
7079 * dumpDumpableObject
7081 * This routine and its subsidiaries are responsible for creating
7082 * ArchiveEntries (TOC objects) for each object to be dumped.
7085 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7087 switch (dobj->objType)
7090 dumpNamespace(fout, (NamespaceInfo *) dobj);
7093 dumpExtension(fout, (ExtensionInfo *) dobj);
7096 dumpType(fout, (TypeInfo *) dobj);
7099 dumpShellType(fout, (ShellTypeInfo *) dobj);
7102 dumpFunc(fout, (FuncInfo *) dobj);
7105 dumpAgg(fout, (AggInfo *) dobj);
7108 dumpOpr(fout, (OprInfo *) dobj);
7111 dumpOpclass(fout, (OpclassInfo *) dobj);
7114 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7117 dumpCollation(fout, (CollInfo *) dobj);
7120 dumpConversion(fout, (ConvInfo *) dobj);
7123 dumpTable(fout, (TableInfo *) dobj);
7126 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7129 dumpIndex(fout, (IndxInfo *) dobj);
7132 dumpRule(fout, (RuleInfo *) dobj);
7135 dumpTrigger(fout, (TriggerInfo *) dobj);
7138 dumpConstraint(fout, (ConstraintInfo *) dobj);
7140 case DO_FK_CONSTRAINT:
7141 dumpConstraint(fout, (ConstraintInfo *) dobj);
7144 dumpProcLang(fout, (ProcLangInfo *) dobj);
7147 dumpCast(fout, (CastInfo *) dobj);
7150 dumpTableData(fout, (TableDataInfo *) dobj);
7153 /* table rowtypes and array types are never dumped separately */
7156 dumpTSParser(fout, (TSParserInfo *) dobj);
7159 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7162 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7165 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7168 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7170 case DO_FOREIGN_SERVER:
7171 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7173 case DO_DEFAULT_ACL:
7174 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7177 dumpBlob(fout, (BlobInfo *) dobj);
7180 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7181 dobj->name, NULL, NULL, "",
7182 false, "BLOBS", SECTION_DATA,
7184 dobj->dependencies, dobj->nDeps,
7192 * writes out to fout the queries to recreate a user-defined namespace
7195 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7202 /* Skip if not to be dumped */
7203 if (!nspinfo->dobj.dump || dataOnly)
7206 /* don't dump dummy namespace from pre-7.3 source */
7207 if (strlen(nspinfo->dobj.name) == 0)
7210 q = createPQExpBuffer();
7211 delq = createPQExpBuffer();
7212 labelq = createPQExpBuffer();
7214 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7216 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7218 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7220 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7223 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7225 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7229 false, "SCHEMA", SECTION_PRE_DATA,
7230 q->data, delq->data, NULL,
7231 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7234 /* Dump Schema Comments and Security Labels */
7235 dumpComment(fout, labelq->data,
7236 NULL, nspinfo->rolname,
7237 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7238 dumpSecLabel(fout, labelq->data,
7239 NULL, nspinfo->rolname,
7240 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7242 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7243 qnspname, NULL, nspinfo->dobj.name, NULL,
7244 nspinfo->rolname, nspinfo->nspacl);
7248 destroyPQExpBuffer(q);
7249 destroyPQExpBuffer(delq);
7250 destroyPQExpBuffer(labelq);
7255 * writes out to fout the queries to recreate an extension
7258 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7265 /* Skip if not to be dumped */
7266 if (!extinfo->dobj.dump || dataOnly)
7269 q = createPQExpBuffer();
7270 delq = createPQExpBuffer();
7271 labelq = createPQExpBuffer();
7273 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7275 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7277 if (!binary_upgrade)
7280 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7281 * problem if the extension already exists in the target database;
7282 * this is essential for installed-by-default extensions such as
7285 * In binary-upgrade mode, that doesn't work well, so instead we skip
7286 * built-in extensions based on their OIDs; see
7287 * selectDumpableExtension.
7289 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7290 qextname, fmtId(extinfo->namespace));
7297 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7298 appendPQExpBuffer(q,
7299 "SELECT binary_upgrade.create_empty_extension(");
7300 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7301 appendPQExpBuffer(q, ", ");
7302 appendStringLiteralAH(q, extinfo->namespace, fout);
7303 appendPQExpBuffer(q, ", ");
7304 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7305 appendStringLiteralAH(q, extinfo->extversion, fout);
7306 appendPQExpBuffer(q, ", ");
7309 * Note that we're pushing extconfig (an OID array) back into
7310 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7311 * preserved in binary upgrade.
7313 if (strlen(extinfo->extconfig) > 2)
7314 appendStringLiteralAH(q, extinfo->extconfig, fout);
7316 appendPQExpBuffer(q, "NULL");
7317 appendPQExpBuffer(q, ", ");
7318 if (strlen(extinfo->extcondition) > 2)
7319 appendStringLiteralAH(q, extinfo->extcondition, fout);
7321 appendPQExpBuffer(q, "NULL");
7322 appendPQExpBuffer(q, ", ");
7323 appendPQExpBuffer(q, "ARRAY[");
7325 for (i = 0; i < extinfo->dobj.nDeps; i++)
7327 DumpableObject *extobj;
7329 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7330 if (extobj && extobj->objType == DO_EXTENSION)
7333 appendPQExpBuffer(q, ",");
7334 appendStringLiteralAH(q, extobj->name, fout);
7337 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7338 appendPQExpBuffer(q, ");\n");
7341 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7343 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7347 false, "EXTENSION", SECTION_PRE_DATA,
7348 q->data, delq->data, NULL,
7349 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7352 /* Dump Extension Comments and Security Labels */
7353 dumpComment(fout, labelq->data,
7355 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7356 dumpSecLabel(fout, labelq->data,
7358 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7362 destroyPQExpBuffer(q);
7363 destroyPQExpBuffer(delq);
7364 destroyPQExpBuffer(labelq);
7369 * writes out to fout the queries to recreate a user-defined type
7372 dumpType(Archive *fout, TypeInfo *tyinfo)
7374 /* Skip if not to be dumped */
7375 if (!tyinfo->dobj.dump || dataOnly)
7378 /* Dump out in proper style */
7379 if (tyinfo->typtype == TYPTYPE_BASE)
7380 dumpBaseType(fout, tyinfo);
7381 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7382 dumpDomain(fout, tyinfo);
7383 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7384 dumpCompositeType(fout, tyinfo);
7385 else if (tyinfo->typtype == TYPTYPE_ENUM)
7386 dumpEnumType(fout, tyinfo);
7387 else if (tyinfo->typtype == TYPTYPE_RANGE)
7388 dumpRangeType(fout, tyinfo);
7390 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7396 * writes out to fout the queries to recreate a user-defined enum type
7399 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7401 PQExpBuffer q = createPQExpBuffer();
7402 PQExpBuffer delq = createPQExpBuffer();
7403 PQExpBuffer labelq = createPQExpBuffer();
7404 PQExpBuffer query = createPQExpBuffer();
7411 /* Set proper schema search path */
7412 selectSourceSchema(fout, "pg_catalog");
7414 if (fout->remoteVersion >= 90100)
7415 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7416 "FROM pg_catalog.pg_enum "
7417 "WHERE enumtypid = '%u'"
7418 "ORDER BY enumsortorder",
7419 tyinfo->dobj.catId.oid);
7421 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7422 "FROM pg_catalog.pg_enum "
7423 "WHERE enumtypid = '%u'"
7425 tyinfo->dobj.catId.oid);
7427 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7429 num = PQntuples(res);
7432 * DROP must be fully qualified in case same name appears in pg_catalog.
7433 * CASCADE shouldn't be required here as for normal types since the I/O
7434 * functions are generic and do not get dropped.
7436 appendPQExpBuffer(delq, "DROP TYPE %s.",
7437 fmtId(tyinfo->dobj.namespace->dobj.name));
7438 appendPQExpBuffer(delq, "%s;\n",
7439 fmtId(tyinfo->dobj.name));
7442 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7443 tyinfo->dobj.catId.oid);
7445 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7446 fmtId(tyinfo->dobj.name));
7448 if (!binary_upgrade)
7450 /* Labels with server-assigned oids */
7451 for (i = 0; i < num; i++)
7453 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7455 appendPQExpBuffer(q, ",");
7456 appendPQExpBuffer(q, "\n ");
7457 appendStringLiteralAH(q, label, fout);
7461 appendPQExpBuffer(q, "\n);\n");
7465 /* Labels with dump-assigned (preserved) oids */
7466 for (i = 0; i < num; i++)
7468 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7469 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7472 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7473 appendPQExpBuffer(q,
7474 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7476 appendPQExpBuffer(q, "ALTER TYPE %s.",
7477 fmtId(tyinfo->dobj.namespace->dobj.name));
7478 appendPQExpBuffer(q, "%s ADD VALUE ",
7479 fmtId(tyinfo->dobj.name));
7480 appendStringLiteralAH(q, label, fout);
7481 appendPQExpBuffer(q, ";\n\n");
7485 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7488 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7490 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7492 tyinfo->dobj.namespace->dobj.name,
7494 tyinfo->rolname, false,
7495 "TYPE", SECTION_PRE_DATA,
7496 q->data, delq->data, NULL,
7497 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7500 /* Dump Type Comments and Security Labels */
7501 dumpComment(fout, labelq->data,
7502 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7503 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7504 dumpSecLabel(fout, labelq->data,
7505 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7506 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7509 destroyPQExpBuffer(q);
7510 destroyPQExpBuffer(delq);
7511 destroyPQExpBuffer(labelq);
7512 destroyPQExpBuffer(query);
7517 * writes out to fout the queries to recreate a user-defined range type
7520 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7522 PQExpBuffer q = createPQExpBuffer();
7523 PQExpBuffer delq = createPQExpBuffer();
7524 PQExpBuffer labelq = createPQExpBuffer();
7525 PQExpBuffer query = createPQExpBuffer();
7531 * select appropriate schema to ensure names in CREATE are properly
7534 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7536 appendPQExpBuffer(query,
7537 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7538 "opc.opcname AS opcname, "
7539 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7540 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7542 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7543 " ELSE rngcollation END AS collation, "
7544 "rngcanonical, rngsubdiff "
7545 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7546 " pg_catalog.pg_opclass opc "
7547 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7549 tyinfo->dobj.catId.oid);
7551 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7554 * DROP must be fully qualified in case same name appears in pg_catalog.
7555 * CASCADE shouldn't be required here as for normal types since the I/O
7556 * functions are generic and do not get dropped.
7558 appendPQExpBuffer(delq, "DROP TYPE %s.",
7559 fmtId(tyinfo->dobj.namespace->dobj.name));
7560 appendPQExpBuffer(delq, "%s;\n",
7561 fmtId(tyinfo->dobj.name));
7564 binary_upgrade_set_type_oids_by_type_oid(fout,
7565 q, tyinfo->dobj.catId.oid);
7567 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7568 fmtId(tyinfo->dobj.name));
7570 appendPQExpBuffer(q, "\n subtype = %s",
7571 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7573 /* print subtype_opclass only if not default for subtype */
7574 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7576 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7577 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7579 /* always schema-qualify, don't try to be smart */
7580 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7582 appendPQExpBuffer(q, "%s", fmtId(opcname));
7585 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7586 if (OidIsValid(collationOid))
7588 CollInfo *coll = findCollationByOid(collationOid);
7592 /* always schema-qualify, don't try to be smart */
7593 appendPQExpBuffer(q, ",\n collation = %s.",
7594 fmtId(coll->dobj.namespace->dobj.name));
7595 appendPQExpBuffer(q, "%s",
7596 fmtId(coll->dobj.name));
7600 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7601 if (strcmp(procname, "-") != 0)
7602 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7604 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7605 if (strcmp(procname, "-") != 0)
7606 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7608 appendPQExpBuffer(q, "\n);\n");
7610 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7613 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7615 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7617 tyinfo->dobj.namespace->dobj.name,
7619 tyinfo->rolname, false,
7620 "TYPE", SECTION_PRE_DATA,
7621 q->data, delq->data, NULL,
7622 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7625 /* Dump Type Comments and Security Labels */
7626 dumpComment(fout, labelq->data,
7627 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7628 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7629 dumpSecLabel(fout, labelq->data,
7630 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7631 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7634 destroyPQExpBuffer(q);
7635 destroyPQExpBuffer(delq);
7636 destroyPQExpBuffer(labelq);
7637 destroyPQExpBuffer(query);
7642 * writes out to fout the queries to recreate a user-defined base type
7645 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7647 PQExpBuffer q = createPQExpBuffer();
7648 PQExpBuffer delq = createPQExpBuffer();
7649 PQExpBuffer labelq = createPQExpBuffer();
7650 PQExpBuffer query = createPQExpBuffer();
7666 char *typispreferred;
7671 char *typcollatable;
7673 bool typdefault_is_literal = false;
7675 /* Set proper schema search path so regproc references list correctly */
7676 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7678 /* Fetch type-specific details */
7679 if (fout->remoteVersion >= 90100)
7681 appendPQExpBuffer(query, "SELECT typlen, "
7682 "typinput, typoutput, typreceive, typsend, "
7683 "typmodin, typmodout, typanalyze, "
7684 "typreceive::pg_catalog.oid AS typreceiveoid, "
7685 "typsend::pg_catalog.oid AS typsendoid, "
7686 "typmodin::pg_catalog.oid AS typmodinoid, "
7687 "typmodout::pg_catalog.oid AS typmodoutoid, "
7688 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7689 "typcategory, typispreferred, "
7690 "typdelim, typbyval, typalign, typstorage, "
7691 "(typcollation <> 0) AS typcollatable, "
7692 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7693 "FROM pg_catalog.pg_type "
7694 "WHERE oid = '%u'::pg_catalog.oid",
7695 tyinfo->dobj.catId.oid);
7697 else if (fout->remoteVersion >= 80400)
7699 appendPQExpBuffer(query, "SELECT typlen, "
7700 "typinput, typoutput, typreceive, typsend, "
7701 "typmodin, typmodout, typanalyze, "
7702 "typreceive::pg_catalog.oid AS typreceiveoid, "
7703 "typsend::pg_catalog.oid AS typsendoid, "
7704 "typmodin::pg_catalog.oid AS typmodinoid, "
7705 "typmodout::pg_catalog.oid AS typmodoutoid, "
7706 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7707 "typcategory, typispreferred, "
7708 "typdelim, typbyval, typalign, typstorage, "
7709 "false AS typcollatable, "
7710 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7711 "FROM pg_catalog.pg_type "
7712 "WHERE oid = '%u'::pg_catalog.oid",
7713 tyinfo->dobj.catId.oid);
7715 else if (fout->remoteVersion >= 80300)
7717 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7718 appendPQExpBuffer(query, "SELECT typlen, "
7719 "typinput, typoutput, typreceive, typsend, "
7720 "typmodin, typmodout, typanalyze, "
7721 "typreceive::pg_catalog.oid AS typreceiveoid, "
7722 "typsend::pg_catalog.oid AS typsendoid, "
7723 "typmodin::pg_catalog.oid AS typmodinoid, "
7724 "typmodout::pg_catalog.oid AS typmodoutoid, "
7725 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7726 "'U' AS typcategory, false AS typispreferred, "
7727 "typdelim, typbyval, typalign, typstorage, "
7728 "false AS typcollatable, "
7729 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7730 "FROM pg_catalog.pg_type "
7731 "WHERE oid = '%u'::pg_catalog.oid",
7732 tyinfo->dobj.catId.oid);
7734 else if (fout->remoteVersion >= 80000)
7736 appendPQExpBuffer(query, "SELECT typlen, "
7737 "typinput, typoutput, typreceive, typsend, "
7738 "'-' AS typmodin, '-' AS typmodout, "
7740 "typreceive::pg_catalog.oid AS typreceiveoid, "
7741 "typsend::pg_catalog.oid AS typsendoid, "
7742 "0 AS typmodinoid, 0 AS typmodoutoid, "
7743 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7744 "'U' AS typcategory, false AS typispreferred, "
7745 "typdelim, typbyval, typalign, typstorage, "
7746 "false AS typcollatable, "
7747 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7748 "FROM pg_catalog.pg_type "
7749 "WHERE oid = '%u'::pg_catalog.oid",
7750 tyinfo->dobj.catId.oid);
7752 else if (fout->remoteVersion >= 70400)
7754 appendPQExpBuffer(query, "SELECT typlen, "
7755 "typinput, typoutput, typreceive, typsend, "
7756 "'-' AS typmodin, '-' AS typmodout, "
7757 "'-' AS typanalyze, "
7758 "typreceive::pg_catalog.oid AS typreceiveoid, "
7759 "typsend::pg_catalog.oid AS typsendoid, "
7760 "0 AS typmodinoid, 0 AS typmodoutoid, "
7761 "0 AS typanalyzeoid, "
7762 "'U' AS typcategory, false AS typispreferred, "
7763 "typdelim, typbyval, typalign, typstorage, "
7764 "false AS typcollatable, "
7765 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7766 "FROM pg_catalog.pg_type "
7767 "WHERE oid = '%u'::pg_catalog.oid",
7768 tyinfo->dobj.catId.oid);
7770 else if (fout->remoteVersion >= 70300)
7772 appendPQExpBuffer(query, "SELECT typlen, "
7773 "typinput, typoutput, "
7774 "'-' AS typreceive, '-' AS typsend, "
7775 "'-' AS typmodin, '-' AS typmodout, "
7776 "'-' AS typanalyze, "
7777 "0 AS typreceiveoid, 0 AS typsendoid, "
7778 "0 AS typmodinoid, 0 AS typmodoutoid, "
7779 "0 AS typanalyzeoid, "
7780 "'U' AS typcategory, false AS typispreferred, "
7781 "typdelim, typbyval, typalign, typstorage, "
7782 "false AS typcollatable, "
7783 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7784 "FROM pg_catalog.pg_type "
7785 "WHERE oid = '%u'::pg_catalog.oid",
7786 tyinfo->dobj.catId.oid);
7788 else if (fout->remoteVersion >= 70200)
7791 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7792 * ignore them because they are not right.
7794 appendPQExpBuffer(query, "SELECT typlen, "
7795 "typinput, typoutput, "
7796 "'-' AS typreceive, '-' AS typsend, "
7797 "'-' AS typmodin, '-' AS typmodout, "
7798 "'-' AS typanalyze, "
7799 "0 AS typreceiveoid, 0 AS typsendoid, "
7800 "0 AS typmodinoid, 0 AS typmodoutoid, "
7801 "0 AS typanalyzeoid, "
7802 "'U' AS typcategory, false AS typispreferred, "
7803 "typdelim, typbyval, typalign, typstorage, "
7804 "false AS typcollatable, "
7805 "NULL AS typdefaultbin, typdefault "
7807 "WHERE oid = '%u'::oid",
7808 tyinfo->dobj.catId.oid);
7810 else if (fout->remoteVersion >= 70100)
7813 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7816 appendPQExpBuffer(query, "SELECT typlen, "
7817 "typinput, typoutput, "
7818 "'-' AS typreceive, '-' AS typsend, "
7819 "'-' AS typmodin, '-' AS typmodout, "
7820 "'-' AS typanalyze, "
7821 "0 AS typreceiveoid, 0 AS typsendoid, "
7822 "0 AS typmodinoid, 0 AS typmodoutoid, "
7823 "0 AS typanalyzeoid, "
7824 "'U' AS typcategory, false AS typispreferred, "
7825 "typdelim, typbyval, typalign, typstorage, "
7826 "false AS typcollatable, "
7827 "NULL AS typdefaultbin, NULL AS typdefault "
7829 "WHERE oid = '%u'::oid",
7830 tyinfo->dobj.catId.oid);
7834 appendPQExpBuffer(query, "SELECT typlen, "
7835 "typinput, typoutput, "
7836 "'-' AS typreceive, '-' AS typsend, "
7837 "'-' AS typmodin, '-' AS typmodout, "
7838 "'-' AS typanalyze, "
7839 "0 AS typreceiveoid, 0 AS typsendoid, "
7840 "0 AS typmodinoid, 0 AS typmodoutoid, "
7841 "0 AS typanalyzeoid, "
7842 "'U' AS typcategory, false AS typispreferred, "
7843 "typdelim, typbyval, typalign, "
7844 "'p'::char AS typstorage, "
7845 "false AS typcollatable, "
7846 "NULL AS typdefaultbin, NULL AS typdefault "
7848 "WHERE oid = '%u'::oid",
7849 tyinfo->dobj.catId.oid);
7852 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7854 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7855 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7856 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7857 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7858 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7859 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7860 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7861 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7862 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7863 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7864 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7865 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7866 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7867 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7868 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7869 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7870 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7871 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7872 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7873 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7874 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7875 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7876 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7878 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7879 typdefault_is_literal = true; /* it needs quotes */
7885 * DROP must be fully qualified in case same name appears in pg_catalog.
7886 * The reason we include CASCADE is that the circular dependency between
7887 * the type and its I/O functions makes it impossible to drop the type any
7890 appendPQExpBuffer(delq, "DROP TYPE %s.",
7891 fmtId(tyinfo->dobj.namespace->dobj.name));
7892 appendPQExpBuffer(delq, "%s CASCADE;\n",
7893 fmtId(tyinfo->dobj.name));
7895 /* We might already have a shell type, but setting pg_type_oid is harmless */
7897 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7898 tyinfo->dobj.catId.oid);
7900 appendPQExpBuffer(q,
7901 "CREATE TYPE %s (\n"
7902 " INTERNALLENGTH = %s",
7903 fmtId(tyinfo->dobj.name),
7904 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7906 if (fout->remoteVersion >= 70300)
7908 /* regproc result is correctly quoted as of 7.3 */
7909 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7910 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7911 if (OidIsValid(typreceiveoid))
7912 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7913 if (OidIsValid(typsendoid))
7914 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7915 if (OidIsValid(typmodinoid))
7916 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7917 if (OidIsValid(typmodoutoid))
7918 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7919 if (OidIsValid(typanalyzeoid))
7920 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7924 /* regproc delivers an unquoted name before 7.3 */
7925 /* cannot combine these because fmtId uses static result area */
7926 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7927 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7928 /* receive/send/typmodin/typmodout/analyze need not be printed */
7931 if (strcmp(typcollatable, "t") == 0)
7932 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7934 if (typdefault != NULL)
7936 appendPQExpBuffer(q, ",\n DEFAULT = ");
7937 if (typdefault_is_literal)
7938 appendStringLiteralAH(q, typdefault, fout);
7940 appendPQExpBufferStr(q, typdefault);
7943 if (OidIsValid(tyinfo->typelem))
7947 /* reselect schema in case changed by function dump */
7948 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7949 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7950 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
7954 if (strcmp(typcategory, "U") != 0)
7956 appendPQExpBuffer(q, ",\n CATEGORY = ");
7957 appendStringLiteralAH(q, typcategory, fout);
7960 if (strcmp(typispreferred, "t") == 0)
7961 appendPQExpBuffer(q, ",\n PREFERRED = true");
7963 if (typdelim && strcmp(typdelim, ",") != 0)
7965 appendPQExpBuffer(q, ",\n DELIMITER = ");
7966 appendStringLiteralAH(q, typdelim, fout);
7969 if (strcmp(typalign, "c") == 0)
7970 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
7971 else if (strcmp(typalign, "s") == 0)
7972 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
7973 else if (strcmp(typalign, "i") == 0)
7974 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
7975 else if (strcmp(typalign, "d") == 0)
7976 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
7978 if (strcmp(typstorage, "p") == 0)
7979 appendPQExpBuffer(q, ",\n STORAGE = plain");
7980 else if (strcmp(typstorage, "e") == 0)
7981 appendPQExpBuffer(q, ",\n STORAGE = external");
7982 else if (strcmp(typstorage, "x") == 0)
7983 appendPQExpBuffer(q, ",\n STORAGE = extended");
7984 else if (strcmp(typstorage, "m") == 0)
7985 appendPQExpBuffer(q, ",\n STORAGE = main");
7987 if (strcmp(typbyval, "t") == 0)
7988 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
7990 appendPQExpBuffer(q, "\n);\n");
7992 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7995 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7997 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7999 tyinfo->dobj.namespace->dobj.name,
8001 tyinfo->rolname, false,
8002 "TYPE", SECTION_PRE_DATA,
8003 q->data, delq->data, NULL,
8004 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8007 /* Dump Type Comments and Security Labels */
8008 dumpComment(fout, labelq->data,
8009 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8010 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8011 dumpSecLabel(fout, labelq->data,
8012 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8013 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8016 destroyPQExpBuffer(q);
8017 destroyPQExpBuffer(delq);
8018 destroyPQExpBuffer(labelq);
8019 destroyPQExpBuffer(query);
8024 * writes out to fout the queries to recreate a user-defined domain
8027 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8029 PQExpBuffer q = createPQExpBuffer();
8030 PQExpBuffer delq = createPQExpBuffer();
8031 PQExpBuffer labelq = createPQExpBuffer();
8032 PQExpBuffer query = createPQExpBuffer();
8039 bool typdefault_is_literal = false;
8041 /* Set proper schema search path so type references list correctly */
8042 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8044 /* Fetch domain specific details */
8045 if (fout->remoteVersion >= 90100)
8047 /* typcollation is new in 9.1 */
8048 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8049 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8050 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8052 "CASE WHEN t.typcollation <> u.typcollation "
8053 "THEN t.typcollation ELSE 0 END AS typcollation "
8054 "FROM pg_catalog.pg_type t "
8055 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8056 "WHERE t.oid = '%u'::pg_catalog.oid",
8057 tyinfo->dobj.catId.oid);
8061 /* We assume here that remoteVersion must be at least 70300 */
8062 appendPQExpBuffer(query, "SELECT typnotnull, "
8063 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8064 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8065 "typdefault, 0 AS typcollation "
8066 "FROM pg_catalog.pg_type "
8067 "WHERE oid = '%u'::pg_catalog.oid",
8068 tyinfo->dobj.catId.oid);
8071 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8073 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8074 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8075 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8076 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8077 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8079 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8080 typdefault_is_literal = true; /* it needs quotes */
8084 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8087 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8088 tyinfo->dobj.catId.oid);
8090 appendPQExpBuffer(q,
8091 "CREATE DOMAIN %s AS %s",
8092 fmtId(tyinfo->dobj.name),
8095 /* Print collation only if different from base type's collation */
8096 if (OidIsValid(typcollation))
8100 coll = findCollationByOid(typcollation);
8103 /* always schema-qualify, don't try to be smart */
8104 appendPQExpBuffer(q, " COLLATE %s.",
8105 fmtId(coll->dobj.namespace->dobj.name));
8106 appendPQExpBuffer(q, "%s",
8107 fmtId(coll->dobj.name));
8111 if (typnotnull[0] == 't')
8112 appendPQExpBuffer(q, " NOT NULL");
8114 if (typdefault != NULL)
8116 appendPQExpBuffer(q, " DEFAULT ");
8117 if (typdefault_is_literal)
8118 appendStringLiteralAH(q, typdefault, fout);
8120 appendPQExpBufferStr(q, typdefault);
8126 * Add any CHECK constraints for the domain
8128 for (i = 0; i < tyinfo->nDomChecks; i++)
8130 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8132 if (!domcheck->separate)
8133 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8134 fmtId(domcheck->dobj.name), domcheck->condef);
8137 appendPQExpBuffer(q, ";\n");
8140 * DROP must be fully qualified in case same name appears in pg_catalog
8142 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8143 fmtId(tyinfo->dobj.namespace->dobj.name));
8144 appendPQExpBuffer(delq, "%s;\n",
8145 fmtId(tyinfo->dobj.name));
8147 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8150 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8152 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8154 tyinfo->dobj.namespace->dobj.name,
8156 tyinfo->rolname, false,
8157 "DOMAIN", SECTION_PRE_DATA,
8158 q->data, delq->data, NULL,
8159 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8162 /* Dump Domain Comments and Security Labels */
8163 dumpComment(fout, labelq->data,
8164 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8165 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8166 dumpSecLabel(fout, labelq->data,
8167 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8168 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8170 destroyPQExpBuffer(q);
8171 destroyPQExpBuffer(delq);
8172 destroyPQExpBuffer(labelq);
8173 destroyPQExpBuffer(query);
8178 * writes out to fout the queries to recreate a user-defined stand-alone
8182 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8184 PQExpBuffer q = createPQExpBuffer();
8185 PQExpBuffer dropped = createPQExpBuffer();
8186 PQExpBuffer delq = createPQExpBuffer();
8187 PQExpBuffer labelq = createPQExpBuffer();
8188 PQExpBuffer query = createPQExpBuffer();
8201 /* Set proper schema search path so type references list correctly */
8202 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8204 /* Fetch type specific details */
8205 if (fout->remoteVersion >= 90100)
8208 * attcollation is new in 9.1. Since we only want to dump COLLATE
8209 * clauses for attributes whose collation is different from their
8210 * type's default, we use a CASE here to suppress uninteresting
8211 * attcollations cheaply. atttypid will be 0 for dropped columns;
8212 * collation does not matter for those.
8214 appendPQExpBuffer(query, "SELECT a.attname, "
8215 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8216 "a.attlen, a.attalign, a.attisdropped, "
8217 "CASE WHEN a.attcollation <> at.typcollation "
8218 "THEN a.attcollation ELSE 0 END AS attcollation, "
8220 "FROM pg_catalog.pg_type ct "
8221 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8222 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8223 "WHERE ct.oid = '%u'::pg_catalog.oid "
8224 "ORDER BY a.attnum ",
8225 tyinfo->dobj.catId.oid);
8230 * We assume here that remoteVersion must be at least 70300. Since
8231 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8234 appendPQExpBuffer(query, "SELECT a.attname, "
8235 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8236 "a.attlen, a.attalign, a.attisdropped, "
8237 "0 AS attcollation, "
8239 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8240 "WHERE ct.oid = '%u'::pg_catalog.oid "
8241 "AND a.attrelid = ct.typrelid "
8242 "ORDER BY a.attnum ",
8243 tyinfo->dobj.catId.oid);
8246 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8248 ntups = PQntuples(res);
8250 i_attname = PQfnumber(res, "attname");
8251 i_atttypdefn = PQfnumber(res, "atttypdefn");
8252 i_attlen = PQfnumber(res, "attlen");
8253 i_attalign = PQfnumber(res, "attalign");
8254 i_attisdropped = PQfnumber(res, "attisdropped");
8255 i_attcollation = PQfnumber(res, "attcollation");
8256 i_typrelid = PQfnumber(res, "typrelid");
8260 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8262 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8263 tyinfo->dobj.catId.oid);
8264 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8267 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8268 fmtId(tyinfo->dobj.name));
8271 for (i = 0; i < ntups; i++)
8280 attname = PQgetvalue(res, i, i_attname);
8281 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8282 attlen = PQgetvalue(res, i, i_attlen);
8283 attalign = PQgetvalue(res, i, i_attalign);
8284 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8285 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8287 if (attisdropped && !binary_upgrade)
8290 /* Format properly if not first attr */
8291 if (actual_atts++ > 0)
8292 appendPQExpBuffer(q, ",");
8293 appendPQExpBuffer(q, "\n\t");
8297 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8299 /* Add collation if not default for the column type */
8300 if (OidIsValid(attcollation))
8304 coll = findCollationByOid(attcollation);
8307 /* always schema-qualify, don't try to be smart */
8308 appendPQExpBuffer(q, " COLLATE %s.",
8309 fmtId(coll->dobj.namespace->dobj.name));
8310 appendPQExpBuffer(q, "%s",
8311 fmtId(coll->dobj.name));
8318 * This is a dropped attribute and we're in binary_upgrade mode.
8319 * Insert a placeholder for it in the CREATE TYPE command, and set
8320 * length and alignment with direct UPDATE to the catalogs
8321 * afterwards. See similar code in dumpTableSchema().
8323 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8325 /* stash separately for insertion after the CREATE TYPE */
8326 appendPQExpBuffer(dropped,
8327 "\n-- For binary upgrade, recreate dropped column.\n");
8328 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8330 "attalign = '%s', attbyval = false\n"
8331 "WHERE attname = ", attlen, attalign);
8332 appendStringLiteralAH(dropped, attname, fout);
8333 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8334 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8335 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8337 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8338 fmtId(tyinfo->dobj.name));
8339 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8343 appendPQExpBuffer(q, "\n);\n");
8344 appendPQExpBufferStr(q, dropped->data);
8347 * DROP must be fully qualified in case same name appears in pg_catalog
8349 appendPQExpBuffer(delq, "DROP TYPE %s.",
8350 fmtId(tyinfo->dobj.namespace->dobj.name));
8351 appendPQExpBuffer(delq, "%s;\n",
8352 fmtId(tyinfo->dobj.name));
8354 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8357 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8359 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8361 tyinfo->dobj.namespace->dobj.name,
8363 tyinfo->rolname, false,
8364 "TYPE", SECTION_PRE_DATA,
8365 q->data, delq->data, NULL,
8366 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8370 /* Dump Type Comments and Security Labels */
8371 dumpComment(fout, labelq->data,
8372 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8373 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8374 dumpSecLabel(fout, labelq->data,
8375 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8376 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8379 destroyPQExpBuffer(q);
8380 destroyPQExpBuffer(dropped);
8381 destroyPQExpBuffer(delq);
8382 destroyPQExpBuffer(labelq);
8383 destroyPQExpBuffer(query);
8385 /* Dump any per-column comments */
8386 dumpCompositeTypeColComments(fout, tyinfo);
8390 * dumpCompositeTypeColComments
8391 * writes out to fout the queries to recreate comments on the columns of
8392 * a user-defined stand-alone composite type
8395 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8397 CommentItem *comments;
8408 query = createPQExpBuffer();
8410 /* We assume here that remoteVersion must be at least 70300 */
8411 appendPQExpBuffer(query,
8412 "SELECT c.tableoid, a.attname, a.attnum "
8413 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8414 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8415 " AND NOT a.attisdropped "
8416 "ORDER BY a.attnum ",
8419 /* Fetch column attnames */
8420 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8422 ntups = PQntuples(res);
8426 destroyPQExpBuffer(query);
8430 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8432 /* Search for comments associated with type's pg_class OID */
8433 ncomments = findComments(fout,
8438 /* If no comments exist, we're done */
8442 destroyPQExpBuffer(query);
8446 /* Build COMMENT ON statements */
8447 target = createPQExpBuffer();
8449 i_attnum = PQfnumber(res, "attnum");
8450 i_attname = PQfnumber(res, "attname");
8451 while (ncomments > 0)
8453 const char *attname;
8456 for (i = 0; i < ntups; i++)
8458 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8460 attname = PQgetvalue(res, i, i_attname);
8464 if (attname) /* just in case we don't find it */
8466 const char *descr = comments->descr;
8468 resetPQExpBuffer(target);
8469 appendPQExpBuffer(target, "COLUMN %s.",
8470 fmtId(tyinfo->dobj.name));
8471 appendPQExpBuffer(target, "%s",
8474 resetPQExpBuffer(query);
8475 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8476 appendStringLiteralAH(query, descr, fout);
8477 appendPQExpBuffer(query, ";\n");
8479 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8481 tyinfo->dobj.namespace->dobj.name,
8482 NULL, tyinfo->rolname,
8483 false, "COMMENT", SECTION_NONE,
8484 query->data, "", NULL,
8485 &(tyinfo->dobj.dumpId), 1,
8494 destroyPQExpBuffer(query);
8495 destroyPQExpBuffer(target);
8500 * writes out to fout the queries to create a shell type
8502 * We dump a shell definition in advance of the I/O functions for the type.
8505 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8509 /* Skip if not to be dumped */
8510 if (!stinfo->dobj.dump || dataOnly)
8513 q = createPQExpBuffer();
8516 * Note the lack of a DROP command for the shell type; any required DROP
8517 * is driven off the base type entry, instead. This interacts with
8518 * _printTocEntry()'s use of the presence of a DROP command to decide
8519 * whether an entry needs an ALTER OWNER command. We don't want to alter
8520 * the shell type's owner immediately on creation; that should happen only
8521 * after it's filled in, otherwise the backend complains.
8525 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8526 stinfo->baseType->dobj.catId.oid);
8528 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8529 fmtId(stinfo->dobj.name));
8531 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8533 stinfo->dobj.namespace->dobj.name,
8535 stinfo->baseType->rolname, false,
8536 "SHELL TYPE", SECTION_PRE_DATA,
8538 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8541 destroyPQExpBuffer(q);
8545 * Determine whether we want to dump definitions for procedural languages.
8546 * Since the languages themselves don't have schemas, we can't rely on
8547 * the normal schema-based selection mechanism. We choose to dump them
8548 * whenever neither --schema nor --table was given. (Before 8.1, we used
8549 * the dump flag of the PL's call handler function, but in 8.1 this will
8550 * probably always be false since call handlers are created in pg_catalog.)
8552 * For some backwards compatibility with the older behavior, we forcibly
8553 * dump a PL if its handler function (and validator if any) are in a
8554 * dumpable namespace. That case is not checked here.
8556 * Also, if the PL belongs to an extension, we do not use this heuristic.
8557 * That case isn't checked here either.
8560 shouldDumpProcLangs(void)
8562 if (!include_everything)
8564 /* And they're schema not data */
8572 * writes out to fout the queries to recreate a user-defined
8573 * procedural language
8576 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8585 FuncInfo *inlineInfo = NULL;
8586 FuncInfo *validatorInfo = NULL;
8588 /* Skip if not to be dumped */
8589 if (!plang->dobj.dump || dataOnly)
8593 * Try to find the support function(s). It is not an error if we don't
8594 * find them --- if the functions are in the pg_catalog schema, as is
8595 * standard in 8.1 and up, then we won't have loaded them. (In this case
8596 * we will emit a parameterless CREATE LANGUAGE command, which will
8597 * require PL template knowledge in the backend to reload.)
8600 funcInfo = findFuncByOid(plang->lanplcallfoid);
8601 if (funcInfo != NULL && !funcInfo->dobj.dump)
8602 funcInfo = NULL; /* treat not-dumped same as not-found */
8604 if (OidIsValid(plang->laninline))
8606 inlineInfo = findFuncByOid(plang->laninline);
8607 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8611 if (OidIsValid(plang->lanvalidator))
8613 validatorInfo = findFuncByOid(plang->lanvalidator);
8614 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8615 validatorInfo = NULL;
8619 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8620 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8623 * However, for a language that belongs to an extension, we must not use
8624 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8625 * told to (via dobj.dump). Generally the support functions will belong
8626 * to the same extension and so have the same dump flags ... if they
8627 * don't, this might not work terribly nicely.
8629 useParams = (funcInfo != NULL &&
8630 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8631 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8633 if (!plang->dobj.ext_member)
8635 if (!useParams && !shouldDumpProcLangs())
8639 defqry = createPQExpBuffer();
8640 delqry = createPQExpBuffer();
8641 labelq = createPQExpBuffer();
8643 qlanname = pg_strdup(fmtId(plang->dobj.name));
8646 * If dumping a HANDLER clause, treat the language as being in the handler
8647 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8648 * it doesn't really have a schema.
8651 lanschema = funcInfo->dobj.namespace->dobj.name;
8655 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8660 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8661 plang->lanpltrusted ? "TRUSTED " : "",
8663 appendPQExpBuffer(defqry, " HANDLER %s",
8664 fmtId(funcInfo->dobj.name));
8665 if (OidIsValid(plang->laninline))
8667 appendPQExpBuffer(defqry, " INLINE ");
8668 /* Cope with possibility that inline is in different schema */
8669 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8670 appendPQExpBuffer(defqry, "%s.",
8671 fmtId(inlineInfo->dobj.namespace->dobj.name));
8672 appendPQExpBuffer(defqry, "%s",
8673 fmtId(inlineInfo->dobj.name));
8675 if (OidIsValid(plang->lanvalidator))
8677 appendPQExpBuffer(defqry, " VALIDATOR ");
8678 /* Cope with possibility that validator is in different schema */
8679 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8680 appendPQExpBuffer(defqry, "%s.",
8681 fmtId(validatorInfo->dobj.namespace->dobj.name));
8682 appendPQExpBuffer(defqry, "%s",
8683 fmtId(validatorInfo->dobj.name));
8689 * If not dumping parameters, then use CREATE OR REPLACE so that the
8690 * command will not fail if the language is preinstalled in the target
8691 * database. We restrict the use of REPLACE to this case so as to
8692 * eliminate the risk of replacing a language with incompatible
8693 * parameter settings: this command will only succeed at all if there
8694 * is a pg_pltemplate entry, and if there is one, the existing entry
8695 * must match it too.
8697 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8700 appendPQExpBuffer(defqry, ";\n");
8702 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8705 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8707 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8709 lanschema, NULL, plang->lanowner,
8710 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8711 defqry->data, delqry->data, NULL,
8712 plang->dobj.dependencies, plang->dobj.nDeps,
8715 /* Dump Proc Lang Comments and Security Labels */
8716 dumpComment(fout, labelq->data,
8718 plang->dobj.catId, 0, plang->dobj.dumpId);
8719 dumpSecLabel(fout, labelq->data,
8721 plang->dobj.catId, 0, plang->dobj.dumpId);
8723 if (plang->lanpltrusted)
8724 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8725 qlanname, NULL, plang->dobj.name,
8727 plang->lanowner, plang->lanacl);
8731 destroyPQExpBuffer(defqry);
8732 destroyPQExpBuffer(delqry);
8733 destroyPQExpBuffer(labelq);
8737 * format_function_arguments: generate function name and argument list
8739 * This is used when we can rely on pg_get_function_arguments to format
8740 * the argument list.
8743 format_function_arguments(FuncInfo *finfo, char *funcargs)
8747 initPQExpBuffer(&fn);
8748 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8753 * format_function_arguments_old: generate function name and argument list
8755 * The argument type names are qualified if needed. The function name
8756 * is never qualified.
8758 * This is used only with pre-8.4 servers, so we aren't expecting to see
8759 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8761 * Any or all of allargtypes, argmodes, argnames may be NULL.
8764 format_function_arguments_old(Archive *fout,
8765 FuncInfo *finfo, int nallargs,
8773 initPQExpBuffer(&fn);
8774 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8775 for (j = 0; j < nallargs; j++)
8779 const char *argmode;
8780 const char *argname;
8782 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8783 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8787 switch (argmodes[j][0])
8792 case PROARGMODE_OUT:
8795 case PROARGMODE_INOUT:
8799 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8807 argname = argnames ? argnames[j] : (char *) NULL;
8808 if (argname && argname[0] == '\0')
8811 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8812 (j > 0) ? ", " : "",
8814 argname ? fmtId(argname) : "",
8819 appendPQExpBuffer(&fn, ")");
8824 * format_function_signature: generate function name and argument list
8826 * This is like format_function_arguments_old except that only a minimal
8827 * list of input argument types is generated; this is sufficient to
8828 * reference the function, but not to define it.
8830 * If honor_quotes is false then the function name is never quoted.
8831 * This is appropriate for use in TOC tags, but not in SQL commands.
8834 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8839 initPQExpBuffer(&fn);
8841 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8843 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8844 for (j = 0; j < finfo->nargs; j++)
8848 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8851 appendPQExpBuffer(&fn, "%s%s",
8852 (j > 0) ? ", " : "",
8856 appendPQExpBuffer(&fn, ")");
8863 * dump out one function
8866 dumpFunc(Archive *fout, FuncInfo *finfo)
8874 char *funcsig; /* identity signature */
8875 char *funcfullsig; /* full signature */
8883 char *proallargtypes;
8897 char **allargtypes = NULL;
8898 char **argmodes = NULL;
8899 char **argnames = NULL;
8900 char **configitems = NULL;
8901 int nconfigitems = 0;
8904 /* Skip if not to be dumped */
8905 if (!finfo->dobj.dump || dataOnly)
8908 query = createPQExpBuffer();
8909 q = createPQExpBuffer();
8910 delqry = createPQExpBuffer();
8911 labelq = createPQExpBuffer();
8912 asPart = createPQExpBuffer();
8914 /* Set proper schema search path so type references list correctly */
8915 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8917 /* Fetch function-specific details */
8918 if (fout->remoteVersion >= 90200)
8921 * proleakproof was added at v9.2
8923 appendPQExpBuffer(query,
8924 "SELECT proretset, prosrc, probin, "
8925 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8926 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8927 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8928 "proiswindow, provolatile, proisstrict, prosecdef, "
8929 "proleakproof, proconfig, procost, prorows, "
8930 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8931 "FROM pg_catalog.pg_proc "
8932 "WHERE oid = '%u'::pg_catalog.oid",
8933 finfo->dobj.catId.oid);
8935 else if (fout->remoteVersion >= 80400)
8938 * In 8.4 and up we rely on pg_get_function_arguments and
8939 * pg_get_function_result instead of examining proallargtypes etc.
8941 appendPQExpBuffer(query,
8942 "SELECT proretset, prosrc, probin, "
8943 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8944 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8945 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8946 "proiswindow, provolatile, proisstrict, prosecdef, "
8947 "false AS proleakproof, "
8948 " proconfig, procost, prorows, "
8949 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8950 "FROM pg_catalog.pg_proc "
8951 "WHERE oid = '%u'::pg_catalog.oid",
8952 finfo->dobj.catId.oid);
8954 else if (fout->remoteVersion >= 80300)
8956 appendPQExpBuffer(query,
8957 "SELECT proretset, prosrc, probin, "
8958 "proallargtypes, proargmodes, proargnames, "
8959 "false AS proiswindow, "
8960 "provolatile, proisstrict, prosecdef, "
8961 "false AS proleakproof, "
8962 "proconfig, procost, prorows, "
8963 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8964 "FROM pg_catalog.pg_proc "
8965 "WHERE oid = '%u'::pg_catalog.oid",
8966 finfo->dobj.catId.oid);
8968 else if (fout->remoteVersion >= 80100)
8970 appendPQExpBuffer(query,
8971 "SELECT proretset, prosrc, probin, "
8972 "proallargtypes, proargmodes, proargnames, "
8973 "false AS proiswindow, "
8974 "provolatile, proisstrict, prosecdef, "
8975 "false AS proleakproof, "
8976 "null AS proconfig, 0 AS procost, 0 AS 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 >= 80000)
8984 appendPQExpBuffer(query,
8985 "SELECT proretset, prosrc, probin, "
8986 "null AS proallargtypes, "
8987 "null AS proargmodes, "
8989 "false AS proiswindow, "
8990 "provolatile, proisstrict, prosecdef, "
8991 "false AS proleakproof, "
8992 "null AS proconfig, 0 AS procost, 0 AS prorows, "
8993 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8994 "FROM pg_catalog.pg_proc "
8995 "WHERE oid = '%u'::pg_catalog.oid",
8996 finfo->dobj.catId.oid);
8998 else if (fout->remoteVersion >= 70300)
9000 appendPQExpBuffer(query,
9001 "SELECT proretset, prosrc, probin, "
9002 "null AS proallargtypes, "
9003 "null AS proargmodes, "
9004 "null AS proargnames, "
9005 "false AS proiswindow, "
9006 "provolatile, proisstrict, prosecdef, "
9007 "false AS proleakproof, "
9008 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9009 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9010 "FROM pg_catalog.pg_proc "
9011 "WHERE oid = '%u'::pg_catalog.oid",
9012 finfo->dobj.catId.oid);
9014 else if (fout->remoteVersion >= 70100)
9016 appendPQExpBuffer(query,
9017 "SELECT proretset, prosrc, probin, "
9018 "null AS proallargtypes, "
9019 "null AS proargmodes, "
9020 "null AS proargnames, "
9021 "false AS proiswindow, "
9022 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9024 "false AS prosecdef, "
9025 "false AS proleakproof, "
9026 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9027 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9029 "WHERE oid = '%u'::oid",
9030 finfo->dobj.catId.oid);
9034 appendPQExpBuffer(query,
9035 "SELECT proretset, prosrc, probin, "
9036 "null AS proallargtypes, "
9037 "null AS proargmodes, "
9038 "null AS proargnames, "
9039 "false AS proiswindow, "
9040 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9041 "false AS proisstrict, "
9042 "false AS prosecdef, "
9043 "false AS proleakproof, "
9044 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9045 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9047 "WHERE oid = '%u'::oid",
9048 finfo->dobj.catId.oid);
9051 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9053 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9054 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9055 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9056 if (fout->remoteVersion >= 80400)
9058 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9059 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9060 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9061 proallargtypes = proargmodes = proargnames = NULL;
9065 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9066 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9067 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9068 funcargs = funciargs = funcresult = NULL;
9070 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9071 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9072 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9073 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9074 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9075 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9076 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9077 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9078 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9081 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9082 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9083 * versions would set it to "-". There are no known cases in which prosrc
9084 * is unused, so the tests below for "-" are probably useless.
9086 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9088 appendPQExpBuffer(asPart, "AS ");
9089 appendStringLiteralAH(asPart, probin, fout);
9090 if (strcmp(prosrc, "-") != 0)
9092 appendPQExpBuffer(asPart, ", ");
9095 * where we have bin, use dollar quoting if allowed and src
9096 * contains quote or backslash; else use regular quoting.
9098 if (disable_dollar_quoting ||
9099 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9100 appendStringLiteralAH(asPart, prosrc, fout);
9102 appendStringLiteralDQ(asPart, prosrc, NULL);
9107 if (strcmp(prosrc, "-") != 0)
9109 appendPQExpBuffer(asPart, "AS ");
9110 /* with no bin, dollar quote src unconditionally if allowed */
9111 if (disable_dollar_quoting)
9112 appendStringLiteralAH(asPart, prosrc, fout);
9114 appendStringLiteralDQ(asPart, prosrc, NULL);
9118 nallargs = finfo->nargs; /* unless we learn different from allargs */
9120 if (proallargtypes && *proallargtypes)
9124 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9125 nitems < finfo->nargs)
9127 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9136 if (proargmodes && *proargmodes)
9140 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9143 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9150 if (proargnames && *proargnames)
9154 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9157 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9164 if (proconfig && *proconfig)
9166 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9168 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9178 /* 8.4 or later; we rely on server-side code for most of the work */
9179 funcfullsig = format_function_arguments(finfo, funcargs);
9180 funcsig = format_function_arguments(finfo, funciargs);
9184 /* pre-8.4, do it ourselves */
9185 funcsig = format_function_arguments_old(fout,
9186 finfo, nallargs, allargtypes,
9187 argmodes, argnames);
9188 funcfullsig = funcsig;
9191 funcsig_tag = format_function_signature(fout, finfo, false);
9194 * DROP must be fully qualified in case same name appears in pg_catalog
9196 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9197 fmtId(finfo->dobj.namespace->dobj.name),
9200 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9202 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9205 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9207 appendPQExpBuffer(q, "RETURNS %s%s",
9208 (proretset[0] == 't') ? "SETOF " : "",
9213 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9215 if (proiswindow[0] == 't')
9216 appendPQExpBuffer(q, " WINDOW");
9218 if (provolatile[0] != PROVOLATILE_VOLATILE)
9220 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9221 appendPQExpBuffer(q, " IMMUTABLE");
9222 else if (provolatile[0] == PROVOLATILE_STABLE)
9223 appendPQExpBuffer(q, " STABLE");
9224 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9225 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9229 if (proisstrict[0] == 't')
9230 appendPQExpBuffer(q, " STRICT");
9232 if (prosecdef[0] == 't')
9233 appendPQExpBuffer(q, " SECURITY DEFINER");
9235 if (proleakproof[0] == 't')
9236 appendPQExpBuffer(q, " LEAKPROOF");
9239 * COST and ROWS are emitted only if present and not default, so as not to
9240 * break backwards-compatibility of the dump without need. Keep this code
9241 * in sync with the defaults in functioncmds.c.
9243 if (strcmp(procost, "0") != 0)
9245 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9247 /* default cost is 1 */
9248 if (strcmp(procost, "1") != 0)
9249 appendPQExpBuffer(q, " COST %s", procost);
9253 /* default cost is 100 */
9254 if (strcmp(procost, "100") != 0)
9255 appendPQExpBuffer(q, " COST %s", procost);
9258 if (proretset[0] == 't' &&
9259 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9260 appendPQExpBuffer(q, " ROWS %s", prorows);
9262 for (i = 0; i < nconfigitems; i++)
9264 /* we feel free to scribble on configitems[] here */
9265 char *configitem = configitems[i];
9268 pos = strchr(configitem, '=');
9272 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9275 * Some GUC variable names are 'LIST' type and hence must not be
9278 if (pg_strcasecmp(configitem, "DateStyle") == 0
9279 || pg_strcasecmp(configitem, "search_path") == 0)
9280 appendPQExpBuffer(q, "%s", pos);
9282 appendStringLiteralAH(q, pos, fout);
9285 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9287 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9290 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9292 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9294 finfo->dobj.namespace->dobj.name,
9296 finfo->rolname, false,
9297 "FUNCTION", SECTION_PRE_DATA,
9298 q->data, delqry->data, NULL,
9299 finfo->dobj.dependencies, finfo->dobj.nDeps,
9302 /* Dump Function Comments and Security Labels */
9303 dumpComment(fout, labelq->data,
9304 finfo->dobj.namespace->dobj.name, finfo->rolname,
9305 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9306 dumpSecLabel(fout, labelq->data,
9307 finfo->dobj.namespace->dobj.name, finfo->rolname,
9308 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9310 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9311 funcsig, NULL, funcsig_tag,
9312 finfo->dobj.namespace->dobj.name,
9313 finfo->rolname, finfo->proacl);
9317 destroyPQExpBuffer(query);
9318 destroyPQExpBuffer(q);
9319 destroyPQExpBuffer(delqry);
9320 destroyPQExpBuffer(labelq);
9321 destroyPQExpBuffer(asPart);
9336 * Dump a user-defined cast
9339 dumpCast(Archive *fout, CastInfo *cast)
9344 FuncInfo *funcInfo = NULL;
9346 /* Skip if not to be dumped */
9347 if (!cast->dobj.dump || dataOnly)
9350 /* Cannot dump if we don't have the cast function's info */
9351 if (OidIsValid(cast->castfunc))
9353 funcInfo = findFuncByOid(cast->castfunc);
9354 if (funcInfo == NULL)
9359 * As per discussion we dump casts if one or more of the underlying
9360 * objects (the conversion function and the two data types) are not
9361 * builtin AND if all of the non-builtin objects are included in the dump.
9362 * Builtin meaning, the namespace name does not start with "pg_".
9364 * However, for a cast that belongs to an extension, we must not use this
9365 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9367 if (!cast->dobj.ext_member)
9369 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9370 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9372 if (sourceInfo == NULL || targetInfo == NULL)
9376 * Skip this cast if all objects are from pg_
9378 if ((funcInfo == NULL ||
9379 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9380 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9381 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9385 * Skip cast if function isn't from pg_ and is not to be dumped.
9388 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9389 !funcInfo->dobj.dump)
9393 * Same for the source type
9395 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9396 !sourceInfo->dobj.dump)
9400 * and the target type.
9402 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9403 !targetInfo->dobj.dump)
9407 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9408 selectSourceSchema(fout, "pg_catalog");
9410 defqry = createPQExpBuffer();
9411 delqry = createPQExpBuffer();
9412 labelq = createPQExpBuffer();
9414 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9415 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9416 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9418 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9419 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9420 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9422 switch (cast->castmethod)
9424 case COERCION_METHOD_BINARY:
9425 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9427 case COERCION_METHOD_INOUT:
9428 appendPQExpBuffer(defqry, "WITH INOUT");
9430 case COERCION_METHOD_FUNCTION:
9433 char *fsig = format_function_signature(fout, funcInfo, true);
9436 * Always qualify the function name, in case it is not in
9437 * pg_catalog schema (format_function_signature won't qualify
9440 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9441 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9445 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9448 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9451 if (cast->castcontext == 'a')
9452 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9453 else if (cast->castcontext == 'i')
9454 appendPQExpBuffer(defqry, " AS IMPLICIT");
9455 appendPQExpBuffer(defqry, ";\n");
9457 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9458 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9459 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9462 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9464 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9466 "pg_catalog", NULL, "",
9467 false, "CAST", SECTION_PRE_DATA,
9468 defqry->data, delqry->data, NULL,
9469 cast->dobj.dependencies, cast->dobj.nDeps,
9472 /* Dump Cast Comments */
9473 dumpComment(fout, labelq->data,
9475 cast->dobj.catId, 0, cast->dobj.dumpId);
9477 destroyPQExpBuffer(defqry);
9478 destroyPQExpBuffer(delqry);
9479 destroyPQExpBuffer(labelq);
9484 * write out a single operator definition
9487 dumpOpr(Archive *fout, OprInfo *oprinfo)
9494 PQExpBuffer details;
9518 /* Skip if not to be dumped */
9519 if (!oprinfo->dobj.dump || dataOnly)
9523 * some operators are invalid because they were the result of user
9524 * defining operators before commutators exist
9526 if (!OidIsValid(oprinfo->oprcode))
9529 query = createPQExpBuffer();
9530 q = createPQExpBuffer();
9531 delq = createPQExpBuffer();
9532 labelq = createPQExpBuffer();
9533 oprid = createPQExpBuffer();
9534 details = createPQExpBuffer();
9536 /* Make sure we are in proper schema so regoperator works correctly */
9537 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9539 if (fout->remoteVersion >= 80300)
9541 appendPQExpBuffer(query, "SELECT oprkind, "
9542 "oprcode::pg_catalog.regprocedure, "
9543 "oprleft::pg_catalog.regtype, "
9544 "oprright::pg_catalog.regtype, "
9545 "oprcom::pg_catalog.regoperator, "
9546 "oprnegate::pg_catalog.regoperator, "
9547 "oprrest::pg_catalog.regprocedure, "
9548 "oprjoin::pg_catalog.regprocedure, "
9549 "oprcanmerge, oprcanhash "
9550 "FROM pg_catalog.pg_operator "
9551 "WHERE oid = '%u'::pg_catalog.oid",
9552 oprinfo->dobj.catId.oid);
9554 else if (fout->remoteVersion >= 70300)
9556 appendPQExpBuffer(query, "SELECT oprkind, "
9557 "oprcode::pg_catalog.regprocedure, "
9558 "oprleft::pg_catalog.regtype, "
9559 "oprright::pg_catalog.regtype, "
9560 "oprcom::pg_catalog.regoperator, "
9561 "oprnegate::pg_catalog.regoperator, "
9562 "oprrest::pg_catalog.regprocedure, "
9563 "oprjoin::pg_catalog.regprocedure, "
9564 "(oprlsortop != 0) AS oprcanmerge, "
9566 "FROM pg_catalog.pg_operator "
9567 "WHERE oid = '%u'::pg_catalog.oid",
9568 oprinfo->dobj.catId.oid);
9570 else if (fout->remoteVersion >= 70100)
9572 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9573 "CASE WHEN oprleft = 0 THEN '-' "
9574 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9575 "CASE WHEN oprright = 0 THEN '-' "
9576 "ELSE format_type(oprright, NULL) END AS oprright, "
9577 "oprcom, oprnegate, oprrest, oprjoin, "
9578 "(oprlsortop != 0) AS oprcanmerge, "
9581 "WHERE oid = '%u'::oid",
9582 oprinfo->dobj.catId.oid);
9586 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9587 "CASE WHEN oprleft = 0 THEN '-'::name "
9588 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9589 "CASE WHEN oprright = 0 THEN '-'::name "
9590 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9591 "oprcom, oprnegate, oprrest, oprjoin, "
9592 "(oprlsortop != 0) AS oprcanmerge, "
9595 "WHERE oid = '%u'::oid",
9596 oprinfo->dobj.catId.oid);
9599 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9601 i_oprkind = PQfnumber(res, "oprkind");
9602 i_oprcode = PQfnumber(res, "oprcode");
9603 i_oprleft = PQfnumber(res, "oprleft");
9604 i_oprright = PQfnumber(res, "oprright");
9605 i_oprcom = PQfnumber(res, "oprcom");
9606 i_oprnegate = PQfnumber(res, "oprnegate");
9607 i_oprrest = PQfnumber(res, "oprrest");
9608 i_oprjoin = PQfnumber(res, "oprjoin");
9609 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9610 i_oprcanhash = PQfnumber(res, "oprcanhash");
9612 oprkind = PQgetvalue(res, 0, i_oprkind);
9613 oprcode = PQgetvalue(res, 0, i_oprcode);
9614 oprleft = PQgetvalue(res, 0, i_oprleft);
9615 oprright = PQgetvalue(res, 0, i_oprright);
9616 oprcom = PQgetvalue(res, 0, i_oprcom);
9617 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9618 oprrest = PQgetvalue(res, 0, i_oprrest);
9619 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9620 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9621 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9623 appendPQExpBuffer(details, " PROCEDURE = %s",
9624 convertRegProcReference(fout, oprcode));
9626 appendPQExpBuffer(oprid, "%s (",
9627 oprinfo->dobj.name);
9630 * right unary means there's a left arg and left unary means there's a
9633 if (strcmp(oprkind, "r") == 0 ||
9634 strcmp(oprkind, "b") == 0)
9636 if (fout->remoteVersion >= 70100)
9639 name = fmtId(oprleft);
9640 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9641 appendPQExpBuffer(oprid, "%s", name);
9644 appendPQExpBuffer(oprid, "NONE");
9646 if (strcmp(oprkind, "l") == 0 ||
9647 strcmp(oprkind, "b") == 0)
9649 if (fout->remoteVersion >= 70100)
9652 name = fmtId(oprright);
9653 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9654 appendPQExpBuffer(oprid, ", %s)", name);
9657 appendPQExpBuffer(oprid, ", NONE)");
9659 name = convertOperatorReference(fout, oprcom);
9661 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9663 name = convertOperatorReference(fout, oprnegate);
9665 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9667 if (strcmp(oprcanmerge, "t") == 0)
9668 appendPQExpBuffer(details, ",\n MERGES");
9670 if (strcmp(oprcanhash, "t") == 0)
9671 appendPQExpBuffer(details, ",\n HASHES");
9673 name = convertRegProcReference(fout, oprrest);
9675 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9677 name = convertRegProcReference(fout, oprjoin);
9679 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9682 * DROP must be fully qualified in case same name appears in pg_catalog
9684 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9685 fmtId(oprinfo->dobj.namespace->dobj.name),
9688 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9689 oprinfo->dobj.name, details->data);
9691 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9694 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9696 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9698 oprinfo->dobj.namespace->dobj.name,
9701 false, "OPERATOR", SECTION_PRE_DATA,
9702 q->data, delq->data, NULL,
9703 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9706 /* Dump Operator Comments */
9707 dumpComment(fout, labelq->data,
9708 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9709 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9713 destroyPQExpBuffer(query);
9714 destroyPQExpBuffer(q);
9715 destroyPQExpBuffer(delq);
9716 destroyPQExpBuffer(labelq);
9717 destroyPQExpBuffer(oprid);
9718 destroyPQExpBuffer(details);
9722 * Convert a function reference obtained from pg_operator
9724 * Returns what to print, or NULL if function references is InvalidOid
9726 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9727 * argument-types part. In prior versions, the input is a REGPROC display.
9730 convertRegProcReference(Archive *fout, const char *proc)
9732 /* In all cases "-" means a null reference */
9733 if (strcmp(proc, "-") == 0)
9736 if (fout->remoteVersion >= 70300)
9742 name = pg_strdup(proc);
9743 /* find non-double-quoted left paren */
9745 for (paren = name; *paren; paren++)
9747 if (*paren == '(' && !inquote)
9758 /* REGPROC before 7.3 does not quote its result */
9763 * Convert an operator cross-reference obtained from pg_operator
9765 * Returns what to print, or NULL to print nothing
9767 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9768 * argument-types part, and add OPERATOR() decoration if the name is
9769 * schema-qualified. In older versions, the input is just a numeric OID,
9770 * which we search our operator list for.
9773 convertOperatorReference(Archive *fout, const char *opr)
9777 /* In all cases "0" means a null reference */
9778 if (strcmp(opr, "0") == 0)
9781 if (fout->remoteVersion >= 70300)
9789 name = pg_strdup(opr);
9790 /* find non-double-quoted left paren, and check for non-quoted dot */
9793 for (ptr = name; *ptr; ptr++)
9797 else if (*ptr == '.' && !inquote)
9799 else if (*ptr == '(' && !inquote)
9805 /* If not schema-qualified, don't need to add OPERATOR() */
9808 oname = pg_malloc(strlen(name) + 11);
9809 sprintf(oname, "OPERATOR(%s)", name);
9814 oprInfo = findOprByOid(atooid(opr));
9815 if (oprInfo == NULL)
9817 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9821 return oprInfo->dobj.name;
9825 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9827 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9828 * argument lists of these functions are predetermined. Note that the
9829 * caller should ensure we are in the proper schema, because the results
9830 * are search path dependent!
9833 convertTSFunction(Archive *fout, Oid funcOid)
9839 snprintf(query, sizeof(query),
9840 "SELECT '%u'::pg_catalog.regproc", funcOid);
9841 res = ExecuteSqlQueryForSingleRow(fout, query);
9843 result = pg_strdup(PQgetvalue(res, 0, 0));
9853 * write out a single operator class definition
9856 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9868 int i_opcfamilyname;
9875 int i_sortfamilynsp;
9878 int i_amproclefttype;
9879 int i_amprocrighttype;
9884 char *opcfamilyname;
9891 char *sortfamilynsp;
9894 char *amproclefttype;
9895 char *amprocrighttype;
9899 /* Skip if not to be dumped */
9900 if (!opcinfo->dobj.dump || dataOnly)
9904 * XXX currently we do not implement dumping of operator classes from
9905 * pre-7.3 databases. This could be done but it seems not worth the
9908 if (fout->remoteVersion < 70300)
9911 query = createPQExpBuffer();
9912 q = createPQExpBuffer();
9913 delq = createPQExpBuffer();
9914 labelq = createPQExpBuffer();
9916 /* Make sure we are in proper schema so regoperator works correctly */
9917 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9919 /* Get additional fields from the pg_opclass row */
9920 if (fout->remoteVersion >= 80300)
9922 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9923 "opckeytype::pg_catalog.regtype, "
9924 "opcdefault, opcfamily, "
9925 "opfname AS opcfamilyname, "
9926 "nspname AS opcfamilynsp, "
9927 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9928 "FROM pg_catalog.pg_opclass c "
9929 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9930 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9931 "WHERE c.oid = '%u'::pg_catalog.oid",
9932 opcinfo->dobj.catId.oid);
9936 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9937 "opckeytype::pg_catalog.regtype, "
9938 "opcdefault, NULL AS opcfamily, "
9939 "NULL AS opcfamilyname, "
9940 "NULL AS opcfamilynsp, "
9941 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9942 "FROM pg_catalog.pg_opclass "
9943 "WHERE oid = '%u'::pg_catalog.oid",
9944 opcinfo->dobj.catId.oid);
9947 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9949 i_opcintype = PQfnumber(res, "opcintype");
9950 i_opckeytype = PQfnumber(res, "opckeytype");
9951 i_opcdefault = PQfnumber(res, "opcdefault");
9952 i_opcfamily = PQfnumber(res, "opcfamily");
9953 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9954 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9955 i_amname = PQfnumber(res, "amname");
9957 opcintype = PQgetvalue(res, 0, i_opcintype);
9958 opckeytype = PQgetvalue(res, 0, i_opckeytype);
9959 opcdefault = PQgetvalue(res, 0, i_opcdefault);
9960 /* opcfamily will still be needed after we PQclear res */
9961 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9962 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9963 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
9964 /* amname will still be needed after we PQclear res */
9965 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
9968 * DROP must be fully qualified in case same name appears in pg_catalog
9970 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
9971 fmtId(opcinfo->dobj.namespace->dobj.name));
9972 appendPQExpBuffer(delq, ".%s",
9973 fmtId(opcinfo->dobj.name));
9974 appendPQExpBuffer(delq, " USING %s;\n",
9977 /* Build the fixed portion of the CREATE command */
9978 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
9979 fmtId(opcinfo->dobj.name));
9980 if (strcmp(opcdefault, "t") == 0)
9981 appendPQExpBuffer(q, "DEFAULT ");
9982 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
9985 if (strlen(opcfamilyname) > 0 &&
9986 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
9987 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
9989 appendPQExpBuffer(q, " FAMILY ");
9990 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
9991 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
9992 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
9994 appendPQExpBuffer(q, " AS\n ");
9998 if (strcmp(opckeytype, "-") != 0)
10000 appendPQExpBuffer(q, "STORAGE %s",
10008 * Now fetch and print the OPERATOR entries (pg_amop rows).
10010 * Print only those opfamily members that are tied to the opclass by
10011 * pg_depend entries.
10013 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10014 * older server's opclass in which it is used. This is to avoid
10015 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10016 * older server and then reload into that old version. This can go away
10017 * once 8.3 is so old as to not be of interest to anyone.
10019 resetPQExpBuffer(query);
10021 if (fout->remoteVersion >= 90100)
10023 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10024 "amopopr::pg_catalog.regoperator, "
10025 "opfname AS sortfamily, "
10026 "nspname AS sortfamilynsp "
10027 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10028 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10029 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10030 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10031 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10032 "AND refobjid = '%u'::pg_catalog.oid "
10033 "AND amopfamily = '%s'::pg_catalog.oid "
10034 "ORDER BY amopstrategy",
10035 opcinfo->dobj.catId.oid,
10038 else if (fout->remoteVersion >= 80400)
10040 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10041 "amopopr::pg_catalog.regoperator, "
10042 "NULL AS sortfamily, "
10043 "NULL AS sortfamilynsp "
10044 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10045 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10046 "AND refobjid = '%u'::pg_catalog.oid "
10047 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10048 "AND objid = ao.oid "
10049 "ORDER BY amopstrategy",
10050 opcinfo->dobj.catId.oid);
10052 else if (fout->remoteVersion >= 80300)
10054 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10055 "amopopr::pg_catalog.regoperator, "
10056 "NULL AS sortfamily, "
10057 "NULL AS sortfamilynsp "
10058 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10059 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10060 "AND refobjid = '%u'::pg_catalog.oid "
10061 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10062 "AND objid = ao.oid "
10063 "ORDER BY amopstrategy",
10064 opcinfo->dobj.catId.oid);
10069 * Here, we print all entries since there are no opfamilies and hence
10070 * no loose operators to worry about.
10072 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10073 "amopopr::pg_catalog.regoperator, "
10074 "NULL AS sortfamily, "
10075 "NULL AS sortfamilynsp "
10076 "FROM pg_catalog.pg_amop "
10077 "WHERE amopclaid = '%u'::pg_catalog.oid "
10078 "ORDER BY amopstrategy",
10079 opcinfo->dobj.catId.oid);
10082 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10084 ntups = PQntuples(res);
10086 i_amopstrategy = PQfnumber(res, "amopstrategy");
10087 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10088 i_amopopr = PQfnumber(res, "amopopr");
10089 i_sortfamily = PQfnumber(res, "sortfamily");
10090 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10092 for (i = 0; i < ntups; i++)
10094 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10095 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10096 amopopr = PQgetvalue(res, i, i_amopopr);
10097 sortfamily = PQgetvalue(res, i, i_sortfamily);
10098 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10101 appendPQExpBuffer(q, " ,\n ");
10103 appendPQExpBuffer(q, "OPERATOR %s %s",
10104 amopstrategy, amopopr);
10106 if (strlen(sortfamily) > 0)
10108 appendPQExpBuffer(q, " FOR ORDER BY ");
10109 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10110 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10111 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10114 if (strcmp(amopreqcheck, "t") == 0)
10115 appendPQExpBuffer(q, " RECHECK");
10123 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10125 * Print only those opfamily members that are tied to the opclass by
10126 * pg_depend entries.
10128 * We print the amproclefttype/amprocrighttype even though in most cases
10129 * the backend could deduce the right values, because of the corner case
10130 * of a btree sort support function for a cross-type comparison. That's
10131 * only allowed in 9.2 and later, but for simplicity print them in all
10132 * versions that have the columns.
10134 resetPQExpBuffer(query);
10136 if (fout->remoteVersion >= 80300)
10138 appendPQExpBuffer(query, "SELECT amprocnum, "
10139 "amproc::pg_catalog.regprocedure, "
10140 "amproclefttype::pg_catalog.regtype, "
10141 "amprocrighttype::pg_catalog.regtype "
10142 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10143 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10144 "AND refobjid = '%u'::pg_catalog.oid "
10145 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10146 "AND objid = ap.oid "
10147 "ORDER BY amprocnum",
10148 opcinfo->dobj.catId.oid);
10152 appendPQExpBuffer(query, "SELECT amprocnum, "
10153 "amproc::pg_catalog.regprocedure, "
10154 "'' AS amproclefttype, "
10155 "'' AS amprocrighttype "
10156 "FROM pg_catalog.pg_amproc "
10157 "WHERE amopclaid = '%u'::pg_catalog.oid "
10158 "ORDER BY amprocnum",
10159 opcinfo->dobj.catId.oid);
10162 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10164 ntups = PQntuples(res);
10166 i_amprocnum = PQfnumber(res, "amprocnum");
10167 i_amproc = PQfnumber(res, "amproc");
10168 i_amproclefttype = PQfnumber(res, "amproclefttype");
10169 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10171 for (i = 0; i < ntups; i++)
10173 amprocnum = PQgetvalue(res, i, i_amprocnum);
10174 amproc = PQgetvalue(res, i, i_amproc);
10175 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10176 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10179 appendPQExpBuffer(q, " ,\n ");
10181 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10183 if (*amproclefttype && *amprocrighttype)
10184 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10186 appendPQExpBuffer(q, " %s", amproc);
10193 appendPQExpBuffer(q, ";\n");
10195 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10196 fmtId(opcinfo->dobj.name));
10197 appendPQExpBuffer(labelq, " USING %s",
10200 if (binary_upgrade)
10201 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10203 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10204 opcinfo->dobj.name,
10205 opcinfo->dobj.namespace->dobj.name,
10208 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10209 q->data, delq->data, NULL,
10210 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10213 /* Dump Operator Class Comments */
10214 dumpComment(fout, labelq->data,
10215 NULL, opcinfo->rolname,
10216 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10219 destroyPQExpBuffer(query);
10220 destroyPQExpBuffer(q);
10221 destroyPQExpBuffer(delq);
10222 destroyPQExpBuffer(labelq);
10227 * write out a single operator family definition
10229 * Note: this also dumps any "loose" operator members that aren't bound to a
10230 * specific opclass within the opfamily.
10233 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10238 PQExpBuffer labelq;
10241 PGresult *res_procs;
10244 int i_amopstrategy;
10245 int i_amopreqcheck;
10248 int i_sortfamilynsp;
10251 int i_amproclefttype;
10252 int i_amprocrighttype;
10254 char *amopstrategy;
10255 char *amopreqcheck;
10258 char *sortfamilynsp;
10261 char *amproclefttype;
10262 char *amprocrighttype;
10266 /* Skip if not to be dumped */
10267 if (!opfinfo->dobj.dump || dataOnly)
10271 * We want to dump the opfamily only if (1) it contains "loose" operators
10272 * or functions, or (2) it contains an opclass with a different name or
10273 * owner. Otherwise it's sufficient to let it be created during creation
10274 * of the contained opclass, and not dumping it improves portability of
10275 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10279 query = createPQExpBuffer();
10280 q = createPQExpBuffer();
10281 delq = createPQExpBuffer();
10282 labelq = createPQExpBuffer();
10284 /* Make sure we are in proper schema so regoperator works correctly */
10285 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10288 * Fetch only those opfamily members that are tied directly to the
10289 * opfamily by pg_depend entries.
10291 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10292 * older server's opclass in which it is used. This is to avoid
10293 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10294 * older server and then reload into that old version. This can go away
10295 * once 8.3 is so old as to not be of interest to anyone.
10297 if (fout->remoteVersion >= 90100)
10299 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10300 "amopopr::pg_catalog.regoperator, "
10301 "opfname AS sortfamily, "
10302 "nspname AS sortfamilynsp "
10303 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10304 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10305 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10306 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10307 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10308 "AND refobjid = '%u'::pg_catalog.oid "
10309 "AND amopfamily = '%u'::pg_catalog.oid "
10310 "ORDER BY amopstrategy",
10311 opfinfo->dobj.catId.oid,
10312 opfinfo->dobj.catId.oid);
10314 else if (fout->remoteVersion >= 80400)
10316 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10317 "amopopr::pg_catalog.regoperator, "
10318 "NULL AS sortfamily, "
10319 "NULL AS sortfamilynsp "
10320 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10321 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10322 "AND refobjid = '%u'::pg_catalog.oid "
10323 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10324 "AND objid = ao.oid "
10325 "ORDER BY amopstrategy",
10326 opfinfo->dobj.catId.oid);
10330 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10331 "amopopr::pg_catalog.regoperator, "
10332 "NULL AS sortfamily, "
10333 "NULL AS sortfamilynsp "
10334 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10335 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10336 "AND refobjid = '%u'::pg_catalog.oid "
10337 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10338 "AND objid = ao.oid "
10339 "ORDER BY amopstrategy",
10340 opfinfo->dobj.catId.oid);
10343 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10345 resetPQExpBuffer(query);
10347 appendPQExpBuffer(query, "SELECT amprocnum, "
10348 "amproc::pg_catalog.regprocedure, "
10349 "amproclefttype::pg_catalog.regtype, "
10350 "amprocrighttype::pg_catalog.regtype "
10351 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10352 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10353 "AND refobjid = '%u'::pg_catalog.oid "
10354 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10355 "AND objid = ap.oid "
10356 "ORDER BY amprocnum",
10357 opfinfo->dobj.catId.oid);
10359 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10361 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10363 /* No loose members, so check contained opclasses */
10364 resetPQExpBuffer(query);
10366 appendPQExpBuffer(query, "SELECT 1 "
10367 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10368 "WHERE f.oid = '%u'::pg_catalog.oid "
10369 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10370 "AND refobjid = f.oid "
10371 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10372 "AND objid = c.oid "
10373 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10375 opfinfo->dobj.catId.oid);
10377 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10379 if (PQntuples(res) == 0)
10381 /* no need to dump it, so bail out */
10384 PQclear(res_procs);
10385 destroyPQExpBuffer(query);
10386 destroyPQExpBuffer(q);
10387 destroyPQExpBuffer(delq);
10388 destroyPQExpBuffer(labelq);
10395 /* Get additional fields from the pg_opfamily row */
10396 resetPQExpBuffer(query);
10398 appendPQExpBuffer(query, "SELECT "
10399 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10400 "FROM pg_catalog.pg_opfamily "
10401 "WHERE oid = '%u'::pg_catalog.oid",
10402 opfinfo->dobj.catId.oid);
10404 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10406 i_amname = PQfnumber(res, "amname");
10408 /* amname will still be needed after we PQclear res */
10409 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10412 * DROP must be fully qualified in case same name appears in pg_catalog
10414 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10415 fmtId(opfinfo->dobj.namespace->dobj.name));
10416 appendPQExpBuffer(delq, ".%s",
10417 fmtId(opfinfo->dobj.name));
10418 appendPQExpBuffer(delq, " USING %s;\n",
10421 /* Build the fixed portion of the CREATE command */
10422 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10423 fmtId(opfinfo->dobj.name));
10424 appendPQExpBuffer(q, " USING %s;\n",
10429 /* Do we need an ALTER to add loose members? */
10430 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10432 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10433 fmtId(opfinfo->dobj.name));
10434 appendPQExpBuffer(q, " USING %s ADD\n ",
10440 * Now fetch and print the OPERATOR entries (pg_amop rows).
10442 ntups = PQntuples(res_ops);
10444 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10445 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10446 i_amopopr = PQfnumber(res_ops, "amopopr");
10447 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10448 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10450 for (i = 0; i < ntups; i++)
10452 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10453 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10454 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10455 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10456 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10459 appendPQExpBuffer(q, " ,\n ");
10461 appendPQExpBuffer(q, "OPERATOR %s %s",
10462 amopstrategy, amopopr);
10464 if (strlen(sortfamily) > 0)
10466 appendPQExpBuffer(q, " FOR ORDER BY ");
10467 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10468 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10469 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10472 if (strcmp(amopreqcheck, "t") == 0)
10473 appendPQExpBuffer(q, " RECHECK");
10479 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10481 ntups = PQntuples(res_procs);
10483 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10484 i_amproc = PQfnumber(res_procs, "amproc");
10485 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10486 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10488 for (i = 0; i < ntups; i++)
10490 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10491 amproc = PQgetvalue(res_procs, i, i_amproc);
10492 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10493 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10496 appendPQExpBuffer(q, " ,\n ");
10498 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10499 amprocnum, amproclefttype, amprocrighttype,
10505 appendPQExpBuffer(q, ";\n");
10508 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10509 fmtId(opfinfo->dobj.name));
10510 appendPQExpBuffer(labelq, " USING %s",
10513 if (binary_upgrade)
10514 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10516 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10517 opfinfo->dobj.name,
10518 opfinfo->dobj.namespace->dobj.name,
10521 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10522 q->data, delq->data, NULL,
10523 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10526 /* Dump Operator Family Comments */
10527 dumpComment(fout, labelq->data,
10528 NULL, opfinfo->rolname,
10529 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10533 PQclear(res_procs);
10534 destroyPQExpBuffer(query);
10535 destroyPQExpBuffer(q);
10536 destroyPQExpBuffer(delq);
10537 destroyPQExpBuffer(labelq);
10542 * write out a single collation definition
10545 dumpCollation(Archive *fout, CollInfo *collinfo)
10550 PQExpBuffer labelq;
10554 const char *collcollate;
10555 const char *collctype;
10557 /* Skip if not to be dumped */
10558 if (!collinfo->dobj.dump || dataOnly)
10561 query = createPQExpBuffer();
10562 q = createPQExpBuffer();
10563 delq = createPQExpBuffer();
10564 labelq = createPQExpBuffer();
10566 /* Make sure we are in proper schema */
10567 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10569 /* Get conversion-specific details */
10570 appendPQExpBuffer(query, "SELECT "
10573 "FROM pg_catalog.pg_collation c "
10574 "WHERE c.oid = '%u'::pg_catalog.oid",
10575 collinfo->dobj.catId.oid);
10577 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10579 i_collcollate = PQfnumber(res, "collcollate");
10580 i_collctype = PQfnumber(res, "collctype");
10582 collcollate = PQgetvalue(res, 0, i_collcollate);
10583 collctype = PQgetvalue(res, 0, i_collctype);
10586 * DROP must be fully qualified in case same name appears in pg_catalog
10588 appendPQExpBuffer(delq, "DROP COLLATION %s",
10589 fmtId(collinfo->dobj.namespace->dobj.name));
10590 appendPQExpBuffer(delq, ".%s;\n",
10591 fmtId(collinfo->dobj.name));
10593 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10594 fmtId(collinfo->dobj.name));
10595 appendStringLiteralAH(q, collcollate, fout);
10596 appendPQExpBuffer(q, ", lc_ctype = ");
10597 appendStringLiteralAH(q, collctype, fout);
10598 appendPQExpBuffer(q, ");\n");
10600 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10602 if (binary_upgrade)
10603 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10605 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10606 collinfo->dobj.name,
10607 collinfo->dobj.namespace->dobj.name,
10610 false, "COLLATION", SECTION_PRE_DATA,
10611 q->data, delq->data, NULL,
10612 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10615 /* Dump Collation Comments */
10616 dumpComment(fout, labelq->data,
10617 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10618 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10622 destroyPQExpBuffer(query);
10623 destroyPQExpBuffer(q);
10624 destroyPQExpBuffer(delq);
10625 destroyPQExpBuffer(labelq);
10630 * write out a single conversion definition
10633 dumpConversion(Archive *fout, ConvInfo *convinfo)
10638 PQExpBuffer labelq;
10640 int i_conforencoding;
10641 int i_contoencoding;
10644 const char *conforencoding;
10645 const char *contoencoding;
10646 const char *conproc;
10649 /* Skip if not to be dumped */
10650 if (!convinfo->dobj.dump || dataOnly)
10653 query = createPQExpBuffer();
10654 q = createPQExpBuffer();
10655 delq = createPQExpBuffer();
10656 labelq = createPQExpBuffer();
10658 /* Make sure we are in proper schema */
10659 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10661 /* Get conversion-specific details */
10662 appendPQExpBuffer(query, "SELECT "
10663 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10664 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10665 "conproc, condefault "
10666 "FROM pg_catalog.pg_conversion c "
10667 "WHERE c.oid = '%u'::pg_catalog.oid",
10668 convinfo->dobj.catId.oid);
10670 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10672 i_conforencoding = PQfnumber(res, "conforencoding");
10673 i_contoencoding = PQfnumber(res, "contoencoding");
10674 i_conproc = PQfnumber(res, "conproc");
10675 i_condefault = PQfnumber(res, "condefault");
10677 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10678 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10679 conproc = PQgetvalue(res, 0, i_conproc);
10680 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10683 * DROP must be fully qualified in case same name appears in pg_catalog
10685 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10686 fmtId(convinfo->dobj.namespace->dobj.name));
10687 appendPQExpBuffer(delq, ".%s;\n",
10688 fmtId(convinfo->dobj.name));
10690 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10691 (condefault) ? "DEFAULT " : "",
10692 fmtId(convinfo->dobj.name));
10693 appendStringLiteralAH(q, conforencoding, fout);
10694 appendPQExpBuffer(q, " TO ");
10695 appendStringLiteralAH(q, contoencoding, fout);
10696 /* regproc is automatically quoted in 7.3 and above */
10697 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10699 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10701 if (binary_upgrade)
10702 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10704 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10705 convinfo->dobj.name,
10706 convinfo->dobj.namespace->dobj.name,
10709 false, "CONVERSION", SECTION_PRE_DATA,
10710 q->data, delq->data, NULL,
10711 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10714 /* Dump Conversion Comments */
10715 dumpComment(fout, labelq->data,
10716 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10717 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10721 destroyPQExpBuffer(query);
10722 destroyPQExpBuffer(q);
10723 destroyPQExpBuffer(delq);
10724 destroyPQExpBuffer(labelq);
10728 * format_aggregate_signature: generate aggregate name and argument list
10730 * The argument type names are qualified if needed. The aggregate name
10731 * is never qualified.
10734 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10736 PQExpBufferData buf;
10739 initPQExpBuffer(&buf);
10741 appendPQExpBuffer(&buf, "%s",
10742 fmtId(agginfo->aggfn.dobj.name));
10744 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10746 if (agginfo->aggfn.nargs == 0)
10747 appendPQExpBuffer(&buf, "(*)");
10750 appendPQExpBuffer(&buf, "(");
10751 for (j = 0; j < agginfo->aggfn.nargs; j++)
10755 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10758 appendPQExpBuffer(&buf, "%s%s",
10759 (j > 0) ? ", " : "",
10763 appendPQExpBuffer(&buf, ")");
10770 * write out a single aggregate definition
10773 dumpAgg(Archive *fout, AggInfo *agginfo)
10778 PQExpBuffer labelq;
10779 PQExpBuffer details;
10786 int i_aggtranstype;
10789 const char *aggtransfn;
10790 const char *aggfinalfn;
10791 const char *aggsortop;
10792 const char *aggtranstype;
10793 const char *agginitval;
10796 /* Skip if not to be dumped */
10797 if (!agginfo->aggfn.dobj.dump || dataOnly)
10800 query = createPQExpBuffer();
10801 q = createPQExpBuffer();
10802 delq = createPQExpBuffer();
10803 labelq = createPQExpBuffer();
10804 details = createPQExpBuffer();
10806 /* Make sure we are in proper schema */
10807 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10809 /* Get aggregate-specific details */
10810 if (fout->remoteVersion >= 80100)
10812 appendPQExpBuffer(query, "SELECT aggtransfn, "
10813 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10814 "aggsortop::pg_catalog.regoperator, "
10816 "'t'::boolean AS convertok "
10817 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10818 "WHERE a.aggfnoid = p.oid "
10819 "AND p.oid = '%u'::pg_catalog.oid",
10820 agginfo->aggfn.dobj.catId.oid);
10822 else if (fout->remoteVersion >= 70300)
10824 appendPQExpBuffer(query, "SELECT aggtransfn, "
10825 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10828 "'t'::boolean AS convertok "
10829 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10830 "WHERE a.aggfnoid = p.oid "
10831 "AND p.oid = '%u'::pg_catalog.oid",
10832 agginfo->aggfn.dobj.catId.oid);
10834 else if (fout->remoteVersion >= 70100)
10836 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10837 "format_type(aggtranstype, NULL) AS aggtranstype, "
10840 "'t'::boolean AS convertok "
10841 "FROM pg_aggregate "
10842 "WHERE oid = '%u'::oid",
10843 agginfo->aggfn.dobj.catId.oid);
10847 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10849 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10851 "agginitval1 AS agginitval, "
10852 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10853 "FROM pg_aggregate "
10854 "WHERE oid = '%u'::oid",
10855 agginfo->aggfn.dobj.catId.oid);
10858 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10860 i_aggtransfn = PQfnumber(res, "aggtransfn");
10861 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10862 i_aggsortop = PQfnumber(res, "aggsortop");
10863 i_aggtranstype = PQfnumber(res, "aggtranstype");
10864 i_agginitval = PQfnumber(res, "agginitval");
10865 i_convertok = PQfnumber(res, "convertok");
10867 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10868 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10869 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10870 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10871 agginitval = PQgetvalue(res, 0, i_agginitval);
10872 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10874 aggsig = format_aggregate_signature(agginfo, fout, true);
10875 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10879 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10884 if (fout->remoteVersion >= 70300)
10886 /* If using 7.3's regproc or regtype, data is already quoted */
10887 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10891 else if (fout->remoteVersion >= 70100)
10893 /* format_type quotes, regproc does not */
10894 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10900 /* need quotes all around */
10901 appendPQExpBuffer(details, " SFUNC = %s,\n",
10902 fmtId(aggtransfn));
10903 appendPQExpBuffer(details, " STYPE = %s",
10904 fmtId(aggtranstype));
10907 if (!PQgetisnull(res, 0, i_agginitval))
10909 appendPQExpBuffer(details, ",\n INITCOND = ");
10910 appendStringLiteralAH(details, agginitval, fout);
10913 if (strcmp(aggfinalfn, "-") != 0)
10915 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
10919 aggsortop = convertOperatorReference(fout, aggsortop);
10922 appendPQExpBuffer(details, ",\n SORTOP = %s",
10927 * DROP must be fully qualified in case same name appears in pg_catalog
10929 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10930 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10933 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10934 aggsig, details->data);
10936 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10938 if (binary_upgrade)
10939 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10941 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10943 agginfo->aggfn.dobj.namespace->dobj.name,
10945 agginfo->aggfn.rolname,
10946 false, "AGGREGATE", SECTION_PRE_DATA,
10947 q->data, delq->data, NULL,
10948 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10951 /* Dump Aggregate Comments */
10952 dumpComment(fout, labelq->data,
10953 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10954 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10955 dumpSecLabel(fout, labelq->data,
10956 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10957 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10960 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10961 * command look like a function's GRANT; in particular this affects the
10962 * syntax for zero-argument aggregates.
10967 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
10968 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
10970 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10972 aggsig, NULL, aggsig_tag,
10973 agginfo->aggfn.dobj.namespace->dobj.name,
10974 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
10981 destroyPQExpBuffer(query);
10982 destroyPQExpBuffer(q);
10983 destroyPQExpBuffer(delq);
10984 destroyPQExpBuffer(labelq);
10985 destroyPQExpBuffer(details);
10990 * write out a single text search parser
10993 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
10997 PQExpBuffer labelq;
10999 /* Skip if not to be dumped */
11000 if (!prsinfo->dobj.dump || dataOnly)
11003 q = createPQExpBuffer();
11004 delq = createPQExpBuffer();
11005 labelq = createPQExpBuffer();
11007 /* Make sure we are in proper schema */
11008 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11010 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11011 fmtId(prsinfo->dobj.name));
11013 appendPQExpBuffer(q, " START = %s,\n",
11014 convertTSFunction(fout, prsinfo->prsstart));
11015 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11016 convertTSFunction(fout, prsinfo->prstoken));
11017 appendPQExpBuffer(q, " END = %s,\n",
11018 convertTSFunction(fout, prsinfo->prsend));
11019 if (prsinfo->prsheadline != InvalidOid)
11020 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11021 convertTSFunction(fout, prsinfo->prsheadline));
11022 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11023 convertTSFunction(fout, prsinfo->prslextype));
11026 * DROP must be fully qualified in case same name appears in pg_catalog
11028 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11029 fmtId(prsinfo->dobj.namespace->dobj.name));
11030 appendPQExpBuffer(delq, ".%s;\n",
11031 fmtId(prsinfo->dobj.name));
11033 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11034 fmtId(prsinfo->dobj.name));
11036 if (binary_upgrade)
11037 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11039 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11040 prsinfo->dobj.name,
11041 prsinfo->dobj.namespace->dobj.name,
11044 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11045 q->data, delq->data, NULL,
11046 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11049 /* Dump Parser Comments */
11050 dumpComment(fout, labelq->data,
11052 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11054 destroyPQExpBuffer(q);
11055 destroyPQExpBuffer(delq);
11056 destroyPQExpBuffer(labelq);
11061 * write out a single text search dictionary
11064 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11068 PQExpBuffer labelq;
11074 /* Skip if not to be dumped */
11075 if (!dictinfo->dobj.dump || dataOnly)
11078 q = createPQExpBuffer();
11079 delq = createPQExpBuffer();
11080 labelq = createPQExpBuffer();
11081 query = createPQExpBuffer();
11083 /* Fetch name and namespace of the dictionary's template */
11084 selectSourceSchema(fout, "pg_catalog");
11085 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11086 "FROM pg_ts_template p, pg_namespace n "
11087 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11088 dictinfo->dicttemplate);
11089 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11090 nspname = PQgetvalue(res, 0, 0);
11091 tmplname = PQgetvalue(res, 0, 1);
11093 /* Make sure we are in proper schema */
11094 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11096 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11097 fmtId(dictinfo->dobj.name));
11099 appendPQExpBuffer(q, " TEMPLATE = ");
11100 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11101 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11102 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11106 /* the dictinitoption can be dumped straight into the command */
11107 if (dictinfo->dictinitoption)
11108 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11110 appendPQExpBuffer(q, " );\n");
11113 * DROP must be fully qualified in case same name appears in pg_catalog
11115 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11116 fmtId(dictinfo->dobj.namespace->dobj.name));
11117 appendPQExpBuffer(delq, ".%s;\n",
11118 fmtId(dictinfo->dobj.name));
11120 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11121 fmtId(dictinfo->dobj.name));
11123 if (binary_upgrade)
11124 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11126 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11127 dictinfo->dobj.name,
11128 dictinfo->dobj.namespace->dobj.name,
11131 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11132 q->data, delq->data, NULL,
11133 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11136 /* Dump Dictionary Comments */
11137 dumpComment(fout, labelq->data,
11138 NULL, dictinfo->rolname,
11139 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11141 destroyPQExpBuffer(q);
11142 destroyPQExpBuffer(delq);
11143 destroyPQExpBuffer(labelq);
11144 destroyPQExpBuffer(query);
11149 * write out a single text search template
11152 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11156 PQExpBuffer labelq;
11158 /* Skip if not to be dumped */
11159 if (!tmplinfo->dobj.dump || dataOnly)
11162 q = createPQExpBuffer();
11163 delq = createPQExpBuffer();
11164 labelq = createPQExpBuffer();
11166 /* Make sure we are in proper schema */
11167 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11169 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11170 fmtId(tmplinfo->dobj.name));
11172 if (tmplinfo->tmplinit != InvalidOid)
11173 appendPQExpBuffer(q, " INIT = %s,\n",
11174 convertTSFunction(fout, tmplinfo->tmplinit));
11175 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11176 convertTSFunction(fout, tmplinfo->tmpllexize));
11179 * DROP must be fully qualified in case same name appears in pg_catalog
11181 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11182 fmtId(tmplinfo->dobj.namespace->dobj.name));
11183 appendPQExpBuffer(delq, ".%s;\n",
11184 fmtId(tmplinfo->dobj.name));
11186 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11187 fmtId(tmplinfo->dobj.name));
11189 if (binary_upgrade)
11190 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11192 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11193 tmplinfo->dobj.name,
11194 tmplinfo->dobj.namespace->dobj.name,
11197 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11198 q->data, delq->data, NULL,
11199 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11202 /* Dump Template Comments */
11203 dumpComment(fout, labelq->data,
11205 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11207 destroyPQExpBuffer(q);
11208 destroyPQExpBuffer(delq);
11209 destroyPQExpBuffer(labelq);
11214 * write out a single text search configuration
11217 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11221 PQExpBuffer labelq;
11231 /* Skip if not to be dumped */
11232 if (!cfginfo->dobj.dump || dataOnly)
11235 q = createPQExpBuffer();
11236 delq = createPQExpBuffer();
11237 labelq = createPQExpBuffer();
11238 query = createPQExpBuffer();
11240 /* Fetch name and namespace of the config's parser */
11241 selectSourceSchema(fout, "pg_catalog");
11242 appendPQExpBuffer(query, "SELECT nspname, prsname "
11243 "FROM pg_ts_parser p, pg_namespace n "
11244 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11245 cfginfo->cfgparser);
11246 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11247 nspname = PQgetvalue(res, 0, 0);
11248 prsname = PQgetvalue(res, 0, 1);
11250 /* Make sure we are in proper schema */
11251 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11253 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11254 fmtId(cfginfo->dobj.name));
11256 appendPQExpBuffer(q, " PARSER = ");
11257 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11258 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11259 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11263 resetPQExpBuffer(query);
11264 appendPQExpBuffer(query,
11266 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11267 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11268 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11269 "FROM pg_catalog.pg_ts_config_map AS m \n"
11270 "WHERE m.mapcfg = '%u' \n"
11271 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11272 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11274 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11275 ntups = PQntuples(res);
11277 i_tokenname = PQfnumber(res, "tokenname");
11278 i_dictname = PQfnumber(res, "dictname");
11280 for (i = 0; i < ntups; i++)
11282 char *tokenname = PQgetvalue(res, i, i_tokenname);
11283 char *dictname = PQgetvalue(res, i, i_dictname);
11286 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11288 /* starting a new token type, so start a new command */
11290 appendPQExpBuffer(q, ";\n");
11291 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11292 fmtId(cfginfo->dobj.name));
11293 /* tokenname needs quoting, dictname does NOT */
11294 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11295 fmtId(tokenname), dictname);
11298 appendPQExpBuffer(q, ", %s", dictname);
11302 appendPQExpBuffer(q, ";\n");
11307 * DROP must be fully qualified in case same name appears in pg_catalog
11309 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11310 fmtId(cfginfo->dobj.namespace->dobj.name));
11311 appendPQExpBuffer(delq, ".%s;\n",
11312 fmtId(cfginfo->dobj.name));
11314 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11315 fmtId(cfginfo->dobj.name));
11317 if (binary_upgrade)
11318 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11320 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11321 cfginfo->dobj.name,
11322 cfginfo->dobj.namespace->dobj.name,
11325 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11326 q->data, delq->data, NULL,
11327 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11330 /* Dump Configuration Comments */
11331 dumpComment(fout, labelq->data,
11332 NULL, cfginfo->rolname,
11333 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11335 destroyPQExpBuffer(q);
11336 destroyPQExpBuffer(delq);
11337 destroyPQExpBuffer(labelq);
11338 destroyPQExpBuffer(query);
11342 * dumpForeignDataWrapper
11343 * write out a single foreign-data wrapper definition
11346 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11350 PQExpBuffer labelq;
11353 /* Skip if not to be dumped */
11354 if (!fdwinfo->dobj.dump || dataOnly)
11358 * FDWs that belong to an extension are dumped based on their "dump"
11359 * field. Otherwise omit them if we are only dumping some specific object.
11361 if (!fdwinfo->dobj.ext_member)
11362 if (!include_everything)
11365 q = createPQExpBuffer();
11366 delq = createPQExpBuffer();
11367 labelq = createPQExpBuffer();
11369 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11371 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11374 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11375 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11377 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11378 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11380 if (strlen(fdwinfo->fdwoptions) > 0)
11381 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11383 appendPQExpBuffer(q, ";\n");
11385 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11388 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11391 if (binary_upgrade)
11392 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11394 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11395 fdwinfo->dobj.name,
11399 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11400 q->data, delq->data, NULL,
11401 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11404 /* Handle the ACL */
11405 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11406 "FOREIGN DATA WRAPPER",
11407 qfdwname, NULL, fdwinfo->dobj.name,
11408 NULL, fdwinfo->rolname,
11411 /* Dump Foreign Data Wrapper Comments */
11412 dumpComment(fout, labelq->data,
11413 NULL, fdwinfo->rolname,
11414 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11418 destroyPQExpBuffer(q);
11419 destroyPQExpBuffer(delq);
11420 destroyPQExpBuffer(labelq);
11424 * dumpForeignServer
11425 * write out a foreign server definition
11428 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11432 PQExpBuffer labelq;
11438 /* Skip if not to be dumped */
11439 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11442 q = createPQExpBuffer();
11443 delq = createPQExpBuffer();
11444 labelq = createPQExpBuffer();
11445 query = createPQExpBuffer();
11447 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11449 /* look up the foreign-data wrapper */
11450 selectSourceSchema(fout, "pg_catalog");
11451 appendPQExpBuffer(query, "SELECT fdwname "
11452 "FROM pg_foreign_data_wrapper w "
11453 "WHERE w.oid = '%u'",
11455 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11456 fdwname = PQgetvalue(res, 0, 0);
11458 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11459 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11461 appendPQExpBuffer(q, " TYPE ");
11462 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11464 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11466 appendPQExpBuffer(q, " VERSION ");
11467 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11470 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11471 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11473 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11474 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11476 appendPQExpBuffer(q, ";\n");
11478 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11481 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11483 if (binary_upgrade)
11484 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11486 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11487 srvinfo->dobj.name,
11491 false, "SERVER", SECTION_PRE_DATA,
11492 q->data, delq->data, NULL,
11493 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11496 /* Handle the ACL */
11497 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11499 qsrvname, NULL, srvinfo->dobj.name,
11500 NULL, srvinfo->rolname,
11503 /* Dump user mappings */
11504 dumpUserMappings(fout,
11505 srvinfo->dobj.name, NULL,
11507 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11509 /* Dump Foreign Server Comments */
11510 dumpComment(fout, labelq->data,
11511 NULL, srvinfo->rolname,
11512 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11516 destroyPQExpBuffer(q);
11517 destroyPQExpBuffer(delq);
11518 destroyPQExpBuffer(labelq);
11524 * This routine is used to dump any user mappings associated with the
11525 * server handed to this routine. Should be called after ArchiveEntry()
11529 dumpUserMappings(Archive *fout,
11530 const char *servername, const char *namespace,
11532 CatalogId catalogId, DumpId dumpId)
11544 q = createPQExpBuffer();
11545 tag = createPQExpBuffer();
11546 delq = createPQExpBuffer();
11547 query = createPQExpBuffer();
11550 * We read from the publicly accessible view pg_user_mappings, so as not
11551 * to fail if run by a non-superuser. Note that the view will show
11552 * umoptions as null if the user hasn't got privileges for the associated
11553 * server; this means that pg_dump will dump such a mapping, but with no
11554 * OPTIONS clause. A possible alternative is to skip such mappings
11555 * altogether, but it's not clear that that's an improvement.
11557 selectSourceSchema(fout, "pg_catalog");
11559 appendPQExpBuffer(query,
11561 "array_to_string(ARRAY("
11562 "SELECT quote_ident(option_name) || ' ' || "
11563 "quote_literal(option_value) "
11564 "FROM pg_options_to_table(umoptions) "
11565 "ORDER BY option_name"
11566 "), E',\n ') AS umoptions "
11567 "FROM pg_user_mappings "
11568 "WHERE srvid = '%u' "
11569 "ORDER BY usename",
11572 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11574 ntups = PQntuples(res);
11575 i_usename = PQfnumber(res, "usename");
11576 i_umoptions = PQfnumber(res, "umoptions");
11578 for (i = 0; i < ntups; i++)
11583 usename = PQgetvalue(res, i, i_usename);
11584 umoptions = PQgetvalue(res, i, i_umoptions);
11586 resetPQExpBuffer(q);
11587 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11588 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11590 if (umoptions && strlen(umoptions) > 0)
11591 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11593 appendPQExpBuffer(q, ";\n");
11595 resetPQExpBuffer(delq);
11596 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11597 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11599 resetPQExpBuffer(tag);
11600 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11601 usename, servername);
11603 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11608 "USER MAPPING", SECTION_PRE_DATA,
11609 q->data, delq->data, NULL,
11616 destroyPQExpBuffer(query);
11617 destroyPQExpBuffer(delq);
11618 destroyPQExpBuffer(q);
11622 * Write out default privileges information
11625 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11631 /* Skip if not to be dumped */
11632 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11635 q = createPQExpBuffer();
11636 tag = createPQExpBuffer();
11638 switch (daclinfo->defaclobjtype)
11640 case DEFACLOBJ_RELATION:
11643 case DEFACLOBJ_SEQUENCE:
11644 type = "SEQUENCES";
11646 case DEFACLOBJ_FUNCTION:
11647 type = "FUNCTIONS";
11650 /* shouldn't get here */
11651 exit_horribly(NULL,
11652 "unknown object type (%d) in default privileges\n",
11653 (int) daclinfo->defaclobjtype);
11654 type = ""; /* keep compiler quiet */
11657 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11659 /* build the actual command(s) for this tuple */
11660 if (!buildDefaultACLCommands(type,
11661 daclinfo->dobj.namespace != NULL ?
11662 daclinfo->dobj.namespace->dobj.name : NULL,
11663 daclinfo->defaclacl,
11664 daclinfo->defaclrole,
11665 fout->remoteVersion,
11667 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11668 daclinfo->defaclacl);
11670 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11672 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11674 daclinfo->defaclrole,
11675 false, "DEFAULT ACL", SECTION_NONE,
11677 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11680 destroyPQExpBuffer(tag);
11681 destroyPQExpBuffer(q);
11685 * Write out grant/revoke information
11687 * 'objCatId' is the catalog ID of the underlying object.
11688 * 'objDumpId' is the dump ID of the underlying object.
11689 * 'type' must be one of
11690 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11691 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11692 * 'name' is the formatted name of the object. Must be quoted etc. already.
11693 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11694 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11695 * 'nspname' is the namespace the object is in (NULL if none).
11696 * 'owner' is the owner, NULL if there is no owner (for languages).
11697 * 'acls' is the string read out of the fooacl system catalog field;
11698 * it will be parsed here.
11702 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11703 const char *type, const char *name, const char *subname,
11704 const char *tag, const char *nspname, const char *owner,
11709 /* Do nothing if ACL dump is not enabled */
11713 /* --data-only skips ACLs *except* BLOB ACLs */
11714 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11717 sql = createPQExpBuffer();
11719 if (!buildACLCommands(name, subname, type, acls, owner,
11720 "", fout->remoteVersion, sql))
11721 exit_horribly(NULL,
11722 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11726 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11729 owner ? owner : "",
11730 false, "ACL", SECTION_NONE,
11731 sql->data, "", NULL,
11735 destroyPQExpBuffer(sql);
11741 * This routine is used to dump any security labels associated with the
11742 * object handed to this routine. The routine takes a constant character
11743 * string for the target part of the security-label command, plus
11744 * the namespace and owner of the object (for labeling the ArchiveEntry),
11745 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11746 * plus the dump ID for the object (for setting a dependency).
11747 * If a matching pg_seclabel entry is found, it is dumped.
11749 * Note: although this routine takes a dumpId for dependency purposes,
11750 * that purpose is just to mark the dependency in the emitted dump file
11751 * for possible future use by pg_restore. We do NOT use it for determining
11752 * ordering of the label in the dump file, because this routine is called
11753 * after dependency sorting occurs. This routine should be called just after
11754 * calling ArchiveEntry() for the specified object.
11757 dumpSecLabel(Archive *fout, const char *target,
11758 const char *namespace, const char *owner,
11759 CatalogId catalogId, int subid, DumpId dumpId)
11761 SecLabelItem *labels;
11766 /* do nothing, if --no-security-labels is supplied */
11767 if (no_security_labels)
11770 /* Comments are schema not data ... except blob comments are data */
11771 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11782 /* Search for security labels associated with catalogId, using table */
11783 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11785 query = createPQExpBuffer();
11787 for (i = 0; i < nlabels; i++)
11790 * Ignore label entries for which the subid doesn't match.
11792 if (labels[i].objsubid != subid)
11795 appendPQExpBuffer(query,
11796 "SECURITY LABEL FOR %s ON %s IS ",
11797 fmtId(labels[i].provider), target);
11798 appendStringLiteralAH(query, labels[i].label, fout);
11799 appendPQExpBuffer(query, ";\n");
11802 if (query->len > 0)
11804 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11805 target, namespace, NULL, owner,
11806 false, "SECURITY LABEL", SECTION_NONE,
11807 query->data, "", NULL,
11811 destroyPQExpBuffer(query);
11815 * dumpTableSecLabel
11817 * As above, but dump security label for both the specified table (or view)
11821 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11823 SecLabelItem *labels;
11827 PQExpBuffer target;
11829 /* do nothing, if --no-security-labels is supplied */
11830 if (no_security_labels)
11833 /* SecLabel are SCHEMA not data */
11837 /* Search for comments associated with relation, using table */
11838 nlabels = findSecLabels(fout,
11839 tbinfo->dobj.catId.tableoid,
11840 tbinfo->dobj.catId.oid,
11843 /* If security labels exist, build SECURITY LABEL statements */
11847 query = createPQExpBuffer();
11848 target = createPQExpBuffer();
11850 for (i = 0; i < nlabels; i++)
11852 const char *colname;
11853 const char *provider = labels[i].provider;
11854 const char *label = labels[i].label;
11855 int objsubid = labels[i].objsubid;
11857 resetPQExpBuffer(target);
11860 appendPQExpBuffer(target, "%s %s", reltypename,
11861 fmtId(tbinfo->dobj.name));
11865 colname = getAttrName(objsubid, tbinfo);
11866 /* first fmtId result must be consumed before calling it again */
11867 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11868 appendPQExpBuffer(target, ".%s", fmtId(colname));
11870 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11871 fmtId(provider), target->data);
11872 appendStringLiteralAH(query, label, fout);
11873 appendPQExpBuffer(query, ";\n");
11875 if (query->len > 0)
11877 resetPQExpBuffer(target);
11878 appendPQExpBuffer(target, "%s %s", reltypename,
11879 fmtId(tbinfo->dobj.name));
11880 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11882 tbinfo->dobj.namespace->dobj.name,
11883 NULL, tbinfo->rolname,
11884 false, "SECURITY LABEL", SECTION_NONE,
11885 query->data, "", NULL,
11886 &(tbinfo->dobj.dumpId), 1,
11889 destroyPQExpBuffer(query);
11890 destroyPQExpBuffer(target);
11896 * Find the security label(s), if any, associated with the given object.
11897 * All the objsubid values associated with the given classoid/objoid are
11898 * found with one search.
11901 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11903 /* static storage for table of security labels */
11904 static SecLabelItem *labels = NULL;
11905 static int nlabels = -1;
11907 SecLabelItem *middle = NULL;
11909 SecLabelItem *high;
11912 /* Get security labels if we didn't already */
11914 nlabels = collectSecLabels(fout, &labels);
11916 if (nlabels <= 0) /* no labels, so no match is possible */
11923 * Do binary search to find some item matching the object.
11926 high = &labels[nlabels - 1];
11927 while (low <= high)
11929 middle = low + (high - low) / 2;
11931 if (classoid < middle->classoid)
11933 else if (classoid > middle->classoid)
11935 else if (objoid < middle->objoid)
11937 else if (objoid > middle->objoid)
11940 break; /* found a match */
11943 if (low > high) /* no matches */
11950 * Now determine how many items match the object. The search loop
11951 * invariant still holds: only items between low and high inclusive could
11955 while (middle > low)
11957 if (classoid != middle[-1].classoid ||
11958 objoid != middle[-1].objoid)
11967 while (middle <= high)
11969 if (classoid != middle->classoid ||
11970 objoid != middle->objoid)
11982 * Construct a table of all security labels available for database objects.
11983 * It's much faster to pull them all at once.
11985 * The table is sorted by classoid/objid/objsubid for speed in lookup.
11988 collectSecLabels(Archive *fout, SecLabelItem **items)
11999 SecLabelItem *labels;
12001 query = createPQExpBuffer();
12003 appendPQExpBuffer(query,
12004 "SELECT label, provider, classoid, objoid, objsubid "
12005 "FROM pg_catalog.pg_seclabel "
12006 "ORDER BY classoid, objoid, objsubid");
12008 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12010 /* Construct lookup table containing OIDs in numeric form */
12011 i_label = PQfnumber(res, "label");
12012 i_provider = PQfnumber(res, "provider");
12013 i_classoid = PQfnumber(res, "classoid");
12014 i_objoid = PQfnumber(res, "objoid");
12015 i_objsubid = PQfnumber(res, "objsubid");
12017 ntups = PQntuples(res);
12019 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12021 for (i = 0; i < ntups; i++)
12023 labels[i].label = PQgetvalue(res, i, i_label);
12024 labels[i].provider = PQgetvalue(res, i, i_provider);
12025 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12026 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12027 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12030 /* Do NOT free the PGresult since we are keeping pointers into it */
12031 destroyPQExpBuffer(query);
12039 * write out to fout the declarations (not data) of a user-defined table
12042 dumpTable(Archive *fout, TableInfo *tbinfo)
12044 if (tbinfo->dobj.dump)
12048 if (tbinfo->relkind == RELKIND_SEQUENCE)
12049 dumpSequence(fout, tbinfo);
12050 else if (!dataOnly)
12051 dumpTableSchema(fout, tbinfo);
12053 /* Handle the ACL here */
12054 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12055 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12056 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12058 namecopy, NULL, tbinfo->dobj.name,
12059 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12063 * Handle column ACLs, if any. Note: we pull these with a separate
12064 * query rather than trying to fetch them during getTableAttrs, so
12065 * that we won't miss ACLs on system columns.
12067 if (fout->remoteVersion >= 80400)
12069 PQExpBuffer query = createPQExpBuffer();
12073 appendPQExpBuffer(query,
12074 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12075 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12077 tbinfo->dobj.catId.oid);
12078 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12080 for (i = 0; i < PQntuples(res); i++)
12082 char *attname = PQgetvalue(res, i, 0);
12083 char *attacl = PQgetvalue(res, i, 1);
12087 attnamecopy = pg_strdup(fmtId(attname));
12088 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12089 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12090 /* Column's GRANT type is always TABLE */
12091 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12092 namecopy, attnamecopy, acltag,
12093 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12099 destroyPQExpBuffer(query);
12108 * write the declaration (not data) of one user-defined table or view
12111 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12113 PQExpBuffer query = createPQExpBuffer();
12114 PQExpBuffer q = createPQExpBuffer();
12115 PQExpBuffer delq = createPQExpBuffer();
12116 PQExpBuffer labelq = createPQExpBuffer();
12119 TableInfo **parents;
12120 int actual_atts; /* number of attrs in this CREATE statement */
12121 const char *reltypename;
12128 /* Make sure we are in proper schema */
12129 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12131 if (binary_upgrade)
12132 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12133 tbinfo->dobj.catId.oid);
12135 /* Is it a table or a view? */
12136 if (tbinfo->relkind == RELKIND_VIEW)
12140 reltypename = "VIEW";
12142 /* Fetch the view definition */
12143 if (fout->remoteVersion >= 70300)
12145 /* Beginning in 7.3, viewname is not unique; rely on OID */
12146 appendPQExpBuffer(query,
12147 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12148 tbinfo->dobj.catId.oid);
12152 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12153 "FROM pg_views WHERE viewname = ");
12154 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12155 appendPQExpBuffer(query, ";");
12158 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12160 if (PQntuples(res) != 1)
12162 if (PQntuples(res) < 1)
12163 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12164 tbinfo->dobj.name);
12166 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12167 tbinfo->dobj.name);
12170 viewdef = PQgetvalue(res, 0, 0);
12172 if (strlen(viewdef) == 0)
12173 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12174 tbinfo->dobj.name);
12177 * DROP must be fully qualified in case same name appears in
12180 appendPQExpBuffer(delq, "DROP VIEW %s.",
12181 fmtId(tbinfo->dobj.namespace->dobj.name));
12182 appendPQExpBuffer(delq, "%s;\n",
12183 fmtId(tbinfo->dobj.name));
12185 if (binary_upgrade)
12186 binary_upgrade_set_pg_class_oids(fout, q,
12187 tbinfo->dobj.catId.oid, false);
12189 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12190 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12191 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12192 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12194 appendPQExpBuffer(labelq, "VIEW %s",
12195 fmtId(tbinfo->dobj.name));
12201 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12206 reltypename = "FOREIGN TABLE";
12208 /* retrieve name of foreign server and generic options */
12209 appendPQExpBuffer(query,
12210 "SELECT fs.srvname, "
12211 "pg_catalog.array_to_string(ARRAY("
12212 "SELECT pg_catalog.quote_ident(option_name) || "
12213 "' ' || pg_catalog.quote_literal(option_value) "
12214 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12215 "ORDER BY option_name"
12216 "), E',\n ') AS ftoptions "
12217 "FROM pg_catalog.pg_foreign_table ft "
12218 "JOIN pg_catalog.pg_foreign_server fs "
12219 "ON (fs.oid = ft.ftserver) "
12220 "WHERE ft.ftrelid = '%u'",
12221 tbinfo->dobj.catId.oid);
12222 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12223 i_srvname = PQfnumber(res, "srvname");
12224 i_ftoptions = PQfnumber(res, "ftoptions");
12225 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12226 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12231 reltypename = "TABLE";
12235 numParents = tbinfo->numParents;
12236 parents = tbinfo->parents;
12239 * DROP must be fully qualified in case same name appears in
12242 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12243 fmtId(tbinfo->dobj.namespace->dobj.name));
12244 appendPQExpBuffer(delq, "%s;\n",
12245 fmtId(tbinfo->dobj.name));
12247 appendPQExpBuffer(labelq, "%s %s", reltypename,
12248 fmtId(tbinfo->dobj.name));
12250 if (binary_upgrade)
12251 binary_upgrade_set_pg_class_oids(fout, q,
12252 tbinfo->dobj.catId.oid, false);
12254 appendPQExpBuffer(q, "CREATE %s%s %s",
12255 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12258 fmtId(tbinfo->dobj.name));
12261 * Attach to type, if reloftype; except in case of a binary upgrade,
12262 * we dump the table normally and attach it to the type afterward.
12264 if (tbinfo->reloftype && !binary_upgrade)
12265 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12267 /* Dump the attributes */
12269 for (j = 0; j < tbinfo->numatts; j++)
12272 * Normally, dump if it's locally defined in this table, and not
12273 * dropped. But for binary upgrade, we'll dump all the columns,
12274 * and then fix up the dropped and nonlocal cases below.
12276 if (shouldPrintColumn(tbinfo, j))
12279 * Default value --- suppress if to be printed separately.
12281 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12282 !tbinfo->attrdefs[j]->separate);
12285 * Not Null constraint --- suppress if inherited, except in
12286 * binary-upgrade case where that won't work.
12288 bool has_notnull = (tbinfo->notnull[j] &&
12289 (!tbinfo->inhNotNull[j] ||
12292 /* Skip column if fully defined by reloftype */
12293 if (tbinfo->reloftype &&
12294 !has_default && !has_notnull && !binary_upgrade)
12297 /* Format properly if not first attr */
12298 if (actual_atts == 0)
12299 appendPQExpBuffer(q, " (");
12301 appendPQExpBuffer(q, ",");
12302 appendPQExpBuffer(q, "\n ");
12305 /* Attribute name */
12306 appendPQExpBuffer(q, "%s ",
12307 fmtId(tbinfo->attnames[j]));
12309 if (tbinfo->attisdropped[j])
12312 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12313 * so we will not have gotten a valid type name; insert
12314 * INTEGER as a stopgap. We'll clean things up later.
12316 appendPQExpBuffer(q, "INTEGER /* dummy */");
12317 /* Skip all the rest, too */
12321 /* Attribute type */
12322 if (tbinfo->reloftype && !binary_upgrade)
12324 appendPQExpBuffer(q, "WITH OPTIONS");
12326 else if (fout->remoteVersion >= 70100)
12328 appendPQExpBuffer(q, "%s",
12329 tbinfo->atttypnames[j]);
12333 /* If no format_type, fake it */
12334 appendPQExpBuffer(q, "%s",
12335 myFormatType(tbinfo->atttypnames[j],
12336 tbinfo->atttypmod[j]));
12339 /* Add collation if not default for the type */
12340 if (OidIsValid(tbinfo->attcollation[j]))
12344 coll = findCollationByOid(tbinfo->attcollation[j]);
12347 /* always schema-qualify, don't try to be smart */
12348 appendPQExpBuffer(q, " COLLATE %s.",
12349 fmtId(coll->dobj.namespace->dobj.name));
12350 appendPQExpBuffer(q, "%s",
12351 fmtId(coll->dobj.name));
12356 appendPQExpBuffer(q, " DEFAULT %s",
12357 tbinfo->attrdefs[j]->adef_expr);
12360 appendPQExpBuffer(q, " NOT NULL");
12365 * Add non-inherited CHECK constraints, if any.
12367 for (j = 0; j < tbinfo->ncheck; j++)
12369 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12371 if (constr->separate || !constr->conislocal)
12374 if (actual_atts == 0)
12375 appendPQExpBuffer(q, " (\n ");
12377 appendPQExpBuffer(q, ",\n ");
12379 appendPQExpBuffer(q, "CONSTRAINT %s ",
12380 fmtId(constr->dobj.name));
12381 appendPQExpBuffer(q, "%s", constr->condef);
12387 appendPQExpBuffer(q, "\n)");
12388 else if (!(tbinfo->reloftype && !binary_upgrade))
12391 * We must have a parenthesized attribute list, even though empty,
12392 * when not using the OF TYPE syntax.
12394 appendPQExpBuffer(q, " (\n)");
12397 if (numParents > 0 && !binary_upgrade)
12399 appendPQExpBuffer(q, "\nINHERITS (");
12400 for (k = 0; k < numParents; k++)
12402 TableInfo *parentRel = parents[k];
12405 appendPQExpBuffer(q, ", ");
12406 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12407 appendPQExpBuffer(q, "%s.",
12408 fmtId(parentRel->dobj.namespace->dobj.name));
12409 appendPQExpBuffer(q, "%s",
12410 fmtId(parentRel->dobj.name));
12412 appendPQExpBuffer(q, ")");
12415 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12416 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12418 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12419 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12421 bool addcomma = false;
12423 appendPQExpBuffer(q, "\nWITH (");
12424 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12427 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12429 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12431 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12432 tbinfo->toast_reloptions);
12434 appendPQExpBuffer(q, ")");
12437 /* Dump generic options if any */
12438 if (ftoptions && ftoptions[0])
12439 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12441 appendPQExpBuffer(q, ";\n");
12444 * To create binary-compatible heap files, we have to ensure the same
12445 * physical column order, including dropped columns, as in the
12446 * original. Therefore, we create dropped columns above and drop them
12447 * here, also updating their attlen/attalign values so that the
12448 * dropped column can be skipped properly. (We do not bother with
12449 * restoring the original attbyval setting.) Also, inheritance
12450 * relationships are set up by doing ALTER INHERIT rather than using
12451 * an INHERITS clause --- the latter would possibly mess up the column
12452 * order. That also means we have to take care about setting
12453 * attislocal correctly, plus fix up any inherited CHECK constraints.
12454 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12456 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12458 for (j = 0; j < tbinfo->numatts; j++)
12460 if (tbinfo->attisdropped[j])
12462 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12463 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12464 "SET attlen = %d, "
12465 "attalign = '%c', attbyval = false\n"
12466 "WHERE attname = ",
12468 tbinfo->attalign[j]);
12469 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12470 appendPQExpBuffer(q, "\n AND attrelid = ");
12471 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12472 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12474 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12475 fmtId(tbinfo->dobj.name));
12476 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12477 fmtId(tbinfo->attnames[j]));
12479 else if (!tbinfo->attislocal[j])
12481 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12482 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12483 "SET attislocal = false\n"
12484 "WHERE attname = ");
12485 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12486 appendPQExpBuffer(q, "\n AND attrelid = ");
12487 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12488 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12492 for (k = 0; k < tbinfo->ncheck; k++)
12494 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12496 if (constr->separate || constr->conislocal)
12499 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12500 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12501 fmtId(tbinfo->dobj.name));
12502 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12503 fmtId(constr->dobj.name));
12504 appendPQExpBuffer(q, "%s;\n", constr->condef);
12505 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12506 "SET conislocal = false\n"
12507 "WHERE contype = 'c' AND conname = ");
12508 appendStringLiteralAH(q, constr->dobj.name, fout);
12509 appendPQExpBuffer(q, "\n AND conrelid = ");
12510 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12511 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12514 if (numParents > 0)
12516 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12517 for (k = 0; k < numParents; k++)
12519 TableInfo *parentRel = parents[k];
12521 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12522 fmtId(tbinfo->dobj.name));
12523 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12524 appendPQExpBuffer(q, "%s.",
12525 fmtId(parentRel->dobj.namespace->dobj.name));
12526 appendPQExpBuffer(q, "%s;\n",
12527 fmtId(parentRel->dobj.name));
12531 if (tbinfo->reloftype)
12533 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12534 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12535 fmtId(tbinfo->dobj.name),
12536 tbinfo->reloftype);
12539 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12540 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12541 "SET relfrozenxid = '%u'\n"
12543 tbinfo->frozenxid);
12544 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12545 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12547 if (tbinfo->toast_oid)
12549 /* We preserve the toast oids, so we can use it during restore */
12550 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12551 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12552 "SET relfrozenxid = '%u'\n"
12553 "WHERE oid = '%u';\n",
12554 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12559 * Dump additional per-column properties that we can't handle in the
12560 * main CREATE TABLE command.
12562 for (j = 0; j < tbinfo->numatts; j++)
12564 /* None of this applies to dropped columns */
12565 if (tbinfo->attisdropped[j])
12569 * If we didn't dump the column definition explicitly above, and
12570 * it is NOT NULL and did not inherit that property from a parent,
12571 * we have to mark it separately.
12573 if (!shouldPrintColumn(tbinfo, j) &&
12574 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12576 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12577 fmtId(tbinfo->dobj.name));
12578 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12579 fmtId(tbinfo->attnames[j]));
12583 * Dump per-column statistics information. We only issue an ALTER
12584 * TABLE statement if the attstattarget entry for this column is
12585 * non-negative (i.e. it's not the default value)
12587 if (tbinfo->attstattarget[j] >= 0)
12589 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12590 fmtId(tbinfo->dobj.name));
12591 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12592 fmtId(tbinfo->attnames[j]));
12593 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12594 tbinfo->attstattarget[j]);
12598 * Dump per-column storage information. The statement is only
12599 * dumped if the storage has been changed from the type's default.
12601 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12603 switch (tbinfo->attstorage[j])
12609 storage = "EXTERNAL";
12615 storage = "EXTENDED";
12622 * Only dump the statement if it's a storage type we recognize
12624 if (storage != NULL)
12626 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12627 fmtId(tbinfo->dobj.name));
12628 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12629 fmtId(tbinfo->attnames[j]));
12630 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12636 * Dump per-column attributes.
12638 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12640 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12641 fmtId(tbinfo->dobj.name));
12642 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12643 fmtId(tbinfo->attnames[j]));
12644 appendPQExpBuffer(q, "SET (%s);\n",
12645 tbinfo->attoptions[j]);
12649 * Dump per-column fdw options.
12651 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12652 tbinfo->attfdwoptions[j] &&
12653 tbinfo->attfdwoptions[j][0] != '\0')
12655 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12656 fmtId(tbinfo->dobj.name));
12657 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12658 fmtId(tbinfo->attnames[j]));
12659 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12660 tbinfo->attfdwoptions[j]);
12665 if (binary_upgrade)
12666 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12668 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12670 tbinfo->dobj.namespace->dobj.name,
12671 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12673 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12674 reltypename, SECTION_PRE_DATA,
12675 q->data, delq->data, NULL,
12676 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12680 /* Dump Table Comments */
12681 dumpTableComment(fout, tbinfo, reltypename);
12683 /* Dump Table Security Labels */
12684 dumpTableSecLabel(fout, tbinfo, reltypename);
12686 /* Dump comments on inlined table constraints */
12687 for (j = 0; j < tbinfo->ncheck; j++)
12689 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12691 if (constr->separate || !constr->conislocal)
12694 dumpTableConstraintComment(fout, constr);
12697 destroyPQExpBuffer(query);
12698 destroyPQExpBuffer(q);
12699 destroyPQExpBuffer(delq);
12700 destroyPQExpBuffer(labelq);
12704 * dumpAttrDef --- dump an attribute's default-value declaration
12707 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12709 TableInfo *tbinfo = adinfo->adtable;
12710 int adnum = adinfo->adnum;
12714 /* Skip if table definition not to be dumped */
12715 if (!tbinfo->dobj.dump || dataOnly)
12718 /* Skip if not "separate"; it was dumped in the table's definition */
12719 if (!adinfo->separate)
12722 q = createPQExpBuffer();
12723 delq = createPQExpBuffer();
12725 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12726 fmtId(tbinfo->dobj.name));
12727 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12728 fmtId(tbinfo->attnames[adnum - 1]),
12729 adinfo->adef_expr);
12732 * DROP must be fully qualified in case same name appears in pg_catalog
12734 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12735 fmtId(tbinfo->dobj.namespace->dobj.name));
12736 appendPQExpBuffer(delq, "%s ",
12737 fmtId(tbinfo->dobj.name));
12738 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12739 fmtId(tbinfo->attnames[adnum - 1]));
12741 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12742 tbinfo->attnames[adnum - 1],
12743 tbinfo->dobj.namespace->dobj.name,
12746 false, "DEFAULT", SECTION_PRE_DATA,
12747 q->data, delq->data, NULL,
12748 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12751 destroyPQExpBuffer(q);
12752 destroyPQExpBuffer(delq);
12756 * getAttrName: extract the correct name for an attribute
12758 * The array tblInfo->attnames[] only provides names of user attributes;
12759 * if a system attribute number is supplied, we have to fake it.
12760 * We also do a little bit of bounds checking for safety's sake.
12762 static const char *
12763 getAttrName(int attrnum, TableInfo *tblInfo)
12765 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12766 return tblInfo->attnames[attrnum - 1];
12769 case SelfItemPointerAttributeNumber:
12771 case ObjectIdAttributeNumber:
12773 case MinTransactionIdAttributeNumber:
12775 case MinCommandIdAttributeNumber:
12777 case MaxTransactionIdAttributeNumber:
12779 case MaxCommandIdAttributeNumber:
12781 case TableOidAttributeNumber:
12784 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12785 attrnum, tblInfo->dobj.name);
12786 return NULL; /* keep compiler quiet */
12791 * write out to fout a user-defined index
12794 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12796 TableInfo *tbinfo = indxinfo->indextable;
12799 PQExpBuffer labelq;
12804 q = createPQExpBuffer();
12805 delq = createPQExpBuffer();
12806 labelq = createPQExpBuffer();
12808 appendPQExpBuffer(labelq, "INDEX %s",
12809 fmtId(indxinfo->dobj.name));
12812 * If there's an associated constraint, don't dump the index per se, but
12813 * do dump any comment for it. (This is safe because dependency ordering
12814 * will have ensured the constraint is emitted first.)
12816 if (indxinfo->indexconstraint == 0)
12818 if (binary_upgrade)
12819 binary_upgrade_set_pg_class_oids(fout, q,
12820 indxinfo->dobj.catId.oid, true);
12822 /* Plain secondary index */
12823 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12825 /* If the index is clustered, we need to record that. */
12826 if (indxinfo->indisclustered)
12828 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12829 fmtId(tbinfo->dobj.name));
12830 appendPQExpBuffer(q, " ON %s;\n",
12831 fmtId(indxinfo->dobj.name));
12835 * DROP must be fully qualified in case same name appears in
12838 appendPQExpBuffer(delq, "DROP INDEX %s.",
12839 fmtId(tbinfo->dobj.namespace->dobj.name));
12840 appendPQExpBuffer(delq, "%s;\n",
12841 fmtId(indxinfo->dobj.name));
12843 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12844 indxinfo->dobj.name,
12845 tbinfo->dobj.namespace->dobj.name,
12846 indxinfo->tablespace,
12847 tbinfo->rolname, false,
12848 "INDEX", SECTION_POST_DATA,
12849 q->data, delq->data, NULL,
12850 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12854 /* Dump Index Comments */
12855 dumpComment(fout, labelq->data,
12856 tbinfo->dobj.namespace->dobj.name,
12858 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12860 destroyPQExpBuffer(q);
12861 destroyPQExpBuffer(delq);
12862 destroyPQExpBuffer(labelq);
12867 * write out to fout a user-defined constraint
12870 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12872 TableInfo *tbinfo = coninfo->contable;
12876 /* Skip if not to be dumped */
12877 if (!coninfo->dobj.dump || dataOnly)
12880 q = createPQExpBuffer();
12881 delq = createPQExpBuffer();
12883 if (coninfo->contype == 'p' ||
12884 coninfo->contype == 'u' ||
12885 coninfo->contype == 'x')
12887 /* Index-related constraint */
12888 IndxInfo *indxinfo;
12891 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12893 if (indxinfo == NULL)
12894 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12895 coninfo->dobj.name);
12897 if (binary_upgrade)
12898 binary_upgrade_set_pg_class_oids(fout, q,
12899 indxinfo->dobj.catId.oid, true);
12901 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12902 fmtId(tbinfo->dobj.name));
12903 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12904 fmtId(coninfo->dobj.name));
12906 if (coninfo->condef)
12908 /* pg_get_constraintdef should have provided everything */
12909 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12913 appendPQExpBuffer(q, "%s (",
12914 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12915 for (k = 0; k < indxinfo->indnkeys; k++)
12917 int indkey = (int) indxinfo->indkeys[k];
12918 const char *attname;
12920 if (indkey == InvalidAttrNumber)
12922 attname = getAttrName(indkey, tbinfo);
12924 appendPQExpBuffer(q, "%s%s",
12925 (k == 0) ? "" : ", ",
12929 appendPQExpBuffer(q, ")");
12931 if (indxinfo->options && strlen(indxinfo->options) > 0)
12932 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12934 if (coninfo->condeferrable)
12936 appendPQExpBuffer(q, " DEFERRABLE");
12937 if (coninfo->condeferred)
12938 appendPQExpBuffer(q, " INITIALLY DEFERRED");
12941 appendPQExpBuffer(q, ";\n");
12944 /* If the index is clustered, we need to record that. */
12945 if (indxinfo->indisclustered)
12947 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12948 fmtId(tbinfo->dobj.name));
12949 appendPQExpBuffer(q, " ON %s;\n",
12950 fmtId(indxinfo->dobj.name));
12954 * DROP must be fully qualified in case same name appears in
12957 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12958 fmtId(tbinfo->dobj.namespace->dobj.name));
12959 appendPQExpBuffer(delq, "%s ",
12960 fmtId(tbinfo->dobj.name));
12961 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12962 fmtId(coninfo->dobj.name));
12964 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
12965 coninfo->dobj.name,
12966 tbinfo->dobj.namespace->dobj.name,
12967 indxinfo->tablespace,
12968 tbinfo->rolname, false,
12969 "CONSTRAINT", SECTION_POST_DATA,
12970 q->data, delq->data, NULL,
12971 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
12974 else if (coninfo->contype == 'f')
12977 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
12978 * current table data is not processed
12980 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12981 fmtId(tbinfo->dobj.name));
12982 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
12983 fmtId(coninfo->dobj.name),
12987 * DROP must be fully qualified in case same name appears in
12990 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12991 fmtId(tbinfo->dobj.namespace->dobj.name));
12992 appendPQExpBuffer(delq, "%s ",
12993 fmtId(tbinfo->dobj.name));
12994 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12995 fmtId(coninfo->dobj.name));
12997 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
12998 coninfo->dobj.name,
12999 tbinfo->dobj.namespace->dobj.name,
13001 tbinfo->rolname, false,
13002 "FK CONSTRAINT", SECTION_POST_DATA,
13003 q->data, delq->data, NULL,
13004 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13007 else if (coninfo->contype == 'c' && tbinfo)
13009 /* CHECK constraint on a table */
13011 /* Ignore if not to be dumped separately */
13012 if (coninfo->separate)
13014 /* not ONLY since we want it to propagate to children */
13015 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13016 fmtId(tbinfo->dobj.name));
13017 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13018 fmtId(coninfo->dobj.name),
13022 * DROP must be fully qualified in case same name appears in
13025 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13026 fmtId(tbinfo->dobj.namespace->dobj.name));
13027 appendPQExpBuffer(delq, "%s ",
13028 fmtId(tbinfo->dobj.name));
13029 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13030 fmtId(coninfo->dobj.name));
13032 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13033 coninfo->dobj.name,
13034 tbinfo->dobj.namespace->dobj.name,
13036 tbinfo->rolname, false,
13037 "CHECK CONSTRAINT", SECTION_POST_DATA,
13038 q->data, delq->data, NULL,
13039 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13043 else if (coninfo->contype == 'c' && tbinfo == NULL)
13045 /* CHECK constraint on a domain */
13046 TypeInfo *tyinfo = coninfo->condomain;
13048 /* Ignore if not to be dumped separately */
13049 if (coninfo->separate)
13051 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13052 fmtId(tyinfo->dobj.name));
13053 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13054 fmtId(coninfo->dobj.name),
13058 * DROP must be fully qualified in case same name appears in
13061 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13062 fmtId(tyinfo->dobj.namespace->dobj.name));
13063 appendPQExpBuffer(delq, "%s ",
13064 fmtId(tyinfo->dobj.name));
13065 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13066 fmtId(coninfo->dobj.name));
13068 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13069 coninfo->dobj.name,
13070 tyinfo->dobj.namespace->dobj.name,
13072 tyinfo->rolname, false,
13073 "CHECK CONSTRAINT", SECTION_POST_DATA,
13074 q->data, delq->data, NULL,
13075 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13081 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13085 /* Dump Constraint Comments --- only works for table constraints */
13086 if (tbinfo && coninfo->separate)
13087 dumpTableConstraintComment(fout, coninfo);
13089 destroyPQExpBuffer(q);
13090 destroyPQExpBuffer(delq);
13094 * dumpTableConstraintComment --- dump a constraint's comment if any
13096 * This is split out because we need the function in two different places
13097 * depending on whether the constraint is dumped as part of CREATE TABLE
13098 * or as a separate ALTER command.
13101 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13103 TableInfo *tbinfo = coninfo->contable;
13104 PQExpBuffer labelq = createPQExpBuffer();
13106 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13107 fmtId(coninfo->dobj.name));
13108 appendPQExpBuffer(labelq, "ON %s",
13109 fmtId(tbinfo->dobj.name));
13110 dumpComment(fout, labelq->data,
13111 tbinfo->dobj.namespace->dobj.name,
13113 coninfo->dobj.catId, 0,
13114 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13116 destroyPQExpBuffer(labelq);
13120 * findLastBuiltInOid -
13121 * find the last built in oid
13123 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13124 * pg_database entry for the current database
13127 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13131 PQExpBuffer query = createPQExpBuffer();
13133 resetPQExpBuffer(query);
13134 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13135 appendStringLiteralAH(query, dbname, fout);
13137 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13138 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13140 destroyPQExpBuffer(query);
13145 * findLastBuiltInOid -
13146 * find the last built in oid
13148 * For 7.0, we do this by assuming that the last thing that initdb does is to
13149 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13150 * initdb won't be changing anymore, it'll do.
13153 findLastBuiltinOid_V70(Archive *fout)
13158 res = ExecuteSqlQueryForSingleRow(fout,
13159 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13160 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13166 dumpSequence(Archive *fout, TableInfo *tbinfo)
13179 PQExpBuffer query = createPQExpBuffer();
13180 PQExpBuffer delqry = createPQExpBuffer();
13181 PQExpBuffer labelq = createPQExpBuffer();
13183 /* Make sure we are in proper schema */
13184 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13186 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13187 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13189 if (fout->remoteVersion >= 80400)
13191 appendPQExpBuffer(query,
13192 "SELECT sequence_name, "
13193 "start_value, last_value, increment_by, "
13194 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13195 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13197 "END AS max_value, "
13198 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13199 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13201 "END AS min_value, "
13202 "cache_value, is_cycled, is_called from %s",
13204 fmtId(tbinfo->dobj.name));
13208 appendPQExpBuffer(query,
13209 "SELECT sequence_name, "
13210 "0 AS start_value, last_value, increment_by, "
13211 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13212 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13214 "END AS max_value, "
13215 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13216 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13218 "END AS min_value, "
13219 "cache_value, is_cycled, is_called from %s",
13221 fmtId(tbinfo->dobj.name));
13224 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13226 if (PQntuples(res) != 1)
13228 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13229 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13231 tbinfo->dobj.name, PQntuples(res));
13235 /* Disable this check: it fails if sequence has been renamed */
13237 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13239 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13240 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13245 startv = PQgetvalue(res, 0, 1);
13246 last = PQgetvalue(res, 0, 2);
13247 incby = PQgetvalue(res, 0, 3);
13248 if (!PQgetisnull(res, 0, 4))
13249 maxv = PQgetvalue(res, 0, 4);
13250 if (!PQgetisnull(res, 0, 5))
13251 minv = PQgetvalue(res, 0, 5);
13252 cache = PQgetvalue(res, 0, 6);
13253 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13254 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13257 * The logic we use for restoring sequences is as follows:
13259 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13260 * last_val for start if called is false, else use min_val for start_val).
13261 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13262 * BY command for it.
13264 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13269 * DROP must be fully qualified in case same name appears in
13272 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13273 fmtId(tbinfo->dobj.namespace->dobj.name));
13274 appendPQExpBuffer(delqry, "%s;\n",
13275 fmtId(tbinfo->dobj.name));
13277 resetPQExpBuffer(query);
13279 if (binary_upgrade)
13281 binary_upgrade_set_pg_class_oids(fout, query,
13282 tbinfo->dobj.catId.oid, false);
13283 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13284 tbinfo->dobj.catId.oid);
13287 appendPQExpBuffer(query,
13288 "CREATE SEQUENCE %s\n",
13289 fmtId(tbinfo->dobj.name));
13291 if (fout->remoteVersion >= 80400)
13292 appendPQExpBuffer(query, " START WITH %s\n", startv);
13296 * Versions before 8.4 did not remember the true start value. If
13297 * is_called is false then the sequence has never been incremented
13298 * so we can use last_val. Otherwise punt and let it default.
13301 appendPQExpBuffer(query, " START WITH %s\n", last);
13304 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13307 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13309 appendPQExpBuffer(query, " NO MINVALUE\n");
13312 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13314 appendPQExpBuffer(query, " NO MAXVALUE\n");
13316 appendPQExpBuffer(query,
13318 cache, (cycled ? "\n CYCLE" : ""));
13320 appendPQExpBuffer(query, ";\n");
13322 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13324 /* binary_upgrade: no need to clear TOAST table oid */
13326 if (binary_upgrade)
13327 binary_upgrade_extension_member(query, &tbinfo->dobj,
13330 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13332 tbinfo->dobj.namespace->dobj.name,
13335 false, "SEQUENCE", SECTION_PRE_DATA,
13336 query->data, delqry->data, NULL,
13337 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13341 * If the sequence is owned by a table column, emit the ALTER for it
13342 * as a separate TOC entry immediately following the sequence's own
13343 * entry. It's OK to do this rather than using full sorting logic,
13344 * because the dependency that tells us it's owned will have forced
13345 * the table to be created first. We can't just include the ALTER in
13346 * the TOC entry because it will fail if we haven't reassigned the
13347 * sequence owner to match the table's owner.
13349 * We need not schema-qualify the table reference because both
13350 * sequence and table must be in the same schema.
13352 if (OidIsValid(tbinfo->owning_tab))
13354 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13356 if (owning_tab && owning_tab->dobj.dump)
13358 resetPQExpBuffer(query);
13359 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13360 fmtId(tbinfo->dobj.name));
13361 appendPQExpBuffer(query, " OWNED BY %s",
13362 fmtId(owning_tab->dobj.name));
13363 appendPQExpBuffer(query, ".%s;\n",
13364 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13366 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13368 tbinfo->dobj.namespace->dobj.name,
13371 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13372 query->data, "", NULL,
13373 &(tbinfo->dobj.dumpId), 1,
13378 /* Dump Sequence Comments and Security Labels */
13379 dumpComment(fout, labelq->data,
13380 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13381 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13382 dumpSecLabel(fout, labelq->data,
13383 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13384 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13389 resetPQExpBuffer(query);
13390 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13391 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13392 appendPQExpBuffer(query, ", %s, %s);\n",
13393 last, (called ? "true" : "false"));
13395 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13397 tbinfo->dobj.namespace->dobj.name,
13400 false, "SEQUENCE SET", SECTION_PRE_DATA,
13401 query->data, "", NULL,
13402 &(tbinfo->dobj.dumpId), 1,
13408 destroyPQExpBuffer(query);
13409 destroyPQExpBuffer(delqry);
13410 destroyPQExpBuffer(labelq);
13414 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13416 TableInfo *tbinfo = tginfo->tgtable;
13418 PQExpBuffer delqry;
13419 PQExpBuffer labelq;
13428 query = createPQExpBuffer();
13429 delqry = createPQExpBuffer();
13430 labelq = createPQExpBuffer();
13433 * DROP must be fully qualified in case same name appears in pg_catalog
13435 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13436 fmtId(tginfo->dobj.name));
13437 appendPQExpBuffer(delqry, "ON %s.",
13438 fmtId(tbinfo->dobj.namespace->dobj.name));
13439 appendPQExpBuffer(delqry, "%s;\n",
13440 fmtId(tbinfo->dobj.name));
13444 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13448 if (tginfo->tgisconstraint)
13450 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13451 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13455 appendPQExpBuffer(query, "CREATE TRIGGER ");
13456 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13458 appendPQExpBuffer(query, "\n ");
13461 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13462 appendPQExpBuffer(query, "BEFORE");
13463 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13464 appendPQExpBuffer(query, "AFTER");
13465 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13466 appendPQExpBuffer(query, "INSTEAD OF");
13469 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13474 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13476 appendPQExpBuffer(query, " INSERT");
13479 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13482 appendPQExpBuffer(query, " OR DELETE");
13484 appendPQExpBuffer(query, " DELETE");
13487 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13490 appendPQExpBuffer(query, " OR UPDATE");
13492 appendPQExpBuffer(query, " UPDATE");
13495 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13498 appendPQExpBuffer(query, " OR TRUNCATE");
13500 appendPQExpBuffer(query, " TRUNCATE");
13503 appendPQExpBuffer(query, " ON %s\n",
13504 fmtId(tbinfo->dobj.name));
13506 if (tginfo->tgisconstraint)
13508 if (OidIsValid(tginfo->tgconstrrelid))
13510 /* If we are using regclass, name is already quoted */
13511 if (fout->remoteVersion >= 70300)
13512 appendPQExpBuffer(query, " FROM %s\n ",
13513 tginfo->tgconstrrelname);
13515 appendPQExpBuffer(query, " FROM %s\n ",
13516 fmtId(tginfo->tgconstrrelname));
13518 if (!tginfo->tgdeferrable)
13519 appendPQExpBuffer(query, "NOT ");
13520 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13521 if (tginfo->tginitdeferred)
13522 appendPQExpBuffer(query, "DEFERRED\n");
13524 appendPQExpBuffer(query, "IMMEDIATE\n");
13527 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13528 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13530 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13532 /* In 7.3, result of regproc is already quoted */
13533 if (fout->remoteVersion >= 70300)
13534 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13537 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13538 fmtId(tginfo->tgfname));
13540 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13543 for (findx = 0; findx < tginfo->tgnargs; findx++)
13545 /* find the embedded null that terminates this trigger argument */
13546 size_t tlen = strlen(p);
13548 if (p + tlen >= tgargs + lentgargs)
13550 /* hm, not found before end of bytea value... */
13551 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13554 tbinfo->dobj.name);
13559 appendPQExpBuffer(query, ", ");
13560 appendStringLiteralAH(query, p, fout);
13564 appendPQExpBuffer(query, ");\n");
13567 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13569 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13570 fmtId(tbinfo->dobj.name));
13571 switch (tginfo->tgenabled)
13575 appendPQExpBuffer(query, "DISABLE");
13578 appendPQExpBuffer(query, "ENABLE ALWAYS");
13581 appendPQExpBuffer(query, "ENABLE REPLICA");
13584 appendPQExpBuffer(query, "ENABLE");
13587 appendPQExpBuffer(query, " TRIGGER %s;\n",
13588 fmtId(tginfo->dobj.name));
13591 appendPQExpBuffer(labelq, "TRIGGER %s ",
13592 fmtId(tginfo->dobj.name));
13593 appendPQExpBuffer(labelq, "ON %s",
13594 fmtId(tbinfo->dobj.name));
13596 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13598 tbinfo->dobj.namespace->dobj.name,
13600 tbinfo->rolname, false,
13601 "TRIGGER", SECTION_POST_DATA,
13602 query->data, delqry->data, NULL,
13603 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13606 dumpComment(fout, labelq->data,
13607 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13608 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13610 destroyPQExpBuffer(query);
13611 destroyPQExpBuffer(delqry);
13612 destroyPQExpBuffer(labelq);
13620 dumpRule(Archive *fout, RuleInfo *rinfo)
13622 TableInfo *tbinfo = rinfo->ruletable;
13625 PQExpBuffer delcmd;
13626 PQExpBuffer labelq;
13629 /* Skip if not to be dumped */
13630 if (!rinfo->dobj.dump || dataOnly)
13634 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13635 * we do not want to dump it as a separate object.
13637 if (!rinfo->separate)
13641 * Make sure we are in proper schema.
13643 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13645 query = createPQExpBuffer();
13646 cmd = createPQExpBuffer();
13647 delcmd = createPQExpBuffer();
13648 labelq = createPQExpBuffer();
13650 if (fout->remoteVersion >= 70300)
13652 appendPQExpBuffer(query,
13653 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13654 rinfo->dobj.catId.oid);
13658 /* Rule name was unique before 7.3 ... */
13659 appendPQExpBuffer(query,
13660 "SELECT pg_get_ruledef('%s') AS definition",
13664 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13666 if (PQntuples(res) != 1)
13668 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13669 rinfo->dobj.name, tbinfo->dobj.name);
13673 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13676 * Add the command to alter the rules replication firing semantics if it
13677 * differs from the default.
13679 if (rinfo->ev_enabled != 'O')
13681 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13682 fmtId(tbinfo->dobj.namespace->dobj.name));
13683 appendPQExpBuffer(cmd, "%s ",
13684 fmtId(tbinfo->dobj.name));
13685 switch (rinfo->ev_enabled)
13688 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13689 fmtId(rinfo->dobj.name));
13692 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13693 fmtId(rinfo->dobj.name));
13696 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13697 fmtId(rinfo->dobj.name));
13703 * DROP must be fully qualified in case same name appears in pg_catalog
13705 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13706 fmtId(rinfo->dobj.name));
13707 appendPQExpBuffer(delcmd, "ON %s.",
13708 fmtId(tbinfo->dobj.namespace->dobj.name));
13709 appendPQExpBuffer(delcmd, "%s;\n",
13710 fmtId(tbinfo->dobj.name));
13712 appendPQExpBuffer(labelq, "RULE %s",
13713 fmtId(rinfo->dobj.name));
13714 appendPQExpBuffer(labelq, " ON %s",
13715 fmtId(tbinfo->dobj.name));
13717 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13719 tbinfo->dobj.namespace->dobj.name,
13721 tbinfo->rolname, false,
13722 "RULE", SECTION_POST_DATA,
13723 cmd->data, delcmd->data, NULL,
13724 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13727 /* Dump rule comments */
13728 dumpComment(fout, labelq->data,
13729 tbinfo->dobj.namespace->dobj.name,
13731 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13735 destroyPQExpBuffer(query);
13736 destroyPQExpBuffer(cmd);
13737 destroyPQExpBuffer(delcmd);
13738 destroyPQExpBuffer(labelq);
13742 * getExtensionMembership --- obtain extension membership data
13745 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13756 DumpableObject *dobj,
13759 /* Nothing to do if no extensions */
13760 if (numExtensions == 0)
13763 /* Make sure we are in proper schema */
13764 selectSourceSchema(fout, "pg_catalog");
13766 query = createPQExpBuffer();
13768 /* refclassid constraint is redundant but may speed the search */
13769 appendPQExpBuffer(query, "SELECT "
13770 "classid, objid, refclassid, refobjid "
13772 "WHERE refclassid = 'pg_extension'::regclass "
13773 "AND deptype = 'e' "
13776 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13778 ntups = PQntuples(res);
13780 i_classid = PQfnumber(res, "classid");
13781 i_objid = PQfnumber(res, "objid");
13782 i_refclassid = PQfnumber(res, "refclassid");
13783 i_refobjid = PQfnumber(res, "refobjid");
13786 * Since we ordered the SELECT by referenced ID, we can expect that
13787 * multiple entries for the same extension will appear together; this
13788 * saves on searches.
13792 for (i = 0; i < ntups; i++)
13795 CatalogId refobjId;
13797 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13798 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13799 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13800 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13802 if (refdobj == NULL ||
13803 refdobj->catId.tableoid != refobjId.tableoid ||
13804 refdobj->catId.oid != refobjId.oid)
13805 refdobj = findObjectByCatalogId(refobjId);
13808 * Failure to find objects mentioned in pg_depend is not unexpected,
13809 * since for example we don't collect info about TOAST tables.
13811 if (refdobj == NULL)
13814 fprintf(stderr, "no referenced object %u %u\n",
13815 refobjId.tableoid, refobjId.oid);
13820 dobj = findObjectByCatalogId(objId);
13825 fprintf(stderr, "no referencing object %u %u\n",
13826 objId.tableoid, objId.oid);
13831 /* Record dependency so that getDependencies needn't repeat this */
13832 addObjectDependency(dobj, refdobj->dumpId);
13834 dobj->ext_member = true;
13837 * Normally, mark the member object as not to be dumped. But in
13838 * binary upgrades, we still dump the members individually, since the
13839 * idea is to exactly reproduce the database contents rather than
13840 * replace the extension contents with something different.
13842 if (!binary_upgrade)
13843 dobj->dump = false;
13845 dobj->dump = refdobj->dump;
13851 * Now identify extension configuration tables and create TableDataInfo
13852 * objects for them, ensuring their data will be dumped even though the
13853 * tables themselves won't be.
13855 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13856 * user data in a configuration table is treated like schema data. This
13857 * seems appropriate since system data in a config table would get
13858 * reloaded by CREATE EXTENSION.
13860 for (i = 0; i < numExtensions; i++)
13862 ExtensionInfo *curext = &(extinfo[i]);
13863 char *extconfig = curext->extconfig;
13864 char *extcondition = curext->extcondition;
13865 char **extconfigarray = NULL;
13866 char **extconditionarray = NULL;
13868 int nconditionitems;
13870 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13871 if (!curext->dobj.dump)
13874 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13875 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13876 nconfigitems == nconditionitems)
13880 for (j = 0; j < nconfigitems; j++)
13882 TableInfo *configtbl;
13884 configtbl = findTableByOid(atooid(extconfigarray[j]));
13885 if (configtbl == NULL)
13889 * Note: config tables are dumped without OIDs regardless of
13890 * the --oids setting. This is because row filtering
13891 * conditions aren't compatible with dumping OIDs.
13893 makeTableDataInfo(configtbl, false);
13894 if (configtbl->dataObj != NULL)
13896 if (strlen(extconditionarray[j]) > 0)
13897 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13901 if (extconfigarray)
13902 free(extconfigarray);
13903 if (extconditionarray)
13904 free(extconditionarray);
13907 destroyPQExpBuffer(query);
13911 * getDependencies --- obtain available dependency data
13914 getDependencies(Archive *fout)
13925 DumpableObject *dobj,
13928 /* No dependency info available before 7.3 */
13929 if (fout->remoteVersion < 70300)
13933 write_msg(NULL, "reading dependency data\n");
13935 /* Make sure we are in proper schema */
13936 selectSourceSchema(fout, "pg_catalog");
13938 query = createPQExpBuffer();
13941 * PIN dependencies aren't interesting, and EXTENSION dependencies were
13942 * already processed by getExtensionMembership.
13944 appendPQExpBuffer(query, "SELECT "
13945 "classid, objid, refclassid, refobjid, deptype "
13947 "WHERE deptype != 'p' AND deptype != 'e' "
13950 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13952 ntups = PQntuples(res);
13954 i_classid = PQfnumber(res, "classid");
13955 i_objid = PQfnumber(res, "objid");
13956 i_refclassid = PQfnumber(res, "refclassid");
13957 i_refobjid = PQfnumber(res, "refobjid");
13958 i_deptype = PQfnumber(res, "deptype");
13961 * Since we ordered the SELECT by referencing ID, we can expect that
13962 * multiple entries for the same object will appear together; this saves
13967 for (i = 0; i < ntups; i++)
13970 CatalogId refobjId;
13973 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13974 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13975 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13976 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13977 deptype = *(PQgetvalue(res, i, i_deptype));
13979 if (dobj == NULL ||
13980 dobj->catId.tableoid != objId.tableoid ||
13981 dobj->catId.oid != objId.oid)
13982 dobj = findObjectByCatalogId(objId);
13985 * Failure to find objects mentioned in pg_depend is not unexpected,
13986 * since for example we don't collect info about TOAST tables.
13991 fprintf(stderr, "no referencing object %u %u\n",
13992 objId.tableoid, objId.oid);
13997 refdobj = findObjectByCatalogId(refobjId);
13999 if (refdobj == NULL)
14002 fprintf(stderr, "no referenced object %u %u\n",
14003 refobjId.tableoid, refobjId.oid);
14009 * Ordinarily, table rowtypes have implicit dependencies on their
14010 * tables. However, for a composite type the implicit dependency goes
14011 * the other way in pg_depend; which is the right thing for DROP but
14012 * it doesn't produce the dependency ordering we need. So in that one
14013 * case, we reverse the direction of the dependency.
14015 if (deptype == 'i' &&
14016 dobj->objType == DO_TABLE &&
14017 refdobj->objType == DO_TYPE)
14018 addObjectDependency(refdobj, dobj->dumpId);
14021 addObjectDependency(dobj, refdobj->dumpId);
14026 destroyPQExpBuffer(query);
14031 * selectSourceSchema - make the specified schema the active search path
14032 * in the source database.
14034 * NB: pg_catalog is explicitly searched after the specified schema;
14035 * so user names are only qualified if they are cross-schema references,
14036 * and system names are only qualified if they conflict with a user name
14037 * in the current schema.
14039 * Whenever the selected schema is not pg_catalog, be careful to qualify
14040 * references to system catalogs and types in our emitted commands!
14043 selectSourceSchema(Archive *fout, const char *schemaName)
14045 static char *curSchemaName = NULL;
14048 /* Not relevant if fetching from pre-7.3 DB */
14049 if (fout->remoteVersion < 70300)
14051 /* Ignore null schema names */
14052 if (schemaName == NULL || *schemaName == '\0')
14054 /* Optimize away repeated selection of same schema */
14055 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14058 query = createPQExpBuffer();
14059 appendPQExpBuffer(query, "SET search_path = %s",
14060 fmtId(schemaName));
14061 if (strcmp(schemaName, "pg_catalog") != 0)
14062 appendPQExpBuffer(query, ", pg_catalog");
14064 ExecuteSqlStatement(fout, query->data);
14066 destroyPQExpBuffer(query);
14068 free(curSchemaName);
14069 curSchemaName = pg_strdup(schemaName);
14073 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14076 * NB: in 7.3 and up the result may depend on the currently-selected
14077 * schema; this is why we don't try to cache the names.
14080 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14088 if ((opts & zeroAsOpaque) != 0)
14089 return pg_strdup(g_opaque_type);
14090 else if ((opts & zeroAsAny) != 0)
14091 return pg_strdup("'any'");
14092 else if ((opts & zeroAsStar) != 0)
14093 return pg_strdup("*");
14094 else if ((opts & zeroAsNone) != 0)
14095 return pg_strdup("NONE");
14098 query = createPQExpBuffer();
14099 if (fout->remoteVersion >= 70300)
14101 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14104 else if (fout->remoteVersion >= 70100)
14106 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14111 appendPQExpBuffer(query, "SELECT typname "
14113 "WHERE oid = '%u'::oid",
14117 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14119 if (fout->remoteVersion >= 70100)
14121 /* already quoted */
14122 result = pg_strdup(PQgetvalue(res, 0, 0));
14126 /* may need to quote it */
14127 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14131 destroyPQExpBuffer(query);
14137 * myFormatType --- local implementation of format_type for use with 7.0.
14140 myFormatType(const char *typname, int32 typmod)
14143 bool isarray = false;
14144 PQExpBuffer buf = createPQExpBuffer();
14146 /* Handle array types */
14147 if (typname[0] == '_')
14153 /* Show lengths on bpchar and varchar */
14154 if (strcmp(typname, "bpchar") == 0)
14156 int len = (typmod - VARHDRSZ);
14158 appendPQExpBuffer(buf, "character");
14160 appendPQExpBuffer(buf, "(%d)",
14161 typmod - VARHDRSZ);
14163 else if (strcmp(typname, "varchar") == 0)
14165 appendPQExpBuffer(buf, "character varying");
14167 appendPQExpBuffer(buf, "(%d)",
14168 typmod - VARHDRSZ);
14170 else if (strcmp(typname, "numeric") == 0)
14172 appendPQExpBuffer(buf, "numeric");
14179 tmp_typmod = typmod - VARHDRSZ;
14180 precision = (tmp_typmod >> 16) & 0xffff;
14181 scale = tmp_typmod & 0xffff;
14182 appendPQExpBuffer(buf, "(%d,%d)",
14188 * char is an internal single-byte data type; Let's make sure we force it
14189 * through with quotes. - thomas 1998-12-13
14191 else if (strcmp(typname, "char") == 0)
14192 appendPQExpBuffer(buf, "\"char\"");
14194 appendPQExpBuffer(buf, "%s", fmtId(typname));
14196 /* Append array qualifier for array types */
14198 appendPQExpBuffer(buf, "[]");
14200 result = pg_strdup(buf->data);
14201 destroyPQExpBuffer(buf);
14207 * fmtQualifiedId - convert a qualified name to the proper format for
14208 * the source database.
14210 * Like fmtId, use the result before calling again.
14212 static const char *
14213 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14215 static PQExpBuffer id_return = NULL;
14217 if (id_return) /* first time through? */
14218 resetPQExpBuffer(id_return);
14220 id_return = createPQExpBuffer();
14222 /* Suppress schema name if fetching from pre-7.3 DB */
14223 if (fout->remoteVersion >= 70300 && schema && *schema)
14225 appendPQExpBuffer(id_return, "%s.",
14228 appendPQExpBuffer(id_return, "%s",
14231 return id_return->data;
14235 * Return a column list clause for the given relation.
14237 * Special case: if there are no undropped columns in the relation, return
14238 * "", not an invalid "()" column list.
14240 static const char *
14241 fmtCopyColumnList(const TableInfo *ti)
14243 static PQExpBuffer q = NULL;
14244 int numatts = ti->numatts;
14245 char **attnames = ti->attnames;
14246 bool *attisdropped = ti->attisdropped;
14250 if (q) /* first time through? */
14251 resetPQExpBuffer(q);
14253 q = createPQExpBuffer();
14255 appendPQExpBuffer(q, "(");
14257 for (i = 0; i < numatts; i++)
14259 if (attisdropped[i])
14262 appendPQExpBuffer(q, ", ");
14263 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14268 return ""; /* no undropped columns */
14270 appendPQExpBuffer(q, ")");
14275 * Execute an SQL query and verify that we got exactly one row back.
14278 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14283 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14285 /* Expecting a single result only */
14286 ntups = PQntuples(res);
14288 exit_horribly(NULL,
14289 ngettext("query returned %d row instead of one: %s\n",
14290 "query returned %d rows instead of one: %s\n",