1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
14 * Note that pg_dump runs in a transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to run on
18 * SnapshotNow time, ie they look at the currently committed state. So
19 * it is possible to get 'cache lookup failed' error if someone
20 * performs DDL changes while a dump is happening. The window for this
21 * sort of thing is from the acquisition of the transaction snapshot to
22 * getSchemaData() (when pg_dump acquires AccessShareLock on every
23 * table it intends to dump). It isn't very large, but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
33 #include "postgres_fe.h"
44 #include "getopt_long.h"
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_largeobject.h"
53 #include "catalog/pg_largeobject_metadata.h"
54 #include "catalog/pg_proc.h"
55 #include "catalog/pg_trigger.h"
56 #include "catalog/pg_type.h"
57 #include "libpq/libpq-fs.h"
59 #include "pg_backup_archiver.h"
60 #include "pg_backup_db.h"
62 #include "dumputils.h"
71 const char *descr; /* comment for an object */
72 Oid classoid; /* object class (catalog OID) */
73 Oid objoid; /* object OID */
74 int objsubid; /* subobject (table column #) */
79 const char *provider; /* label provider of this security label */
80 const char *label; /* security label for an object */
81 Oid classoid; /* object class (catalog OID) */
82 Oid objoid; /* object OID */
83 int objsubid; /* subobject (table column #) */
87 bool g_verbose; /* User wants verbose narration of our
90 /* various user-settable parameters */
93 int dumpSections; /* bitmask of chosen sections */
95 const char *lockWaitTimeout;
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
100 /* obsolete as of 7.3: */
101 static Oid g_last_builtin_oid; /* value of the last builtin oid */
104 * Object inclusion/exclusion lists
106 * The string lists record the patterns given by command-line switches,
107 * which we then convert to lists of OIDs of matching objects.
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
124 char g_opaque_type[10]; /* name for the opaque type */
126 /* placeholders for the delimiters for comments */
127 char g_comment_start[10];
128 char g_comment_end[10];
130 static const CatalogId nilCatalogId = {0, 0};
132 /* these are to avoid passing around info for findNamespace() */
133 static NamespaceInfo *g_namespaces;
134 static int g_numNamespaces;
136 /* flags for various command-line long options */
137 static int binary_upgrade = 0;
138 static int disable_dollar_quoting = 0;
139 static int dump_inserts = 0;
140 static int column_inserts = 0;
141 static int no_security_labels = 0;
142 static int no_unlogged_table_data = 0;
143 static int serializable_deferrable = 0;
146 static void help(const char *progname);
147 static void pgdump_cleanup_at_exit(int code, void *arg);
148 static void setup_connection(Archive *AH, const char *dumpencoding,
150 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
151 static void expand_schema_name_patterns(Archive *fout,
152 SimpleStringList *patterns,
153 SimpleOidList *oids);
154 static void expand_table_name_patterns(Archive *fout,
155 SimpleStringList *patterns,
156 SimpleOidList *oids);
157 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
158 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *target,
161 const char *namespace, const char *owner,
162 CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164 CommentItem **items);
165 static int collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *target,
167 const char *namespace, const char *owner,
168 CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170 SecLabelItem **items);
171 static int collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
182 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
183 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
184 static void dumpFunc(Archive *fout, FuncInfo *finfo);
185 static void dumpCast(Archive *fout, CastInfo *cast);
186 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
187 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
188 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
189 static void dumpCollation(Archive *fout, CollInfo *convinfo);
190 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
191 static void dumpRule(Archive *fout, RuleInfo *rinfo);
192 static void dumpAgg(Archive *fout, AggInfo *agginfo);
193 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
194 static void dumpTable(Archive *fout, TableInfo *tbinfo);
195 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
196 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
197 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
198 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
199 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
201 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
202 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
203 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
204 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
205 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
206 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
207 static void dumpUserMappings(Archive *fout,
208 const char *servername, const char *namespace,
209 const char *owner, CatalogId catalogId, DumpId dumpId);
210 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
212 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
213 const char *type, const char *name, const char *subname,
214 const char *tag, const char *nspname, const char *owner,
217 static void getDependencies(Archive *fout);
218 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
219 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
220 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
221 static void getTableDataFKConstraints(void);
222 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
223 static char *format_function_arguments_old(Archive *fout,
224 FuncInfo *finfo, int nallargs,
228 static char *format_function_signature(Archive *fout,
229 FuncInfo *finfo, bool honor_quotes);
230 static const char *convertRegProcReference(Archive *fout,
232 static const char *convertOperatorReference(Archive *fout, const char *opr);
233 static const char *convertTSFunction(Archive *fout, Oid funcOid);
234 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
235 static Oid findLastBuiltinOid_V70(Archive *fout);
236 static void selectSourceSchema(Archive *fout, const char *schemaName);
237 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
238 static char *myFormatType(const char *typname, int32 typmod);
239 static const char *fmtQualifiedId(Archive *fout,
240 const char *schema, const char *id);
241 static void getBlobs(Archive *fout);
242 static void dumpBlob(Archive *fout, BlobInfo *binfo);
243 static int dumpBlobs(Archive *fout, void *arg);
244 static void dumpDatabase(Archive *AH);
245 static void dumpEncoding(Archive *AH);
246 static void dumpStdStrings(Archive *AH);
247 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
248 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
249 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
250 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
251 static void binary_upgrade_set_pg_class_oids(Archive *fout,
252 PQExpBuffer upgrade_buffer,
253 Oid pg_class_oid, bool is_index);
254 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
255 DumpableObject *dobj,
256 const char *objlabel);
257 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
258 static const char *fmtCopyColumnList(const TableInfo *ti);
259 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
262 main(int argc, char **argv)
265 const char *filename = NULL;
266 const char *format = "p";
267 const char *dbname = NULL;
268 const char *pghost = NULL;
269 const char *pgport = NULL;
270 const char *username = NULL;
271 const char *dumpencoding = NULL;
275 DumpableObject **dobjs;
278 enum trivalue prompt_password = TRI_DEFAULT;
279 int compressLevel = -1;
282 int outputCreateDB = 0;
283 bool outputBlobs = false;
284 int outputNoOwner = 0;
285 char *outputSuperuser = NULL;
286 char *use_role = NULL;
289 RestoreOptions *ropt;
290 ArchiveFormat archiveFormat = archUnknown;
291 ArchiveMode archiveMode;
292 Archive *fout; /* the script file */
294 static int disable_triggers = 0;
295 static int outputNoTablespaces = 0;
296 static int use_setsessauth = 0;
298 static struct option long_options[] = {
299 {"data-only", no_argument, NULL, 'a'},
300 {"blobs", no_argument, NULL, 'b'},
301 {"clean", no_argument, NULL, 'c'},
302 {"create", no_argument, NULL, 'C'},
303 {"file", required_argument, NULL, 'f'},
304 {"format", required_argument, NULL, 'F'},
305 {"host", required_argument, NULL, 'h'},
306 {"ignore-version", no_argument, NULL, 'i'},
307 {"no-reconnect", no_argument, NULL, 'R'},
308 {"oids", no_argument, NULL, 'o'},
309 {"no-owner", no_argument, NULL, 'O'},
310 {"port", required_argument, NULL, 'p'},
311 {"schema", required_argument, NULL, 'n'},
312 {"exclude-schema", required_argument, NULL, 'N'},
313 {"schema-only", no_argument, NULL, 's'},
314 {"superuser", required_argument, NULL, 'S'},
315 {"table", required_argument, NULL, 't'},
316 {"exclude-table", required_argument, NULL, 'T'},
317 {"no-password", no_argument, NULL, 'w'},
318 {"password", no_argument, NULL, 'W'},
319 {"username", required_argument, NULL, 'U'},
320 {"verbose", no_argument, NULL, 'v'},
321 {"no-privileges", no_argument, NULL, 'x'},
322 {"no-acl", no_argument, NULL, 'x'},
323 {"compress", required_argument, NULL, 'Z'},
324 {"encoding", required_argument, NULL, 'E'},
325 {"help", no_argument, NULL, '?'},
326 {"version", no_argument, NULL, 'V'},
329 * the following options don't have an equivalent short option letter
331 {"attribute-inserts", no_argument, &column_inserts, 1},
332 {"binary-upgrade", no_argument, &binary_upgrade, 1},
333 {"column-inserts", no_argument, &column_inserts, 1},
334 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
335 {"disable-triggers", no_argument, &disable_triggers, 1},
336 {"exclude-table-data", required_argument, NULL, 4},
337 {"inserts", no_argument, &dump_inserts, 1},
338 {"lock-wait-timeout", required_argument, NULL, 2},
339 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
340 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
341 {"role", required_argument, NULL, 3},
342 {"section", required_argument, NULL, 5},
343 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
344 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
345 {"no-security-labels", no_argument, &no_security_labels, 1},
346 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
351 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
355 strcpy(g_comment_start, "-- ");
356 g_comment_end[0] = '\0';
357 strcpy(g_opaque_type, "opaque");
359 dataOnly = schemaOnly = false;
360 dumpSections = DUMP_UNSECTIONED;
361 lockWaitTimeout = NULL;
363 progname = get_progname(argv[0]);
365 /* Set default options based on progname */
366 if (strcmp(progname, "pg_backup") == 0)
371 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
376 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
378 puts("pg_dump (PostgreSQL) " PG_VERSION);
383 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
384 long_options, &optindex)) != -1)
388 case 'a': /* Dump data only */
392 case 'b': /* Dump blobs */
396 case 'c': /* clean (i.e., drop) schema prior to create */
400 case 'C': /* Create DB */
404 case 'E': /* Dump encoding */
405 dumpencoding = optarg;
416 case 'h': /* server host */
421 /* ignored, deprecated option */
424 case 'n': /* include schema(s) */
425 simple_string_list_append(&schema_include_patterns, optarg);
426 include_everything = false;
429 case 'N': /* exclude schema(s) */
430 simple_string_list_append(&schema_exclude_patterns, optarg);
433 case 'o': /* Dump oids */
437 case 'O': /* Don't reconnect to match owner */
441 case 'p': /* server port */
446 /* no-op, still accepted for backwards compatibility */
449 case 's': /* dump schema only */
453 case 'S': /* Username for superuser in plain text output */
454 outputSuperuser = pg_strdup(optarg);
457 case 't': /* include table(s) */
458 simple_string_list_append(&table_include_patterns, optarg);
459 include_everything = false;
462 case 'T': /* exclude table(s) */
463 simple_string_list_append(&table_exclude_patterns, optarg);
470 case 'v': /* verbose */
475 prompt_password = TRI_NO;
479 prompt_password = TRI_YES;
482 case 'x': /* skip ACL dump */
486 case 'Z': /* Compression Level */
487 compressLevel = atoi(optarg);
491 /* This covers the long options. */
494 case 2: /* lock-wait-timeout */
495 lockWaitTimeout = optarg;
498 case 3: /* SET ROLE */
502 case 4: /* exclude table(s) data */
503 simple_string_list_append(&tabledata_exclude_patterns, optarg);
506 case 5: /* section */
507 set_section(optarg, &dumpSections);
511 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
516 /* Get database name from command line */
518 dbname = argv[optind++];
520 /* Complain if any arguments remain */
523 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
524 progname, argv[optind]);
525 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
530 /* --column-inserts implies --inserts */
534 if (dataOnly && schemaOnly)
535 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
537 if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
538 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
541 dumpSections = DUMP_DATA;
543 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
544 else if ( dumpSections != DUMP_UNSECTIONED)
546 dataOnly = dumpSections == DUMP_DATA;
547 schemaOnly = !(dumpSections & DUMP_DATA);
550 if (dataOnly && outputClean)
551 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
553 if (dump_inserts && oids)
555 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
556 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
560 /* Identify archive format to emit */
561 archiveFormat = parseArchiveFormat(format, &archiveMode);
563 /* archiveFormat specific setup */
564 if (archiveFormat == archNull)
567 /* Custom and directory formats are compressed by default, others not */
568 if (compressLevel == -1)
570 if (archiveFormat == archCustom || archiveFormat == archDirectory)
571 compressLevel = Z_DEFAULT_COMPRESSION;
576 /* Open the output file */
577 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
578 on_exit_nicely(pgdump_cleanup_at_exit, fout);
581 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
583 /* Let the archiver know how noisy to be */
584 fout->verbose = g_verbose;
586 my_version = parse_version(PG_VERSION);
588 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
591 * We allow the server to be back to 7.0, and up to any minor release of
592 * our own major version. (See also version check in pg_dumpall.c.)
594 fout->minRemoteVersion = 70000;
595 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
598 * Open the database using the Archiver, so it knows about it. Errors mean
601 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
602 setup_connection(fout, dumpencoding, use_role);
605 * Disable security label support if server version < v9.1.x (prevents
606 * access to nonexistent pg_seclabel catalog)
608 if (fout->remoteVersion < 90100)
609 no_security_labels = 1;
612 * Start transaction-snapshot mode transaction to dump consistent data.
614 ExecuteSqlStatement(fout, "BEGIN");
615 if (fout->remoteVersion >= 90100)
617 if (serializable_deferrable)
618 ExecuteSqlStatement(fout,
619 "SET TRANSACTION ISOLATION LEVEL "
620 "SERIALIZABLE, READ ONLY, DEFERRABLE");
622 ExecuteSqlStatement(fout,
623 "SET TRANSACTION ISOLATION LEVEL "
627 ExecuteSqlStatement(fout,
628 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
630 /* Select the appropriate subquery to convert user IDs to names */
631 if (fout->remoteVersion >= 80100)
632 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
633 else if (fout->remoteVersion >= 70300)
634 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
636 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
638 /* Find the last built-in OID, if needed */
639 if (fout->remoteVersion < 70300)
641 if (fout->remoteVersion >= 70100)
642 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
643 PQdb(GetConnection(fout)));
645 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
647 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
650 /* Expand schema selection patterns into OID lists */
651 if (schema_include_patterns.head != NULL)
653 expand_schema_name_patterns(fout, &schema_include_patterns,
654 &schema_include_oids);
655 if (schema_include_oids.head == NULL)
656 exit_horribly(NULL, "No matching schemas were found\n");
658 expand_schema_name_patterns(fout, &schema_exclude_patterns,
659 &schema_exclude_oids);
660 /* non-matching exclusion patterns aren't an error */
662 /* Expand table selection patterns into OID lists */
663 if (table_include_patterns.head != NULL)
665 expand_table_name_patterns(fout, &table_include_patterns,
666 &table_include_oids);
667 if (table_include_oids.head == NULL)
668 exit_horribly(NULL, "No matching tables were found\n");
670 expand_table_name_patterns(fout, &table_exclude_patterns,
671 &table_exclude_oids);
673 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
674 &tabledata_exclude_oids);
676 /* non-matching exclusion patterns aren't an error */
679 * Dumping blobs is now default unless we saw an inclusion switch or -s
680 * ... but even if we did see one of these, -b turns it back on.
682 if (include_everything && !schemaOnly)
686 * Now scan the database and create DumpableObject structs for all the
687 * objects we intend to dump.
689 tblinfo = getSchemaData(fout, &numTables);
691 if (fout->remoteVersion < 80400)
692 guessConstraintInheritance(tblinfo, numTables);
696 getTableData(tblinfo, numTables, oids);
698 getTableDataFKConstraints();
705 * Collect dependency data to assist in ordering the objects.
707 getDependencies(fout);
710 * Sort the objects into a safe dump order (no forward references).
712 * In 7.3 or later, we can rely on dependency information to help us
713 * determine a safe order, so the initial sort is mostly for cosmetic
714 * purposes: we sort by name to ensure that logically identical schemas
715 * will dump identically. Before 7.3 we don't have dependencies and we
716 * use OID ordering as an (unreliable) guide to creation order.
718 getDumpableObjects(&dobjs, &numObjs);
720 if (fout->remoteVersion >= 70300)
721 sortDumpableObjectsByTypeName(dobjs, numObjs);
723 sortDumpableObjectsByTypeOid(dobjs, numObjs);
725 sortDumpableObjects(dobjs, numObjs);
728 * Create archive TOC entries for all the objects to be dumped, in a safe
732 /* First the special ENCODING and STDSTRINGS entries. */
734 dumpStdStrings(fout);
736 /* The database item is always next, unless we don't want it at all */
737 if (include_everything && !dataOnly)
740 /* Now the rearrangeable objects. */
741 for (i = 0; i < numObjs; i++)
742 dumpDumpableObject(fout, dobjs[i]);
745 * And finally we can do the actual output.
749 ropt = NewRestoreOptions();
750 ropt->filename = filename;
751 ropt->dropSchema = outputClean;
752 ropt->aclsSkip = aclsSkip;
753 ropt->superuser = outputSuperuser;
754 ropt->createDB = outputCreateDB;
755 ropt->noOwner = outputNoOwner;
756 ropt->noTablespace = outputNoTablespaces;
757 ropt->disable_triggers = disable_triggers;
758 ropt->use_setsessauth = use_setsessauth;
759 ropt->dataOnly = dataOnly;
761 if (compressLevel == -1)
762 ropt->compression = 0;
764 ropt->compression = compressLevel;
766 ropt->suppressDumpWarnings = true; /* We've already shown them */
768 RestoreArchive(fout, ropt);
778 help(const char *progname)
780 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
781 printf(_("Usage:\n"));
782 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
784 printf(_("\nGeneral options:\n"));
785 printf(_(" -f, --file=FILENAME output file or directory name\n"));
786 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
787 " plain text (default))\n"));
788 printf(_(" -v, --verbose verbose mode\n"));
789 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
790 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
791 printf(_(" --help show this help, then exit\n"));
792 printf(_(" --version output version information, then exit\n"));
794 printf(_("\nOptions controlling the output content:\n"));
795 printf(_(" -a, --data-only dump only the data, not the schema\n"));
796 printf(_(" -b, --blobs include large objects in dump\n"));
797 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
798 printf(_(" -C, --create include commands to create database in dump\n"));
799 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
800 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
801 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
802 printf(_(" -o, --oids include OIDs in dump\n"));
803 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
804 " plain-text format\n"));
805 printf(_(" -s, --schema-only dump only the schema, no data\n"));
806 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
807 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
808 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
809 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
810 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
811 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
812 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
813 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
814 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
815 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
816 printf(_(" --no-security-labels do not dump security label assignments\n"));
817 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
818 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
819 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
820 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
821 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
822 printf(_(" --use-set-session-authorization\n"
823 " use SET SESSION AUTHORIZATION commands instead of\n"
824 " ALTER OWNER commands to set ownership\n"));
826 printf(_("\nConnection options:\n"));
827 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
828 printf(_(" -p, --port=PORT database server port number\n"));
829 printf(_(" -U, --username=NAME connect as specified database user\n"));
830 printf(_(" -w, --no-password never prompt for password\n"));
831 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
832 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
834 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
835 "variable value is used.\n\n"));
836 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
840 pgdump_cleanup_at_exit(int code, void *arg)
842 Archive *AH = (Archive *) arg;
844 DisconnectDatabase(AH);
848 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
850 PGconn *conn = GetConnection(AH);
851 const char *std_strings;
853 /* Set the client encoding if requested */
856 if (PQsetClientEncoding(conn, dumpencoding) < 0)
857 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
862 * Get the active encoding and the standard_conforming_strings setting, so
863 * we know how to escape strings.
865 AH->encoding = PQclientEncoding(conn);
867 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
868 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
870 /* Set the role if requested */
871 if (use_role && AH->remoteVersion >= 80100)
873 PQExpBuffer query = createPQExpBuffer();
875 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
876 ExecuteSqlStatement(AH, query->data);
877 destroyPQExpBuffer(query);
880 /* Set the datestyle to ISO to ensure the dump's portability */
881 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
883 /* Likewise, avoid using sql_standard intervalstyle */
884 if (AH->remoteVersion >= 80400)
885 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
888 * If supported, set extra_float_digits so that we can dump float data
889 * exactly (given correctly implemented float I/O code, anyway)
891 if (AH->remoteVersion >= 90000)
892 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
893 else if (AH->remoteVersion >= 70400)
894 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
897 * If synchronized scanning is supported, disable it, to prevent
898 * unpredictable changes in row ordering across a dump and reload.
900 if (AH->remoteVersion >= 80300)
901 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
904 * Disable timeouts if supported.
906 if (AH->remoteVersion >= 70300)
907 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
910 * Quote all identifiers, if requested.
912 if (quote_all_identifiers && AH->remoteVersion >= 90100)
913 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
917 parseArchiveFormat(const char *format, ArchiveMode *mode)
919 ArchiveFormat archiveFormat;
921 *mode = archModeWrite;
923 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
925 /* This is used by pg_dumpall, and is not documented */
926 archiveFormat = archNull;
927 *mode = archModeAppend;
929 else if (pg_strcasecmp(format, "c") == 0)
930 archiveFormat = archCustom;
931 else if (pg_strcasecmp(format, "custom") == 0)
932 archiveFormat = archCustom;
933 else if (pg_strcasecmp(format, "d") == 0)
934 archiveFormat = archDirectory;
935 else if (pg_strcasecmp(format, "directory") == 0)
936 archiveFormat = archDirectory;
937 else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
940 * Dump files into the current directory; for demonstration only, not
943 archiveFormat = archFiles;
944 else if (pg_strcasecmp(format, "p") == 0)
945 archiveFormat = archNull;
946 else if (pg_strcasecmp(format, "plain") == 0)
947 archiveFormat = archNull;
948 else if (pg_strcasecmp(format, "t") == 0)
949 archiveFormat = archTar;
950 else if (pg_strcasecmp(format, "tar") == 0)
951 archiveFormat = archTar;
953 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
954 return archiveFormat;
958 * Find the OIDs of all schemas matching the given list of patterns,
959 * and append them to the given OID list.
962 expand_schema_name_patterns(Archive *fout,
963 SimpleStringList *patterns,
968 SimpleStringListCell *cell;
971 if (patterns->head == NULL)
972 return; /* nothing to do */
974 if (fout->remoteVersion < 70300)
975 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
977 query = createPQExpBuffer();
980 * We use UNION ALL rather than UNION; this might sometimes result in
981 * duplicate entries in the OID list, but we don't care.
984 for (cell = patterns->head; cell; cell = cell->next)
986 if (cell != patterns->head)
987 appendPQExpBuffer(query, "UNION ALL\n");
988 appendPQExpBuffer(query,
989 "SELECT oid FROM pg_catalog.pg_namespace n\n");
990 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
991 false, NULL, "n.nspname", NULL, NULL);
994 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
996 for (i = 0; i < PQntuples(res); i++)
998 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1002 destroyPQExpBuffer(query);
1006 * Find the OIDs of all tables matching the given list of patterns,
1007 * and append them to the given OID list.
1010 expand_table_name_patterns(Archive *fout,
1011 SimpleStringList *patterns, SimpleOidList *oids)
1015 SimpleStringListCell *cell;
1018 if (patterns->head == NULL)
1019 return; /* nothing to do */
1021 query = createPQExpBuffer();
1024 * We use UNION ALL rather than UNION; this might sometimes result in
1025 * duplicate entries in the OID list, but we don't care.
1028 for (cell = patterns->head; cell; cell = cell->next)
1030 if (cell != patterns->head)
1031 appendPQExpBuffer(query, "UNION ALL\n");
1032 appendPQExpBuffer(query,
1034 "\nFROM pg_catalog.pg_class c"
1035 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1036 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1037 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1038 RELKIND_FOREIGN_TABLE);
1039 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1040 false, "n.nspname", "c.relname", NULL,
1041 "pg_catalog.pg_table_is_visible(c.oid)");
1044 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1046 for (i = 0; i < PQntuples(res); i++)
1048 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1052 destroyPQExpBuffer(query);
1056 * selectDumpableNamespace: policy-setting subroutine
1057 * Mark a namespace as to be dumped or not
1060 selectDumpableNamespace(NamespaceInfo *nsinfo)
1063 * If specific tables are being dumped, do not dump any complete
1064 * namespaces. If specific namespaces are being dumped, dump just those
1065 * namespaces. Otherwise, dump all non-system namespaces.
1067 if (table_include_oids.head != NULL)
1068 nsinfo->dobj.dump = false;
1069 else if (schema_include_oids.head != NULL)
1070 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1071 nsinfo->dobj.catId.oid);
1072 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1073 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1074 nsinfo->dobj.dump = false;
1076 nsinfo->dobj.dump = true;
1079 * In any case, a namespace can be excluded by an exclusion switch
1081 if (nsinfo->dobj.dump &&
1082 simple_oid_list_member(&schema_exclude_oids,
1083 nsinfo->dobj.catId.oid))
1084 nsinfo->dobj.dump = false;
1088 * selectDumpableTable: policy-setting subroutine
1089 * Mark a table as to be dumped or not
1092 selectDumpableTable(TableInfo *tbinfo)
1095 * If specific tables are being dumped, dump just those tables; else, dump
1096 * according to the parent namespace's dump flag.
1098 if (table_include_oids.head != NULL)
1099 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1100 tbinfo->dobj.catId.oid);
1102 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1105 * In any case, a table can be excluded by an exclusion switch
1107 if (tbinfo->dobj.dump &&
1108 simple_oid_list_member(&table_exclude_oids,
1109 tbinfo->dobj.catId.oid))
1110 tbinfo->dobj.dump = false;
1114 * selectDumpableType: policy-setting subroutine
1115 * Mark a type as to be dumped or not
1117 * If it's a table's rowtype or an autogenerated array type, we also apply a
1118 * special type code to facilitate sorting into the desired order. (We don't
1119 * want to consider those to be ordinary types because that would bring tables
1120 * up into the datatype part of the dump order.) We still set the object's
1121 * dump flag; that's not going to cause the dummy type to be dumped, but we
1122 * need it so that casts involving such types will be dumped correctly -- see
1123 * dumpCast. This means the flag should be set the same as for the underlying
1124 * object (the table or base type).
1127 selectDumpableType(TypeInfo *tyinfo)
1129 /* skip complex types, except for standalone composite types */
1130 if (OidIsValid(tyinfo->typrelid) &&
1131 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1133 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1135 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1136 if (tytable != NULL)
1137 tyinfo->dobj.dump = tytable->dobj.dump;
1139 tyinfo->dobj.dump = false;
1143 /* skip auto-generated array types */
1144 if (tyinfo->isArray)
1146 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1148 * Fall through to set the dump flag; we assume that the subsequent
1149 * rules will do the same thing as they would for the array's base
1150 * type. (We cannot reliably look up the base type here, since
1151 * getTypes may not have processed it yet.)
1155 /* dump only types in dumpable namespaces */
1156 if (!tyinfo->dobj.namespace->dobj.dump)
1157 tyinfo->dobj.dump = false;
1159 /* skip undefined placeholder types */
1160 else if (!tyinfo->isDefined)
1161 tyinfo->dobj.dump = false;
1164 tyinfo->dobj.dump = true;
1168 * selectDumpableDefaultACL: policy-setting subroutine
1169 * Mark a default ACL as to be dumped or not
1171 * For per-schema default ACLs, dump if the schema is to be dumped.
1172 * Otherwise dump if we are dumping "everything". Note that dataOnly
1173 * and aclsSkip are checked separately.
1176 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1178 if (dinfo->dobj.namespace)
1179 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1181 dinfo->dobj.dump = include_everything;
1185 * selectDumpableExtension: policy-setting subroutine
1186 * Mark an extension as to be dumped or not
1188 * Normally, we dump all extensions, or none of them if include_everything
1189 * is false (i.e., a --schema or --table switch was given). However, in
1190 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1191 * assume those will already be installed in the target database. We identify
1192 * such extensions by their having OIDs in the range reserved for initdb.
1195 selectDumpableExtension(ExtensionInfo *extinfo)
1197 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1198 extinfo->dobj.dump = false;
1200 extinfo->dobj.dump = include_everything;
1204 * selectDumpableObject: policy-setting subroutine
1205 * Mark a generic dumpable object as to be dumped or not
1207 * Use this only for object types without a special-case routine above.
1210 selectDumpableObject(DumpableObject *dobj)
1213 * Default policy is to dump if parent namespace is dumpable, or always
1214 * for non-namespace-associated items.
1216 if (dobj->namespace)
1217 dobj->dump = dobj->namespace->dobj.dump;
1223 * Dump a table's contents for loading using the COPY command
1224 * - this routine is called by the Archiver when it wants the table
1229 dumpTableData_copy(Archive *fout, void *dcontext)
1231 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1232 TableInfo *tbinfo = tdinfo->tdtable;
1233 const char *classname = tbinfo->dobj.name;
1234 const bool hasoids = tbinfo->hasoids;
1235 const bool oids = tdinfo->oids;
1236 PQExpBuffer q = createPQExpBuffer();
1237 PGconn *conn = GetConnection(fout);
1241 const char *column_list;
1244 write_msg(NULL, "dumping contents of table %s\n", classname);
1247 * Make sure we are in proper schema. We will qualify the table name
1248 * below anyway (in case its name conflicts with a pg_catalog table); but
1249 * this ensures reproducible results in case the table contains regproc,
1250 * regclass, etc columns.
1252 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1255 * If possible, specify the column list explicitly so that we have no
1256 * possibility of retrieving data in the wrong column order. (The default
1257 * column ordering of COPY will not be what we want in certain corner
1258 * cases involving ADD COLUMN and inheritance.)
1260 if (fout->remoteVersion >= 70300)
1261 column_list = fmtCopyColumnList(tbinfo);
1263 column_list = ""; /* can't select columns in COPY */
1265 if (oids && hasoids)
1267 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1268 fmtQualifiedId(fout,
1269 tbinfo->dobj.namespace->dobj.name,
1273 else if (tdinfo->filtercond)
1275 /* Note: this syntax is only supported in 8.2 and up */
1276 appendPQExpBufferStr(q, "COPY (SELECT ");
1277 /* klugery to get rid of parens in column list */
1278 if (strlen(column_list) > 2)
1280 appendPQExpBufferStr(q, column_list + 1);
1281 q->data[q->len - 1] = ' ';
1284 appendPQExpBufferStr(q, "* ");
1285 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1286 fmtQualifiedId(fout,
1287 tbinfo->dobj.namespace->dobj.name,
1289 tdinfo->filtercond);
1293 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1294 fmtQualifiedId(fout,
1295 tbinfo->dobj.namespace->dobj.name,
1299 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1304 ret = PQgetCopyData(conn, ©buf, 0);
1307 break; /* done or error */
1311 WriteData(fout, copybuf, ret);
1318 * There was considerable discussion in late July, 2000 regarding
1319 * slowing down pg_dump when backing up large tables. Users with both
1320 * slow & fast (multi-processor) machines experienced performance
1321 * degradation when doing a backup.
1323 * Initial attempts based on sleeping for a number of ms for each ms
1324 * of work were deemed too complex, then a simple 'sleep in each loop'
1325 * implementation was suggested. The latter failed because the loop
1326 * was too tight. Finally, the following was implemented:
1328 * If throttle is non-zero, then
1329 * See how long since the last sleep.
1330 * Work out how long to sleep (based on ratio).
1331 * If sleep is more than 100ms, then
1337 * where the throttle value was the number of ms to sleep per ms of
1338 * work. The calculation was done in each loop.
1340 * Most of the hard work is done in the backend, and this solution
1341 * still did not work particularly well: on slow machines, the ratio
1342 * was 50:1, and on medium paced machines, 1:1, and on fast
1343 * multi-processor machines, it had little or no effect, for reasons
1344 * that were unclear.
1346 * Further discussion ensued, and the proposal was dropped.
1348 * For those people who want this feature, it can be implemented using
1349 * gettimeofday in each loop, calculating the time since last sleep,
1350 * multiplying that by the sleep ratio, then if the result is more
1351 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1352 * function to sleep for a subsecond period ie.
1354 * select(0, NULL, NULL, NULL, &tvi);
1356 * This will return after the interval specified in the structure tvi.
1357 * Finally, call gettimeofday again to save the 'last sleep time'.
1361 archprintf(fout, "\\.\n\n\n");
1365 /* copy data transfer failed */
1366 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1367 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1368 write_msg(NULL, "The command was: %s\n", q->data);
1372 /* Check command status and return to normal libpq state */
1373 res = PQgetResult(conn);
1374 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1376 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1377 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1378 write_msg(NULL, "The command was: %s\n", q->data);
1383 destroyPQExpBuffer(q);
1388 * Dump table data using INSERT commands.
1390 * Caution: when we restore from an archive file direct to database, the
1391 * INSERT commands emitted by this function have to be parsed by
1392 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1393 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1396 dumpTableData_insert(Archive *fout, void *dcontext)
1398 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1399 TableInfo *tbinfo = tdinfo->tdtable;
1400 const char *classname = tbinfo->dobj.name;
1401 PQExpBuffer q = createPQExpBuffer();
1408 * Make sure we are in proper schema. We will qualify the table name
1409 * below anyway (in case its name conflicts with a pg_catalog table); but
1410 * this ensures reproducible results in case the table contains regproc,
1411 * regclass, etc columns.
1413 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1415 if (fout->remoteVersion >= 70100)
1417 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1418 "SELECT * FROM ONLY %s",
1419 fmtQualifiedId(fout,
1420 tbinfo->dobj.namespace->dobj.name,
1425 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1427 fmtQualifiedId(fout,
1428 tbinfo->dobj.namespace->dobj.name,
1431 if (tdinfo->filtercond)
1432 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1434 ExecuteSqlStatement(fout, q->data);
1438 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1440 nfields = PQnfields(res);
1441 for (tuple = 0; tuple < PQntuples(res); tuple++)
1443 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1446 /* corner case for zero-column table */
1447 archprintf(fout, "DEFAULT VALUES;\n");
1452 resetPQExpBuffer(q);
1453 appendPQExpBuffer(q, "(");
1454 for (field = 0; field < nfields; field++)
1457 appendPQExpBuffer(q, ", ");
1458 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1460 appendPQExpBuffer(q, ") ");
1461 archputs(q->data, fout);
1463 archprintf(fout, "VALUES (");
1464 for (field = 0; field < nfields; field++)
1467 archprintf(fout, ", ");
1468 if (PQgetisnull(res, tuple, field))
1470 archprintf(fout, "NULL");
1474 /* XXX This code is partially duplicated in ruleutils.c */
1475 switch (PQftype(res, field))
1486 * These types are printed without quotes unless
1487 * they contain values that aren't accepted by the
1488 * scanner unquoted (e.g., 'NaN'). Note that
1489 * strtod() and friends might accept NaN, so we
1490 * can't use that to test.
1492 * In reality we only need to defend against
1493 * infinity and NaN, so we need not get too crazy
1494 * about pattern matching here.
1496 const char *s = PQgetvalue(res, tuple, field);
1498 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1499 archprintf(fout, "%s", s);
1501 archprintf(fout, "'%s'", s);
1507 archprintf(fout, "B'%s'",
1508 PQgetvalue(res, tuple, field));
1512 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1513 archprintf(fout, "true");
1515 archprintf(fout, "false");
1519 /* All other types are printed as string literals. */
1520 resetPQExpBuffer(q);
1521 appendStringLiteralAH(q,
1522 PQgetvalue(res, tuple, field),
1524 archputs(q->data, fout);
1528 archprintf(fout, ");\n");
1531 if (PQntuples(res) <= 0)
1539 archprintf(fout, "\n\n");
1541 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1543 destroyPQExpBuffer(q);
1550 * dump the contents of a single table
1552 * Actually, this just makes an ArchiveEntry for the table contents.
1555 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1557 TableInfo *tbinfo = tdinfo->tdtable;
1558 PQExpBuffer copyBuf = createPQExpBuffer();
1559 DataDumperPtr dumpFn;
1564 /* Dump/restore using COPY */
1565 dumpFn = dumpTableData_copy;
1566 /* must use 2 steps here 'cause fmtId is nonreentrant */
1567 appendPQExpBuffer(copyBuf, "COPY %s ",
1568 fmtId(tbinfo->dobj.name));
1569 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1570 fmtCopyColumnList(tbinfo),
1571 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1572 copyStmt = copyBuf->data;
1576 /* Restore using INSERT */
1577 dumpFn = dumpTableData_insert;
1581 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1582 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1583 NULL, tbinfo->rolname,
1584 false, "TABLE DATA", SECTION_DATA,
1586 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1589 destroyPQExpBuffer(copyBuf);
1594 * set up dumpable objects representing the contents of tables
1597 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1601 for (i = 0; i < numTables; i++)
1603 if (tblinfo[i].dobj.dump)
1604 makeTableDataInfo(&(tblinfo[i]), oids);
1609 * Make a dumpable object for the data of this specific table
1611 * Note: we make a TableDataInfo if and only if we are going to dump the
1612 * table data; the "dump" flag in such objects isn't used.
1615 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1617 TableDataInfo *tdinfo;
1620 * Nothing to do if we already decided to dump the table. This will
1621 * happen for "config" tables.
1623 if (tbinfo->dataObj != NULL)
1626 /* Skip VIEWs (no data to dump) */
1627 if (tbinfo->relkind == RELKIND_VIEW)
1629 /* Skip SEQUENCEs (handled elsewhere) */
1630 if (tbinfo->relkind == RELKIND_SEQUENCE)
1632 /* Skip FOREIGN TABLEs (no data to dump) */
1633 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1636 /* Don't dump data in unlogged tables, if so requested */
1637 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1638 no_unlogged_table_data)
1641 /* Check that the data is not explicitly excluded */
1642 if (simple_oid_list_member(&tabledata_exclude_oids,
1643 tbinfo->dobj.catId.oid))
1646 /* OK, let's dump it */
1647 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1649 tdinfo->dobj.objType = DO_TABLE_DATA;
1652 * Note: use tableoid 0 so that this object won't be mistaken for
1653 * something that pg_depend entries apply to.
1655 tdinfo->dobj.catId.tableoid = 0;
1656 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1657 AssignDumpId(&tdinfo->dobj);
1658 tdinfo->dobj.name = tbinfo->dobj.name;
1659 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1660 tdinfo->tdtable = tbinfo;
1661 tdinfo->oids = oids;
1662 tdinfo->filtercond = NULL; /* might get set later */
1663 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1665 tbinfo->dataObj = tdinfo;
1669 * getTableDataFKConstraints -
1670 * add dump-order dependencies reflecting foreign key constraints
1672 * This code is executed only in a data-only dump --- in schema+data dumps
1673 * we handle foreign key issues by not creating the FK constraints until
1674 * after the data is loaded. In a data-only dump, however, we want to
1675 * order the table data objects in such a way that a table's referenced
1676 * tables are restored first. (In the presence of circular references or
1677 * self-references this may be impossible; we'll detect and complain about
1678 * that during the dependency sorting step.)
1681 getTableDataFKConstraints(void)
1683 DumpableObject **dobjs;
1687 /* Search through all the dumpable objects for FK constraints */
1688 getDumpableObjects(&dobjs, &numObjs);
1689 for (i = 0; i < numObjs; i++)
1691 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1693 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1696 /* Not interesting unless both tables are to be dumped */
1697 if (cinfo->contable == NULL ||
1698 cinfo->contable->dataObj == NULL)
1700 ftable = findTableByOid(cinfo->confrelid);
1701 if (ftable == NULL ||
1702 ftable->dataObj == NULL)
1706 * Okay, make referencing table's TABLE_DATA object depend on the
1707 * referenced table's TABLE_DATA object.
1709 addObjectDependency(&cinfo->contable->dataObj->dobj,
1710 ftable->dataObj->dobj.dumpId);
1718 * guessConstraintInheritance:
1719 * In pre-8.4 databases, we can't tell for certain which constraints
1720 * are inherited. We assume a CHECK constraint is inherited if its name
1721 * matches the name of any constraint in the parent. Originally this code
1722 * tried to compare the expression texts, but that can fail for various
1723 * reasons --- for example, if the parent and child tables are in different
1724 * schemas, reverse-listing of function calls may produce different text
1725 * (schema-qualified or not) depending on search path.
1727 * In 8.4 and up we can rely on the conislocal field to decide which
1728 * constraints must be dumped; much safer.
1730 * This function assumes all conislocal flags were initialized to TRUE.
1731 * It clears the flag on anything that seems to be inherited.
1734 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1740 for (i = 0; i < numTables; i++)
1742 TableInfo *tbinfo = &(tblinfo[i]);
1744 TableInfo **parents;
1747 /* Sequences and views never have parents */
1748 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1749 tbinfo->relkind == RELKIND_VIEW)
1752 /* Don't bother computing anything for non-target tables, either */
1753 if (!tbinfo->dobj.dump)
1756 numParents = tbinfo->numParents;
1757 parents = tbinfo->parents;
1759 if (numParents == 0)
1760 continue; /* nothing to see here, move along */
1762 /* scan for inherited CHECK constraints */
1763 for (j = 0; j < tbinfo->ncheck; j++)
1765 ConstraintInfo *constr;
1767 constr = &(tbinfo->checkexprs[j]);
1769 for (k = 0; k < numParents; k++)
1773 parent = parents[k];
1774 for (l = 0; l < parent->ncheck; l++)
1776 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1778 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1780 constr->conislocal = false;
1784 if (!constr->conislocal)
1794 * dump the database definition
1797 dumpDatabase(Archive *fout)
1799 PQExpBuffer dbQry = createPQExpBuffer();
1800 PQExpBuffer delQry = createPQExpBuffer();
1801 PQExpBuffer creaQry = createPQExpBuffer();
1802 PGconn *conn = GetConnection(fout);
1814 const char *datname,
1822 datname = PQdb(conn);
1825 write_msg(NULL, "saving database definition\n");
1827 /* Make sure we are in proper schema */
1828 selectSourceSchema(fout, "pg_catalog");
1830 /* Get the database owner and parameters from pg_database */
1831 if (fout->remoteVersion >= 80400)
1833 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1834 "(%s datdba) AS dba, "
1835 "pg_encoding_to_char(encoding) AS encoding, "
1836 "datcollate, datctype, datfrozenxid, "
1837 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1838 "shobj_description(oid, 'pg_database') AS description "
1843 appendStringLiteralAH(dbQry, datname, fout);
1845 else if (fout->remoteVersion >= 80200)
1847 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1848 "(%s datdba) AS dba, "
1849 "pg_encoding_to_char(encoding) AS encoding, "
1850 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1851 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1852 "shobj_description(oid, 'pg_database') AS description "
1857 appendStringLiteralAH(dbQry, datname, fout);
1859 else if (fout->remoteVersion >= 80000)
1861 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1862 "(%s datdba) AS dba, "
1863 "pg_encoding_to_char(encoding) AS encoding, "
1864 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1865 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1869 appendStringLiteralAH(dbQry, datname, fout);
1871 else if (fout->remoteVersion >= 70100)
1873 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1874 "(%s datdba) AS dba, "
1875 "pg_encoding_to_char(encoding) AS encoding, "
1876 "NULL AS datcollate, NULL AS datctype, "
1877 "0 AS datfrozenxid, "
1878 "NULL AS tablespace "
1882 appendStringLiteralAH(dbQry, datname, fout);
1886 appendPQExpBuffer(dbQry, "SELECT "
1887 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1889 "(%s datdba) AS dba, "
1890 "pg_encoding_to_char(encoding) AS encoding, "
1891 "NULL AS datcollate, NULL AS datctype, "
1892 "0 AS datfrozenxid, "
1893 "NULL AS tablespace "
1897 appendStringLiteralAH(dbQry, datname, fout);
1900 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1902 i_tableoid = PQfnumber(res, "tableoid");
1903 i_oid = PQfnumber(res, "oid");
1904 i_dba = PQfnumber(res, "dba");
1905 i_encoding = PQfnumber(res, "encoding");
1906 i_collate = PQfnumber(res, "datcollate");
1907 i_ctype = PQfnumber(res, "datctype");
1908 i_frozenxid = PQfnumber(res, "datfrozenxid");
1909 i_tablespace = PQfnumber(res, "tablespace");
1911 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1912 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1913 dba = PQgetvalue(res, 0, i_dba);
1914 encoding = PQgetvalue(res, 0, i_encoding);
1915 collate = PQgetvalue(res, 0, i_collate);
1916 ctype = PQgetvalue(res, 0, i_ctype);
1917 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1918 tablespace = PQgetvalue(res, 0, i_tablespace);
1920 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1922 if (strlen(encoding) > 0)
1924 appendPQExpBuffer(creaQry, " ENCODING = ");
1925 appendStringLiteralAH(creaQry, encoding, fout);
1927 if (strlen(collate) > 0)
1929 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1930 appendStringLiteralAH(creaQry, collate, fout);
1932 if (strlen(ctype) > 0)
1934 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1935 appendStringLiteralAH(creaQry, ctype, fout);
1937 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1938 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1940 appendPQExpBuffer(creaQry, ";\n");
1944 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1945 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1946 "SET datfrozenxid = '%u'\n"
1949 appendStringLiteralAH(creaQry, datname, fout);
1950 appendPQExpBuffer(creaQry, ";\n");
1954 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1957 dbDumpId = createDumpId();
1960 dbCatId, /* catalog ID */
1961 dbDumpId, /* dump ID */
1963 NULL, /* Namespace */
1964 NULL, /* Tablespace */
1966 false, /* with oids */
1967 "DATABASE", /* Desc */
1968 SECTION_PRE_DATA, /* Section */
1969 creaQry->data, /* Create */
1970 delQry->data, /* Del */
1975 NULL); /* Dumper Arg */
1978 * pg_largeobject and pg_largeobject_metadata come from the old system
1979 * intact, so set their relfrozenxids.
1984 PQExpBuffer loFrozenQry = createPQExpBuffer();
1985 PQExpBuffer loOutQry = createPQExpBuffer();
1991 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1992 "FROM pg_catalog.pg_class\n"
1993 "WHERE oid = %u;\n",
1994 LargeObjectRelationId);
1996 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1998 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2000 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2001 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2002 "SET relfrozenxid = '%u'\n"
2003 "WHERE oid = %u;\n",
2004 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2005 LargeObjectRelationId);
2006 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2007 "pg_largeobject", NULL, NULL, "",
2008 false, "pg_largeobject", SECTION_PRE_DATA,
2009 loOutQry->data, "", NULL,
2016 * pg_largeobject_metadata
2018 if (fout->remoteVersion >= 90000)
2020 resetPQExpBuffer(loFrozenQry);
2021 resetPQExpBuffer(loOutQry);
2023 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2024 "FROM pg_catalog.pg_class\n"
2025 "WHERE oid = %u;\n",
2026 LargeObjectMetadataRelationId);
2028 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2030 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2032 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2033 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2034 "SET relfrozenxid = '%u'\n"
2035 "WHERE oid = %u;\n",
2036 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2037 LargeObjectMetadataRelationId);
2038 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2039 "pg_largeobject_metadata", NULL, NULL, "",
2040 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2041 loOutQry->data, "", NULL,
2048 destroyPQExpBuffer(loFrozenQry);
2049 destroyPQExpBuffer(loOutQry);
2052 /* Dump DB comment if any */
2053 if (fout->remoteVersion >= 80200)
2056 * 8.2 keeps comments on shared objects in a shared table, so we
2057 * cannot use the dumpComment used for other database objects.
2059 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2061 if (comment && strlen(comment))
2063 resetPQExpBuffer(dbQry);
2066 * Generates warning when loaded into a differently-named
2069 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2070 appendStringLiteralAH(dbQry, comment, fout);
2071 appendPQExpBuffer(dbQry, ";\n");
2073 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2074 dba, false, "COMMENT", SECTION_NONE,
2075 dbQry->data, "", NULL,
2076 &dbDumpId, 1, NULL, NULL);
2081 resetPQExpBuffer(dbQry);
2082 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2083 dumpComment(fout, dbQry->data, NULL, "",
2084 dbCatId, 0, dbDumpId);
2089 /* Dump shared security label. */
2090 if (!no_security_labels && fout->remoteVersion >= 90200)
2092 PQExpBuffer seclabelQry = createPQExpBuffer();
2094 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2095 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2096 resetPQExpBuffer(seclabelQry);
2097 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2098 if (strlen(seclabelQry->data))
2099 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2100 dba, false, "SECURITY LABEL", SECTION_NONE,
2101 seclabelQry->data, "", NULL,
2102 &dbDumpId, 1, NULL, NULL);
2103 destroyPQExpBuffer(seclabelQry);
2106 destroyPQExpBuffer(dbQry);
2107 destroyPQExpBuffer(delQry);
2108 destroyPQExpBuffer(creaQry);
2113 * dumpEncoding: put the correct encoding into the archive
2116 dumpEncoding(Archive *AH)
2118 const char *encname = pg_encoding_to_char(AH->encoding);
2119 PQExpBuffer qry = createPQExpBuffer();
2122 write_msg(NULL, "saving encoding = %s\n", encname);
2124 appendPQExpBuffer(qry, "SET client_encoding = ");
2125 appendStringLiteralAH(qry, encname, AH);
2126 appendPQExpBuffer(qry, ";\n");
2128 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2129 "ENCODING", NULL, NULL, "",
2130 false, "ENCODING", SECTION_PRE_DATA,
2131 qry->data, "", NULL,
2135 destroyPQExpBuffer(qry);
2140 * dumpStdStrings: put the correct escape string behavior into the archive
2143 dumpStdStrings(Archive *AH)
2145 const char *stdstrings = AH->std_strings ? "on" : "off";
2146 PQExpBuffer qry = createPQExpBuffer();
2149 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2152 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2155 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2156 "STDSTRINGS", NULL, NULL, "",
2157 false, "STDSTRINGS", SECTION_PRE_DATA,
2158 qry->data, "", NULL,
2162 destroyPQExpBuffer(qry);
2168 * Collect schema-level data about large objects
2171 getBlobs(Archive *fout)
2173 PQExpBuffer blobQry = createPQExpBuffer();
2175 DumpableObject *bdata;
2180 /* Verbose message */
2182 write_msg(NULL, "reading large objects\n");
2184 /* Make sure we are in proper schema */
2185 selectSourceSchema(fout, "pg_catalog");
2187 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2188 if (fout->remoteVersion >= 90000)
2189 appendPQExpBuffer(blobQry,
2190 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2191 " FROM pg_largeobject_metadata",
2193 else if (fout->remoteVersion >= 70100)
2194 appendPQExpBuffer(blobQry,
2195 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2196 " FROM pg_largeobject");
2198 appendPQExpBuffer(blobQry,
2199 "SELECT oid, NULL::oid, NULL::oid"
2200 " FROM pg_class WHERE relkind = 'l'");
2202 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2204 ntups = PQntuples(res);
2208 * Each large object has its own BLOB archive entry.
2210 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2212 for (i = 0; i < ntups; i++)
2214 binfo[i].dobj.objType = DO_BLOB;
2215 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2216 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2217 AssignDumpId(&binfo[i].dobj);
2219 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2220 if (!PQgetisnull(res, i, 1))
2221 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2223 binfo[i].rolname = "";
2224 if (!PQgetisnull(res, i, 2))
2225 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2227 binfo[i].blobacl = NULL;
2231 * If we have any large objects, a "BLOBS" archive entry is needed.
2232 * This is just a placeholder for sorting; it carries no data now.
2234 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2235 bdata->objType = DO_BLOB_DATA;
2236 bdata->catId = nilCatalogId;
2237 AssignDumpId(bdata);
2238 bdata->name = pg_strdup("BLOBS");
2242 destroyPQExpBuffer(blobQry);
2248 * dump the definition (metadata) of the given large object
2251 dumpBlob(Archive *fout, BlobInfo *binfo)
2253 PQExpBuffer cquery = createPQExpBuffer();
2254 PQExpBuffer dquery = createPQExpBuffer();
2256 appendPQExpBuffer(cquery,
2257 "SELECT pg_catalog.lo_create('%s');\n",
2260 appendPQExpBuffer(dquery,
2261 "SELECT pg_catalog.lo_unlink('%s');\n",
2264 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2267 binfo->rolname, false,
2268 "BLOB", SECTION_PRE_DATA,
2269 cquery->data, dquery->data, NULL,
2270 binfo->dobj.dependencies, binfo->dobj.nDeps,
2273 /* set up tag for comment and/or ACL */
2274 resetPQExpBuffer(cquery);
2275 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2277 /* Dump comment if any */
2278 dumpComment(fout, cquery->data,
2279 NULL, binfo->rolname,
2280 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2282 /* Dump security label if any */
2283 dumpSecLabel(fout, cquery->data,
2284 NULL, binfo->rolname,
2285 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2287 /* Dump ACL if any */
2289 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2290 binfo->dobj.name, NULL, cquery->data,
2291 NULL, binfo->rolname, binfo->blobacl);
2293 destroyPQExpBuffer(cquery);
2294 destroyPQExpBuffer(dquery);
2299 * dump the data contents of all large objects
2302 dumpBlobs(Archive *fout, void *arg)
2304 const char *blobQry;
2305 const char *blobFetchQry;
2306 PGconn *conn = GetConnection(fout);
2308 char buf[LOBBUFSIZE];
2314 write_msg(NULL, "saving large objects\n");
2316 /* Make sure we are in proper schema */
2317 selectSourceSchema(fout, "pg_catalog");
2320 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2321 * the already-in-memory dumpable objects instead...
2323 if (fout->remoteVersion >= 90000)
2324 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2325 else if (fout->remoteVersion >= 70100)
2326 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2328 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2330 ExecuteSqlStatement(fout, blobQry);
2332 /* Command to fetch from cursor */
2333 blobFetchQry = "FETCH 1000 IN bloboid";
2338 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2340 /* Process the tuples, if any */
2341 ntups = PQntuples(res);
2342 for (i = 0; i < ntups; i++)
2347 blobOid = atooid(PQgetvalue(res, i, 0));
2349 loFd = lo_open(conn, blobOid, INV_READ);
2351 exit_horribly(NULL, "could not open large object %u: %s",
2352 blobOid, PQerrorMessage(conn));
2354 StartBlob(fout, blobOid);
2356 /* Now read it in chunks, sending data to archive */
2359 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2361 exit_horribly(NULL, "error reading large object %u: %s",
2362 blobOid, PQerrorMessage(conn));
2364 WriteData(fout, buf, cnt);
2367 lo_close(conn, loFd);
2369 EndBlob(fout, blobOid);
2373 } while (ntups > 0);
2381 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2382 PQExpBuffer upgrade_buffer,
2385 PQExpBuffer upgrade_query = createPQExpBuffer();
2386 PGresult *upgrade_res;
2387 Oid pg_type_array_oid;
2389 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2390 appendPQExpBuffer(upgrade_buffer,
2391 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2394 /* we only support old >= 8.3 for binary upgrades */
2395 appendPQExpBuffer(upgrade_query,
2397 "FROM pg_catalog.pg_type "
2398 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2401 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2403 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2405 if (OidIsValid(pg_type_array_oid))
2407 appendPQExpBuffer(upgrade_buffer,
2408 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2409 appendPQExpBuffer(upgrade_buffer,
2410 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2414 PQclear(upgrade_res);
2415 destroyPQExpBuffer(upgrade_query);
2419 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2420 PQExpBuffer upgrade_buffer,
2423 PQExpBuffer upgrade_query = createPQExpBuffer();
2424 PGresult *upgrade_res;
2426 bool toast_set = false;
2428 /* we only support old >= 8.3 for binary upgrades */
2429 appendPQExpBuffer(upgrade_query,
2430 "SELECT c.reltype AS crel, t.reltype AS trel "
2431 "FROM pg_catalog.pg_class c "
2432 "LEFT JOIN pg_catalog.pg_class t ON "
2433 " (c.reltoastrelid = t.oid) "
2434 "WHERE c.oid = '%u'::pg_catalog.oid;",
2437 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2439 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2441 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2444 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2446 /* Toast tables do not have pg_type array rows */
2447 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2448 PQfnumber(upgrade_res, "trel")));
2450 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2451 appendPQExpBuffer(upgrade_buffer,
2452 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2458 PQclear(upgrade_res);
2459 destroyPQExpBuffer(upgrade_query);
2465 binary_upgrade_set_pg_class_oids(Archive *fout,
2466 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2469 PQExpBuffer upgrade_query = createPQExpBuffer();
2470 PGresult *upgrade_res;
2471 Oid pg_class_reltoastrelid;
2472 Oid pg_class_reltoastidxid;
2474 appendPQExpBuffer(upgrade_query,
2475 "SELECT c.reltoastrelid, t.reltoastidxid "
2476 "FROM pg_catalog.pg_class c LEFT JOIN "
2477 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2478 "WHERE c.oid = '%u'::pg_catalog.oid;",
2481 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2483 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2484 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2486 appendPQExpBuffer(upgrade_buffer,
2487 "\n-- For binary upgrade, must preserve pg_class oids\n");
2491 appendPQExpBuffer(upgrade_buffer,
2492 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2494 /* only tables have toast tables, not indexes */
2495 if (OidIsValid(pg_class_reltoastrelid))
2498 * One complexity is that the table definition might not require
2499 * the creation of a TOAST table, and the TOAST table might have
2500 * been created long after table creation, when the table was
2501 * loaded with wide data. By setting the TOAST oid we force
2502 * creation of the TOAST heap and TOAST index by the backend so we
2503 * can cleanly copy the files during binary upgrade.
2506 appendPQExpBuffer(upgrade_buffer,
2507 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2508 pg_class_reltoastrelid);
2510 /* every toast table has an index */
2511 appendPQExpBuffer(upgrade_buffer,
2512 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2513 pg_class_reltoastidxid);
2517 appendPQExpBuffer(upgrade_buffer,
2518 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2521 appendPQExpBuffer(upgrade_buffer, "\n");
2523 PQclear(upgrade_res);
2524 destroyPQExpBuffer(upgrade_query);
2528 * If the DumpableObject is a member of an extension, add a suitable
2529 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2532 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2533 DumpableObject *dobj,
2534 const char *objlabel)
2536 DumpableObject *extobj = NULL;
2539 if (!dobj->ext_member)
2543 * Find the parent extension. We could avoid this search if we wanted to
2544 * add a link field to DumpableObject, but the space costs of that would
2545 * be considerable. We assume that member objects could only have a
2546 * direct dependency on their own extension, not any others.
2548 for (i = 0; i < dobj->nDeps; i++)
2550 extobj = findObjectByDumpId(dobj->dependencies[i]);
2551 if (extobj && extobj->objType == DO_EXTENSION)
2556 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2558 appendPQExpBuffer(upgrade_buffer,
2559 "\n-- For binary upgrade, handle extension membership the hard way\n");
2560 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2561 fmtId(extobj->name),
2567 * read all namespaces in the system catalogs and return them in the
2568 * NamespaceInfo* structure
2570 * numNamespaces is set to the number of namespaces read in
2573 getNamespaces(Archive *fout, int *numNamespaces)
2579 NamespaceInfo *nsinfo;
2587 * Before 7.3, there are no real namespaces; create two dummy entries, one
2588 * for user stuff and one for system stuff.
2590 if (fout->remoteVersion < 70300)
2592 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2594 nsinfo[0].dobj.objType = DO_NAMESPACE;
2595 nsinfo[0].dobj.catId.tableoid = 0;
2596 nsinfo[0].dobj.catId.oid = 0;
2597 AssignDumpId(&nsinfo[0].dobj);
2598 nsinfo[0].dobj.name = pg_strdup("public");
2599 nsinfo[0].rolname = pg_strdup("");
2600 nsinfo[0].nspacl = pg_strdup("");
2602 selectDumpableNamespace(&nsinfo[0]);
2604 nsinfo[1].dobj.objType = DO_NAMESPACE;
2605 nsinfo[1].dobj.catId.tableoid = 0;
2606 nsinfo[1].dobj.catId.oid = 1;
2607 AssignDumpId(&nsinfo[1].dobj);
2608 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2609 nsinfo[1].rolname = pg_strdup("");
2610 nsinfo[1].nspacl = pg_strdup("");
2612 selectDumpableNamespace(&nsinfo[1]);
2614 g_namespaces = nsinfo;
2615 g_numNamespaces = *numNamespaces = 2;
2620 query = createPQExpBuffer();
2622 /* Make sure we are in proper schema */
2623 selectSourceSchema(fout, "pg_catalog");
2626 * we fetch all namespaces including system ones, so that every object we
2627 * read in can be linked to a containing namespace.
2629 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2630 "(%s nspowner) AS rolname, "
2631 "nspacl FROM pg_namespace",
2634 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2636 ntups = PQntuples(res);
2638 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2640 i_tableoid = PQfnumber(res, "tableoid");
2641 i_oid = PQfnumber(res, "oid");
2642 i_nspname = PQfnumber(res, "nspname");
2643 i_rolname = PQfnumber(res, "rolname");
2644 i_nspacl = PQfnumber(res, "nspacl");
2646 for (i = 0; i < ntups; i++)
2648 nsinfo[i].dobj.objType = DO_NAMESPACE;
2649 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2650 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2651 AssignDumpId(&nsinfo[i].dobj);
2652 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2653 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2654 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2656 /* Decide whether to dump this namespace */
2657 selectDumpableNamespace(&nsinfo[i]);
2659 if (strlen(nsinfo[i].rolname) == 0)
2660 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2661 nsinfo[i].dobj.name);
2665 destroyPQExpBuffer(query);
2667 g_namespaces = nsinfo;
2668 g_numNamespaces = *numNamespaces = ntups;
2675 * given a namespace OID and an object OID, look up the info read by
2678 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2679 * a system object or not. In 7.3 and later there is no guessing.
2681 static NamespaceInfo *
2682 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2686 if (fout->remoteVersion >= 70300)
2688 for (i = 0; i < g_numNamespaces; i++)
2690 NamespaceInfo *nsinfo = &g_namespaces[i];
2692 if (nsoid == nsinfo->dobj.catId.oid)
2695 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2699 /* This code depends on the layout set up by getNamespaces. */
2700 if (objoid > g_last_builtin_oid)
2701 i = 0; /* user object */
2703 i = 1; /* system object */
2704 return &g_namespaces[i];
2707 return NULL; /* keep compiler quiet */
2712 * read all extensions in the system catalogs and return them in the
2713 * ExtensionInfo* structure
2715 * numExtensions is set to the number of extensions read in
2718 getExtensions(Archive *fout, int *numExtensions)
2724 ExtensionInfo *extinfo;
2729 int i_extrelocatable;
2735 * Before 9.1, there are no extensions.
2737 if (fout->remoteVersion < 90100)
2743 query = createPQExpBuffer();
2745 /* Make sure we are in proper schema */
2746 selectSourceSchema(fout, "pg_catalog");
2748 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2749 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2750 "FROM pg_extension x "
2751 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2753 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2755 ntups = PQntuples(res);
2757 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2759 i_tableoid = PQfnumber(res, "tableoid");
2760 i_oid = PQfnumber(res, "oid");
2761 i_extname = PQfnumber(res, "extname");
2762 i_nspname = PQfnumber(res, "nspname");
2763 i_extrelocatable = PQfnumber(res, "extrelocatable");
2764 i_extversion = PQfnumber(res, "extversion");
2765 i_extconfig = PQfnumber(res, "extconfig");
2766 i_extcondition = PQfnumber(res, "extcondition");
2768 for (i = 0; i < ntups; i++)
2770 extinfo[i].dobj.objType = DO_EXTENSION;
2771 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2772 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2773 AssignDumpId(&extinfo[i].dobj);
2774 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2775 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2776 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2777 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2778 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2779 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2781 /* Decide whether we want to dump it */
2782 selectDumpableExtension(&(extinfo[i]));
2786 destroyPQExpBuffer(query);
2788 *numExtensions = ntups;
2795 * read all types in the system catalogs and return them in the
2796 * TypeInfo* structure
2798 * numTypes is set to the number of types read in
2800 * NB: this must run after getFuncs() because we assume we can do
2804 getTypes(Archive *fout, int *numTypes)
2809 PQExpBuffer query = createPQExpBuffer();
2811 ShellTypeInfo *stinfo;
2827 * we include even the built-in types because those may be used as array
2828 * elements by user-defined types
2830 * we filter out the built-in types when we dump out the types
2832 * same approach for undefined (shell) types and array types
2834 * Note: as of 8.3 we can reliably detect whether a type is an
2835 * auto-generated array type by checking the element type's typarray.
2836 * (Before that the test is capable of generating false positives.) We
2837 * still check for name beginning with '_', though, so as to avoid the
2838 * cost of the subselect probe for all standard types. This would have to
2839 * be revisited if the backend ever allows renaming of array types.
2842 /* Make sure we are in proper schema */
2843 selectSourceSchema(fout, "pg_catalog");
2845 if (fout->remoteVersion >= 80300)
2847 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2849 "(%s typowner) AS rolname, "
2850 "typinput::oid AS typinput, "
2851 "typoutput::oid AS typoutput, typelem, typrelid, "
2852 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2853 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2854 "typtype, typisdefined, "
2855 "typname[0] = '_' AND typelem != 0 AND "
2856 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2860 else if (fout->remoteVersion >= 70300)
2862 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2864 "(%s typowner) AS rolname, "
2865 "typinput::oid AS typinput, "
2866 "typoutput::oid AS typoutput, typelem, typrelid, "
2867 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2868 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2869 "typtype, typisdefined, "
2870 "typname[0] = '_' AND typelem != 0 AS isarray "
2874 else if (fout->remoteVersion >= 70100)
2876 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2877 "0::oid AS typnamespace, "
2878 "(%s typowner) AS rolname, "
2879 "typinput::oid AS typinput, "
2880 "typoutput::oid AS typoutput, typelem, typrelid, "
2881 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2882 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2883 "typtype, typisdefined, "
2884 "typname[0] = '_' AND typelem != 0 AS isarray "
2890 appendPQExpBuffer(query, "SELECT "
2891 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2893 "0::oid AS typnamespace, "
2894 "(%s typowner) AS rolname, "
2895 "typinput::oid AS typinput, "
2896 "typoutput::oid AS typoutput, typelem, typrelid, "
2897 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2898 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2899 "typtype, typisdefined, "
2900 "typname[0] = '_' AND typelem != 0 AS isarray "
2905 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2907 ntups = PQntuples(res);
2909 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2911 i_tableoid = PQfnumber(res, "tableoid");
2912 i_oid = PQfnumber(res, "oid");
2913 i_typname = PQfnumber(res, "typname");
2914 i_typnamespace = PQfnumber(res, "typnamespace");
2915 i_rolname = PQfnumber(res, "rolname");
2916 i_typinput = PQfnumber(res, "typinput");
2917 i_typoutput = PQfnumber(res, "typoutput");
2918 i_typelem = PQfnumber(res, "typelem");
2919 i_typrelid = PQfnumber(res, "typrelid");
2920 i_typrelkind = PQfnumber(res, "typrelkind");
2921 i_typtype = PQfnumber(res, "typtype");
2922 i_typisdefined = PQfnumber(res, "typisdefined");
2923 i_isarray = PQfnumber(res, "isarray");
2925 for (i = 0; i < ntups; i++)
2927 tyinfo[i].dobj.objType = DO_TYPE;
2928 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2929 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2930 AssignDumpId(&tyinfo[i].dobj);
2931 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2932 tyinfo[i].dobj.namespace =
2934 atooid(PQgetvalue(res, i, i_typnamespace)),
2935 tyinfo[i].dobj.catId.oid);
2936 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2937 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2938 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2939 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2940 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2941 tyinfo[i].shellType = NULL;
2943 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2944 tyinfo[i].isDefined = true;
2946 tyinfo[i].isDefined = false;
2948 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2949 tyinfo[i].isArray = true;
2951 tyinfo[i].isArray = false;
2953 /* Decide whether we want to dump it */
2954 selectDumpableType(&tyinfo[i]);
2957 * If it's a domain, fetch info about its constraints, if any
2959 tyinfo[i].nDomChecks = 0;
2960 tyinfo[i].domChecks = NULL;
2961 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2962 getDomainConstraints(fout, &(tyinfo[i]));
2965 * If it's a base type, make a DumpableObject representing a shell
2966 * definition of the type. We will need to dump that ahead of the I/O
2967 * functions for the type. Similarly, range types need a shell
2968 * definition in case they have a canonicalize function.
2970 * Note: the shell type doesn't have a catId. You might think it
2971 * should copy the base type's catId, but then it might capture the
2972 * pg_depend entries for the type, which we don't want.
2974 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2975 tyinfo[i].typtype == TYPTYPE_RANGE))
2977 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2978 stinfo->dobj.objType = DO_SHELL_TYPE;
2979 stinfo->dobj.catId = nilCatalogId;
2980 AssignDumpId(&stinfo->dobj);
2981 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2982 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2983 stinfo->baseType = &(tyinfo[i]);
2984 tyinfo[i].shellType = stinfo;
2987 * Initially mark the shell type as not to be dumped. We'll only
2988 * dump it if the I/O or canonicalize functions need to be dumped;
2989 * this is taken care of while sorting dependencies.
2991 stinfo->dobj.dump = false;
2994 * However, if dumping from pre-7.3, there will be no dependency
2995 * info so we have to fake it here. We only need to worry about
2996 * typinput and typoutput since the other functions only exist
2999 if (fout->remoteVersion < 70300)
3005 typinput = atooid(PQgetvalue(res, i, i_typinput));
3006 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3008 funcInfo = findFuncByOid(typinput);
3009 if (funcInfo && funcInfo->dobj.dump)
3011 /* base type depends on function */
3012 addObjectDependency(&tyinfo[i].dobj,
3013 funcInfo->dobj.dumpId);
3014 /* function depends on shell type */
3015 addObjectDependency(&funcInfo->dobj,
3016 stinfo->dobj.dumpId);
3017 /* mark shell type as to be dumped */
3018 stinfo->dobj.dump = true;
3021 funcInfo = findFuncByOid(typoutput);
3022 if (funcInfo && funcInfo->dobj.dump)
3024 /* base type depends on function */
3025 addObjectDependency(&tyinfo[i].dobj,
3026 funcInfo->dobj.dumpId);
3027 /* function depends on shell type */
3028 addObjectDependency(&funcInfo->dobj,
3029 stinfo->dobj.dumpId);
3030 /* mark shell type as to be dumped */
3031 stinfo->dobj.dump = true;
3036 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3037 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3038 tyinfo[i].dobj.name);
3045 destroyPQExpBuffer(query);
3052 * read all operators in the system catalogs and return them in the
3053 * OprInfo* structure
3055 * numOprs is set to the number of operators read in
3058 getOperators(Archive *fout, int *numOprs)
3063 PQExpBuffer query = createPQExpBuffer();
3074 * find all operators, including builtin operators; we filter out
3075 * system-defined operators at dump-out time.
3078 /* Make sure we are in proper schema */
3079 selectSourceSchema(fout, "pg_catalog");
3081 if (fout->remoteVersion >= 70300)
3083 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3085 "(%s oprowner) AS rolname, "
3087 "oprcode::oid AS oprcode "
3091 else if (fout->remoteVersion >= 70100)
3093 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3094 "0::oid AS oprnamespace, "
3095 "(%s oprowner) AS rolname, "
3097 "oprcode::oid AS oprcode "
3103 appendPQExpBuffer(query, "SELECT "
3104 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3106 "0::oid AS oprnamespace, "
3107 "(%s oprowner) AS rolname, "
3109 "oprcode::oid AS oprcode "
3114 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3116 ntups = PQntuples(res);
3119 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3121 i_tableoid = PQfnumber(res, "tableoid");
3122 i_oid = PQfnumber(res, "oid");
3123 i_oprname = PQfnumber(res, "oprname");
3124 i_oprnamespace = PQfnumber(res, "oprnamespace");
3125 i_rolname = PQfnumber(res, "rolname");
3126 i_oprkind = PQfnumber(res, "oprkind");
3127 i_oprcode = PQfnumber(res, "oprcode");
3129 for (i = 0; i < ntups; i++)
3131 oprinfo[i].dobj.objType = DO_OPERATOR;
3132 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3133 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3134 AssignDumpId(&oprinfo[i].dobj);
3135 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3136 oprinfo[i].dobj.namespace =
3138 atooid(PQgetvalue(res, i, i_oprnamespace)),
3139 oprinfo[i].dobj.catId.oid);
3140 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3141 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3142 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3144 /* Decide whether we want to dump it */
3145 selectDumpableObject(&(oprinfo[i].dobj));
3147 if (strlen(oprinfo[i].rolname) == 0)
3148 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3149 oprinfo[i].dobj.name);
3154 destroyPQExpBuffer(query);
3161 * read all collations in the system catalogs and return them in the
3162 * CollInfo* structure
3164 * numCollations is set to the number of collations read in
3167 getCollations(Archive *fout, int *numCollations)
3177 int i_collnamespace;
3180 /* Collations didn't exist pre-9.1 */
3181 if (fout->remoteVersion < 90100)
3187 query = createPQExpBuffer();
3190 * find all collations, including builtin collations; we filter out
3191 * system-defined collations at dump-out time.
3194 /* Make sure we are in proper schema */
3195 selectSourceSchema(fout, "pg_catalog");
3197 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3199 "(%s collowner) AS rolname "
3200 "FROM pg_collation",
3203 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3205 ntups = PQntuples(res);
3206 *numCollations = ntups;
3208 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3210 i_tableoid = PQfnumber(res, "tableoid");
3211 i_oid = PQfnumber(res, "oid");
3212 i_collname = PQfnumber(res, "collname");
3213 i_collnamespace = PQfnumber(res, "collnamespace");
3214 i_rolname = PQfnumber(res, "rolname");
3216 for (i = 0; i < ntups; i++)
3218 collinfo[i].dobj.objType = DO_COLLATION;
3219 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3220 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3221 AssignDumpId(&collinfo[i].dobj);
3222 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3223 collinfo[i].dobj.namespace =
3225 atooid(PQgetvalue(res, i, i_collnamespace)),
3226 collinfo[i].dobj.catId.oid);
3227 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3229 /* Decide whether we want to dump it */
3230 selectDumpableObject(&(collinfo[i].dobj));
3235 destroyPQExpBuffer(query);
3242 * read all conversions in the system catalogs and return them in the
3243 * ConvInfo* structure
3245 * numConversions is set to the number of conversions read in
3248 getConversions(Archive *fout, int *numConversions)
3253 PQExpBuffer query = createPQExpBuffer();
3261 /* Conversions didn't exist pre-7.3 */
3262 if (fout->remoteVersion < 70300)
3264 *numConversions = 0;
3269 * find all conversions, including builtin conversions; we filter out
3270 * system-defined conversions at dump-out time.
3273 /* Make sure we are in proper schema */
3274 selectSourceSchema(fout, "pg_catalog");
3276 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3278 "(%s conowner) AS rolname "
3279 "FROM pg_conversion",
3282 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3284 ntups = PQntuples(res);
3285 *numConversions = ntups;
3287 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3289 i_tableoid = PQfnumber(res, "tableoid");
3290 i_oid = PQfnumber(res, "oid");
3291 i_conname = PQfnumber(res, "conname");
3292 i_connamespace = PQfnumber(res, "connamespace");
3293 i_rolname = PQfnumber(res, "rolname");
3295 for (i = 0; i < ntups; i++)
3297 convinfo[i].dobj.objType = DO_CONVERSION;
3298 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3299 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3300 AssignDumpId(&convinfo[i].dobj);
3301 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3302 convinfo[i].dobj.namespace =
3304 atooid(PQgetvalue(res, i, i_connamespace)),
3305 convinfo[i].dobj.catId.oid);
3306 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3308 /* Decide whether we want to dump it */
3309 selectDumpableObject(&(convinfo[i].dobj));
3314 destroyPQExpBuffer(query);
3321 * read all opclasses in the system catalogs and return them in the
3322 * OpclassInfo* structure
3324 * numOpclasses is set to the number of opclasses read in
3327 getOpclasses(Archive *fout, int *numOpclasses)
3332 PQExpBuffer query = createPQExpBuffer();
3333 OpclassInfo *opcinfo;
3341 * find all opclasses, including builtin opclasses; we filter out
3342 * system-defined opclasses at dump-out time.
3345 /* Make sure we are in proper schema */
3346 selectSourceSchema(fout, "pg_catalog");
3348 if (fout->remoteVersion >= 70300)
3350 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3352 "(%s opcowner) AS rolname "
3356 else if (fout->remoteVersion >= 70100)
3358 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3359 "0::oid AS opcnamespace, "
3360 "''::name AS rolname "
3365 appendPQExpBuffer(query, "SELECT "
3366 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3368 "0::oid AS opcnamespace, "
3369 "''::name AS rolname "
3373 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3375 ntups = PQntuples(res);
3376 *numOpclasses = ntups;
3378 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3380 i_tableoid = PQfnumber(res, "tableoid");
3381 i_oid = PQfnumber(res, "oid");
3382 i_opcname = PQfnumber(res, "opcname");
3383 i_opcnamespace = PQfnumber(res, "opcnamespace");
3384 i_rolname = PQfnumber(res, "rolname");
3386 for (i = 0; i < ntups; i++)
3388 opcinfo[i].dobj.objType = DO_OPCLASS;
3389 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3390 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3391 AssignDumpId(&opcinfo[i].dobj);
3392 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3393 opcinfo[i].dobj.namespace =
3395 atooid(PQgetvalue(res, i, i_opcnamespace)),
3396 opcinfo[i].dobj.catId.oid);
3397 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3399 /* Decide whether we want to dump it */
3400 selectDumpableObject(&(opcinfo[i].dobj));
3402 if (fout->remoteVersion >= 70300)
3404 if (strlen(opcinfo[i].rolname) == 0)
3405 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3406 opcinfo[i].dobj.name);
3412 destroyPQExpBuffer(query);
3419 * read all opfamilies in the system catalogs and return them in the
3420 * OpfamilyInfo* structure
3422 * numOpfamilies is set to the number of opfamilies read in
3425 getOpfamilies(Archive *fout, int *numOpfamilies)
3431 OpfamilyInfo *opfinfo;
3438 /* Before 8.3, there is no separate concept of opfamilies */
3439 if (fout->remoteVersion < 80300)
3445 query = createPQExpBuffer();
3448 * find all opfamilies, including builtin opfamilies; we filter out
3449 * system-defined opfamilies at dump-out time.
3452 /* Make sure we are in proper schema */
3453 selectSourceSchema(fout, "pg_catalog");
3455 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3457 "(%s opfowner) AS rolname "
3461 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3463 ntups = PQntuples(res);
3464 *numOpfamilies = ntups;
3466 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3468 i_tableoid = PQfnumber(res, "tableoid");
3469 i_oid = PQfnumber(res, "oid");
3470 i_opfname = PQfnumber(res, "opfname");
3471 i_opfnamespace = PQfnumber(res, "opfnamespace");
3472 i_rolname = PQfnumber(res, "rolname");
3474 for (i = 0; i < ntups; i++)
3476 opfinfo[i].dobj.objType = DO_OPFAMILY;
3477 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3478 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3479 AssignDumpId(&opfinfo[i].dobj);
3480 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3481 opfinfo[i].dobj.namespace =
3483 atooid(PQgetvalue(res, i, i_opfnamespace)),
3484 opfinfo[i].dobj.catId.oid);
3485 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3487 /* Decide whether we want to dump it */
3488 selectDumpableObject(&(opfinfo[i].dobj));
3490 if (fout->remoteVersion >= 70300)
3492 if (strlen(opfinfo[i].rolname) == 0)
3493 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3494 opfinfo[i].dobj.name);
3500 destroyPQExpBuffer(query);
3507 * read all the user-defined aggregates in the system catalogs and
3508 * return them in the AggInfo* structure
3510 * numAggs is set to the number of aggregates read in
3513 getAggregates(Archive *fout, int *numAggs)
3518 PQExpBuffer query = createPQExpBuffer();
3529 /* Make sure we are in proper schema */
3530 selectSourceSchema(fout, "pg_catalog");
3533 * Find all user-defined aggregates. See comment in getFuncs() for the
3534 * rationale behind the filtering logic.
3537 if (fout->remoteVersion >= 80200)
3539 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3540 "pronamespace AS aggnamespace, "
3541 "pronargs, proargtypes, "
3542 "(%s proowner) AS rolname, "
3545 "WHERE proisagg AND ("
3547 "(SELECT oid FROM pg_namespace "
3548 "WHERE nspname = 'pg_catalog')",
3550 if (binary_upgrade && fout->remoteVersion >= 90100)
3551 appendPQExpBuffer(query,
3552 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3553 "classid = 'pg_proc'::regclass AND "
3554 "objid = p.oid AND "
3555 "refclassid = 'pg_extension'::regclass AND "
3557 appendPQExpBuffer(query, ")");
3559 else if (fout->remoteVersion >= 70300)
3561 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3562 "pronamespace AS aggnamespace, "
3563 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3565 "(%s proowner) AS rolname, "
3569 "AND pronamespace != "
3570 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3573 else if (fout->remoteVersion >= 70100)
3575 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3576 "0::oid AS aggnamespace, "
3577 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3578 "aggbasetype AS proargtypes, "
3579 "(%s aggowner) AS rolname, "
3581 "FROM pg_aggregate "
3582 "where oid > '%u'::oid",
3584 g_last_builtin_oid);
3588 appendPQExpBuffer(query, "SELECT "
3589 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3591 "0::oid AS aggnamespace, "
3592 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3593 "aggbasetype AS proargtypes, "
3594 "(%s aggowner) AS rolname, "
3596 "FROM pg_aggregate "
3597 "where oid > '%u'::oid",
3599 g_last_builtin_oid);
3602 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3604 ntups = PQntuples(res);
3607 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3609 i_tableoid = PQfnumber(res, "tableoid");
3610 i_oid = PQfnumber(res, "oid");
3611 i_aggname = PQfnumber(res, "aggname");
3612 i_aggnamespace = PQfnumber(res, "aggnamespace");
3613 i_pronargs = PQfnumber(res, "pronargs");
3614 i_proargtypes = PQfnumber(res, "proargtypes");
3615 i_rolname = PQfnumber(res, "rolname");
3616 i_aggacl = PQfnumber(res, "aggacl");
3618 for (i = 0; i < ntups; i++)
3620 agginfo[i].aggfn.dobj.objType = DO_AGG;
3621 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3622 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3623 AssignDumpId(&agginfo[i].aggfn.dobj);
3624 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3625 agginfo[i].aggfn.dobj.namespace =
3627 atooid(PQgetvalue(res, i, i_aggnamespace)),
3628 agginfo[i].aggfn.dobj.catId.oid);
3629 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3630 if (strlen(agginfo[i].aggfn.rolname) == 0)
3631 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3632 agginfo[i].aggfn.dobj.name);
3633 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3634 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3635 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3636 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3637 if (agginfo[i].aggfn.nargs == 0)
3638 agginfo[i].aggfn.argtypes = NULL;
3641 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3642 if (fout->remoteVersion >= 70300)
3643 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3644 agginfo[i].aggfn.argtypes,
3645 agginfo[i].aggfn.nargs);
3647 /* it's just aggbasetype */
3648 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3651 /* Decide whether we want to dump it */
3652 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3657 destroyPQExpBuffer(query);
3664 * read all the user-defined functions in the system catalogs and
3665 * return them in the FuncInfo* structure
3667 * numFuncs is set to the number of functions read in
3670 getFuncs(Archive *fout, int *numFuncs)
3675 PQExpBuffer query = createPQExpBuffer();
3688 /* Make sure we are in proper schema */
3689 selectSourceSchema(fout, "pg_catalog");
3692 * Find all user-defined functions. Normally we can exclude functions in
3693 * pg_catalog, which is worth doing since there are several thousand of
3694 * 'em. However, there are some extensions that create functions in
3695 * pg_catalog. In normal dumps we can still ignore those --- but in
3696 * binary-upgrade mode, we must dump the member objects of the extension,
3697 * so be sure to fetch any such functions.
3699 * Also, in 9.2 and up, exclude functions that are internally dependent on
3700 * something else, since presumably those will be created as a result of
3701 * creating the something else. This currently only acts to suppress
3702 * constructor functions for range types. Note that this is OK only
3703 * because the constructors don't have any dependencies the range type
3704 * doesn't have; otherwise we might not get creation ordering correct.
3707 if (fout->remoteVersion >= 70300)
3709 appendPQExpBuffer(query,
3710 "SELECT tableoid, oid, proname, prolang, "
3711 "pronargs, proargtypes, prorettype, proacl, "
3713 "(%s proowner) AS rolname "
3715 "WHERE NOT proisagg AND ("
3717 "(SELECT oid FROM pg_namespace "
3718 "WHERE nspname = 'pg_catalog')",
3720 if (fout->remoteVersion >= 90200)
3721 appendPQExpBuffer(query,
3722 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3723 "WHERE classid = 'pg_proc'::regclass AND "
3724 "objid = p.oid AND deptype = 'i')");
3725 if (binary_upgrade && fout->remoteVersion >= 90100)
3726 appendPQExpBuffer(query,
3727 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3728 "classid = 'pg_proc'::regclass AND "
3729 "objid = p.oid AND "
3730 "refclassid = 'pg_extension'::regclass AND "
3732 appendPQExpBuffer(query, ")");
3734 else if (fout->remoteVersion >= 70100)
3736 appendPQExpBuffer(query,
3737 "SELECT tableoid, oid, proname, prolang, "
3738 "pronargs, proargtypes, prorettype, "
3739 "'{=X}' AS proacl, "
3740 "0::oid AS pronamespace, "
3741 "(%s proowner) AS rolname "
3743 "WHERE pg_proc.oid > '%u'::oid",
3745 g_last_builtin_oid);
3749 appendPQExpBuffer(query,
3751 "(SELECT oid FROM pg_class "
3752 " WHERE relname = 'pg_proc') AS tableoid, "
3753 "oid, proname, prolang, "
3754 "pronargs, proargtypes, prorettype, "
3755 "'{=X}' AS proacl, "
3756 "0::oid AS pronamespace, "
3757 "(%s proowner) AS rolname "
3759 "where pg_proc.oid > '%u'::oid",
3761 g_last_builtin_oid);
3764 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3766 ntups = PQntuples(res);
3770 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3772 i_tableoid = PQfnumber(res, "tableoid");
3773 i_oid = PQfnumber(res, "oid");
3774 i_proname = PQfnumber(res, "proname");
3775 i_pronamespace = PQfnumber(res, "pronamespace");
3776 i_rolname = PQfnumber(res, "rolname");
3777 i_prolang = PQfnumber(res, "prolang");
3778 i_pronargs = PQfnumber(res, "pronargs");
3779 i_proargtypes = PQfnumber(res, "proargtypes");
3780 i_prorettype = PQfnumber(res, "prorettype");
3781 i_proacl = PQfnumber(res, "proacl");
3783 for (i = 0; i < ntups; i++)
3785 finfo[i].dobj.objType = DO_FUNC;
3786 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3787 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3788 AssignDumpId(&finfo[i].dobj);
3789 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3790 finfo[i].dobj.namespace =
3792 atooid(PQgetvalue(res, i, i_pronamespace)),
3793 finfo[i].dobj.catId.oid);
3794 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3795 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3796 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3797 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3798 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3799 if (finfo[i].nargs == 0)
3800 finfo[i].argtypes = NULL;
3803 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3804 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3805 finfo[i].argtypes, finfo[i].nargs);
3808 /* Decide whether we want to dump it */
3809 selectDumpableObject(&(finfo[i].dobj));
3811 if (strlen(finfo[i].rolname) == 0)
3813 "WARNING: owner of function \"%s\" appears to be invalid\n",
3814 finfo[i].dobj.name);
3819 destroyPQExpBuffer(query);
3826 * read all the user-defined tables (no indexes, no catalogs)
3827 * in the system catalogs return them in the TableInfo* structure
3829 * numTables is set to the number of tables read in
3832 getTables(Archive *fout, int *numTables)
3837 PQExpBuffer query = createPQExpBuffer();
3847 int i_relhastriggers;
3853 int i_toastfrozenxid;
3854 int i_relpersistence;
3857 int i_reltablespace;
3859 int i_toastreloptions;
3862 /* Make sure we are in proper schema */
3863 selectSourceSchema(fout, "pg_catalog");
3866 * Find all the tables (including views and sequences).
3868 * We include system catalogs, so that we can work if a user table is
3869 * defined to inherit from a system catalog (pretty weird, but...)
3871 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3872 * (sequence), 'v' (view), or 'c' (composite type).
3874 * Composite-type table entries won't be dumped as such, but we have to
3875 * make a DumpableObject for them so that we can track dependencies of the
3876 * composite type (pg_depend entries for columns of the composite type
3877 * link to the pg_class entry not the pg_type entry).
3879 * Note: in this phase we should collect only a minimal amount of
3880 * information about each table, basically just enough to decide if it is
3881 * interesting. We must fetch all tables in this phase because otherwise
3882 * we cannot correctly identify inherited columns, owned sequences, etc.
3885 if (fout->remoteVersion >= 90100)
3888 * Left join to pick up dependency info linking sequences to their
3889 * owning column, if any (note this dependency is AUTO as of 8.2)
3891 appendPQExpBuffer(query,
3892 "SELECT c.tableoid, c.oid, c.relname, "
3893 "c.relacl, c.relkind, c.relnamespace, "
3894 "(%s c.relowner) AS rolname, "
3895 "c.relchecks, c.relhastriggers, "
3896 "c.relhasindex, c.relhasrules, c.relhasoids, "
3897 "c.relfrozenxid, tc.oid AS toid, "
3898 "tc.relfrozenxid AS tfrozenxid, "
3899 "c.relpersistence, "
3900 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3901 "d.refobjid AS owning_tab, "
3902 "d.refobjsubid AS owning_col, "
3903 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3904 "array_to_string(c.reloptions, ', ') AS reloptions, "
3905 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3907 "LEFT JOIN pg_depend d ON "
3908 "(c.relkind = '%c' AND "
3909 "d.classid = c.tableoid AND d.objid = c.oid AND "
3910 "d.objsubid = 0 AND "
3911 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3912 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3913 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3917 RELKIND_RELATION, RELKIND_SEQUENCE,
3918 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3919 RELKIND_FOREIGN_TABLE);
3921 else if (fout->remoteVersion >= 90000)
3924 * Left join to pick up dependency info linking sequences to their
3925 * owning column, if any (note this dependency is AUTO as of 8.2)
3927 appendPQExpBuffer(query,
3928 "SELECT c.tableoid, c.oid, c.relname, "
3929 "c.relacl, c.relkind, c.relnamespace, "
3930 "(%s c.relowner) AS rolname, "
3931 "c.relchecks, c.relhastriggers, "
3932 "c.relhasindex, c.relhasrules, c.relhasoids, "
3933 "c.relfrozenxid, tc.oid AS toid, "
3934 "tc.relfrozenxid AS tfrozenxid, "
3935 "'p' AS relpersistence, "
3936 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3937 "d.refobjid AS owning_tab, "
3938 "d.refobjsubid AS owning_col, "
3939 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3940 "array_to_string(c.reloptions, ', ') AS reloptions, "
3941 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3943 "LEFT JOIN pg_depend d ON "
3944 "(c.relkind = '%c' AND "
3945 "d.classid = c.tableoid AND d.objid = c.oid AND "
3946 "d.objsubid = 0 AND "
3947 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3948 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3949 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3953 RELKIND_RELATION, RELKIND_SEQUENCE,
3954 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3956 else if (fout->remoteVersion >= 80400)
3959 * Left join to pick up dependency info linking sequences to their
3960 * owning column, if any (note this dependency is AUTO as of 8.2)
3962 appendPQExpBuffer(query,
3963 "SELECT c.tableoid, c.oid, c.relname, "
3964 "c.relacl, c.relkind, c.relnamespace, "
3965 "(%s c.relowner) AS rolname, "
3966 "c.relchecks, c.relhastriggers, "
3967 "c.relhasindex, c.relhasrules, c.relhasoids, "
3968 "c.relfrozenxid, tc.oid AS toid, "
3969 "tc.relfrozenxid AS tfrozenxid, "
3970 "'p' AS relpersistence, "
3971 "NULL AS reloftype, "
3972 "d.refobjid AS owning_tab, "
3973 "d.refobjsubid AS owning_col, "
3974 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3975 "array_to_string(c.reloptions, ', ') AS reloptions, "
3976 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3978 "LEFT JOIN pg_depend d ON "
3979 "(c.relkind = '%c' AND "
3980 "d.classid = c.tableoid AND d.objid = c.oid AND "
3981 "d.objsubid = 0 AND "
3982 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3983 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3984 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3988 RELKIND_RELATION, RELKIND_SEQUENCE,
3989 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3991 else if (fout->remoteVersion >= 80200)
3994 * Left join to pick up dependency info linking sequences to their
3995 * owning column, if any (note this dependency is AUTO as of 8.2)
3997 appendPQExpBuffer(query,
3998 "SELECT c.tableoid, c.oid, c.relname, "
3999 "c.relacl, c.relkind, c.relnamespace, "
4000 "(%s c.relowner) AS rolname, "
4001 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4002 "c.relhasindex, c.relhasrules, c.relhasoids, "
4003 "c.relfrozenxid, tc.oid AS toid, "
4004 "tc.relfrozenxid AS tfrozenxid, "
4005 "'p' AS relpersistence, "
4006 "NULL AS reloftype, "
4007 "d.refobjid AS owning_tab, "
4008 "d.refobjsubid AS owning_col, "
4009 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4010 "array_to_string(c.reloptions, ', ') AS reloptions, "
4011 "NULL AS toast_reloptions "
4013 "LEFT JOIN pg_depend d ON "
4014 "(c.relkind = '%c' AND "
4015 "d.classid = c.tableoid AND d.objid = c.oid AND "
4016 "d.objsubid = 0 AND "
4017 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4018 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4019 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4023 RELKIND_RELATION, RELKIND_SEQUENCE,
4024 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4026 else if (fout->remoteVersion >= 80000)
4029 * Left join to pick up dependency info linking sequences to their
4030 * owning column, if any
4032 appendPQExpBuffer(query,
4033 "SELECT c.tableoid, c.oid, relname, "
4034 "relacl, relkind, relnamespace, "
4035 "(%s relowner) AS rolname, "
4036 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4037 "relhasindex, relhasrules, relhasoids, "
4038 "0 AS relfrozenxid, "
4041 "'p' AS relpersistence, "
4042 "NULL AS reloftype, "
4043 "d.refobjid AS owning_tab, "
4044 "d.refobjsubid AS owning_col, "
4045 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4046 "NULL AS reloptions, "
4047 "NULL AS toast_reloptions "
4049 "LEFT JOIN pg_depend d ON "
4050 "(c.relkind = '%c' AND "
4051 "d.classid = c.tableoid AND d.objid = c.oid AND "
4052 "d.objsubid = 0 AND "
4053 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4054 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4058 RELKIND_RELATION, RELKIND_SEQUENCE,
4059 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4061 else if (fout->remoteVersion >= 70300)
4064 * Left join to pick up dependency info linking sequences to their
4065 * owning column, if any
4067 appendPQExpBuffer(query,
4068 "SELECT c.tableoid, c.oid, relname, "
4069 "relacl, relkind, relnamespace, "
4070 "(%s relowner) AS rolname, "
4071 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4072 "relhasindex, relhasrules, relhasoids, "
4073 "0 AS relfrozenxid, "
4076 "'p' AS relpersistence, "
4077 "NULL AS reloftype, "
4078 "d.refobjid AS owning_tab, "
4079 "d.refobjsubid AS owning_col, "
4080 "NULL AS reltablespace, "
4081 "NULL AS reloptions, "
4082 "NULL AS toast_reloptions "
4084 "LEFT JOIN pg_depend d ON "
4085 "(c.relkind = '%c' AND "
4086 "d.classid = c.tableoid AND d.objid = c.oid AND "
4087 "d.objsubid = 0 AND "
4088 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4089 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4093 RELKIND_RELATION, RELKIND_SEQUENCE,
4094 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4096 else if (fout->remoteVersion >= 70200)
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, relhasoids, "
4104 "0 AS relfrozenxid, "
4107 "'p' AS relpersistence, "
4108 "NULL AS reloftype, "
4109 "NULL::oid AS owning_tab, "
4110 "NULL::int4 AS owning_col, "
4111 "NULL AS reltablespace, "
4112 "NULL AS reloptions, "
4113 "NULL AS toast_reloptions "
4115 "WHERE relkind IN ('%c', '%c', '%c') "
4118 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4120 else if (fout->remoteVersion >= 70100)
4122 /* all tables have oids in 7.1 */
4123 appendPQExpBuffer(query,
4124 "SELECT tableoid, oid, relname, relacl, relkind, "
4125 "0::oid AS relnamespace, "
4126 "(%s relowner) AS rolname, "
4127 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4128 "relhasindex, relhasrules, "
4129 "'t'::bool AS relhasoids, "
4130 "0 AS relfrozenxid, "
4133 "'p' AS relpersistence, "
4134 "NULL AS reloftype, "
4135 "NULL::oid AS owning_tab, "
4136 "NULL::int4 AS owning_col, "
4137 "NULL AS reltablespace, "
4138 "NULL AS reloptions, "
4139 "NULL AS toast_reloptions "
4141 "WHERE relkind IN ('%c', '%c', '%c') "
4144 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4149 * Before 7.1, view relkind was not set to 'v', so we must check if we
4150 * have a view by looking for a rule in pg_rewrite.
4152 appendPQExpBuffer(query,
4154 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4155 "oid, relname, relacl, "
4156 "CASE WHEN relhasrules and relkind = 'r' "
4157 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4158 " r.ev_class = c.oid AND r.ev_type = '1') "
4159 "THEN '%c'::\"char\" "
4160 "ELSE relkind END AS relkind,"
4161 "0::oid AS relnamespace, "
4162 "(%s relowner) AS rolname, "
4163 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4164 "relhasindex, relhasrules, "
4165 "'t'::bool AS relhasoids, "
4166 "0 as relfrozenxid, "
4169 "'p' AS relpersistence, "
4170 "NULL AS reloftype, "
4171 "NULL::oid AS owning_tab, "
4172 "NULL::int4 AS owning_col, "
4173 "NULL AS reltablespace, "
4174 "NULL AS reloptions, "
4175 "NULL AS toast_reloptions "
4177 "WHERE relkind IN ('%c', '%c') "
4181 RELKIND_RELATION, RELKIND_SEQUENCE);
4184 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4186 ntups = PQntuples(res);
4191 * Extract data from result and lock dumpable tables. We do the locking
4192 * before anything else, to minimize the window wherein a table could
4193 * disappear under us.
4195 * Note that we have to save info about all tables here, even when dumping
4196 * only one, because we don't yet know which tables might be inheritance
4197 * ancestors of the target table.
4199 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4201 i_reltableoid = PQfnumber(res, "tableoid");
4202 i_reloid = PQfnumber(res, "oid");
4203 i_relname = PQfnumber(res, "relname");
4204 i_relnamespace = PQfnumber(res, "relnamespace");
4205 i_relacl = PQfnumber(res, "relacl");
4206 i_relkind = PQfnumber(res, "relkind");
4207 i_rolname = PQfnumber(res, "rolname");
4208 i_relchecks = PQfnumber(res, "relchecks");
4209 i_relhastriggers = PQfnumber(res, "relhastriggers");
4210 i_relhasindex = PQfnumber(res, "relhasindex");
4211 i_relhasrules = PQfnumber(res, "relhasrules");
4212 i_relhasoids = PQfnumber(res, "relhasoids");
4213 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4214 i_toastoid = PQfnumber(res, "toid");
4215 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4216 i_relpersistence = PQfnumber(res, "relpersistence");
4217 i_owning_tab = PQfnumber(res, "owning_tab");
4218 i_owning_col = PQfnumber(res, "owning_col");
4219 i_reltablespace = PQfnumber(res, "reltablespace");
4220 i_reloptions = PQfnumber(res, "reloptions");
4221 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4222 i_reloftype = PQfnumber(res, "reloftype");
4224 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4227 * Arrange to fail instead of waiting forever for a table lock.
4229 * NB: this coding assumes that the only queries issued within the
4230 * following loop are LOCK TABLEs; else the timeout may be undesirably
4231 * applied to other things too.
4233 resetPQExpBuffer(query);
4234 appendPQExpBuffer(query, "SET statement_timeout = ");
4235 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4236 ExecuteSqlStatement(fout, query->data);
4239 for (i = 0; i < ntups; i++)
4241 tblinfo[i].dobj.objType = DO_TABLE;
4242 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4243 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4244 AssignDumpId(&tblinfo[i].dobj);
4245 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4246 tblinfo[i].dobj.namespace =
4248 atooid(PQgetvalue(res, i, i_relnamespace)),
4249 tblinfo[i].dobj.catId.oid);
4250 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4251 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4252 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4253 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4254 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4255 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4256 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4257 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4258 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4259 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4260 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4261 if (PQgetisnull(res, i, i_reloftype))
4262 tblinfo[i].reloftype = NULL;
4264 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4265 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4266 if (PQgetisnull(res, i, i_owning_tab))
4268 tblinfo[i].owning_tab = InvalidOid;
4269 tblinfo[i].owning_col = 0;
4273 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4274 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4276 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4277 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4278 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4280 /* other fields were zeroed above */
4283 * Decide whether we want to dump this table.
4285 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4286 tblinfo[i].dobj.dump = false;
4288 selectDumpableTable(&tblinfo[i]);
4289 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4292 * Read-lock target tables to make sure they aren't DROPPED or altered
4293 * in schema before we get around to dumping them.
4295 * Note that we don't explicitly lock parents of the target tables; we
4296 * assume our lock on the child is enough to prevent schema
4297 * alterations to parent tables.
4299 * NOTE: it'd be kinda nice to lock other relations too, not only
4300 * plain tables, but the backend doesn't presently allow that.
4302 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4304 resetPQExpBuffer(query);
4305 appendPQExpBuffer(query,
4306 "LOCK TABLE %s IN ACCESS SHARE MODE",
4307 fmtQualifiedId(fout,
4308 tblinfo[i].dobj.namespace->dobj.name,
4309 tblinfo[i].dobj.name));
4310 ExecuteSqlStatement(fout, query->data);
4313 /* Emit notice if join for owner failed */
4314 if (strlen(tblinfo[i].rolname) == 0)
4315 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4316 tblinfo[i].dobj.name);
4319 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4321 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4327 * Force sequences that are "owned" by table columns to be dumped whenever
4328 * their owning table is being dumped.
4330 for (i = 0; i < ntups; i++)
4332 TableInfo *seqinfo = &tblinfo[i];
4335 if (!OidIsValid(seqinfo->owning_tab))
4336 continue; /* not an owned sequence */
4337 if (seqinfo->dobj.dump)
4338 continue; /* no need to search */
4340 /* can't use findTableByOid yet, unfortunately */
4341 for (j = 0; j < ntups; j++)
4343 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4345 if (tblinfo[j].dobj.dump)
4347 seqinfo->interesting = true;
4348 seqinfo->dobj.dump = true;
4355 destroyPQExpBuffer(query);
4362 * read all the inheritance information
4363 * from the system catalogs return them in the InhInfo* structure
4365 * numInherits is set to the number of pairs read in
4368 getInherits(Archive *fout, int *numInherits)
4373 PQExpBuffer query = createPQExpBuffer();
4379 /* Make sure we are in proper schema */
4380 selectSourceSchema(fout, "pg_catalog");
4382 /* find all the inheritance information */
4384 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4386 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4388 ntups = PQntuples(res);
4390 *numInherits = ntups;
4392 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4394 i_inhrelid = PQfnumber(res, "inhrelid");
4395 i_inhparent = PQfnumber(res, "inhparent");
4397 for (i = 0; i < ntups; i++)
4399 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4400 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4405 destroyPQExpBuffer(query);
4412 * get information about every index on a dumpable table
4414 * Note: index data is not returned directly to the caller, but it
4415 * does get entered into the DumpableObject tables.
4418 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4422 PQExpBuffer query = createPQExpBuffer();
4425 ConstraintInfo *constrinfo;
4444 for (i = 0; i < numTables; i++)
4446 TableInfo *tbinfo = &tblinfo[i];
4448 /* Only plain tables have indexes */
4449 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4452 /* Ignore indexes of tables not to be dumped */
4453 if (!tbinfo->dobj.dump)
4457 write_msg(NULL, "reading indexes for table \"%s\"\n",
4460 /* Make sure we are in proper schema so indexdef is right */
4461 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4464 * The point of the messy-looking outer join is to find a constraint
4465 * that is related by an internal dependency link to the index. If we
4466 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4467 * assume an index won't have more than one internal dependency.
4469 * As of 9.0 we don't need to look at pg_depend but can check for a
4470 * match to pg_constraint.conindid. The check on conrelid is
4471 * redundant but useful because that column is indexed while conindid
4474 resetPQExpBuffer(query);
4475 if (fout->remoteVersion >= 90000)
4477 appendPQExpBuffer(query,
4478 "SELECT t.tableoid, t.oid, "
4479 "t.relname AS indexname, "
4480 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4481 "t.relnatts AS indnkeys, "
4482 "i.indkey, i.indisclustered, "
4483 "c.contype, c.conname, "
4484 "c.condeferrable, c.condeferred, "
4485 "c.tableoid AS contableoid, "
4487 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4488 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4489 "array_to_string(t.reloptions, ', ') AS options "
4490 "FROM pg_catalog.pg_index i "
4491 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4492 "LEFT JOIN pg_catalog.pg_constraint c "
4493 "ON (i.indrelid = c.conrelid AND "
4494 "i.indexrelid = c.conindid AND "
4495 "c.contype IN ('p','u','x')) "
4496 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4497 "ORDER BY indexname",
4498 tbinfo->dobj.catId.oid);
4500 else if (fout->remoteVersion >= 80200)
4502 appendPQExpBuffer(query,
4503 "SELECT t.tableoid, t.oid, "
4504 "t.relname AS indexname, "
4505 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4506 "t.relnatts AS indnkeys, "
4507 "i.indkey, i.indisclustered, "
4508 "c.contype, c.conname, "
4509 "c.condeferrable, c.condeferred, "
4510 "c.tableoid AS contableoid, "
4513 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4514 "array_to_string(t.reloptions, ', ') AS options "
4515 "FROM pg_catalog.pg_index i "
4516 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4517 "LEFT JOIN pg_catalog.pg_depend d "
4518 "ON (d.classid = t.tableoid "
4519 "AND d.objid = t.oid "
4520 "AND d.deptype = 'i') "
4521 "LEFT JOIN pg_catalog.pg_constraint c "
4522 "ON (d.refclassid = c.tableoid "
4523 "AND d.refobjid = c.oid) "
4524 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4525 "ORDER BY indexname",
4526 tbinfo->dobj.catId.oid);
4528 else if (fout->remoteVersion >= 80000)
4530 appendPQExpBuffer(query,
4531 "SELECT t.tableoid, t.oid, "
4532 "t.relname AS indexname, "
4533 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4534 "t.relnatts AS indnkeys, "
4535 "i.indkey, i.indisclustered, "
4536 "c.contype, c.conname, "
4537 "c.condeferrable, c.condeferred, "
4538 "c.tableoid AS contableoid, "
4541 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4543 "FROM pg_catalog.pg_index i "
4544 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4545 "LEFT JOIN pg_catalog.pg_depend d "
4546 "ON (d.classid = t.tableoid "
4547 "AND d.objid = t.oid "
4548 "AND d.deptype = 'i') "
4549 "LEFT JOIN pg_catalog.pg_constraint c "
4550 "ON (d.refclassid = c.tableoid "
4551 "AND d.refobjid = c.oid) "
4552 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4553 "ORDER BY indexname",
4554 tbinfo->dobj.catId.oid);
4556 else if (fout->remoteVersion >= 70300)
4558 appendPQExpBuffer(query,
4559 "SELECT t.tableoid, t.oid, "
4560 "t.relname AS indexname, "
4561 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4562 "t.relnatts AS indnkeys, "
4563 "i.indkey, i.indisclustered, "
4564 "c.contype, c.conname, "
4565 "c.condeferrable, c.condeferred, "
4566 "c.tableoid AS contableoid, "
4569 "NULL AS tablespace, "
4571 "FROM pg_catalog.pg_index i "
4572 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4573 "LEFT JOIN pg_catalog.pg_depend d "
4574 "ON (d.classid = t.tableoid "
4575 "AND d.objid = t.oid "
4576 "AND d.deptype = 'i') "
4577 "LEFT JOIN pg_catalog.pg_constraint c "
4578 "ON (d.refclassid = c.tableoid "
4579 "AND d.refobjid = c.oid) "
4580 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4581 "ORDER BY indexname",
4582 tbinfo->dobj.catId.oid);
4584 else if (fout->remoteVersion >= 70100)
4586 appendPQExpBuffer(query,
4587 "SELECT t.tableoid, t.oid, "
4588 "t.relname AS indexname, "
4589 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4590 "t.relnatts AS indnkeys, "
4591 "i.indkey, false AS indisclustered, "
4592 "CASE WHEN i.indisprimary THEN 'p'::char "
4593 "ELSE '0'::char END AS contype, "
4594 "t.relname AS conname, "
4595 "false AS condeferrable, "
4596 "false AS condeferred, "
4597 "0::oid AS contableoid, "
4600 "NULL AS tablespace, "
4602 "FROM pg_index i, pg_class t "
4603 "WHERE t.oid = i.indexrelid "
4604 "AND i.indrelid = '%u'::oid "
4605 "ORDER BY indexname",
4606 tbinfo->dobj.catId.oid);
4610 appendPQExpBuffer(query,
4612 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4614 "t.relname AS indexname, "
4615 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4616 "t.relnatts AS indnkeys, "
4617 "i.indkey, false AS indisclustered, "
4618 "CASE WHEN i.indisprimary THEN 'p'::char "
4619 "ELSE '0'::char END AS contype, "
4620 "t.relname AS conname, "
4621 "false AS condeferrable, "
4622 "false AS condeferred, "
4623 "0::oid AS contableoid, "
4626 "NULL AS tablespace, "
4628 "FROM pg_index i, pg_class t "
4629 "WHERE t.oid = i.indexrelid "
4630 "AND i.indrelid = '%u'::oid "
4631 "ORDER BY indexname",
4632 tbinfo->dobj.catId.oid);
4635 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4637 ntups = PQntuples(res);
4639 i_tableoid = PQfnumber(res, "tableoid");
4640 i_oid = PQfnumber(res, "oid");
4641 i_indexname = PQfnumber(res, "indexname");
4642 i_indexdef = PQfnumber(res, "indexdef");
4643 i_indnkeys = PQfnumber(res, "indnkeys");
4644 i_indkey = PQfnumber(res, "indkey");
4645 i_indisclustered = PQfnumber(res, "indisclustered");
4646 i_contype = PQfnumber(res, "contype");
4647 i_conname = PQfnumber(res, "conname");
4648 i_condeferrable = PQfnumber(res, "condeferrable");
4649 i_condeferred = PQfnumber(res, "condeferred");
4650 i_contableoid = PQfnumber(res, "contableoid");
4651 i_conoid = PQfnumber(res, "conoid");
4652 i_condef = PQfnumber(res, "condef");
4653 i_tablespace = PQfnumber(res, "tablespace");
4654 i_options = PQfnumber(res, "options");
4656 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4657 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4659 for (j = 0; j < ntups; j++)
4663 indxinfo[j].dobj.objType = DO_INDEX;
4664 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4665 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4666 AssignDumpId(&indxinfo[j].dobj);
4667 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4668 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4669 indxinfo[j].indextable = tbinfo;
4670 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4671 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4672 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4673 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4676 * In pre-7.4 releases, indkeys may contain more entries than
4677 * indnkeys says (since indnkeys will be 1 for a functional
4678 * index). We don't actually care about this case since we don't
4679 * examine indkeys except for indexes associated with PRIMARY and
4680 * UNIQUE constraints, which are never functional indexes. But we
4681 * have to allocate enough space to keep parseOidArray from
4684 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4685 parseOidArray(PQgetvalue(res, j, i_indkey),
4686 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4687 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4688 contype = *(PQgetvalue(res, j, i_contype));
4690 if (contype == 'p' || contype == 'u' || contype == 'x')
4693 * If we found a constraint matching the index, create an
4696 * In a pre-7.3 database, we take this path iff the index was
4697 * marked indisprimary.
4699 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4700 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4701 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4702 AssignDumpId(&constrinfo[j].dobj);
4703 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4704 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4705 constrinfo[j].contable = tbinfo;
4706 constrinfo[j].condomain = NULL;
4707 constrinfo[j].contype = contype;
4709 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4711 constrinfo[j].condef = NULL;
4712 constrinfo[j].confrelid = InvalidOid;
4713 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4714 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4715 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4716 constrinfo[j].conislocal = true;
4717 constrinfo[j].separate = true;
4719 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4721 /* If pre-7.3 DB, better make sure table comes first */
4722 addObjectDependency(&constrinfo[j].dobj,
4723 tbinfo->dobj.dumpId);
4727 /* Plain secondary index */
4728 indxinfo[j].indexconstraint = 0;
4735 destroyPQExpBuffer(query);
4741 * Get info about constraints on dumpable tables.
4743 * Currently handles foreign keys only.
4744 * Unique and primary key constraints are handled with indexes,
4745 * while check constraints are processed in getTableAttrs().
4748 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4752 ConstraintInfo *constrinfo;
4762 /* pg_constraint was created in 7.3, so nothing to do if older */
4763 if (fout->remoteVersion < 70300)
4766 query = createPQExpBuffer();
4768 for (i = 0; i < numTables; i++)
4770 TableInfo *tbinfo = &tblinfo[i];
4772 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4776 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4780 * select table schema to ensure constraint expr is qualified if
4783 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4785 resetPQExpBuffer(query);
4786 appendPQExpBuffer(query,
4787 "SELECT tableoid, oid, conname, confrelid, "
4788 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4789 "FROM pg_catalog.pg_constraint "
4790 "WHERE conrelid = '%u'::pg_catalog.oid "
4791 "AND contype = 'f'",
4792 tbinfo->dobj.catId.oid);
4793 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4795 ntups = PQntuples(res);
4797 i_contableoid = PQfnumber(res, "tableoid");
4798 i_conoid = PQfnumber(res, "oid");
4799 i_conname = PQfnumber(res, "conname");
4800 i_confrelid = PQfnumber(res, "confrelid");
4801 i_condef = PQfnumber(res, "condef");
4803 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4805 for (j = 0; j < ntups; j++)
4807 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4808 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4809 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4810 AssignDumpId(&constrinfo[j].dobj);
4811 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4812 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4813 constrinfo[j].contable = tbinfo;
4814 constrinfo[j].condomain = NULL;
4815 constrinfo[j].contype = 'f';
4816 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4817 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4818 constrinfo[j].conindex = 0;
4819 constrinfo[j].condeferrable = false;
4820 constrinfo[j].condeferred = false;
4821 constrinfo[j].conislocal = true;
4822 constrinfo[j].separate = true;
4828 destroyPQExpBuffer(query);
4832 * getDomainConstraints
4834 * Get info about constraints on a domain.
4837 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4840 ConstraintInfo *constrinfo;
4849 /* pg_constraint was created in 7.3, so nothing to do if older */
4850 if (fout->remoteVersion < 70300)
4854 * select appropriate schema to ensure names in constraint are properly
4857 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4859 query = createPQExpBuffer();
4861 if (fout->remoteVersion >= 90100)
4862 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4863 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4865 "FROM pg_catalog.pg_constraint "
4866 "WHERE contypid = '%u'::pg_catalog.oid "
4868 tyinfo->dobj.catId.oid);
4870 else if (fout->remoteVersion >= 70400)
4871 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4872 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4873 "true as convalidated "
4874 "FROM pg_catalog.pg_constraint "
4875 "WHERE contypid = '%u'::pg_catalog.oid "
4877 tyinfo->dobj.catId.oid);
4879 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4880 "'CHECK (' || consrc || ')' AS consrc, "
4881 "true as convalidated "
4882 "FROM pg_catalog.pg_constraint "
4883 "WHERE contypid = '%u'::pg_catalog.oid "
4885 tyinfo->dobj.catId.oid);
4887 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4889 ntups = PQntuples(res);
4891 i_tableoid = PQfnumber(res, "tableoid");
4892 i_oid = PQfnumber(res, "oid");
4893 i_conname = PQfnumber(res, "conname");
4894 i_consrc = PQfnumber(res, "consrc");
4896 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4898 tyinfo->nDomChecks = ntups;
4899 tyinfo->domChecks = constrinfo;
4901 for (i = 0; i < ntups; i++)
4903 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4905 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4906 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4907 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4908 AssignDumpId(&constrinfo[i].dobj);
4909 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4910 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4911 constrinfo[i].contable = NULL;
4912 constrinfo[i].condomain = tyinfo;
4913 constrinfo[i].contype = 'c';
4914 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4915 constrinfo[i].confrelid = InvalidOid;
4916 constrinfo[i].conindex = 0;
4917 constrinfo[i].condeferrable = false;
4918 constrinfo[i].condeferred = false;
4919 constrinfo[i].conislocal = true;
4921 constrinfo[i].separate = !validated;
4924 * Make the domain depend on the constraint, ensuring it won't be
4925 * output till any constraint dependencies are OK. If the constraint
4926 * has not been validated, it's going to be dumped after the domain
4927 * anyway, so this doesn't matter.
4930 addObjectDependency(&tyinfo->dobj,
4931 constrinfo[i].dobj.dumpId);
4936 destroyPQExpBuffer(query);
4941 * get basic information about every rule in the system
4943 * numRules is set to the number of rules read in
4946 getRules(Archive *fout, int *numRules)
4951 PQExpBuffer query = createPQExpBuffer();
4961 /* Make sure we are in proper schema */
4962 selectSourceSchema(fout, "pg_catalog");
4964 if (fout->remoteVersion >= 80300)
4966 appendPQExpBuffer(query, "SELECT "
4967 "tableoid, oid, rulename, "
4968 "ev_class AS ruletable, ev_type, is_instead, "
4973 else if (fout->remoteVersion >= 70100)
4975 appendPQExpBuffer(query, "SELECT "
4976 "tableoid, oid, rulename, "
4977 "ev_class AS ruletable, ev_type, is_instead, "
4978 "'O'::char AS ev_enabled "
4984 appendPQExpBuffer(query, "SELECT "
4985 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4987 "ev_class AS ruletable, ev_type, is_instead, "
4988 "'O'::char AS ev_enabled "
4993 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4995 ntups = PQntuples(res);
4999 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5001 i_tableoid = PQfnumber(res, "tableoid");
5002 i_oid = PQfnumber(res, "oid");
5003 i_rulename = PQfnumber(res, "rulename");
5004 i_ruletable = PQfnumber(res, "ruletable");
5005 i_ev_type = PQfnumber(res, "ev_type");
5006 i_is_instead = PQfnumber(res, "is_instead");
5007 i_ev_enabled = PQfnumber(res, "ev_enabled");
5009 for (i = 0; i < ntups; i++)
5013 ruleinfo[i].dobj.objType = DO_RULE;
5014 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5015 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5016 AssignDumpId(&ruleinfo[i].dobj);
5017 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5018 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5019 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5020 if (ruleinfo[i].ruletable == NULL)
5021 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5022 ruletableoid, ruleinfo[i].dobj.catId.oid);
5023 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5024 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5025 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5026 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5027 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5028 if (ruleinfo[i].ruletable)
5031 * If the table is a view, force its ON SELECT rule to be sorted
5032 * before the view itself --- this ensures that any dependencies
5033 * for the rule affect the table's positioning. Other rules are
5034 * forced to appear after their table.
5036 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5037 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5039 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5040 ruleinfo[i].dobj.dumpId);
5041 /* We'll merge the rule into CREATE VIEW, if possible */
5042 ruleinfo[i].separate = false;
5046 addObjectDependency(&ruleinfo[i].dobj,
5047 ruleinfo[i].ruletable->dobj.dumpId);
5048 ruleinfo[i].separate = true;
5052 ruleinfo[i].separate = true;
5057 destroyPQExpBuffer(query);
5064 * get information about every trigger on a dumpable table
5066 * Note: trigger data is not returned directly to the caller, but it
5067 * does get entered into the DumpableObject tables.
5070 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5074 PQExpBuffer query = createPQExpBuffer();
5076 TriggerInfo *tginfo;
5094 for (i = 0; i < numTables; i++)
5096 TableInfo *tbinfo = &tblinfo[i];
5098 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5102 write_msg(NULL, "reading triggers for table \"%s\"\n",
5106 * select table schema to ensure regproc name is qualified if needed
5108 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5110 resetPQExpBuffer(query);
5111 if (fout->remoteVersion >= 90000)
5114 * NB: think not to use pretty=true in pg_get_triggerdef. It
5115 * could result in non-forward-compatible dumps of WHEN clauses
5116 * due to under-parenthesization.
5118 appendPQExpBuffer(query,
5120 "tgfoid::pg_catalog.regproc AS tgfname, "
5121 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5122 "tgenabled, tableoid, oid "
5123 "FROM pg_catalog.pg_trigger t "
5124 "WHERE tgrelid = '%u'::pg_catalog.oid "
5125 "AND NOT tgisinternal",
5126 tbinfo->dobj.catId.oid);
5128 else if (fout->remoteVersion >= 80300)
5131 * We ignore triggers that are tied to a foreign-key constraint
5133 appendPQExpBuffer(query,
5135 "tgfoid::pg_catalog.regproc AS tgfname, "
5136 "tgtype, tgnargs, tgargs, tgenabled, "
5137 "tgisconstraint, tgconstrname, tgdeferrable, "
5138 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5139 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5140 "FROM pg_catalog.pg_trigger t "
5141 "WHERE tgrelid = '%u'::pg_catalog.oid "
5142 "AND tgconstraint = 0",
5143 tbinfo->dobj.catId.oid);
5145 else if (fout->remoteVersion >= 70300)
5148 * We ignore triggers that are tied to a foreign-key constraint,
5149 * but in these versions we have to grovel through pg_constraint
5152 appendPQExpBuffer(query,
5154 "tgfoid::pg_catalog.regproc AS tgfname, "
5155 "tgtype, tgnargs, tgargs, tgenabled, "
5156 "tgisconstraint, tgconstrname, tgdeferrable, "
5157 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5158 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5159 "FROM pg_catalog.pg_trigger t "
5160 "WHERE tgrelid = '%u'::pg_catalog.oid "
5161 "AND (NOT tgisconstraint "
5163 " (SELECT 1 FROM pg_catalog.pg_depend d "
5164 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5165 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5166 tbinfo->dobj.catId.oid);
5168 else if (fout->remoteVersion >= 70100)
5170 appendPQExpBuffer(query,
5171 "SELECT tgname, tgfoid::regproc AS tgfname, "
5172 "tgtype, tgnargs, tgargs, tgenabled, "
5173 "tgisconstraint, tgconstrname, tgdeferrable, "
5174 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5175 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5176 " AS tgconstrrelname "
5178 "WHERE tgrelid = '%u'::oid",
5179 tbinfo->dobj.catId.oid);
5183 appendPQExpBuffer(query,
5184 "SELECT tgname, tgfoid::regproc AS tgfname, "
5185 "tgtype, tgnargs, tgargs, tgenabled, "
5186 "tgisconstraint, tgconstrname, tgdeferrable, "
5187 "tgconstrrelid, tginitdeferred, "
5188 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5190 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5191 " AS tgconstrrelname "
5193 "WHERE tgrelid = '%u'::oid",
5194 tbinfo->dobj.catId.oid);
5196 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5198 ntups = PQntuples(res);
5200 i_tableoid = PQfnumber(res, "tableoid");
5201 i_oid = PQfnumber(res, "oid");
5202 i_tgname = PQfnumber(res, "tgname");
5203 i_tgfname = PQfnumber(res, "tgfname");
5204 i_tgtype = PQfnumber(res, "tgtype");
5205 i_tgnargs = PQfnumber(res, "tgnargs");
5206 i_tgargs = PQfnumber(res, "tgargs");
5207 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5208 i_tgconstrname = PQfnumber(res, "tgconstrname");
5209 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5210 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5211 i_tgenabled = PQfnumber(res, "tgenabled");
5212 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5213 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5214 i_tgdef = PQfnumber(res, "tgdef");
5216 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5218 for (j = 0; j < ntups; j++)
5220 tginfo[j].dobj.objType = DO_TRIGGER;
5221 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5222 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5223 AssignDumpId(&tginfo[j].dobj);
5224 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5225 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5226 tginfo[j].tgtable = tbinfo;
5227 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5230 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5232 /* remaining fields are not valid if we have tgdef */
5233 tginfo[j].tgfname = NULL;
5234 tginfo[j].tgtype = 0;
5235 tginfo[j].tgnargs = 0;
5236 tginfo[j].tgargs = NULL;
5237 tginfo[j].tgisconstraint = false;
5238 tginfo[j].tgdeferrable = false;
5239 tginfo[j].tginitdeferred = false;
5240 tginfo[j].tgconstrname = NULL;
5241 tginfo[j].tgconstrrelid = InvalidOid;
5242 tginfo[j].tgconstrrelname = NULL;
5246 tginfo[j].tgdef = NULL;
5248 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5249 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5250 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5251 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5252 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5253 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5254 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5256 if (tginfo[j].tgisconstraint)
5258 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5259 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5260 if (OidIsValid(tginfo[j].tgconstrrelid))
5262 if (PQgetisnull(res, j, i_tgconstrrelname))
5263 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5264 tginfo[j].dobj.name,
5266 tginfo[j].tgconstrrelid);
5267 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5270 tginfo[j].tgconstrrelname = NULL;
5274 tginfo[j].tgconstrname = NULL;
5275 tginfo[j].tgconstrrelid = InvalidOid;
5276 tginfo[j].tgconstrrelname = NULL;
5284 destroyPQExpBuffer(query);
5289 * get basic information about every procedural language in the system
5291 * numProcLangs is set to the number of langs read in
5293 * NB: this must run after getFuncs() because we assume we can do
5297 getProcLangs(Archive *fout, int *numProcLangs)
5302 PQExpBuffer query = createPQExpBuffer();
5303 ProcLangInfo *planginfo;
5308 int i_lanplcallfoid;
5314 /* Make sure we are in proper schema */
5315 selectSourceSchema(fout, "pg_catalog");
5317 if (fout->remoteVersion >= 90000)
5319 /* pg_language has a laninline column */
5320 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5321 "lanname, lanpltrusted, lanplcallfoid, "
5322 "laninline, lanvalidator, lanacl, "
5323 "(%s lanowner) AS lanowner "
5329 else if (fout->remoteVersion >= 80300)
5331 /* pg_language has a lanowner column */
5332 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5333 "lanname, lanpltrusted, lanplcallfoid, "
5334 "lanvalidator, lanacl, "
5335 "(%s lanowner) AS lanowner "
5341 else if (fout->remoteVersion >= 80100)
5343 /* Languages are owned by the bootstrap superuser, OID 10 */
5344 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5345 "(%s '10') AS lanowner "
5351 else if (fout->remoteVersion >= 70400)
5353 /* Languages are owned by the bootstrap superuser, sysid 1 */
5354 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5355 "(%s '1') AS lanowner "
5361 else if (fout->remoteVersion >= 70100)
5363 /* No clear notion of an owner at all before 7.4 ... */
5364 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5370 appendPQExpBuffer(query, "SELECT "
5371 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5372 "oid, * FROM pg_language "
5377 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5379 ntups = PQntuples(res);
5381 *numProcLangs = ntups;
5383 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5385 i_tableoid = PQfnumber(res, "tableoid");
5386 i_oid = PQfnumber(res, "oid");
5387 i_lanname = PQfnumber(res, "lanname");
5388 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5389 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5390 /* these may fail and return -1: */
5391 i_laninline = PQfnumber(res, "laninline");
5392 i_lanvalidator = PQfnumber(res, "lanvalidator");
5393 i_lanacl = PQfnumber(res, "lanacl");
5394 i_lanowner = PQfnumber(res, "lanowner");
5396 for (i = 0; i < ntups; i++)
5398 planginfo[i].dobj.objType = DO_PROCLANG;
5399 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5400 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5401 AssignDumpId(&planginfo[i].dobj);
5403 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5404 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5405 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5406 if (i_laninline >= 0)
5407 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5409 planginfo[i].laninline = InvalidOid;
5410 if (i_lanvalidator >= 0)
5411 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5413 planginfo[i].lanvalidator = InvalidOid;
5415 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5417 planginfo[i].lanacl = pg_strdup("{=U}");
5418 if (i_lanowner >= 0)
5419 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5421 planginfo[i].lanowner = pg_strdup("");
5423 if (fout->remoteVersion < 70300)
5426 * We need to make a dependency to ensure the function will be
5427 * dumped first. (In 7.3 and later the regular dependency
5428 * mechanism will handle this for us.)
5430 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5433 addObjectDependency(&planginfo[i].dobj,
5434 funcInfo->dobj.dumpId);
5440 destroyPQExpBuffer(query);
5447 * get basic information about every cast in the system
5449 * numCasts is set to the number of casts read in
5452 getCasts(Archive *fout, int *numCasts)
5457 PQExpBuffer query = createPQExpBuffer();
5467 /* Make sure we are in proper schema */
5468 selectSourceSchema(fout, "pg_catalog");
5470 if (fout->remoteVersion >= 80400)
5472 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5473 "castsource, casttarget, castfunc, castcontext, "
5475 "FROM pg_cast ORDER BY 3,4");
5477 else if (fout->remoteVersion >= 70300)
5479 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5480 "castsource, casttarget, castfunc, castcontext, "
5481 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5482 "FROM pg_cast ORDER BY 3,4");
5486 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5487 "t1.oid AS castsource, t2.oid AS casttarget, "
5488 "p.oid AS castfunc, 'e' AS castcontext, "
5489 "'f' AS castmethod "
5490 "FROM pg_type t1, pg_type t2, pg_proc p "
5491 "WHERE p.pronargs = 1 AND "
5492 "p.proargtypes[0] = t1.oid AND "
5493 "p.prorettype = t2.oid AND p.proname = t2.typname "
5497 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5499 ntups = PQntuples(res);
5503 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5505 i_tableoid = PQfnumber(res, "tableoid");
5506 i_oid = PQfnumber(res, "oid");
5507 i_castsource = PQfnumber(res, "castsource");
5508 i_casttarget = PQfnumber(res, "casttarget");
5509 i_castfunc = PQfnumber(res, "castfunc");
5510 i_castcontext = PQfnumber(res, "castcontext");
5511 i_castmethod = PQfnumber(res, "castmethod");
5513 for (i = 0; i < ntups; i++)
5515 PQExpBufferData namebuf;
5516 TypeInfo *sTypeInfo;
5517 TypeInfo *tTypeInfo;
5519 castinfo[i].dobj.objType = DO_CAST;
5520 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5521 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5522 AssignDumpId(&castinfo[i].dobj);
5523 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5524 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5525 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5526 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5527 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5530 * Try to name cast as concatenation of typnames. This is only used
5531 * for purposes of sorting. If we fail to find either type, the name
5532 * will be an empty string.
5534 initPQExpBuffer(&namebuf);
5535 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5536 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5537 if (sTypeInfo && tTypeInfo)
5538 appendPQExpBuffer(&namebuf, "%s %s",
5539 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5540 castinfo[i].dobj.name = namebuf.data;
5542 if (OidIsValid(castinfo[i].castfunc))
5545 * We need to make a dependency to ensure the function will be
5546 * dumped first. (In 7.3 and later the regular dependency
5547 * mechanism will handle this for us.)
5551 funcInfo = findFuncByOid(castinfo[i].castfunc);
5553 addObjectDependency(&castinfo[i].dobj,
5554 funcInfo->dobj.dumpId);
5560 destroyPQExpBuffer(query);
5567 * for each interesting table, read info about its attributes
5568 * (names, types, default values, CHECK constraints, etc)
5570 * This is implemented in a very inefficient way right now, looping
5571 * through the tblinfo and doing a join per table to find the attrs and their
5572 * types. However, because we want type names and so forth to be named
5573 * relative to the schema of each table, we couldn't do it in just one
5574 * query. (Maybe one query per schema?)
5579 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5583 PQExpBuffer q = createPQExpBuffer();
5588 int i_attstattarget;
5599 int i_attfdwoptions;
5604 for (i = 0; i < numTables; i++)
5606 TableInfo *tbinfo = &tblinfo[i];
5608 /* Don't bother to collect info for sequences */
5609 if (tbinfo->relkind == RELKIND_SEQUENCE)
5612 /* Don't bother with uninteresting tables, either */
5613 if (!tbinfo->interesting)
5617 * Make sure we are in proper schema for this table; this allows
5618 * correct retrieval of formatted type names and default exprs
5620 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5622 /* find all the user attributes and their types */
5625 * we must read the attribute names in attribute number order! because
5626 * we will use the attnum to index into the attnames array later. We
5627 * actually ask to order by "attrelid, attnum" because (at least up to
5628 * 7.3) the planner is not smart enough to realize it needn't re-sort
5629 * the output of an indexscan on pg_attribute_relid_attnum_index.
5632 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5635 resetPQExpBuffer(q);
5637 if (fout->remoteVersion >= 90200)
5640 * attfdwoptions is new in 9.2.
5642 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5643 "a.attstattarget, a.attstorage, t.typstorage, "
5644 "a.attnotnull, a.atthasdef, a.attisdropped, "
5645 "a.attlen, a.attalign, a.attislocal, "
5646 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5647 "array_to_string(a.attoptions, ', ') AS attoptions, "
5648 "CASE WHEN a.attcollation <> t.typcollation "
5649 "THEN a.attcollation ELSE 0 END AS attcollation, "
5650 "pg_catalog.array_to_string(ARRAY("
5651 "SELECT pg_catalog.quote_ident(option_name) || "
5652 "' ' || pg_catalog.quote_literal(option_value) "
5653 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5654 "ORDER BY option_name"
5655 "), E',\n ') AS attfdwoptions "
5656 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5657 "ON a.atttypid = t.oid "
5658 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5659 "AND a.attnum > 0::pg_catalog.int2 "
5660 "ORDER BY a.attrelid, a.attnum",
5661 tbinfo->dobj.catId.oid);
5663 else if (fout->remoteVersion >= 90100)
5666 * attcollation is new in 9.1. Since we only want to dump COLLATE
5667 * clauses for attributes whose collation is different from their
5668 * type's default, we use a CASE here to suppress uninteresting
5669 * attcollations cheaply.
5671 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5672 "a.attstattarget, a.attstorage, t.typstorage, "
5673 "a.attnotnull, a.atthasdef, a.attisdropped, "
5674 "a.attlen, a.attalign, a.attislocal, "
5675 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5676 "array_to_string(a.attoptions, ', ') AS attoptions, "
5677 "CASE WHEN a.attcollation <> t.typcollation "
5678 "THEN a.attcollation ELSE 0 END AS attcollation, "
5679 "NULL AS attfdwoptions "
5680 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5681 "ON a.atttypid = t.oid "
5682 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5683 "AND a.attnum > 0::pg_catalog.int2 "
5684 "ORDER BY a.attrelid, a.attnum",
5685 tbinfo->dobj.catId.oid);
5687 else if (fout->remoteVersion >= 90000)
5689 /* attoptions is new in 9.0 */
5690 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5691 "a.attstattarget, a.attstorage, t.typstorage, "
5692 "a.attnotnull, a.atthasdef, a.attisdropped, "
5693 "a.attlen, a.attalign, a.attislocal, "
5694 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5695 "array_to_string(a.attoptions, ', ') AS attoptions, "
5696 "0 AS attcollation, "
5697 "NULL AS attfdwoptions "
5698 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5699 "ON a.atttypid = t.oid "
5700 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5701 "AND a.attnum > 0::pg_catalog.int2 "
5702 "ORDER BY a.attrelid, a.attnum",
5703 tbinfo->dobj.catId.oid);
5705 else if (fout->remoteVersion >= 70300)
5707 /* need left join here to not fail on dropped columns ... */
5708 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5709 "a.attstattarget, a.attstorage, t.typstorage, "
5710 "a.attnotnull, a.atthasdef, a.attisdropped, "
5711 "a.attlen, a.attalign, a.attislocal, "
5712 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5713 "'' AS attoptions, 0 AS attcollation, "
5714 "NULL AS attfdwoptions "
5715 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5716 "ON a.atttypid = t.oid "
5717 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5718 "AND a.attnum > 0::pg_catalog.int2 "
5719 "ORDER BY a.attrelid, a.attnum",
5720 tbinfo->dobj.catId.oid);
5722 else if (fout->remoteVersion >= 70100)
5725 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5726 * we don't dump it because we can't tell whether it's been
5727 * explicitly set or was just a default.
5729 * attislocal doesn't exist before 7.3, either; in older databases
5730 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5732 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5733 "-1 AS attstattarget, a.attstorage, "
5734 "t.typstorage, a.attnotnull, a.atthasdef, "
5735 "false AS attisdropped, a.attlen, "
5736 "a.attalign, true AS attislocal, "
5737 "format_type(t.oid,a.atttypmod) AS atttypname, "
5738 "'' AS attoptions, 0 AS attcollation, "
5739 "NULL AS attfdwoptions "
5740 "FROM pg_attribute a LEFT JOIN pg_type t "
5741 "ON a.atttypid = t.oid "
5742 "WHERE a.attrelid = '%u'::oid "
5743 "AND a.attnum > 0::int2 "
5744 "ORDER BY a.attrelid, a.attnum",
5745 tbinfo->dobj.catId.oid);
5749 /* format_type not available before 7.1 */
5750 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5751 "-1 AS attstattarget, "
5752 "attstorage, attstorage AS typstorage, "
5753 "attnotnull, atthasdef, false AS attisdropped, "
5754 "attlen, attalign, "
5755 "true AS attislocal, "
5756 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5757 "'' AS attoptions, 0 AS attcollation, "
5758 "NULL AS attfdwoptions "
5759 "FROM pg_attribute a "
5760 "WHERE attrelid = '%u'::oid "
5761 "AND attnum > 0::int2 "
5762 "ORDER BY attrelid, attnum",
5763 tbinfo->dobj.catId.oid);
5766 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5768 ntups = PQntuples(res);
5770 i_attnum = PQfnumber(res, "attnum");
5771 i_attname = PQfnumber(res, "attname");
5772 i_atttypname = PQfnumber(res, "atttypname");
5773 i_atttypmod = PQfnumber(res, "atttypmod");
5774 i_attstattarget = PQfnumber(res, "attstattarget");
5775 i_attstorage = PQfnumber(res, "attstorage");
5776 i_typstorage = PQfnumber(res, "typstorage");
5777 i_attnotnull = PQfnumber(res, "attnotnull");
5778 i_atthasdef = PQfnumber(res, "atthasdef");
5779 i_attisdropped = PQfnumber(res, "attisdropped");
5780 i_attlen = PQfnumber(res, "attlen");
5781 i_attalign = PQfnumber(res, "attalign");
5782 i_attislocal = PQfnumber(res, "attislocal");
5783 i_attoptions = PQfnumber(res, "attoptions");
5784 i_attcollation = PQfnumber(res, "attcollation");
5785 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5787 tbinfo->numatts = ntups;
5788 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5789 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5790 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5791 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5792 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5793 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5794 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5795 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5796 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5797 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5798 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5799 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5800 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5801 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5802 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5803 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5804 hasdefaults = false;
5806 for (j = 0; j < ntups; j++)
5808 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5810 "invalid column numbering in table \"%s\"\n",
5812 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5813 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5814 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5815 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5816 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5817 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5818 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5819 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5820 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5821 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5822 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5823 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5824 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5825 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5826 tbinfo->attrdefs[j] = NULL; /* fix below */
5827 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5829 /* these flags will be set in flagInhAttrs() */
5830 tbinfo->inhNotNull[j] = false;
5836 * Get info about column defaults
5840 AttrDefInfo *attrdefs;
5844 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5847 resetPQExpBuffer(q);
5848 if (fout->remoteVersion >= 70300)
5850 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5851 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5852 "FROM pg_catalog.pg_attrdef "
5853 "WHERE adrelid = '%u'::pg_catalog.oid",
5854 tbinfo->dobj.catId.oid);
5856 else if (fout->remoteVersion >= 70200)
5858 /* 7.2 did not have OIDs in pg_attrdef */
5859 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5860 "pg_get_expr(adbin, adrelid) AS adsrc "
5862 "WHERE adrelid = '%u'::oid",
5863 tbinfo->dobj.catId.oid);
5865 else if (fout->remoteVersion >= 70100)
5867 /* no pg_get_expr, so must rely on adsrc */
5868 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5870 "WHERE adrelid = '%u'::oid",
5871 tbinfo->dobj.catId.oid);
5875 /* no pg_get_expr, no tableoid either */
5876 appendPQExpBuffer(q, "SELECT "
5877 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5878 "oid, adnum, adsrc "
5880 "WHERE adrelid = '%u'::oid",
5881 tbinfo->dobj.catId.oid);
5883 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5885 numDefaults = PQntuples(res);
5886 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5888 for (j = 0; j < numDefaults; j++)
5892 adnum = atoi(PQgetvalue(res, j, 2));
5894 if (adnum <= 0 || adnum > ntups)
5896 "invalid adnum value %d for table \"%s\"\n",
5897 adnum, tbinfo->dobj.name);
5900 * dropped columns shouldn't have defaults, but just in case,
5903 if (tbinfo->attisdropped[adnum - 1])
5906 attrdefs[j].dobj.objType = DO_ATTRDEF;
5907 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5908 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5909 AssignDumpId(&attrdefs[j].dobj);
5910 attrdefs[j].adtable = tbinfo;
5911 attrdefs[j].adnum = adnum;
5912 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5914 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5915 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5917 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5920 * Defaults on a VIEW must always be dumped as separate ALTER
5921 * TABLE commands. Defaults on regular tables are dumped as
5922 * part of the CREATE TABLE if possible, which it won't be
5923 * if the column is not going to be emitted explicitly.
5925 if (tbinfo->relkind == RELKIND_VIEW)
5927 attrdefs[j].separate = true;
5928 /* needed in case pre-7.3 DB: */
5929 addObjectDependency(&attrdefs[j].dobj,
5930 tbinfo->dobj.dumpId);
5932 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5934 /* column will be suppressed, print default separately */
5935 attrdefs[j].separate = true;
5936 /* needed in case pre-7.3 DB: */
5937 addObjectDependency(&attrdefs[j].dobj,
5938 tbinfo->dobj.dumpId);
5942 attrdefs[j].separate = false;
5944 * Mark the default as needing to appear before the table,
5945 * so that any dependencies it has must be emitted before
5946 * the CREATE TABLE. If this is not possible, we'll
5947 * change to "separate" mode while sorting dependencies.
5949 addObjectDependency(&tbinfo->dobj,
5950 attrdefs[j].dobj.dumpId);
5953 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5959 * Get info about table CHECK constraints
5961 if (tbinfo->ncheck > 0)
5963 ConstraintInfo *constrs;
5967 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5970 resetPQExpBuffer(q);
5971 if (fout->remoteVersion >= 90200)
5974 * conisonly and convalidated are new in 9.2 (actually, the latter
5975 * is there in 9.1, but it wasn't ever false for check constraints
5978 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5979 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5980 "conislocal, convalidated, conisonly "
5981 "FROM pg_catalog.pg_constraint "
5982 "WHERE conrelid = '%u'::pg_catalog.oid "
5983 " AND contype = 'c' "
5985 tbinfo->dobj.catId.oid);
5987 else if (fout->remoteVersion >= 80400)
5989 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5990 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5991 "conislocal, true AS convalidated, "
5992 "false as conisonly "
5993 "FROM pg_catalog.pg_constraint "
5994 "WHERE conrelid = '%u'::pg_catalog.oid "
5995 " AND contype = 'c' "
5997 tbinfo->dobj.catId.oid);
5999 else if (fout->remoteVersion >= 70400)
6001 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6002 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6003 "true AS conislocal, true AS convalidated, "
6004 "false as conisonly "
6005 "FROM pg_catalog.pg_constraint "
6006 "WHERE conrelid = '%u'::pg_catalog.oid "
6007 " AND contype = 'c' "
6009 tbinfo->dobj.catId.oid);
6011 else if (fout->remoteVersion >= 70300)
6013 /* no pg_get_constraintdef, must use consrc */
6014 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6015 "'CHECK (' || consrc || ')' AS consrc, "
6016 "true AS conislocal, true AS convalidated, "
6017 "false as conisonly "
6018 "FROM pg_catalog.pg_constraint "
6019 "WHERE conrelid = '%u'::pg_catalog.oid "
6020 " AND contype = 'c' "
6022 tbinfo->dobj.catId.oid);
6024 else if (fout->remoteVersion >= 70200)
6026 /* 7.2 did not have OIDs in pg_relcheck */
6027 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6028 "rcname AS conname, "
6029 "'CHECK (' || rcsrc || ')' AS consrc, "
6030 "true AS conislocal, true AS convalidated, "
6031 "false as conisonly "
6033 "WHERE rcrelid = '%u'::oid "
6035 tbinfo->dobj.catId.oid);
6037 else if (fout->remoteVersion >= 70100)
6039 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6040 "rcname AS conname, "
6041 "'CHECK (' || rcsrc || ')' AS consrc, "
6042 "true AS conislocal, true AS convalidated, "
6043 "false as conisonly "
6045 "WHERE rcrelid = '%u'::oid "
6047 tbinfo->dobj.catId.oid);
6051 /* no tableoid in 7.0 */
6052 appendPQExpBuffer(q, "SELECT "
6053 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6054 "oid, rcname AS conname, "
6055 "'CHECK (' || rcsrc || ')' AS consrc, "
6056 "true AS conislocal, true AS convalidated, "
6057 "false as conisonly "
6059 "WHERE rcrelid = '%u'::oid "
6061 tbinfo->dobj.catId.oid);
6063 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6065 numConstrs = PQntuples(res);
6066 if (numConstrs != tbinfo->ncheck)
6068 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6069 "expected %d check constraints on table \"%s\" but found %d\n",
6071 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6072 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6076 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6077 tbinfo->checkexprs = constrs;
6079 for (j = 0; j < numConstrs; j++)
6081 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6082 bool isonly = PQgetvalue(res, j, 6)[0] == 't';
6084 constrs[j].dobj.objType = DO_CONSTRAINT;
6085 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6086 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6087 AssignDumpId(&constrs[j].dobj);
6088 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6089 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6090 constrs[j].contable = tbinfo;
6091 constrs[j].condomain = NULL;
6092 constrs[j].contype = 'c';
6093 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6094 constrs[j].confrelid = InvalidOid;
6095 constrs[j].conindex = 0;
6096 constrs[j].condeferrable = false;
6097 constrs[j].condeferred = false;
6098 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6099 constrs[j].conisonly = isonly;
6101 * An unvalidated constraint needs to be dumped separately, so
6102 * that potentially-violating existing data is loaded before
6103 * the constraint. An ONLY constraint needs to be dumped
6106 constrs[j].separate = !validated || isonly;
6108 constrs[j].dobj.dump = tbinfo->dobj.dump;
6111 * Mark the constraint as needing to appear before the table
6112 * --- this is so that any other dependencies of the
6113 * constraint will be emitted before we try to create the
6114 * table. If the constraint is to be dumped separately, it will be
6115 * dumped after data is loaded anyway, so don't do it. (There's
6116 * an automatic dependency in the opposite direction anyway, so
6117 * don't need to add one manually here.)
6119 if (!constrs[j].separate)
6120 addObjectDependency(&tbinfo->dobj,
6121 constrs[j].dobj.dumpId);
6124 * If the constraint is inherited, this will be detected later
6125 * (in pre-8.4 databases). We also detect later if the
6126 * constraint must be split out from the table definition.
6133 destroyPQExpBuffer(q);
6137 * Test whether a column should be printed as part of table's CREATE TABLE.
6138 * Column number is zero-based.
6140 * Normally this is always true, but it's false for dropped columns, as well
6141 * as those that were inherited without any local definition. (If we print
6142 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6143 * However, in binary_upgrade mode, we must print all such columns anyway and
6144 * fix the attislocal/attisdropped state later, so as to keep control of the
6145 * physical column order.
6147 * This function exists because there are scattered nonobvious places that
6148 * must be kept in sync with this decision.
6151 shouldPrintColumn(TableInfo *tbinfo, int colno)
6155 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6161 * read all text search parsers in the system catalogs and return them
6162 * in the TSParserInfo* structure
6164 * numTSParsers is set to the number of parsers read in
6167 getTSParsers(Archive *fout, int *numTSParsers)
6173 TSParserInfo *prsinfo;
6184 /* Before 8.3, there is no built-in text search support */
6185 if (fout->remoteVersion < 80300)
6191 query = createPQExpBuffer();
6194 * find all text search objects, including builtin ones; we filter out
6195 * system-defined objects at dump-out time.
6198 /* Make sure we are in proper schema */
6199 selectSourceSchema(fout, "pg_catalog");
6201 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6202 "prsstart::oid, prstoken::oid, "
6203 "prsend::oid, prsheadline::oid, prslextype::oid "
6204 "FROM pg_ts_parser");
6206 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6208 ntups = PQntuples(res);
6209 *numTSParsers = ntups;
6211 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6213 i_tableoid = PQfnumber(res, "tableoid");
6214 i_oid = PQfnumber(res, "oid");
6215 i_prsname = PQfnumber(res, "prsname");
6216 i_prsnamespace = PQfnumber(res, "prsnamespace");
6217 i_prsstart = PQfnumber(res, "prsstart");
6218 i_prstoken = PQfnumber(res, "prstoken");
6219 i_prsend = PQfnumber(res, "prsend");
6220 i_prsheadline = PQfnumber(res, "prsheadline");
6221 i_prslextype = PQfnumber(res, "prslextype");
6223 for (i = 0; i < ntups; i++)
6225 prsinfo[i].dobj.objType = DO_TSPARSER;
6226 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6227 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6228 AssignDumpId(&prsinfo[i].dobj);
6229 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6230 prsinfo[i].dobj.namespace =
6232 atooid(PQgetvalue(res, i, i_prsnamespace)),
6233 prsinfo[i].dobj.catId.oid);
6234 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6235 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6236 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6237 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6238 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6240 /* Decide whether we want to dump it */
6241 selectDumpableObject(&(prsinfo[i].dobj));
6246 destroyPQExpBuffer(query);
6252 * getTSDictionaries:
6253 * read all text search dictionaries in the system catalogs and return them
6254 * in the TSDictInfo* structure
6256 * numTSDicts is set to the number of dictionaries read in
6259 getTSDictionaries(Archive *fout, int *numTSDicts)
6265 TSDictInfo *dictinfo;
6269 int i_dictnamespace;
6272 int i_dictinitoption;
6274 /* Before 8.3, there is no built-in text search support */
6275 if (fout->remoteVersion < 80300)
6281 query = createPQExpBuffer();
6283 /* Make sure we are in proper schema */
6284 selectSourceSchema(fout, "pg_catalog");
6286 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6287 "dictnamespace, (%s dictowner) AS rolname, "
6288 "dicttemplate, dictinitoption "
6292 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6294 ntups = PQntuples(res);
6295 *numTSDicts = ntups;
6297 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6299 i_tableoid = PQfnumber(res, "tableoid");
6300 i_oid = PQfnumber(res, "oid");
6301 i_dictname = PQfnumber(res, "dictname");
6302 i_dictnamespace = PQfnumber(res, "dictnamespace");
6303 i_rolname = PQfnumber(res, "rolname");
6304 i_dictinitoption = PQfnumber(res, "dictinitoption");
6305 i_dicttemplate = PQfnumber(res, "dicttemplate");
6307 for (i = 0; i < ntups; i++)
6309 dictinfo[i].dobj.objType = DO_TSDICT;
6310 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6311 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6312 AssignDumpId(&dictinfo[i].dobj);
6313 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6314 dictinfo[i].dobj.namespace =
6316 atooid(PQgetvalue(res, i, i_dictnamespace)),
6317 dictinfo[i].dobj.catId.oid);
6318 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6319 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6320 if (PQgetisnull(res, i, i_dictinitoption))
6321 dictinfo[i].dictinitoption = NULL;
6323 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6325 /* Decide whether we want to dump it */
6326 selectDumpableObject(&(dictinfo[i].dobj));
6331 destroyPQExpBuffer(query);
6338 * read all text search templates in the system catalogs and return them
6339 * in the TSTemplateInfo* structure
6341 * numTSTemplates is set to the number of templates read in
6344 getTSTemplates(Archive *fout, int *numTSTemplates)
6350 TSTemplateInfo *tmplinfo;
6354 int i_tmplnamespace;
6358 /* Before 8.3, there is no built-in text search support */
6359 if (fout->remoteVersion < 80300)
6361 *numTSTemplates = 0;
6365 query = createPQExpBuffer();
6367 /* Make sure we are in proper schema */
6368 selectSourceSchema(fout, "pg_catalog");
6370 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6371 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6372 "FROM pg_ts_template");
6374 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6376 ntups = PQntuples(res);
6377 *numTSTemplates = ntups;
6379 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6381 i_tableoid = PQfnumber(res, "tableoid");
6382 i_oid = PQfnumber(res, "oid");
6383 i_tmplname = PQfnumber(res, "tmplname");
6384 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6385 i_tmplinit = PQfnumber(res, "tmplinit");
6386 i_tmpllexize = PQfnumber(res, "tmpllexize");
6388 for (i = 0; i < ntups; i++)
6390 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6391 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6392 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6393 AssignDumpId(&tmplinfo[i].dobj);
6394 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6395 tmplinfo[i].dobj.namespace =
6397 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6398 tmplinfo[i].dobj.catId.oid);
6399 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6400 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6402 /* Decide whether we want to dump it */
6403 selectDumpableObject(&(tmplinfo[i].dobj));
6408 destroyPQExpBuffer(query);
6414 * getTSConfigurations:
6415 * read all text search configurations in the system catalogs and return
6416 * them in the TSConfigInfo* structure
6418 * numTSConfigs is set to the number of configurations read in
6421 getTSConfigurations(Archive *fout, int *numTSConfigs)
6427 TSConfigInfo *cfginfo;
6435 /* Before 8.3, there is no built-in text search support */
6436 if (fout->remoteVersion < 80300)
6442 query = createPQExpBuffer();
6444 /* Make sure we are in proper schema */
6445 selectSourceSchema(fout, "pg_catalog");
6447 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6448 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6449 "FROM pg_ts_config",
6452 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6454 ntups = PQntuples(res);
6455 *numTSConfigs = ntups;
6457 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6459 i_tableoid = PQfnumber(res, "tableoid");
6460 i_oid = PQfnumber(res, "oid");
6461 i_cfgname = PQfnumber(res, "cfgname");
6462 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6463 i_rolname = PQfnumber(res, "rolname");
6464 i_cfgparser = PQfnumber(res, "cfgparser");
6466 for (i = 0; i < ntups; i++)
6468 cfginfo[i].dobj.objType = DO_TSCONFIG;
6469 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6470 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6471 AssignDumpId(&cfginfo[i].dobj);
6472 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6473 cfginfo[i].dobj.namespace =
6475 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6476 cfginfo[i].dobj.catId.oid);
6477 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6478 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6480 /* Decide whether we want to dump it */
6481 selectDumpableObject(&(cfginfo[i].dobj));
6486 destroyPQExpBuffer(query);
6492 * getForeignDataWrappers:
6493 * read all foreign-data wrappers in the system catalogs and return
6494 * them in the FdwInfo* structure
6496 * numForeignDataWrappers is set to the number of fdws read in
6499 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6504 PQExpBuffer query = createPQExpBuffer();
6515 /* Before 8.4, there are no foreign-data wrappers */
6516 if (fout->remoteVersion < 80400)
6518 *numForeignDataWrappers = 0;
6522 /* Make sure we are in proper schema */
6523 selectSourceSchema(fout, "pg_catalog");
6525 if (fout->remoteVersion >= 90100)
6527 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6528 "(%s fdwowner) AS rolname, "
6529 "fdwhandler::pg_catalog.regproc, "
6530 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6531 "array_to_string(ARRAY("
6532 "SELECT quote_ident(option_name) || ' ' || "
6533 "quote_literal(option_value) "
6534 "FROM pg_options_to_table(fdwoptions) "
6535 "ORDER BY option_name"
6536 "), E',\n ') AS fdwoptions "
6537 "FROM pg_foreign_data_wrapper",
6542 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6543 "(%s fdwowner) AS rolname, "
6544 "'-' AS fdwhandler, "
6545 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6546 "array_to_string(ARRAY("
6547 "SELECT quote_ident(option_name) || ' ' || "
6548 "quote_literal(option_value) "
6549 "FROM pg_options_to_table(fdwoptions) "
6550 "ORDER BY option_name"
6551 "), E',\n ') AS fdwoptions "
6552 "FROM pg_foreign_data_wrapper",
6556 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6558 ntups = PQntuples(res);
6559 *numForeignDataWrappers = ntups;
6561 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6563 i_tableoid = PQfnumber(res, "tableoid");
6564 i_oid = PQfnumber(res, "oid");
6565 i_fdwname = PQfnumber(res, "fdwname");
6566 i_rolname = PQfnumber(res, "rolname");
6567 i_fdwhandler = PQfnumber(res, "fdwhandler");
6568 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6569 i_fdwacl = PQfnumber(res, "fdwacl");
6570 i_fdwoptions = PQfnumber(res, "fdwoptions");
6572 for (i = 0; i < ntups; i++)
6574 fdwinfo[i].dobj.objType = DO_FDW;
6575 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6576 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6577 AssignDumpId(&fdwinfo[i].dobj);
6578 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6579 fdwinfo[i].dobj.namespace = NULL;
6580 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6581 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6582 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6583 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6584 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6586 /* Decide whether we want to dump it */
6587 selectDumpableObject(&(fdwinfo[i].dobj));
6592 destroyPQExpBuffer(query);
6598 * getForeignServers:
6599 * read all foreign servers in the system catalogs and return
6600 * them in the ForeignServerInfo * structure
6602 * numForeignServers is set to the number of servers read in
6605 getForeignServers(Archive *fout, int *numForeignServers)
6610 PQExpBuffer query = createPQExpBuffer();
6611 ForeignServerInfo *srvinfo;
6622 /* Before 8.4, there are no foreign servers */
6623 if (fout->remoteVersion < 80400)
6625 *numForeignServers = 0;
6629 /* Make sure we are in proper schema */
6630 selectSourceSchema(fout,"pg_catalog");
6632 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6633 "(%s srvowner) AS rolname, "
6634 "srvfdw, srvtype, srvversion, srvacl,"
6635 "array_to_string(ARRAY("
6636 "SELECT quote_ident(option_name) || ' ' || "
6637 "quote_literal(option_value) "
6638 "FROM pg_options_to_table(srvoptions) "
6639 "ORDER BY option_name"
6640 "), E',\n ') AS srvoptions "
6641 "FROM pg_foreign_server",
6644 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6646 ntups = PQntuples(res);
6647 *numForeignServers = ntups;
6649 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6651 i_tableoid = PQfnumber(res, "tableoid");
6652 i_oid = PQfnumber(res, "oid");
6653 i_srvname = PQfnumber(res, "srvname");
6654 i_rolname = PQfnumber(res, "rolname");
6655 i_srvfdw = PQfnumber(res, "srvfdw");
6656 i_srvtype = PQfnumber(res, "srvtype");
6657 i_srvversion = PQfnumber(res, "srvversion");
6658 i_srvacl = PQfnumber(res, "srvacl");
6659 i_srvoptions = PQfnumber(res, "srvoptions");
6661 for (i = 0; i < ntups; i++)
6663 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6664 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6665 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6666 AssignDumpId(&srvinfo[i].dobj);
6667 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6668 srvinfo[i].dobj.namespace = NULL;
6669 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6670 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6671 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6672 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6673 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6674 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6676 /* Decide whether we want to dump it */
6677 selectDumpableObject(&(srvinfo[i].dobj));
6682 destroyPQExpBuffer(query);
6689 * read all default ACL information in the system catalogs and return
6690 * them in the DefaultACLInfo structure
6692 * numDefaultACLs is set to the number of ACLs read in
6695 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6697 DefaultACLInfo *daclinfo;
6703 int i_defaclnamespace;
6704 int i_defaclobjtype;
6709 if (fout->remoteVersion < 90000)
6711 *numDefaultACLs = 0;
6715 query = createPQExpBuffer();
6717 /* Make sure we are in proper schema */
6718 selectSourceSchema(fout, "pg_catalog");
6720 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6721 "(%s defaclrole) AS defaclrole, "
6725 "FROM pg_default_acl",
6728 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6730 ntups = PQntuples(res);
6731 *numDefaultACLs = ntups;
6733 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6735 i_oid = PQfnumber(res, "oid");
6736 i_tableoid = PQfnumber(res, "tableoid");
6737 i_defaclrole = PQfnumber(res, "defaclrole");
6738 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6739 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6740 i_defaclacl = PQfnumber(res, "defaclacl");
6742 for (i = 0; i < ntups; i++)
6744 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6746 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6747 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6748 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6749 AssignDumpId(&daclinfo[i].dobj);
6750 /* cheesy ... is it worth coming up with a better object name? */
6751 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6753 if (nspid != InvalidOid)
6754 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6755 daclinfo[i].dobj.catId.oid);
6757 daclinfo[i].dobj.namespace = NULL;
6759 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6760 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6761 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6763 /* Decide whether we want to dump it */
6764 selectDumpableDefaultACL(&(daclinfo[i]));
6769 destroyPQExpBuffer(query);
6777 * This routine is used to dump any comments associated with the
6778 * object handed to this routine. The routine takes a constant character
6779 * string for the target part of the comment-creation command, plus
6780 * the namespace and owner of the object (for labeling the ArchiveEntry),
6781 * plus catalog ID and subid which are the lookup key for pg_description,
6782 * plus the dump ID for the object (for setting a dependency).
6783 * If a matching pg_description entry is found, it is dumped.
6785 * Note: although this routine takes a dumpId for dependency purposes,
6786 * that purpose is just to mark the dependency in the emitted dump file
6787 * for possible future use by pg_restore. We do NOT use it for determining
6788 * ordering of the comment in the dump file, because this routine is called
6789 * after dependency sorting occurs. This routine should be called just after
6790 * calling ArchiveEntry() for the specified object.
6793 dumpComment(Archive *fout, const char *target,
6794 const char *namespace, const char *owner,
6795 CatalogId catalogId, int subid, DumpId dumpId)
6797 CommentItem *comments;
6800 /* Comments are schema not data ... except blob comments are data */
6801 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6812 /* Search for comments associated with catalogId, using table */
6813 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6816 /* Is there one matching the subid? */
6817 while (ncomments > 0)
6819 if (comments->objsubid == subid)
6825 /* If a comment exists, build COMMENT ON statement */
6828 PQExpBuffer query = createPQExpBuffer();
6830 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6831 appendStringLiteralAH(query, comments->descr, fout);
6832 appendPQExpBuffer(query, ";\n");
6835 * We mark comments as SECTION_NONE because they really belong in the
6836 * same section as their parent, whether that is pre-data or
6839 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6840 target, namespace, NULL, owner,
6841 false, "COMMENT", SECTION_NONE,
6842 query->data, "", NULL,
6846 destroyPQExpBuffer(query);
6851 * dumpTableComment --
6853 * As above, but dump comments for both the specified table (or view)
6857 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6858 const char *reltypename)
6860 CommentItem *comments;
6865 /* Comments are SCHEMA not data */
6869 /* Search for comments associated with relation, using table */
6870 ncomments = findComments(fout,
6871 tbinfo->dobj.catId.tableoid,
6872 tbinfo->dobj.catId.oid,
6875 /* If comments exist, build COMMENT ON statements */
6879 query = createPQExpBuffer();
6880 target = createPQExpBuffer();
6882 while (ncomments > 0)
6884 const char *descr = comments->descr;
6885 int objsubid = comments->objsubid;
6889 resetPQExpBuffer(target);
6890 appendPQExpBuffer(target, "%s %s", reltypename,
6891 fmtId(tbinfo->dobj.name));
6893 resetPQExpBuffer(query);
6894 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6895 appendStringLiteralAH(query, descr, fout);
6896 appendPQExpBuffer(query, ";\n");
6898 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6900 tbinfo->dobj.namespace->dobj.name,
6901 NULL, tbinfo->rolname,
6902 false, "COMMENT", SECTION_NONE,
6903 query->data, "", NULL,
6904 &(tbinfo->dobj.dumpId), 1,
6907 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6909 resetPQExpBuffer(target);
6910 appendPQExpBuffer(target, "COLUMN %s.",
6911 fmtId(tbinfo->dobj.name));
6912 appendPQExpBuffer(target, "%s",
6913 fmtId(tbinfo->attnames[objsubid - 1]));
6915 resetPQExpBuffer(query);
6916 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6917 appendStringLiteralAH(query, descr, fout);
6918 appendPQExpBuffer(query, ";\n");
6920 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6922 tbinfo->dobj.namespace->dobj.name,
6923 NULL, tbinfo->rolname,
6924 false, "COMMENT", SECTION_NONE,
6925 query->data, "", NULL,
6926 &(tbinfo->dobj.dumpId), 1,
6934 destroyPQExpBuffer(query);
6935 destroyPQExpBuffer(target);
6941 * Find the comment(s), if any, associated with the given object. All the
6942 * objsubid values associated with the given classoid/objoid are found with
6946 findComments(Archive *fout, Oid classoid, Oid objoid,
6947 CommentItem **items)
6949 /* static storage for table of comments */
6950 static CommentItem *comments = NULL;
6951 static int ncomments = -1;
6953 CommentItem *middle = NULL;
6958 /* Get comments if we didn't already */
6960 ncomments = collectComments(fout, &comments);
6963 * Pre-7.2, pg_description does not contain classoid, so collectComments
6964 * just stores a zero. If there's a collision on object OID, well, you
6965 * get duplicate comments.
6967 if (fout->remoteVersion < 70200)
6971 * Do binary search to find some item matching the object.
6974 high = &comments[ncomments - 1];
6977 middle = low + (high - low) / 2;
6979 if (classoid < middle->classoid)
6981 else if (classoid > middle->classoid)
6983 else if (objoid < middle->objoid)
6985 else if (objoid > middle->objoid)
6988 break; /* found a match */
6991 if (low > high) /* no matches */
6998 * Now determine how many items match the object. The search loop
6999 * invariant still holds: only items between low and high inclusive could
7003 while (middle > low)
7005 if (classoid != middle[-1].classoid ||
7006 objoid != middle[-1].objoid)
7015 while (middle <= high)
7017 if (classoid != middle->classoid ||
7018 objoid != middle->objoid)
7028 * collectComments --
7030 * Construct a table of all comments available for database objects.
7031 * We used to do per-object queries for the comments, but it's much faster
7032 * to pull them all over at once, and on most databases the memory cost
7035 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7038 collectComments(Archive *fout, CommentItem **items)
7048 CommentItem *comments;
7051 * Note we do NOT change source schema here; preserve the caller's
7055 query = createPQExpBuffer();
7057 if (fout->remoteVersion >= 70300)
7059 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7060 "FROM pg_catalog.pg_description "
7061 "ORDER BY classoid, objoid, objsubid");
7063 else if (fout->remoteVersion >= 70200)
7065 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7066 "FROM pg_description "
7067 "ORDER BY classoid, objoid, objsubid");
7071 /* Note: this will fail to find attribute comments in pre-7.2... */
7072 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7073 "FROM pg_description "
7077 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7079 /* Construct lookup table containing OIDs in numeric form */
7081 i_description = PQfnumber(res, "description");
7082 i_classoid = PQfnumber(res, "classoid");
7083 i_objoid = PQfnumber(res, "objoid");
7084 i_objsubid = PQfnumber(res, "objsubid");
7086 ntups = PQntuples(res);
7088 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7090 for (i = 0; i < ntups; i++)
7092 comments[i].descr = PQgetvalue(res, i, i_description);
7093 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7094 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7095 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7098 /* Do NOT free the PGresult since we are keeping pointers into it */
7099 destroyPQExpBuffer(query);
7106 * dumpDumpableObject
7108 * This routine and its subsidiaries are responsible for creating
7109 * ArchiveEntries (TOC objects) for each object to be dumped.
7112 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7117 switch (dobj->objType)
7122 case DO_FK_CONSTRAINT:
7124 skip = !(dumpSections & DUMP_POST_DATA);
7127 skip = !(dumpSections & DUMP_DATA);
7130 skip = !(dumpSections & DUMP_PRE_DATA);
7136 switch (dobj->objType)
7139 dumpNamespace(fout, (NamespaceInfo *) dobj);
7142 dumpExtension(fout, (ExtensionInfo *) dobj);
7145 dumpType(fout, (TypeInfo *) dobj);
7148 dumpShellType(fout, (ShellTypeInfo *) dobj);
7151 dumpFunc(fout, (FuncInfo *) dobj);
7154 dumpAgg(fout, (AggInfo *) dobj);
7157 dumpOpr(fout, (OprInfo *) dobj);
7160 dumpOpclass(fout, (OpclassInfo *) dobj);
7163 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7166 dumpCollation(fout, (CollInfo *) dobj);
7169 dumpConversion(fout, (ConvInfo *) dobj);
7172 dumpTable(fout, (TableInfo *) dobj);
7175 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7178 dumpIndex(fout, (IndxInfo *) dobj);
7181 dumpRule(fout, (RuleInfo *) dobj);
7184 dumpTrigger(fout, (TriggerInfo *) dobj);
7187 dumpConstraint(fout, (ConstraintInfo *) dobj);
7189 case DO_FK_CONSTRAINT:
7190 dumpConstraint(fout, (ConstraintInfo *) dobj);
7193 dumpProcLang(fout, (ProcLangInfo *) dobj);
7196 dumpCast(fout, (CastInfo *) dobj);
7199 dumpTableData(fout, (TableDataInfo *) dobj);
7202 /* table rowtypes and array types are never dumped separately */
7205 dumpTSParser(fout, (TSParserInfo *) dobj);
7208 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7211 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7214 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7217 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7219 case DO_FOREIGN_SERVER:
7220 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7222 case DO_DEFAULT_ACL:
7223 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7226 dumpBlob(fout, (BlobInfo *) dobj);
7229 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7230 dobj->name, NULL, NULL, "",
7231 false, "BLOBS", SECTION_DATA,
7233 dobj->dependencies, dobj->nDeps,
7241 * writes out to fout the queries to recreate a user-defined namespace
7244 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7251 /* Skip if not to be dumped */
7252 if (!nspinfo->dobj.dump || dataOnly)
7255 /* don't dump dummy namespace from pre-7.3 source */
7256 if (strlen(nspinfo->dobj.name) == 0)
7259 q = createPQExpBuffer();
7260 delq = createPQExpBuffer();
7261 labelq = createPQExpBuffer();
7263 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7265 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7267 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7269 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7272 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7274 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7278 false, "SCHEMA", SECTION_PRE_DATA,
7279 q->data, delq->data, NULL,
7280 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7283 /* Dump Schema Comments and Security Labels */
7284 dumpComment(fout, labelq->data,
7285 NULL, nspinfo->rolname,
7286 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7287 dumpSecLabel(fout, labelq->data,
7288 NULL, nspinfo->rolname,
7289 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7291 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7292 qnspname, NULL, nspinfo->dobj.name, NULL,
7293 nspinfo->rolname, nspinfo->nspacl);
7297 destroyPQExpBuffer(q);
7298 destroyPQExpBuffer(delq);
7299 destroyPQExpBuffer(labelq);
7304 * writes out to fout the queries to recreate an extension
7307 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7314 /* Skip if not to be dumped */
7315 if (!extinfo->dobj.dump || dataOnly)
7318 q = createPQExpBuffer();
7319 delq = createPQExpBuffer();
7320 labelq = createPQExpBuffer();
7322 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7324 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7326 if (!binary_upgrade)
7329 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7330 * problem if the extension already exists in the target database;
7331 * this is essential for installed-by-default extensions such as
7334 * In binary-upgrade mode, that doesn't work well, so instead we skip
7335 * built-in extensions based on their OIDs; see
7336 * selectDumpableExtension.
7338 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7339 qextname, fmtId(extinfo->namespace));
7346 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7347 appendPQExpBuffer(q,
7348 "SELECT binary_upgrade.create_empty_extension(");
7349 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7350 appendPQExpBuffer(q, ", ");
7351 appendStringLiteralAH(q, extinfo->namespace, fout);
7352 appendPQExpBuffer(q, ", ");
7353 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7354 appendStringLiteralAH(q, extinfo->extversion, fout);
7355 appendPQExpBuffer(q, ", ");
7358 * Note that we're pushing extconfig (an OID array) back into
7359 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7360 * preserved in binary upgrade.
7362 if (strlen(extinfo->extconfig) > 2)
7363 appendStringLiteralAH(q, extinfo->extconfig, fout);
7365 appendPQExpBuffer(q, "NULL");
7366 appendPQExpBuffer(q, ", ");
7367 if (strlen(extinfo->extcondition) > 2)
7368 appendStringLiteralAH(q, extinfo->extcondition, fout);
7370 appendPQExpBuffer(q, "NULL");
7371 appendPQExpBuffer(q, ", ");
7372 appendPQExpBuffer(q, "ARRAY[");
7374 for (i = 0; i < extinfo->dobj.nDeps; i++)
7376 DumpableObject *extobj;
7378 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7379 if (extobj && extobj->objType == DO_EXTENSION)
7382 appendPQExpBuffer(q, ",");
7383 appendStringLiteralAH(q, extobj->name, fout);
7386 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7387 appendPQExpBuffer(q, ");\n");
7390 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7392 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7396 false, "EXTENSION", SECTION_PRE_DATA,
7397 q->data, delq->data, NULL,
7398 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7401 /* Dump Extension Comments and Security Labels */
7402 dumpComment(fout, labelq->data,
7404 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7405 dumpSecLabel(fout, labelq->data,
7407 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7411 destroyPQExpBuffer(q);
7412 destroyPQExpBuffer(delq);
7413 destroyPQExpBuffer(labelq);
7418 * writes out to fout the queries to recreate a user-defined type
7421 dumpType(Archive *fout, TypeInfo *tyinfo)
7423 /* Skip if not to be dumped */
7424 if (!tyinfo->dobj.dump || dataOnly)
7427 /* Dump out in proper style */
7428 if (tyinfo->typtype == TYPTYPE_BASE)
7429 dumpBaseType(fout, tyinfo);
7430 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7431 dumpDomain(fout, tyinfo);
7432 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7433 dumpCompositeType(fout, tyinfo);
7434 else if (tyinfo->typtype == TYPTYPE_ENUM)
7435 dumpEnumType(fout, tyinfo);
7436 else if (tyinfo->typtype == TYPTYPE_RANGE)
7437 dumpRangeType(fout, tyinfo);
7439 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7445 * writes out to fout the queries to recreate a user-defined enum type
7448 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7450 PQExpBuffer q = createPQExpBuffer();
7451 PQExpBuffer delq = createPQExpBuffer();
7452 PQExpBuffer labelq = createPQExpBuffer();
7453 PQExpBuffer query = createPQExpBuffer();
7460 /* Set proper schema search path */
7461 selectSourceSchema(fout, "pg_catalog");
7463 if (fout->remoteVersion >= 90100)
7464 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7465 "FROM pg_catalog.pg_enum "
7466 "WHERE enumtypid = '%u'"
7467 "ORDER BY enumsortorder",
7468 tyinfo->dobj.catId.oid);
7470 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7471 "FROM pg_catalog.pg_enum "
7472 "WHERE enumtypid = '%u'"
7474 tyinfo->dobj.catId.oid);
7476 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7478 num = PQntuples(res);
7481 * DROP must be fully qualified in case same name appears in pg_catalog.
7482 * CASCADE shouldn't be required here as for normal types since the I/O
7483 * functions are generic and do not get dropped.
7485 appendPQExpBuffer(delq, "DROP TYPE %s.",
7486 fmtId(tyinfo->dobj.namespace->dobj.name));
7487 appendPQExpBuffer(delq, "%s;\n",
7488 fmtId(tyinfo->dobj.name));
7491 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7492 tyinfo->dobj.catId.oid);
7494 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7495 fmtId(tyinfo->dobj.name));
7497 if (!binary_upgrade)
7499 /* Labels with server-assigned oids */
7500 for (i = 0; i < num; i++)
7502 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7504 appendPQExpBuffer(q, ",");
7505 appendPQExpBuffer(q, "\n ");
7506 appendStringLiteralAH(q, label, fout);
7510 appendPQExpBuffer(q, "\n);\n");
7514 /* Labels with dump-assigned (preserved) oids */
7515 for (i = 0; i < num; i++)
7517 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7518 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7521 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7522 appendPQExpBuffer(q,
7523 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7525 appendPQExpBuffer(q, "ALTER TYPE %s.",
7526 fmtId(tyinfo->dobj.namespace->dobj.name));
7527 appendPQExpBuffer(q, "%s ADD VALUE ",
7528 fmtId(tyinfo->dobj.name));
7529 appendStringLiteralAH(q, label, fout);
7530 appendPQExpBuffer(q, ";\n\n");
7534 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7537 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7539 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7541 tyinfo->dobj.namespace->dobj.name,
7543 tyinfo->rolname, false,
7544 "TYPE", SECTION_PRE_DATA,
7545 q->data, delq->data, NULL,
7546 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7549 /* Dump Type Comments and Security Labels */
7550 dumpComment(fout, labelq->data,
7551 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7552 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7553 dumpSecLabel(fout, labelq->data,
7554 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7555 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7558 destroyPQExpBuffer(q);
7559 destroyPQExpBuffer(delq);
7560 destroyPQExpBuffer(labelq);
7561 destroyPQExpBuffer(query);
7566 * writes out to fout the queries to recreate a user-defined range type
7569 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7571 PQExpBuffer q = createPQExpBuffer();
7572 PQExpBuffer delq = createPQExpBuffer();
7573 PQExpBuffer labelq = createPQExpBuffer();
7574 PQExpBuffer query = createPQExpBuffer();
7580 * select appropriate schema to ensure names in CREATE are properly
7583 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7585 appendPQExpBuffer(query,
7586 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7587 "opc.opcname AS opcname, "
7588 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7589 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7591 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7592 " ELSE rngcollation END AS collation, "
7593 "rngcanonical, rngsubdiff "
7594 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7595 " pg_catalog.pg_opclass opc "
7596 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7598 tyinfo->dobj.catId.oid);
7600 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7603 * DROP must be fully qualified in case same name appears in pg_catalog.
7604 * CASCADE shouldn't be required here as for normal types since the I/O
7605 * functions are generic and do not get dropped.
7607 appendPQExpBuffer(delq, "DROP TYPE %s.",
7608 fmtId(tyinfo->dobj.namespace->dobj.name));
7609 appendPQExpBuffer(delq, "%s;\n",
7610 fmtId(tyinfo->dobj.name));
7613 binary_upgrade_set_type_oids_by_type_oid(fout,
7614 q, tyinfo->dobj.catId.oid);
7616 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7617 fmtId(tyinfo->dobj.name));
7619 appendPQExpBuffer(q, "\n subtype = %s",
7620 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7622 /* print subtype_opclass only if not default for subtype */
7623 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7625 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7626 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7628 /* always schema-qualify, don't try to be smart */
7629 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7631 appendPQExpBuffer(q, "%s", fmtId(opcname));
7634 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7635 if (OidIsValid(collationOid))
7637 CollInfo *coll = findCollationByOid(collationOid);
7641 /* always schema-qualify, don't try to be smart */
7642 appendPQExpBuffer(q, ",\n collation = %s.",
7643 fmtId(coll->dobj.namespace->dobj.name));
7644 appendPQExpBuffer(q, "%s",
7645 fmtId(coll->dobj.name));
7649 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7650 if (strcmp(procname, "-") != 0)
7651 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7653 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7654 if (strcmp(procname, "-") != 0)
7655 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7657 appendPQExpBuffer(q, "\n);\n");
7659 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7662 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7664 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7666 tyinfo->dobj.namespace->dobj.name,
7668 tyinfo->rolname, false,
7669 "TYPE", SECTION_PRE_DATA,
7670 q->data, delq->data, NULL,
7671 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7674 /* Dump Type Comments and Security Labels */
7675 dumpComment(fout, labelq->data,
7676 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7677 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7678 dumpSecLabel(fout, labelq->data,
7679 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7680 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7683 destroyPQExpBuffer(q);
7684 destroyPQExpBuffer(delq);
7685 destroyPQExpBuffer(labelq);
7686 destroyPQExpBuffer(query);
7691 * writes out to fout the queries to recreate a user-defined base type
7694 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7696 PQExpBuffer q = createPQExpBuffer();
7697 PQExpBuffer delq = createPQExpBuffer();
7698 PQExpBuffer labelq = createPQExpBuffer();
7699 PQExpBuffer query = createPQExpBuffer();
7715 char *typispreferred;
7720 char *typcollatable;
7722 bool typdefault_is_literal = false;
7724 /* Set proper schema search path so regproc references list correctly */
7725 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7727 /* Fetch type-specific details */
7728 if (fout->remoteVersion >= 90100)
7730 appendPQExpBuffer(query, "SELECT typlen, "
7731 "typinput, typoutput, typreceive, typsend, "
7732 "typmodin, typmodout, typanalyze, "
7733 "typreceive::pg_catalog.oid AS typreceiveoid, "
7734 "typsend::pg_catalog.oid AS typsendoid, "
7735 "typmodin::pg_catalog.oid AS typmodinoid, "
7736 "typmodout::pg_catalog.oid AS typmodoutoid, "
7737 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7738 "typcategory, typispreferred, "
7739 "typdelim, typbyval, typalign, typstorage, "
7740 "(typcollation <> 0) AS typcollatable, "
7741 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7742 "FROM pg_catalog.pg_type "
7743 "WHERE oid = '%u'::pg_catalog.oid",
7744 tyinfo->dobj.catId.oid);
7746 else if (fout->remoteVersion >= 80400)
7748 appendPQExpBuffer(query, "SELECT typlen, "
7749 "typinput, typoutput, typreceive, typsend, "
7750 "typmodin, typmodout, typanalyze, "
7751 "typreceive::pg_catalog.oid AS typreceiveoid, "
7752 "typsend::pg_catalog.oid AS typsendoid, "
7753 "typmodin::pg_catalog.oid AS typmodinoid, "
7754 "typmodout::pg_catalog.oid AS typmodoutoid, "
7755 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7756 "typcategory, typispreferred, "
7757 "typdelim, typbyval, typalign, typstorage, "
7758 "false AS typcollatable, "
7759 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7760 "FROM pg_catalog.pg_type "
7761 "WHERE oid = '%u'::pg_catalog.oid",
7762 tyinfo->dobj.catId.oid);
7764 else if (fout->remoteVersion >= 80300)
7766 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7767 appendPQExpBuffer(query, "SELECT typlen, "
7768 "typinput, typoutput, typreceive, typsend, "
7769 "typmodin, typmodout, typanalyze, "
7770 "typreceive::pg_catalog.oid AS typreceiveoid, "
7771 "typsend::pg_catalog.oid AS typsendoid, "
7772 "typmodin::pg_catalog.oid AS typmodinoid, "
7773 "typmodout::pg_catalog.oid AS typmodoutoid, "
7774 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7775 "'U' AS typcategory, false AS typispreferred, "
7776 "typdelim, typbyval, typalign, typstorage, "
7777 "false AS typcollatable, "
7778 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7779 "FROM pg_catalog.pg_type "
7780 "WHERE oid = '%u'::pg_catalog.oid",
7781 tyinfo->dobj.catId.oid);
7783 else if (fout->remoteVersion >= 80000)
7785 appendPQExpBuffer(query, "SELECT typlen, "
7786 "typinput, typoutput, typreceive, typsend, "
7787 "'-' AS typmodin, '-' AS typmodout, "
7789 "typreceive::pg_catalog.oid AS typreceiveoid, "
7790 "typsend::pg_catalog.oid AS typsendoid, "
7791 "0 AS typmodinoid, 0 AS typmodoutoid, "
7792 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7793 "'U' AS typcategory, false AS typispreferred, "
7794 "typdelim, typbyval, typalign, typstorage, "
7795 "false AS typcollatable, "
7796 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7797 "FROM pg_catalog.pg_type "
7798 "WHERE oid = '%u'::pg_catalog.oid",
7799 tyinfo->dobj.catId.oid);
7801 else if (fout->remoteVersion >= 70400)
7803 appendPQExpBuffer(query, "SELECT typlen, "
7804 "typinput, typoutput, typreceive, typsend, "
7805 "'-' AS typmodin, '-' AS typmodout, "
7806 "'-' AS typanalyze, "
7807 "typreceive::pg_catalog.oid AS typreceiveoid, "
7808 "typsend::pg_catalog.oid AS typsendoid, "
7809 "0 AS typmodinoid, 0 AS typmodoutoid, "
7810 "0 AS typanalyzeoid, "
7811 "'U' AS typcategory, false AS typispreferred, "
7812 "typdelim, typbyval, typalign, typstorage, "
7813 "false AS typcollatable, "
7814 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7815 "FROM pg_catalog.pg_type "
7816 "WHERE oid = '%u'::pg_catalog.oid",
7817 tyinfo->dobj.catId.oid);
7819 else if (fout->remoteVersion >= 70300)
7821 appendPQExpBuffer(query, "SELECT typlen, "
7822 "typinput, typoutput, "
7823 "'-' AS typreceive, '-' AS typsend, "
7824 "'-' AS typmodin, '-' AS typmodout, "
7825 "'-' AS typanalyze, "
7826 "0 AS typreceiveoid, 0 AS typsendoid, "
7827 "0 AS typmodinoid, 0 AS typmodoutoid, "
7828 "0 AS typanalyzeoid, "
7829 "'U' AS typcategory, false AS typispreferred, "
7830 "typdelim, typbyval, typalign, typstorage, "
7831 "false AS typcollatable, "
7832 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7833 "FROM pg_catalog.pg_type "
7834 "WHERE oid = '%u'::pg_catalog.oid",
7835 tyinfo->dobj.catId.oid);
7837 else if (fout->remoteVersion >= 70200)
7840 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7841 * ignore them because they are not right.
7843 appendPQExpBuffer(query, "SELECT typlen, "
7844 "typinput, typoutput, "
7845 "'-' AS typreceive, '-' AS typsend, "
7846 "'-' AS typmodin, '-' AS typmodout, "
7847 "'-' AS typanalyze, "
7848 "0 AS typreceiveoid, 0 AS typsendoid, "
7849 "0 AS typmodinoid, 0 AS typmodoutoid, "
7850 "0 AS typanalyzeoid, "
7851 "'U' AS typcategory, false AS typispreferred, "
7852 "typdelim, typbyval, typalign, typstorage, "
7853 "false AS typcollatable, "
7854 "NULL AS typdefaultbin, typdefault "
7856 "WHERE oid = '%u'::oid",
7857 tyinfo->dobj.catId.oid);
7859 else if (fout->remoteVersion >= 70100)
7862 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7865 appendPQExpBuffer(query, "SELECT typlen, "
7866 "typinput, typoutput, "
7867 "'-' AS typreceive, '-' AS typsend, "
7868 "'-' AS typmodin, '-' AS typmodout, "
7869 "'-' AS typanalyze, "
7870 "0 AS typreceiveoid, 0 AS typsendoid, "
7871 "0 AS typmodinoid, 0 AS typmodoutoid, "
7872 "0 AS typanalyzeoid, "
7873 "'U' AS typcategory, false AS typispreferred, "
7874 "typdelim, typbyval, typalign, typstorage, "
7875 "false AS typcollatable, "
7876 "NULL AS typdefaultbin, NULL AS typdefault "
7878 "WHERE oid = '%u'::oid",
7879 tyinfo->dobj.catId.oid);
7883 appendPQExpBuffer(query, "SELECT typlen, "
7884 "typinput, typoutput, "
7885 "'-' AS typreceive, '-' AS typsend, "
7886 "'-' AS typmodin, '-' AS typmodout, "
7887 "'-' AS typanalyze, "
7888 "0 AS typreceiveoid, 0 AS typsendoid, "
7889 "0 AS typmodinoid, 0 AS typmodoutoid, "
7890 "0 AS typanalyzeoid, "
7891 "'U' AS typcategory, false AS typispreferred, "
7892 "typdelim, typbyval, typalign, "
7893 "'p'::char AS typstorage, "
7894 "false AS typcollatable, "
7895 "NULL AS typdefaultbin, NULL AS typdefault "
7897 "WHERE oid = '%u'::oid",
7898 tyinfo->dobj.catId.oid);
7901 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7903 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7904 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7905 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7906 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7907 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7908 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7909 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7910 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7911 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7912 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7913 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7914 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7915 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7916 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7917 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7918 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7919 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7920 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7921 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7922 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7923 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7924 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7925 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7927 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7928 typdefault_is_literal = true; /* it needs quotes */
7934 * DROP must be fully qualified in case same name appears in pg_catalog.
7935 * The reason we include CASCADE is that the circular dependency between
7936 * the type and its I/O functions makes it impossible to drop the type any
7939 appendPQExpBuffer(delq, "DROP TYPE %s.",
7940 fmtId(tyinfo->dobj.namespace->dobj.name));
7941 appendPQExpBuffer(delq, "%s CASCADE;\n",
7942 fmtId(tyinfo->dobj.name));
7944 /* We might already have a shell type, but setting pg_type_oid is harmless */
7946 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7947 tyinfo->dobj.catId.oid);
7949 appendPQExpBuffer(q,
7950 "CREATE TYPE %s (\n"
7951 " INTERNALLENGTH = %s",
7952 fmtId(tyinfo->dobj.name),
7953 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7955 if (fout->remoteVersion >= 70300)
7957 /* regproc result is correctly quoted as of 7.3 */
7958 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7959 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7960 if (OidIsValid(typreceiveoid))
7961 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7962 if (OidIsValid(typsendoid))
7963 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7964 if (OidIsValid(typmodinoid))
7965 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7966 if (OidIsValid(typmodoutoid))
7967 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7968 if (OidIsValid(typanalyzeoid))
7969 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7973 /* regproc delivers an unquoted name before 7.3 */
7974 /* cannot combine these because fmtId uses static result area */
7975 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7976 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7977 /* receive/send/typmodin/typmodout/analyze need not be printed */
7980 if (strcmp(typcollatable, "t") == 0)
7981 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7983 if (typdefault != NULL)
7985 appendPQExpBuffer(q, ",\n DEFAULT = ");
7986 if (typdefault_is_literal)
7987 appendStringLiteralAH(q, typdefault, fout);
7989 appendPQExpBufferStr(q, typdefault);
7992 if (OidIsValid(tyinfo->typelem))
7996 /* reselect schema in case changed by function dump */
7997 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7998 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7999 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8003 if (strcmp(typcategory, "U") != 0)
8005 appendPQExpBuffer(q, ",\n CATEGORY = ");
8006 appendStringLiteralAH(q, typcategory, fout);
8009 if (strcmp(typispreferred, "t") == 0)
8010 appendPQExpBuffer(q, ",\n PREFERRED = true");
8012 if (typdelim && strcmp(typdelim, ",") != 0)
8014 appendPQExpBuffer(q, ",\n DELIMITER = ");
8015 appendStringLiteralAH(q, typdelim, fout);
8018 if (strcmp(typalign, "c") == 0)
8019 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8020 else if (strcmp(typalign, "s") == 0)
8021 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8022 else if (strcmp(typalign, "i") == 0)
8023 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8024 else if (strcmp(typalign, "d") == 0)
8025 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8027 if (strcmp(typstorage, "p") == 0)
8028 appendPQExpBuffer(q, ",\n STORAGE = plain");
8029 else if (strcmp(typstorage, "e") == 0)
8030 appendPQExpBuffer(q, ",\n STORAGE = external");
8031 else if (strcmp(typstorage, "x") == 0)
8032 appendPQExpBuffer(q, ",\n STORAGE = extended");
8033 else if (strcmp(typstorage, "m") == 0)
8034 appendPQExpBuffer(q, ",\n STORAGE = main");
8036 if (strcmp(typbyval, "t") == 0)
8037 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8039 appendPQExpBuffer(q, "\n);\n");
8041 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8044 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8046 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8048 tyinfo->dobj.namespace->dobj.name,
8050 tyinfo->rolname, false,
8051 "TYPE", SECTION_PRE_DATA,
8052 q->data, delq->data, NULL,
8053 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8056 /* Dump Type Comments and Security Labels */
8057 dumpComment(fout, labelq->data,
8058 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8059 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8060 dumpSecLabel(fout, labelq->data,
8061 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8062 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8065 destroyPQExpBuffer(q);
8066 destroyPQExpBuffer(delq);
8067 destroyPQExpBuffer(labelq);
8068 destroyPQExpBuffer(query);
8073 * writes out to fout the queries to recreate a user-defined domain
8076 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8078 PQExpBuffer q = createPQExpBuffer();
8079 PQExpBuffer delq = createPQExpBuffer();
8080 PQExpBuffer labelq = createPQExpBuffer();
8081 PQExpBuffer query = createPQExpBuffer();
8088 bool typdefault_is_literal = false;
8090 /* Set proper schema search path so type references list correctly */
8091 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8093 /* Fetch domain specific details */
8094 if (fout->remoteVersion >= 90100)
8096 /* typcollation is new in 9.1 */
8097 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8098 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8099 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8101 "CASE WHEN t.typcollation <> u.typcollation "
8102 "THEN t.typcollation ELSE 0 END AS typcollation "
8103 "FROM pg_catalog.pg_type t "
8104 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8105 "WHERE t.oid = '%u'::pg_catalog.oid",
8106 tyinfo->dobj.catId.oid);
8110 /* We assume here that remoteVersion must be at least 70300 */
8111 appendPQExpBuffer(query, "SELECT typnotnull, "
8112 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8113 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8114 "typdefault, 0 AS typcollation "
8115 "FROM pg_catalog.pg_type "
8116 "WHERE oid = '%u'::pg_catalog.oid",
8117 tyinfo->dobj.catId.oid);
8120 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8122 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8123 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8124 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8125 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8126 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8128 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8129 typdefault_is_literal = true; /* it needs quotes */
8133 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8136 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8137 tyinfo->dobj.catId.oid);
8139 appendPQExpBuffer(q,
8140 "CREATE DOMAIN %s AS %s",
8141 fmtId(tyinfo->dobj.name),
8144 /* Print collation only if different from base type's collation */
8145 if (OidIsValid(typcollation))
8149 coll = findCollationByOid(typcollation);
8152 /* always schema-qualify, don't try to be smart */
8153 appendPQExpBuffer(q, " COLLATE %s.",
8154 fmtId(coll->dobj.namespace->dobj.name));
8155 appendPQExpBuffer(q, "%s",
8156 fmtId(coll->dobj.name));
8160 if (typnotnull[0] == 't')
8161 appendPQExpBuffer(q, " NOT NULL");
8163 if (typdefault != NULL)
8165 appendPQExpBuffer(q, " DEFAULT ");
8166 if (typdefault_is_literal)
8167 appendStringLiteralAH(q, typdefault, fout);
8169 appendPQExpBufferStr(q, typdefault);
8175 * Add any CHECK constraints for the domain
8177 for (i = 0; i < tyinfo->nDomChecks; i++)
8179 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8181 if (!domcheck->separate)
8182 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8183 fmtId(domcheck->dobj.name), domcheck->condef);
8186 appendPQExpBuffer(q, ";\n");
8189 * DROP must be fully qualified in case same name appears in pg_catalog
8191 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8192 fmtId(tyinfo->dobj.namespace->dobj.name));
8193 appendPQExpBuffer(delq, "%s;\n",
8194 fmtId(tyinfo->dobj.name));
8196 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8199 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8201 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8203 tyinfo->dobj.namespace->dobj.name,
8205 tyinfo->rolname, false,
8206 "DOMAIN", SECTION_PRE_DATA,
8207 q->data, delq->data, NULL,
8208 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8211 /* Dump Domain Comments and Security Labels */
8212 dumpComment(fout, labelq->data,
8213 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8214 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8215 dumpSecLabel(fout, labelq->data,
8216 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8217 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8219 destroyPQExpBuffer(q);
8220 destroyPQExpBuffer(delq);
8221 destroyPQExpBuffer(labelq);
8222 destroyPQExpBuffer(query);
8227 * writes out to fout the queries to recreate a user-defined stand-alone
8231 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8233 PQExpBuffer q = createPQExpBuffer();
8234 PQExpBuffer dropped = createPQExpBuffer();
8235 PQExpBuffer delq = createPQExpBuffer();
8236 PQExpBuffer labelq = createPQExpBuffer();
8237 PQExpBuffer query = createPQExpBuffer();
8250 /* Set proper schema search path so type references list correctly */
8251 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8253 /* Fetch type specific details */
8254 if (fout->remoteVersion >= 90100)
8257 * attcollation is new in 9.1. Since we only want to dump COLLATE
8258 * clauses for attributes whose collation is different from their
8259 * type's default, we use a CASE here to suppress uninteresting
8260 * attcollations cheaply. atttypid will be 0 for dropped columns;
8261 * collation does not matter for those.
8263 appendPQExpBuffer(query, "SELECT a.attname, "
8264 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8265 "a.attlen, a.attalign, a.attisdropped, "
8266 "CASE WHEN a.attcollation <> at.typcollation "
8267 "THEN a.attcollation ELSE 0 END AS attcollation, "
8269 "FROM pg_catalog.pg_type ct "
8270 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8271 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8272 "WHERE ct.oid = '%u'::pg_catalog.oid "
8273 "ORDER BY a.attnum ",
8274 tyinfo->dobj.catId.oid);
8279 * We assume here that remoteVersion must be at least 70300. Since
8280 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8283 appendPQExpBuffer(query, "SELECT a.attname, "
8284 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8285 "a.attlen, a.attalign, a.attisdropped, "
8286 "0 AS attcollation, "
8288 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8289 "WHERE ct.oid = '%u'::pg_catalog.oid "
8290 "AND a.attrelid = ct.typrelid "
8291 "ORDER BY a.attnum ",
8292 tyinfo->dobj.catId.oid);
8295 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8297 ntups = PQntuples(res);
8299 i_attname = PQfnumber(res, "attname");
8300 i_atttypdefn = PQfnumber(res, "atttypdefn");
8301 i_attlen = PQfnumber(res, "attlen");
8302 i_attalign = PQfnumber(res, "attalign");
8303 i_attisdropped = PQfnumber(res, "attisdropped");
8304 i_attcollation = PQfnumber(res, "attcollation");
8305 i_typrelid = PQfnumber(res, "typrelid");
8309 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8311 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8312 tyinfo->dobj.catId.oid);
8313 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8316 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8317 fmtId(tyinfo->dobj.name));
8320 for (i = 0; i < ntups; i++)
8329 attname = PQgetvalue(res, i, i_attname);
8330 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8331 attlen = PQgetvalue(res, i, i_attlen);
8332 attalign = PQgetvalue(res, i, i_attalign);
8333 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8334 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8336 if (attisdropped && !binary_upgrade)
8339 /* Format properly if not first attr */
8340 if (actual_atts++ > 0)
8341 appendPQExpBuffer(q, ",");
8342 appendPQExpBuffer(q, "\n\t");
8346 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8348 /* Add collation if not default for the column type */
8349 if (OidIsValid(attcollation))
8353 coll = findCollationByOid(attcollation);
8356 /* always schema-qualify, don't try to be smart */
8357 appendPQExpBuffer(q, " COLLATE %s.",
8358 fmtId(coll->dobj.namespace->dobj.name));
8359 appendPQExpBuffer(q, "%s",
8360 fmtId(coll->dobj.name));
8367 * This is a dropped attribute and we're in binary_upgrade mode.
8368 * Insert a placeholder for it in the CREATE TYPE command, and set
8369 * length and alignment with direct UPDATE to the catalogs
8370 * afterwards. See similar code in dumpTableSchema().
8372 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8374 /* stash separately for insertion after the CREATE TYPE */
8375 appendPQExpBuffer(dropped,
8376 "\n-- For binary upgrade, recreate dropped column.\n");
8377 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8379 "attalign = '%s', attbyval = false\n"
8380 "WHERE attname = ", attlen, attalign);
8381 appendStringLiteralAH(dropped, attname, fout);
8382 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8383 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8384 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8386 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8387 fmtId(tyinfo->dobj.name));
8388 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8392 appendPQExpBuffer(q, "\n);\n");
8393 appendPQExpBufferStr(q, dropped->data);
8396 * DROP must be fully qualified in case same name appears in pg_catalog
8398 appendPQExpBuffer(delq, "DROP TYPE %s.",
8399 fmtId(tyinfo->dobj.namespace->dobj.name));
8400 appendPQExpBuffer(delq, "%s;\n",
8401 fmtId(tyinfo->dobj.name));
8403 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8406 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8408 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8410 tyinfo->dobj.namespace->dobj.name,
8412 tyinfo->rolname, false,
8413 "TYPE", SECTION_PRE_DATA,
8414 q->data, delq->data, NULL,
8415 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8419 /* Dump Type Comments and Security Labels */
8420 dumpComment(fout, labelq->data,
8421 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8422 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8423 dumpSecLabel(fout, labelq->data,
8424 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8425 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8428 destroyPQExpBuffer(q);
8429 destroyPQExpBuffer(dropped);
8430 destroyPQExpBuffer(delq);
8431 destroyPQExpBuffer(labelq);
8432 destroyPQExpBuffer(query);
8434 /* Dump any per-column comments */
8435 dumpCompositeTypeColComments(fout, tyinfo);
8439 * dumpCompositeTypeColComments
8440 * writes out to fout the queries to recreate comments on the columns of
8441 * a user-defined stand-alone composite type
8444 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8446 CommentItem *comments;
8457 query = createPQExpBuffer();
8459 /* We assume here that remoteVersion must be at least 70300 */
8460 appendPQExpBuffer(query,
8461 "SELECT c.tableoid, a.attname, a.attnum "
8462 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8463 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8464 " AND NOT a.attisdropped "
8465 "ORDER BY a.attnum ",
8468 /* Fetch column attnames */
8469 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8471 ntups = PQntuples(res);
8475 destroyPQExpBuffer(query);
8479 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8481 /* Search for comments associated with type's pg_class OID */
8482 ncomments = findComments(fout,
8487 /* If no comments exist, we're done */
8491 destroyPQExpBuffer(query);
8495 /* Build COMMENT ON statements */
8496 target = createPQExpBuffer();
8498 i_attnum = PQfnumber(res, "attnum");
8499 i_attname = PQfnumber(res, "attname");
8500 while (ncomments > 0)
8502 const char *attname;
8505 for (i = 0; i < ntups; i++)
8507 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8509 attname = PQgetvalue(res, i, i_attname);
8513 if (attname) /* just in case we don't find it */
8515 const char *descr = comments->descr;
8517 resetPQExpBuffer(target);
8518 appendPQExpBuffer(target, "COLUMN %s.",
8519 fmtId(tyinfo->dobj.name));
8520 appendPQExpBuffer(target, "%s",
8523 resetPQExpBuffer(query);
8524 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8525 appendStringLiteralAH(query, descr, fout);
8526 appendPQExpBuffer(query, ";\n");
8528 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8530 tyinfo->dobj.namespace->dobj.name,
8531 NULL, tyinfo->rolname,
8532 false, "COMMENT", SECTION_NONE,
8533 query->data, "", NULL,
8534 &(tyinfo->dobj.dumpId), 1,
8543 destroyPQExpBuffer(query);
8544 destroyPQExpBuffer(target);
8549 * writes out to fout the queries to create a shell type
8551 * We dump a shell definition in advance of the I/O functions for the type.
8554 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8558 /* Skip if not to be dumped */
8559 if (!stinfo->dobj.dump || dataOnly)
8562 q = createPQExpBuffer();
8565 * Note the lack of a DROP command for the shell type; any required DROP
8566 * is driven off the base type entry, instead. This interacts with
8567 * _printTocEntry()'s use of the presence of a DROP command to decide
8568 * whether an entry needs an ALTER OWNER command. We don't want to alter
8569 * the shell type's owner immediately on creation; that should happen only
8570 * after it's filled in, otherwise the backend complains.
8574 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8575 stinfo->baseType->dobj.catId.oid);
8577 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8578 fmtId(stinfo->dobj.name));
8580 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8582 stinfo->dobj.namespace->dobj.name,
8584 stinfo->baseType->rolname, false,
8585 "SHELL TYPE", SECTION_PRE_DATA,
8587 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8590 destroyPQExpBuffer(q);
8594 * Determine whether we want to dump definitions for procedural languages.
8595 * Since the languages themselves don't have schemas, we can't rely on
8596 * the normal schema-based selection mechanism. We choose to dump them
8597 * whenever neither --schema nor --table was given. (Before 8.1, we used
8598 * the dump flag of the PL's call handler function, but in 8.1 this will
8599 * probably always be false since call handlers are created in pg_catalog.)
8601 * For some backwards compatibility with the older behavior, we forcibly
8602 * dump a PL if its handler function (and validator if any) are in a
8603 * dumpable namespace. That case is not checked here.
8605 * Also, if the PL belongs to an extension, we do not use this heuristic.
8606 * That case isn't checked here either.
8609 shouldDumpProcLangs(void)
8611 if (!include_everything)
8613 /* And they're schema not data */
8621 * writes out to fout the queries to recreate a user-defined
8622 * procedural language
8625 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8634 FuncInfo *inlineInfo = NULL;
8635 FuncInfo *validatorInfo = NULL;
8637 /* Skip if not to be dumped */
8638 if (!plang->dobj.dump || dataOnly)
8642 * Try to find the support function(s). It is not an error if we don't
8643 * find them --- if the functions are in the pg_catalog schema, as is
8644 * standard in 8.1 and up, then we won't have loaded them. (In this case
8645 * we will emit a parameterless CREATE LANGUAGE command, which will
8646 * require PL template knowledge in the backend to reload.)
8649 funcInfo = findFuncByOid(plang->lanplcallfoid);
8650 if (funcInfo != NULL && !funcInfo->dobj.dump)
8651 funcInfo = NULL; /* treat not-dumped same as not-found */
8653 if (OidIsValid(plang->laninline))
8655 inlineInfo = findFuncByOid(plang->laninline);
8656 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8660 if (OidIsValid(plang->lanvalidator))
8662 validatorInfo = findFuncByOid(plang->lanvalidator);
8663 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8664 validatorInfo = NULL;
8668 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8669 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8672 * However, for a language that belongs to an extension, we must not use
8673 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8674 * told to (via dobj.dump). Generally the support functions will belong
8675 * to the same extension and so have the same dump flags ... if they
8676 * don't, this might not work terribly nicely.
8678 useParams = (funcInfo != NULL &&
8679 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8680 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8682 if (!plang->dobj.ext_member)
8684 if (!useParams && !shouldDumpProcLangs())
8688 defqry = createPQExpBuffer();
8689 delqry = createPQExpBuffer();
8690 labelq = createPQExpBuffer();
8692 qlanname = pg_strdup(fmtId(plang->dobj.name));
8695 * If dumping a HANDLER clause, treat the language as being in the handler
8696 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8697 * it doesn't really have a schema.
8700 lanschema = funcInfo->dobj.namespace->dobj.name;
8704 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8709 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8710 plang->lanpltrusted ? "TRUSTED " : "",
8712 appendPQExpBuffer(defqry, " HANDLER %s",
8713 fmtId(funcInfo->dobj.name));
8714 if (OidIsValid(plang->laninline))
8716 appendPQExpBuffer(defqry, " INLINE ");
8717 /* Cope with possibility that inline is in different schema */
8718 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8719 appendPQExpBuffer(defqry, "%s.",
8720 fmtId(inlineInfo->dobj.namespace->dobj.name));
8721 appendPQExpBuffer(defqry, "%s",
8722 fmtId(inlineInfo->dobj.name));
8724 if (OidIsValid(plang->lanvalidator))
8726 appendPQExpBuffer(defqry, " VALIDATOR ");
8727 /* Cope with possibility that validator is in different schema */
8728 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8729 appendPQExpBuffer(defqry, "%s.",
8730 fmtId(validatorInfo->dobj.namespace->dobj.name));
8731 appendPQExpBuffer(defqry, "%s",
8732 fmtId(validatorInfo->dobj.name));
8738 * If not dumping parameters, then use CREATE OR REPLACE so that the
8739 * command will not fail if the language is preinstalled in the target
8740 * database. We restrict the use of REPLACE to this case so as to
8741 * eliminate the risk of replacing a language with incompatible
8742 * parameter settings: this command will only succeed at all if there
8743 * is a pg_pltemplate entry, and if there is one, the existing entry
8744 * must match it too.
8746 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8749 appendPQExpBuffer(defqry, ";\n");
8751 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8754 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8756 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8758 lanschema, NULL, plang->lanowner,
8759 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8760 defqry->data, delqry->data, NULL,
8761 plang->dobj.dependencies, plang->dobj.nDeps,
8764 /* Dump Proc Lang Comments and Security Labels */
8765 dumpComment(fout, labelq->data,
8767 plang->dobj.catId, 0, plang->dobj.dumpId);
8768 dumpSecLabel(fout, labelq->data,
8770 plang->dobj.catId, 0, plang->dobj.dumpId);
8772 if (plang->lanpltrusted)
8773 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8774 qlanname, NULL, plang->dobj.name,
8776 plang->lanowner, plang->lanacl);
8780 destroyPQExpBuffer(defqry);
8781 destroyPQExpBuffer(delqry);
8782 destroyPQExpBuffer(labelq);
8786 * format_function_arguments: generate function name and argument list
8788 * This is used when we can rely on pg_get_function_arguments to format
8789 * the argument list.
8792 format_function_arguments(FuncInfo *finfo, char *funcargs)
8796 initPQExpBuffer(&fn);
8797 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8802 * format_function_arguments_old: generate function name and argument list
8804 * The argument type names are qualified if needed. The function name
8805 * is never qualified.
8807 * This is used only with pre-8.4 servers, so we aren't expecting to see
8808 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8810 * Any or all of allargtypes, argmodes, argnames may be NULL.
8813 format_function_arguments_old(Archive *fout,
8814 FuncInfo *finfo, int nallargs,
8822 initPQExpBuffer(&fn);
8823 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8824 for (j = 0; j < nallargs; j++)
8828 const char *argmode;
8829 const char *argname;
8831 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8832 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8836 switch (argmodes[j][0])
8841 case PROARGMODE_OUT:
8844 case PROARGMODE_INOUT:
8848 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8856 argname = argnames ? argnames[j] : (char *) NULL;
8857 if (argname && argname[0] == '\0')
8860 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8861 (j > 0) ? ", " : "",
8863 argname ? fmtId(argname) : "",
8868 appendPQExpBuffer(&fn, ")");
8873 * format_function_signature: generate function name and argument list
8875 * This is like format_function_arguments_old except that only a minimal
8876 * list of input argument types is generated; this is sufficient to
8877 * reference the function, but not to define it.
8879 * If honor_quotes is false then the function name is never quoted.
8880 * This is appropriate for use in TOC tags, but not in SQL commands.
8883 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8888 initPQExpBuffer(&fn);
8890 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8892 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8893 for (j = 0; j < finfo->nargs; j++)
8897 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8900 appendPQExpBuffer(&fn, "%s%s",
8901 (j > 0) ? ", " : "",
8905 appendPQExpBuffer(&fn, ")");
8912 * dump out one function
8915 dumpFunc(Archive *fout, FuncInfo *finfo)
8923 char *funcsig; /* identity signature */
8924 char *funcfullsig; /* full signature */
8932 char *proallargtypes;
8946 char **allargtypes = NULL;
8947 char **argmodes = NULL;
8948 char **argnames = NULL;
8949 char **configitems = NULL;
8950 int nconfigitems = 0;
8953 /* Skip if not to be dumped */
8954 if (!finfo->dobj.dump || dataOnly)
8957 query = createPQExpBuffer();
8958 q = createPQExpBuffer();
8959 delqry = createPQExpBuffer();
8960 labelq = createPQExpBuffer();
8961 asPart = createPQExpBuffer();
8963 /* Set proper schema search path so type references list correctly */
8964 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8966 /* Fetch function-specific details */
8967 if (fout->remoteVersion >= 90200)
8970 * proleakproof was added at v9.2
8972 appendPQExpBuffer(query,
8973 "SELECT proretset, prosrc, probin, "
8974 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8975 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8976 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8977 "proiswindow, provolatile, proisstrict, prosecdef, "
8978 "proleakproof, proconfig, procost, prorows, "
8979 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8980 "FROM pg_catalog.pg_proc "
8981 "WHERE oid = '%u'::pg_catalog.oid",
8982 finfo->dobj.catId.oid);
8984 else if (fout->remoteVersion >= 80400)
8987 * In 8.4 and up we rely on pg_get_function_arguments and
8988 * pg_get_function_result instead of examining proallargtypes etc.
8990 appendPQExpBuffer(query,
8991 "SELECT proretset, prosrc, probin, "
8992 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8993 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8994 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8995 "proiswindow, provolatile, proisstrict, prosecdef, "
8996 "false AS proleakproof, "
8997 " proconfig, procost, prorows, "
8998 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8999 "FROM pg_catalog.pg_proc "
9000 "WHERE oid = '%u'::pg_catalog.oid",
9001 finfo->dobj.catId.oid);
9003 else if (fout->remoteVersion >= 80300)
9005 appendPQExpBuffer(query,
9006 "SELECT proretset, prosrc, probin, "
9007 "proallargtypes, proargmodes, proargnames, "
9008 "false AS proiswindow, "
9009 "provolatile, proisstrict, prosecdef, "
9010 "false AS proleakproof, "
9011 "proconfig, procost, prorows, "
9012 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9013 "FROM pg_catalog.pg_proc "
9014 "WHERE oid = '%u'::pg_catalog.oid",
9015 finfo->dobj.catId.oid);
9017 else if (fout->remoteVersion >= 80100)
9019 appendPQExpBuffer(query,
9020 "SELECT proretset, prosrc, probin, "
9021 "proallargtypes, proargmodes, proargnames, "
9022 "false AS proiswindow, "
9023 "provolatile, proisstrict, prosecdef, "
9024 "false AS proleakproof, "
9025 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9026 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9027 "FROM pg_catalog.pg_proc "
9028 "WHERE oid = '%u'::pg_catalog.oid",
9029 finfo->dobj.catId.oid);
9031 else if (fout->remoteVersion >= 80000)
9033 appendPQExpBuffer(query,
9034 "SELECT proretset, prosrc, probin, "
9035 "null AS proallargtypes, "
9036 "null AS proargmodes, "
9038 "false AS proiswindow, "
9039 "provolatile, proisstrict, prosecdef, "
9040 "false AS proleakproof, "
9041 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9042 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9043 "FROM pg_catalog.pg_proc "
9044 "WHERE oid = '%u'::pg_catalog.oid",
9045 finfo->dobj.catId.oid);
9047 else if (fout->remoteVersion >= 70300)
9049 appendPQExpBuffer(query,
9050 "SELECT proretset, prosrc, probin, "
9051 "null AS proallargtypes, "
9052 "null AS proargmodes, "
9053 "null AS proargnames, "
9054 "false AS proiswindow, "
9055 "provolatile, proisstrict, prosecdef, "
9056 "false AS proleakproof, "
9057 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9058 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9059 "FROM pg_catalog.pg_proc "
9060 "WHERE oid = '%u'::pg_catalog.oid",
9061 finfo->dobj.catId.oid);
9063 else if (fout->remoteVersion >= 70100)
9065 appendPQExpBuffer(query,
9066 "SELECT proretset, prosrc, probin, "
9067 "null AS proallargtypes, "
9068 "null AS proargmodes, "
9069 "null AS proargnames, "
9070 "false AS proiswindow, "
9071 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9073 "false AS prosecdef, "
9074 "false AS proleakproof, "
9075 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9076 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9078 "WHERE oid = '%u'::oid",
9079 finfo->dobj.catId.oid);
9083 appendPQExpBuffer(query,
9084 "SELECT proretset, prosrc, probin, "
9085 "null AS proallargtypes, "
9086 "null AS proargmodes, "
9087 "null AS proargnames, "
9088 "false AS proiswindow, "
9089 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9090 "false AS proisstrict, "
9091 "false AS prosecdef, "
9092 "false AS proleakproof, "
9093 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9094 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9096 "WHERE oid = '%u'::oid",
9097 finfo->dobj.catId.oid);
9100 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9102 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9103 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9104 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9105 if (fout->remoteVersion >= 80400)
9107 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9108 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9109 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9110 proallargtypes = proargmodes = proargnames = NULL;
9114 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9115 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9116 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9117 funcargs = funciargs = funcresult = NULL;
9119 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9120 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9121 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9122 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9123 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9124 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9125 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9126 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9127 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9130 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9131 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9132 * versions would set it to "-". There are no known cases in which prosrc
9133 * is unused, so the tests below for "-" are probably useless.
9135 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9137 appendPQExpBuffer(asPart, "AS ");
9138 appendStringLiteralAH(asPart, probin, fout);
9139 if (strcmp(prosrc, "-") != 0)
9141 appendPQExpBuffer(asPart, ", ");
9144 * where we have bin, use dollar quoting if allowed and src
9145 * contains quote or backslash; else use regular quoting.
9147 if (disable_dollar_quoting ||
9148 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9149 appendStringLiteralAH(asPart, prosrc, fout);
9151 appendStringLiteralDQ(asPart, prosrc, NULL);
9156 if (strcmp(prosrc, "-") != 0)
9158 appendPQExpBuffer(asPart, "AS ");
9159 /* with no bin, dollar quote src unconditionally if allowed */
9160 if (disable_dollar_quoting)
9161 appendStringLiteralAH(asPart, prosrc, fout);
9163 appendStringLiteralDQ(asPart, prosrc, NULL);
9167 nallargs = finfo->nargs; /* unless we learn different from allargs */
9169 if (proallargtypes && *proallargtypes)
9173 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9174 nitems < finfo->nargs)
9176 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9185 if (proargmodes && *proargmodes)
9189 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9192 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9199 if (proargnames && *proargnames)
9203 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9206 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9213 if (proconfig && *proconfig)
9215 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9217 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9227 /* 8.4 or later; we rely on server-side code for most of the work */
9228 funcfullsig = format_function_arguments(finfo, funcargs);
9229 funcsig = format_function_arguments(finfo, funciargs);
9233 /* pre-8.4, do it ourselves */
9234 funcsig = format_function_arguments_old(fout,
9235 finfo, nallargs, allargtypes,
9236 argmodes, argnames);
9237 funcfullsig = funcsig;
9240 funcsig_tag = format_function_signature(fout, finfo, false);
9243 * DROP must be fully qualified in case same name appears in pg_catalog
9245 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9246 fmtId(finfo->dobj.namespace->dobj.name),
9249 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9251 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9254 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9256 appendPQExpBuffer(q, "RETURNS %s%s",
9257 (proretset[0] == 't') ? "SETOF " : "",
9262 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9264 if (proiswindow[0] == 't')
9265 appendPQExpBuffer(q, " WINDOW");
9267 if (provolatile[0] != PROVOLATILE_VOLATILE)
9269 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9270 appendPQExpBuffer(q, " IMMUTABLE");
9271 else if (provolatile[0] == PROVOLATILE_STABLE)
9272 appendPQExpBuffer(q, " STABLE");
9273 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9274 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9278 if (proisstrict[0] == 't')
9279 appendPQExpBuffer(q, " STRICT");
9281 if (prosecdef[0] == 't')
9282 appendPQExpBuffer(q, " SECURITY DEFINER");
9284 if (proleakproof[0] == 't')
9285 appendPQExpBuffer(q, " LEAKPROOF");
9288 * COST and ROWS are emitted only if present and not default, so as not to
9289 * break backwards-compatibility of the dump without need. Keep this code
9290 * in sync with the defaults in functioncmds.c.
9292 if (strcmp(procost, "0") != 0)
9294 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9296 /* default cost is 1 */
9297 if (strcmp(procost, "1") != 0)
9298 appendPQExpBuffer(q, " COST %s", procost);
9302 /* default cost is 100 */
9303 if (strcmp(procost, "100") != 0)
9304 appendPQExpBuffer(q, " COST %s", procost);
9307 if (proretset[0] == 't' &&
9308 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9309 appendPQExpBuffer(q, " ROWS %s", prorows);
9311 for (i = 0; i < nconfigitems; i++)
9313 /* we feel free to scribble on configitems[] here */
9314 char *configitem = configitems[i];
9317 pos = strchr(configitem, '=');
9321 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9324 * Some GUC variable names are 'LIST' type and hence must not be
9327 if (pg_strcasecmp(configitem, "DateStyle") == 0
9328 || pg_strcasecmp(configitem, "search_path") == 0)
9329 appendPQExpBuffer(q, "%s", pos);
9331 appendStringLiteralAH(q, pos, fout);
9334 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9336 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9339 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9341 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9343 finfo->dobj.namespace->dobj.name,
9345 finfo->rolname, false,
9346 "FUNCTION", SECTION_PRE_DATA,
9347 q->data, delqry->data, NULL,
9348 finfo->dobj.dependencies, finfo->dobj.nDeps,
9351 /* Dump Function Comments and Security Labels */
9352 dumpComment(fout, labelq->data,
9353 finfo->dobj.namespace->dobj.name, finfo->rolname,
9354 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9355 dumpSecLabel(fout, labelq->data,
9356 finfo->dobj.namespace->dobj.name, finfo->rolname,
9357 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9359 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9360 funcsig, NULL, funcsig_tag,
9361 finfo->dobj.namespace->dobj.name,
9362 finfo->rolname, finfo->proacl);
9366 destroyPQExpBuffer(query);
9367 destroyPQExpBuffer(q);
9368 destroyPQExpBuffer(delqry);
9369 destroyPQExpBuffer(labelq);
9370 destroyPQExpBuffer(asPart);
9385 * Dump a user-defined cast
9388 dumpCast(Archive *fout, CastInfo *cast)
9393 FuncInfo *funcInfo = NULL;
9395 /* Skip if not to be dumped */
9396 if (!cast->dobj.dump || dataOnly)
9399 /* Cannot dump if we don't have the cast function's info */
9400 if (OidIsValid(cast->castfunc))
9402 funcInfo = findFuncByOid(cast->castfunc);
9403 if (funcInfo == NULL)
9408 * As per discussion we dump casts if one or more of the underlying
9409 * objects (the conversion function and the two data types) are not
9410 * builtin AND if all of the non-builtin objects are included in the dump.
9411 * Builtin meaning, the namespace name does not start with "pg_".
9413 * However, for a cast that belongs to an extension, we must not use this
9414 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9416 if (!cast->dobj.ext_member)
9418 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9419 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9421 if (sourceInfo == NULL || targetInfo == NULL)
9425 * Skip this cast if all objects are from pg_
9427 if ((funcInfo == NULL ||
9428 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9429 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9430 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9434 * Skip cast if function isn't from pg_ and is not to be dumped.
9437 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9438 !funcInfo->dobj.dump)
9442 * Same for the source type
9444 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9445 !sourceInfo->dobj.dump)
9449 * and the target type.
9451 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9452 !targetInfo->dobj.dump)
9456 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9457 selectSourceSchema(fout, "pg_catalog");
9459 defqry = createPQExpBuffer();
9460 delqry = createPQExpBuffer();
9461 labelq = createPQExpBuffer();
9463 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9464 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9465 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9467 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9468 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9469 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9471 switch (cast->castmethod)
9473 case COERCION_METHOD_BINARY:
9474 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9476 case COERCION_METHOD_INOUT:
9477 appendPQExpBuffer(defqry, "WITH INOUT");
9479 case COERCION_METHOD_FUNCTION:
9481 char *fsig = format_function_signature(fout, funcInfo, true);
9484 * Always qualify the function name, in case it is not in
9485 * pg_catalog schema (format_function_signature won't qualify it).
9487 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9488 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9493 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9496 if (cast->castcontext == 'a')
9497 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9498 else if (cast->castcontext == 'i')
9499 appendPQExpBuffer(defqry, " AS IMPLICIT");
9500 appendPQExpBuffer(defqry, ";\n");
9502 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9503 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9504 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9507 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9509 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9511 "pg_catalog", NULL, "",
9512 false, "CAST", SECTION_PRE_DATA,
9513 defqry->data, delqry->data, NULL,
9514 cast->dobj.dependencies, cast->dobj.nDeps,
9517 /* Dump Cast Comments */
9518 dumpComment(fout, labelq->data,
9520 cast->dobj.catId, 0, cast->dobj.dumpId);
9522 destroyPQExpBuffer(defqry);
9523 destroyPQExpBuffer(delqry);
9524 destroyPQExpBuffer(labelq);
9529 * write out a single operator definition
9532 dumpOpr(Archive *fout, OprInfo *oprinfo)
9539 PQExpBuffer details;
9563 /* Skip if not to be dumped */
9564 if (!oprinfo->dobj.dump || dataOnly)
9568 * some operators are invalid because they were the result of user
9569 * defining operators before commutators exist
9571 if (!OidIsValid(oprinfo->oprcode))
9574 query = createPQExpBuffer();
9575 q = createPQExpBuffer();
9576 delq = createPQExpBuffer();
9577 labelq = createPQExpBuffer();
9578 oprid = createPQExpBuffer();
9579 details = createPQExpBuffer();
9581 /* Make sure we are in proper schema so regoperator works correctly */
9582 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9584 if (fout->remoteVersion >= 80300)
9586 appendPQExpBuffer(query, "SELECT oprkind, "
9587 "oprcode::pg_catalog.regprocedure, "
9588 "oprleft::pg_catalog.regtype, "
9589 "oprright::pg_catalog.regtype, "
9590 "oprcom::pg_catalog.regoperator, "
9591 "oprnegate::pg_catalog.regoperator, "
9592 "oprrest::pg_catalog.regprocedure, "
9593 "oprjoin::pg_catalog.regprocedure, "
9594 "oprcanmerge, oprcanhash "
9595 "FROM pg_catalog.pg_operator "
9596 "WHERE oid = '%u'::pg_catalog.oid",
9597 oprinfo->dobj.catId.oid);
9599 else if (fout->remoteVersion >= 70300)
9601 appendPQExpBuffer(query, "SELECT oprkind, "
9602 "oprcode::pg_catalog.regprocedure, "
9603 "oprleft::pg_catalog.regtype, "
9604 "oprright::pg_catalog.regtype, "
9605 "oprcom::pg_catalog.regoperator, "
9606 "oprnegate::pg_catalog.regoperator, "
9607 "oprrest::pg_catalog.regprocedure, "
9608 "oprjoin::pg_catalog.regprocedure, "
9609 "(oprlsortop != 0) AS oprcanmerge, "
9611 "FROM pg_catalog.pg_operator "
9612 "WHERE oid = '%u'::pg_catalog.oid",
9613 oprinfo->dobj.catId.oid);
9615 else if (fout->remoteVersion >= 70100)
9617 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9618 "CASE WHEN oprleft = 0 THEN '-' "
9619 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9620 "CASE WHEN oprright = 0 THEN '-' "
9621 "ELSE format_type(oprright, NULL) END AS oprright, "
9622 "oprcom, oprnegate, oprrest, oprjoin, "
9623 "(oprlsortop != 0) AS oprcanmerge, "
9626 "WHERE oid = '%u'::oid",
9627 oprinfo->dobj.catId.oid);
9631 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9632 "CASE WHEN oprleft = 0 THEN '-'::name "
9633 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9634 "CASE WHEN oprright = 0 THEN '-'::name "
9635 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9636 "oprcom, oprnegate, oprrest, oprjoin, "
9637 "(oprlsortop != 0) AS oprcanmerge, "
9640 "WHERE oid = '%u'::oid",
9641 oprinfo->dobj.catId.oid);
9644 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9646 i_oprkind = PQfnumber(res, "oprkind");
9647 i_oprcode = PQfnumber(res, "oprcode");
9648 i_oprleft = PQfnumber(res, "oprleft");
9649 i_oprright = PQfnumber(res, "oprright");
9650 i_oprcom = PQfnumber(res, "oprcom");
9651 i_oprnegate = PQfnumber(res, "oprnegate");
9652 i_oprrest = PQfnumber(res, "oprrest");
9653 i_oprjoin = PQfnumber(res, "oprjoin");
9654 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9655 i_oprcanhash = PQfnumber(res, "oprcanhash");
9657 oprkind = PQgetvalue(res, 0, i_oprkind);
9658 oprcode = PQgetvalue(res, 0, i_oprcode);
9659 oprleft = PQgetvalue(res, 0, i_oprleft);
9660 oprright = PQgetvalue(res, 0, i_oprright);
9661 oprcom = PQgetvalue(res, 0, i_oprcom);
9662 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9663 oprrest = PQgetvalue(res, 0, i_oprrest);
9664 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9665 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9666 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9668 appendPQExpBuffer(details, " PROCEDURE = %s",
9669 convertRegProcReference(fout, oprcode));
9671 appendPQExpBuffer(oprid, "%s (",
9672 oprinfo->dobj.name);
9675 * right unary means there's a left arg and left unary means there's a
9678 if (strcmp(oprkind, "r") == 0 ||
9679 strcmp(oprkind, "b") == 0)
9681 if (fout->remoteVersion >= 70100)
9684 name = fmtId(oprleft);
9685 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9686 appendPQExpBuffer(oprid, "%s", name);
9689 appendPQExpBuffer(oprid, "NONE");
9691 if (strcmp(oprkind, "l") == 0 ||
9692 strcmp(oprkind, "b") == 0)
9694 if (fout->remoteVersion >= 70100)
9697 name = fmtId(oprright);
9698 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9699 appendPQExpBuffer(oprid, ", %s)", name);
9702 appendPQExpBuffer(oprid, ", NONE)");
9704 name = convertOperatorReference(fout, oprcom);
9706 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9708 name = convertOperatorReference(fout, oprnegate);
9710 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9712 if (strcmp(oprcanmerge, "t") == 0)
9713 appendPQExpBuffer(details, ",\n MERGES");
9715 if (strcmp(oprcanhash, "t") == 0)
9716 appendPQExpBuffer(details, ",\n HASHES");
9718 name = convertRegProcReference(fout, oprrest);
9720 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9722 name = convertRegProcReference(fout, oprjoin);
9724 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9727 * DROP must be fully qualified in case same name appears in pg_catalog
9729 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9730 fmtId(oprinfo->dobj.namespace->dobj.name),
9733 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9734 oprinfo->dobj.name, details->data);
9736 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9739 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9741 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9743 oprinfo->dobj.namespace->dobj.name,
9746 false, "OPERATOR", SECTION_PRE_DATA,
9747 q->data, delq->data, NULL,
9748 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9751 /* Dump Operator Comments */
9752 dumpComment(fout, labelq->data,
9753 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9754 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9758 destroyPQExpBuffer(query);
9759 destroyPQExpBuffer(q);
9760 destroyPQExpBuffer(delq);
9761 destroyPQExpBuffer(labelq);
9762 destroyPQExpBuffer(oprid);
9763 destroyPQExpBuffer(details);
9767 * Convert a function reference obtained from pg_operator
9769 * Returns what to print, or NULL if function references is InvalidOid
9771 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9772 * argument-types part. In prior versions, the input is a REGPROC display.
9775 convertRegProcReference(Archive *fout, const char *proc)
9777 /* In all cases "-" means a null reference */
9778 if (strcmp(proc, "-") == 0)
9781 if (fout->remoteVersion >= 70300)
9787 name = pg_strdup(proc);
9788 /* find non-double-quoted left paren */
9790 for (paren = name; *paren; paren++)
9792 if (*paren == '(' && !inquote)
9803 /* REGPROC before 7.3 does not quote its result */
9808 * Convert an operator cross-reference obtained from pg_operator
9810 * Returns what to print, or NULL to print nothing
9812 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9813 * argument-types part, and add OPERATOR() decoration if the name is
9814 * schema-qualified. In older versions, the input is just a numeric OID,
9815 * which we search our operator list for.
9818 convertOperatorReference(Archive *fout, const char *opr)
9822 /* In all cases "0" means a null reference */
9823 if (strcmp(opr, "0") == 0)
9826 if (fout->remoteVersion >= 70300)
9834 name = pg_strdup(opr);
9835 /* find non-double-quoted left paren, and check for non-quoted dot */
9838 for (ptr = name; *ptr; ptr++)
9842 else if (*ptr == '.' && !inquote)
9844 else if (*ptr == '(' && !inquote)
9850 /* If not schema-qualified, don't need to add OPERATOR() */
9853 oname = pg_malloc(strlen(name) + 11);
9854 sprintf(oname, "OPERATOR(%s)", name);
9859 oprInfo = findOprByOid(atooid(opr));
9860 if (oprInfo == NULL)
9862 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9866 return oprInfo->dobj.name;
9870 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9872 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9873 * argument lists of these functions are predetermined. Note that the
9874 * caller should ensure we are in the proper schema, because the results
9875 * are search path dependent!
9878 convertTSFunction(Archive *fout, Oid funcOid)
9884 snprintf(query, sizeof(query),
9885 "SELECT '%u'::pg_catalog.regproc", funcOid);
9886 res = ExecuteSqlQueryForSingleRow(fout, query);
9888 result = pg_strdup(PQgetvalue(res, 0, 0));
9898 * write out a single operator class definition
9901 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9913 int i_opcfamilyname;
9920 int i_sortfamilynsp;
9923 int i_amproclefttype;
9924 int i_amprocrighttype;
9929 char *opcfamilyname;
9936 char *sortfamilynsp;
9939 char *amproclefttype;
9940 char *amprocrighttype;
9944 /* Skip if not to be dumped */
9945 if (!opcinfo->dobj.dump || dataOnly)
9949 * XXX currently we do not implement dumping of operator classes from
9950 * pre-7.3 databases. This could be done but it seems not worth the
9953 if (fout->remoteVersion < 70300)
9956 query = createPQExpBuffer();
9957 q = createPQExpBuffer();
9958 delq = createPQExpBuffer();
9959 labelq = createPQExpBuffer();
9961 /* Make sure we are in proper schema so regoperator works correctly */
9962 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9964 /* Get additional fields from the pg_opclass row */
9965 if (fout->remoteVersion >= 80300)
9967 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9968 "opckeytype::pg_catalog.regtype, "
9969 "opcdefault, opcfamily, "
9970 "opfname AS opcfamilyname, "
9971 "nspname AS opcfamilynsp, "
9972 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9973 "FROM pg_catalog.pg_opclass c "
9974 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9975 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9976 "WHERE c.oid = '%u'::pg_catalog.oid",
9977 opcinfo->dobj.catId.oid);
9981 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9982 "opckeytype::pg_catalog.regtype, "
9983 "opcdefault, NULL AS opcfamily, "
9984 "NULL AS opcfamilyname, "
9985 "NULL AS opcfamilynsp, "
9986 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9987 "FROM pg_catalog.pg_opclass "
9988 "WHERE oid = '%u'::pg_catalog.oid",
9989 opcinfo->dobj.catId.oid);
9992 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9994 i_opcintype = PQfnumber(res, "opcintype");
9995 i_opckeytype = PQfnumber(res, "opckeytype");
9996 i_opcdefault = PQfnumber(res, "opcdefault");
9997 i_opcfamily = PQfnumber(res, "opcfamily");
9998 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9999 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10000 i_amname = PQfnumber(res, "amname");
10002 opcintype = PQgetvalue(res, 0, i_opcintype);
10003 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10004 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10005 /* opcfamily will still be needed after we PQclear res */
10006 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10007 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10008 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10009 /* amname will still be needed after we PQclear res */
10010 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10013 * DROP must be fully qualified in case same name appears in pg_catalog
10015 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10016 fmtId(opcinfo->dobj.namespace->dobj.name));
10017 appendPQExpBuffer(delq, ".%s",
10018 fmtId(opcinfo->dobj.name));
10019 appendPQExpBuffer(delq, " USING %s;\n",
10022 /* Build the fixed portion of the CREATE command */
10023 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10024 fmtId(opcinfo->dobj.name));
10025 if (strcmp(opcdefault, "t") == 0)
10026 appendPQExpBuffer(q, "DEFAULT ");
10027 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10030 if (strlen(opcfamilyname) > 0 &&
10031 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10032 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10034 appendPQExpBuffer(q, " FAMILY ");
10035 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10036 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10037 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10039 appendPQExpBuffer(q, " AS\n ");
10043 if (strcmp(opckeytype, "-") != 0)
10045 appendPQExpBuffer(q, "STORAGE %s",
10053 * Now fetch and print the OPERATOR entries (pg_amop rows).
10055 * Print only those opfamily members that are tied to the opclass by
10056 * pg_depend entries.
10058 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10059 * older server's opclass in which it is used. This is to avoid
10060 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10061 * older server and then reload into that old version. This can go away
10062 * once 8.3 is so old as to not be of interest to anyone.
10064 resetPQExpBuffer(query);
10066 if (fout->remoteVersion >= 90100)
10068 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10069 "amopopr::pg_catalog.regoperator, "
10070 "opfname AS sortfamily, "
10071 "nspname AS sortfamilynsp "
10072 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10073 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10074 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10075 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10076 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10077 "AND refobjid = '%u'::pg_catalog.oid "
10078 "AND amopfamily = '%s'::pg_catalog.oid "
10079 "ORDER BY amopstrategy",
10080 opcinfo->dobj.catId.oid,
10083 else if (fout->remoteVersion >= 80400)
10085 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10086 "amopopr::pg_catalog.regoperator, "
10087 "NULL AS sortfamily, "
10088 "NULL AS sortfamilynsp "
10089 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10090 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10091 "AND refobjid = '%u'::pg_catalog.oid "
10092 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10093 "AND objid = ao.oid "
10094 "ORDER BY amopstrategy",
10095 opcinfo->dobj.catId.oid);
10097 else if (fout->remoteVersion >= 80300)
10099 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10100 "amopopr::pg_catalog.regoperator, "
10101 "NULL AS sortfamily, "
10102 "NULL AS sortfamilynsp "
10103 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10104 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10105 "AND refobjid = '%u'::pg_catalog.oid "
10106 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10107 "AND objid = ao.oid "
10108 "ORDER BY amopstrategy",
10109 opcinfo->dobj.catId.oid);
10114 * Here, we print all entries since there are no opfamilies and hence
10115 * no loose operators to worry about.
10117 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10118 "amopopr::pg_catalog.regoperator, "
10119 "NULL AS sortfamily, "
10120 "NULL AS sortfamilynsp "
10121 "FROM pg_catalog.pg_amop "
10122 "WHERE amopclaid = '%u'::pg_catalog.oid "
10123 "ORDER BY amopstrategy",
10124 opcinfo->dobj.catId.oid);
10127 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10129 ntups = PQntuples(res);
10131 i_amopstrategy = PQfnumber(res, "amopstrategy");
10132 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10133 i_amopopr = PQfnumber(res, "amopopr");
10134 i_sortfamily = PQfnumber(res, "sortfamily");
10135 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10137 for (i = 0; i < ntups; i++)
10139 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10140 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10141 amopopr = PQgetvalue(res, i, i_amopopr);
10142 sortfamily = PQgetvalue(res, i, i_sortfamily);
10143 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10146 appendPQExpBuffer(q, " ,\n ");
10148 appendPQExpBuffer(q, "OPERATOR %s %s",
10149 amopstrategy, amopopr);
10151 if (strlen(sortfamily) > 0)
10153 appendPQExpBuffer(q, " FOR ORDER BY ");
10154 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10155 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10156 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10159 if (strcmp(amopreqcheck, "t") == 0)
10160 appendPQExpBuffer(q, " RECHECK");
10168 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10170 * Print only those opfamily members that are tied to the opclass by
10171 * pg_depend entries.
10173 * We print the amproclefttype/amprocrighttype even though in most cases
10174 * the backend could deduce the right values, because of the corner case
10175 * of a btree sort support function for a cross-type comparison. That's
10176 * only allowed in 9.2 and later, but for simplicity print them in all
10177 * versions that have the columns.
10179 resetPQExpBuffer(query);
10181 if (fout->remoteVersion >= 80300)
10183 appendPQExpBuffer(query, "SELECT amprocnum, "
10184 "amproc::pg_catalog.regprocedure, "
10185 "amproclefttype::pg_catalog.regtype, "
10186 "amprocrighttype::pg_catalog.regtype "
10187 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10188 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10189 "AND refobjid = '%u'::pg_catalog.oid "
10190 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10191 "AND objid = ap.oid "
10192 "ORDER BY amprocnum",
10193 opcinfo->dobj.catId.oid);
10197 appendPQExpBuffer(query, "SELECT amprocnum, "
10198 "amproc::pg_catalog.regprocedure, "
10199 "'' AS amproclefttype, "
10200 "'' AS amprocrighttype "
10201 "FROM pg_catalog.pg_amproc "
10202 "WHERE amopclaid = '%u'::pg_catalog.oid "
10203 "ORDER BY amprocnum",
10204 opcinfo->dobj.catId.oid);
10207 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10209 ntups = PQntuples(res);
10211 i_amprocnum = PQfnumber(res, "amprocnum");
10212 i_amproc = PQfnumber(res, "amproc");
10213 i_amproclefttype = PQfnumber(res, "amproclefttype");
10214 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10216 for (i = 0; i < ntups; i++)
10218 amprocnum = PQgetvalue(res, i, i_amprocnum);
10219 amproc = PQgetvalue(res, i, i_amproc);
10220 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10221 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10224 appendPQExpBuffer(q, " ,\n ");
10226 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10228 if (*amproclefttype && *amprocrighttype)
10229 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10231 appendPQExpBuffer(q, " %s", amproc);
10238 appendPQExpBuffer(q, ";\n");
10240 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10241 fmtId(opcinfo->dobj.name));
10242 appendPQExpBuffer(labelq, " USING %s",
10245 if (binary_upgrade)
10246 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10248 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10249 opcinfo->dobj.name,
10250 opcinfo->dobj.namespace->dobj.name,
10253 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10254 q->data, delq->data, NULL,
10255 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10258 /* Dump Operator Class Comments */
10259 dumpComment(fout, labelq->data,
10260 NULL, opcinfo->rolname,
10261 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10264 destroyPQExpBuffer(query);
10265 destroyPQExpBuffer(q);
10266 destroyPQExpBuffer(delq);
10267 destroyPQExpBuffer(labelq);
10272 * write out a single operator family definition
10274 * Note: this also dumps any "loose" operator members that aren't bound to a
10275 * specific opclass within the opfamily.
10278 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10283 PQExpBuffer labelq;
10286 PGresult *res_procs;
10289 int i_amopstrategy;
10290 int i_amopreqcheck;
10293 int i_sortfamilynsp;
10296 int i_amproclefttype;
10297 int i_amprocrighttype;
10299 char *amopstrategy;
10300 char *amopreqcheck;
10303 char *sortfamilynsp;
10306 char *amproclefttype;
10307 char *amprocrighttype;
10311 /* Skip if not to be dumped */
10312 if (!opfinfo->dobj.dump || dataOnly)
10316 * We want to dump the opfamily only if (1) it contains "loose" operators
10317 * or functions, or (2) it contains an opclass with a different name or
10318 * owner. Otherwise it's sufficient to let it be created during creation
10319 * of the contained opclass, and not dumping it improves portability of
10320 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10324 query = createPQExpBuffer();
10325 q = createPQExpBuffer();
10326 delq = createPQExpBuffer();
10327 labelq = createPQExpBuffer();
10329 /* Make sure we are in proper schema so regoperator works correctly */
10330 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10333 * Fetch only those opfamily members that are tied directly to the
10334 * opfamily by pg_depend entries.
10336 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10337 * older server's opclass in which it is used. This is to avoid
10338 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10339 * older server and then reload into that old version. This can go away
10340 * once 8.3 is so old as to not be of interest to anyone.
10342 if (fout->remoteVersion >= 90100)
10344 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10345 "amopopr::pg_catalog.regoperator, "
10346 "opfname AS sortfamily, "
10347 "nspname AS sortfamilynsp "
10348 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10349 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10350 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10351 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10352 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10353 "AND refobjid = '%u'::pg_catalog.oid "
10354 "AND amopfamily = '%u'::pg_catalog.oid "
10355 "ORDER BY amopstrategy",
10356 opfinfo->dobj.catId.oid,
10357 opfinfo->dobj.catId.oid);
10359 else if (fout->remoteVersion >= 80400)
10361 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10362 "amopopr::pg_catalog.regoperator, "
10363 "NULL AS sortfamily, "
10364 "NULL AS sortfamilynsp "
10365 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10366 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10367 "AND refobjid = '%u'::pg_catalog.oid "
10368 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10369 "AND objid = ao.oid "
10370 "ORDER BY amopstrategy",
10371 opfinfo->dobj.catId.oid);
10375 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10376 "amopopr::pg_catalog.regoperator, "
10377 "NULL AS sortfamily, "
10378 "NULL AS sortfamilynsp "
10379 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10380 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10381 "AND refobjid = '%u'::pg_catalog.oid "
10382 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10383 "AND objid = ao.oid "
10384 "ORDER BY amopstrategy",
10385 opfinfo->dobj.catId.oid);
10388 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10390 resetPQExpBuffer(query);
10392 appendPQExpBuffer(query, "SELECT amprocnum, "
10393 "amproc::pg_catalog.regprocedure, "
10394 "amproclefttype::pg_catalog.regtype, "
10395 "amprocrighttype::pg_catalog.regtype "
10396 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10397 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10398 "AND refobjid = '%u'::pg_catalog.oid "
10399 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10400 "AND objid = ap.oid "
10401 "ORDER BY amprocnum",
10402 opfinfo->dobj.catId.oid);
10404 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10406 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10408 /* No loose members, so check contained opclasses */
10409 resetPQExpBuffer(query);
10411 appendPQExpBuffer(query, "SELECT 1 "
10412 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10413 "WHERE f.oid = '%u'::pg_catalog.oid "
10414 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10415 "AND refobjid = f.oid "
10416 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10417 "AND objid = c.oid "
10418 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10420 opfinfo->dobj.catId.oid);
10422 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10424 if (PQntuples(res) == 0)
10426 /* no need to dump it, so bail out */
10429 PQclear(res_procs);
10430 destroyPQExpBuffer(query);
10431 destroyPQExpBuffer(q);
10432 destroyPQExpBuffer(delq);
10433 destroyPQExpBuffer(labelq);
10440 /* Get additional fields from the pg_opfamily row */
10441 resetPQExpBuffer(query);
10443 appendPQExpBuffer(query, "SELECT "
10444 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10445 "FROM pg_catalog.pg_opfamily "
10446 "WHERE oid = '%u'::pg_catalog.oid",
10447 opfinfo->dobj.catId.oid);
10449 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10451 i_amname = PQfnumber(res, "amname");
10453 /* amname will still be needed after we PQclear res */
10454 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10457 * DROP must be fully qualified in case same name appears in pg_catalog
10459 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10460 fmtId(opfinfo->dobj.namespace->dobj.name));
10461 appendPQExpBuffer(delq, ".%s",
10462 fmtId(opfinfo->dobj.name));
10463 appendPQExpBuffer(delq, " USING %s;\n",
10466 /* Build the fixed portion of the CREATE command */
10467 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10468 fmtId(opfinfo->dobj.name));
10469 appendPQExpBuffer(q, " USING %s;\n",
10474 /* Do we need an ALTER to add loose members? */
10475 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10477 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10478 fmtId(opfinfo->dobj.name));
10479 appendPQExpBuffer(q, " USING %s ADD\n ",
10485 * Now fetch and print the OPERATOR entries (pg_amop rows).
10487 ntups = PQntuples(res_ops);
10489 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10490 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10491 i_amopopr = PQfnumber(res_ops, "amopopr");
10492 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10493 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10495 for (i = 0; i < ntups; i++)
10497 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10498 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10499 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10500 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10501 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10504 appendPQExpBuffer(q, " ,\n ");
10506 appendPQExpBuffer(q, "OPERATOR %s %s",
10507 amopstrategy, amopopr);
10509 if (strlen(sortfamily) > 0)
10511 appendPQExpBuffer(q, " FOR ORDER BY ");
10512 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10513 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10514 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10517 if (strcmp(amopreqcheck, "t") == 0)
10518 appendPQExpBuffer(q, " RECHECK");
10524 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10526 ntups = PQntuples(res_procs);
10528 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10529 i_amproc = PQfnumber(res_procs, "amproc");
10530 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10531 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10533 for (i = 0; i < ntups; i++)
10535 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10536 amproc = PQgetvalue(res_procs, i, i_amproc);
10537 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10538 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10541 appendPQExpBuffer(q, " ,\n ");
10543 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10544 amprocnum, amproclefttype, amprocrighttype,
10550 appendPQExpBuffer(q, ";\n");
10553 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10554 fmtId(opfinfo->dobj.name));
10555 appendPQExpBuffer(labelq, " USING %s",
10558 if (binary_upgrade)
10559 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10561 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10562 opfinfo->dobj.name,
10563 opfinfo->dobj.namespace->dobj.name,
10566 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10567 q->data, delq->data, NULL,
10568 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10571 /* Dump Operator Family Comments */
10572 dumpComment(fout, labelq->data,
10573 NULL, opfinfo->rolname,
10574 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10578 PQclear(res_procs);
10579 destroyPQExpBuffer(query);
10580 destroyPQExpBuffer(q);
10581 destroyPQExpBuffer(delq);
10582 destroyPQExpBuffer(labelq);
10587 * write out a single collation definition
10590 dumpCollation(Archive *fout, CollInfo *collinfo)
10595 PQExpBuffer labelq;
10599 const char *collcollate;
10600 const char *collctype;
10602 /* Skip if not to be dumped */
10603 if (!collinfo->dobj.dump || dataOnly)
10606 query = createPQExpBuffer();
10607 q = createPQExpBuffer();
10608 delq = createPQExpBuffer();
10609 labelq = createPQExpBuffer();
10611 /* Make sure we are in proper schema */
10612 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10614 /* Get conversion-specific details */
10615 appendPQExpBuffer(query, "SELECT "
10618 "FROM pg_catalog.pg_collation c "
10619 "WHERE c.oid = '%u'::pg_catalog.oid",
10620 collinfo->dobj.catId.oid);
10622 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10624 i_collcollate = PQfnumber(res, "collcollate");
10625 i_collctype = PQfnumber(res, "collctype");
10627 collcollate = PQgetvalue(res, 0, i_collcollate);
10628 collctype = PQgetvalue(res, 0, i_collctype);
10631 * DROP must be fully qualified in case same name appears in pg_catalog
10633 appendPQExpBuffer(delq, "DROP COLLATION %s",
10634 fmtId(collinfo->dobj.namespace->dobj.name));
10635 appendPQExpBuffer(delq, ".%s;\n",
10636 fmtId(collinfo->dobj.name));
10638 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10639 fmtId(collinfo->dobj.name));
10640 appendStringLiteralAH(q, collcollate, fout);
10641 appendPQExpBuffer(q, ", lc_ctype = ");
10642 appendStringLiteralAH(q, collctype, fout);
10643 appendPQExpBuffer(q, ");\n");
10645 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10647 if (binary_upgrade)
10648 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10650 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10651 collinfo->dobj.name,
10652 collinfo->dobj.namespace->dobj.name,
10655 false, "COLLATION", SECTION_PRE_DATA,
10656 q->data, delq->data, NULL,
10657 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10660 /* Dump Collation Comments */
10661 dumpComment(fout, labelq->data,
10662 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10663 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10667 destroyPQExpBuffer(query);
10668 destroyPQExpBuffer(q);
10669 destroyPQExpBuffer(delq);
10670 destroyPQExpBuffer(labelq);
10675 * write out a single conversion definition
10678 dumpConversion(Archive *fout, ConvInfo *convinfo)
10683 PQExpBuffer labelq;
10685 int i_conforencoding;
10686 int i_contoencoding;
10689 const char *conforencoding;
10690 const char *contoencoding;
10691 const char *conproc;
10694 /* Skip if not to be dumped */
10695 if (!convinfo->dobj.dump || dataOnly)
10698 query = createPQExpBuffer();
10699 q = createPQExpBuffer();
10700 delq = createPQExpBuffer();
10701 labelq = createPQExpBuffer();
10703 /* Make sure we are in proper schema */
10704 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10706 /* Get conversion-specific details */
10707 appendPQExpBuffer(query, "SELECT "
10708 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10709 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10710 "conproc, condefault "
10711 "FROM pg_catalog.pg_conversion c "
10712 "WHERE c.oid = '%u'::pg_catalog.oid",
10713 convinfo->dobj.catId.oid);
10715 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10717 i_conforencoding = PQfnumber(res, "conforencoding");
10718 i_contoencoding = PQfnumber(res, "contoencoding");
10719 i_conproc = PQfnumber(res, "conproc");
10720 i_condefault = PQfnumber(res, "condefault");
10722 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10723 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10724 conproc = PQgetvalue(res, 0, i_conproc);
10725 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10728 * DROP must be fully qualified in case same name appears in pg_catalog
10730 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10731 fmtId(convinfo->dobj.namespace->dobj.name));
10732 appendPQExpBuffer(delq, ".%s;\n",
10733 fmtId(convinfo->dobj.name));
10735 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10736 (condefault) ? "DEFAULT " : "",
10737 fmtId(convinfo->dobj.name));
10738 appendStringLiteralAH(q, conforencoding, fout);
10739 appendPQExpBuffer(q, " TO ");
10740 appendStringLiteralAH(q, contoencoding, fout);
10741 /* regproc is automatically quoted in 7.3 and above */
10742 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10744 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10746 if (binary_upgrade)
10747 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10749 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10750 convinfo->dobj.name,
10751 convinfo->dobj.namespace->dobj.name,
10754 false, "CONVERSION", SECTION_PRE_DATA,
10755 q->data, delq->data, NULL,
10756 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10759 /* Dump Conversion Comments */
10760 dumpComment(fout, labelq->data,
10761 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10762 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10766 destroyPQExpBuffer(query);
10767 destroyPQExpBuffer(q);
10768 destroyPQExpBuffer(delq);
10769 destroyPQExpBuffer(labelq);
10773 * format_aggregate_signature: generate aggregate name and argument list
10775 * The argument type names are qualified if needed. The aggregate name
10776 * is never qualified.
10779 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10781 PQExpBufferData buf;
10784 initPQExpBuffer(&buf);
10786 appendPQExpBuffer(&buf, "%s",
10787 fmtId(agginfo->aggfn.dobj.name));
10789 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10791 if (agginfo->aggfn.nargs == 0)
10792 appendPQExpBuffer(&buf, "(*)");
10795 appendPQExpBuffer(&buf, "(");
10796 for (j = 0; j < agginfo->aggfn.nargs; j++)
10800 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10803 appendPQExpBuffer(&buf, "%s%s",
10804 (j > 0) ? ", " : "",
10808 appendPQExpBuffer(&buf, ")");
10815 * write out a single aggregate definition
10818 dumpAgg(Archive *fout, AggInfo *agginfo)
10823 PQExpBuffer labelq;
10824 PQExpBuffer details;
10831 int i_aggtranstype;
10834 const char *aggtransfn;
10835 const char *aggfinalfn;
10836 const char *aggsortop;
10837 const char *aggtranstype;
10838 const char *agginitval;
10841 /* Skip if not to be dumped */
10842 if (!agginfo->aggfn.dobj.dump || dataOnly)
10845 query = createPQExpBuffer();
10846 q = createPQExpBuffer();
10847 delq = createPQExpBuffer();
10848 labelq = createPQExpBuffer();
10849 details = createPQExpBuffer();
10851 /* Make sure we are in proper schema */
10852 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10854 /* Get aggregate-specific details */
10855 if (fout->remoteVersion >= 80100)
10857 appendPQExpBuffer(query, "SELECT aggtransfn, "
10858 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10859 "aggsortop::pg_catalog.regoperator, "
10861 "'t'::boolean AS convertok "
10862 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10863 "WHERE a.aggfnoid = p.oid "
10864 "AND p.oid = '%u'::pg_catalog.oid",
10865 agginfo->aggfn.dobj.catId.oid);
10867 else if (fout->remoteVersion >= 70300)
10869 appendPQExpBuffer(query, "SELECT aggtransfn, "
10870 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10873 "'t'::boolean AS convertok "
10874 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10875 "WHERE a.aggfnoid = p.oid "
10876 "AND p.oid = '%u'::pg_catalog.oid",
10877 agginfo->aggfn.dobj.catId.oid);
10879 else if (fout->remoteVersion >= 70100)
10881 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10882 "format_type(aggtranstype, NULL) AS aggtranstype, "
10885 "'t'::boolean AS convertok "
10886 "FROM pg_aggregate "
10887 "WHERE oid = '%u'::oid",
10888 agginfo->aggfn.dobj.catId.oid);
10892 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10894 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10896 "agginitval1 AS agginitval, "
10897 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10898 "FROM pg_aggregate "
10899 "WHERE oid = '%u'::oid",
10900 agginfo->aggfn.dobj.catId.oid);
10903 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10905 i_aggtransfn = PQfnumber(res, "aggtransfn");
10906 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10907 i_aggsortop = PQfnumber(res, "aggsortop");
10908 i_aggtranstype = PQfnumber(res, "aggtranstype");
10909 i_agginitval = PQfnumber(res, "agginitval");
10910 i_convertok = PQfnumber(res, "convertok");
10912 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10913 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10914 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10915 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10916 agginitval = PQgetvalue(res, 0, i_agginitval);
10917 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10919 aggsig = format_aggregate_signature(agginfo, fout, true);
10920 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10924 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10929 if (fout->remoteVersion >= 70300)
10931 /* If using 7.3's regproc or regtype, data is already quoted */
10932 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10936 else if (fout->remoteVersion >= 70100)
10938 /* format_type quotes, regproc does not */
10939 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10945 /* need quotes all around */
10946 appendPQExpBuffer(details, " SFUNC = %s,\n",
10947 fmtId(aggtransfn));
10948 appendPQExpBuffer(details, " STYPE = %s",
10949 fmtId(aggtranstype));
10952 if (!PQgetisnull(res, 0, i_agginitval))
10954 appendPQExpBuffer(details, ",\n INITCOND = ");
10955 appendStringLiteralAH(details, agginitval, fout);
10958 if (strcmp(aggfinalfn, "-") != 0)
10960 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
10964 aggsortop = convertOperatorReference(fout, aggsortop);
10967 appendPQExpBuffer(details, ",\n SORTOP = %s",
10972 * DROP must be fully qualified in case same name appears in pg_catalog
10974 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10975 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10978 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10979 aggsig, details->data);
10981 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10983 if (binary_upgrade)
10984 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10986 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10988 agginfo->aggfn.dobj.namespace->dobj.name,
10990 agginfo->aggfn.rolname,
10991 false, "AGGREGATE", SECTION_PRE_DATA,
10992 q->data, delq->data, NULL,
10993 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10996 /* Dump Aggregate Comments */
10997 dumpComment(fout, labelq->data,
10998 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10999 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11000 dumpSecLabel(fout, labelq->data,
11001 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11002 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11005 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11006 * command look like a function's GRANT; in particular this affects the
11007 * syntax for zero-argument aggregates.
11012 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11013 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11015 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11017 aggsig, NULL, aggsig_tag,
11018 agginfo->aggfn.dobj.namespace->dobj.name,
11019 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11026 destroyPQExpBuffer(query);
11027 destroyPQExpBuffer(q);
11028 destroyPQExpBuffer(delq);
11029 destroyPQExpBuffer(labelq);
11030 destroyPQExpBuffer(details);
11035 * write out a single text search parser
11038 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11042 PQExpBuffer labelq;
11044 /* Skip if not to be dumped */
11045 if (!prsinfo->dobj.dump || dataOnly)
11048 q = createPQExpBuffer();
11049 delq = createPQExpBuffer();
11050 labelq = createPQExpBuffer();
11052 /* Make sure we are in proper schema */
11053 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11055 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11056 fmtId(prsinfo->dobj.name));
11058 appendPQExpBuffer(q, " START = %s,\n",
11059 convertTSFunction(fout, prsinfo->prsstart));
11060 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11061 convertTSFunction(fout, prsinfo->prstoken));
11062 appendPQExpBuffer(q, " END = %s,\n",
11063 convertTSFunction(fout, prsinfo->prsend));
11064 if (prsinfo->prsheadline != InvalidOid)
11065 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11066 convertTSFunction(fout, prsinfo->prsheadline));
11067 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11068 convertTSFunction(fout, prsinfo->prslextype));
11071 * DROP must be fully qualified in case same name appears in pg_catalog
11073 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11074 fmtId(prsinfo->dobj.namespace->dobj.name));
11075 appendPQExpBuffer(delq, ".%s;\n",
11076 fmtId(prsinfo->dobj.name));
11078 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11079 fmtId(prsinfo->dobj.name));
11081 if (binary_upgrade)
11082 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11084 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11085 prsinfo->dobj.name,
11086 prsinfo->dobj.namespace->dobj.name,
11089 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11090 q->data, delq->data, NULL,
11091 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11094 /* Dump Parser Comments */
11095 dumpComment(fout, labelq->data,
11097 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11099 destroyPQExpBuffer(q);
11100 destroyPQExpBuffer(delq);
11101 destroyPQExpBuffer(labelq);
11106 * write out a single text search dictionary
11109 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11113 PQExpBuffer labelq;
11119 /* Skip if not to be dumped */
11120 if (!dictinfo->dobj.dump || dataOnly)
11123 q = createPQExpBuffer();
11124 delq = createPQExpBuffer();
11125 labelq = createPQExpBuffer();
11126 query = createPQExpBuffer();
11128 /* Fetch name and namespace of the dictionary's template */
11129 selectSourceSchema(fout, "pg_catalog");
11130 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11131 "FROM pg_ts_template p, pg_namespace n "
11132 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11133 dictinfo->dicttemplate);
11134 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11135 nspname = PQgetvalue(res, 0, 0);
11136 tmplname = PQgetvalue(res, 0, 1);
11138 /* Make sure we are in proper schema */
11139 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11141 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11142 fmtId(dictinfo->dobj.name));
11144 appendPQExpBuffer(q, " TEMPLATE = ");
11145 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11146 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11147 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11151 /* the dictinitoption can be dumped straight into the command */
11152 if (dictinfo->dictinitoption)
11153 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11155 appendPQExpBuffer(q, " );\n");
11158 * DROP must be fully qualified in case same name appears in pg_catalog
11160 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11161 fmtId(dictinfo->dobj.namespace->dobj.name));
11162 appendPQExpBuffer(delq, ".%s;\n",
11163 fmtId(dictinfo->dobj.name));
11165 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11166 fmtId(dictinfo->dobj.name));
11168 if (binary_upgrade)
11169 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11171 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11172 dictinfo->dobj.name,
11173 dictinfo->dobj.namespace->dobj.name,
11176 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11177 q->data, delq->data, NULL,
11178 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11181 /* Dump Dictionary Comments */
11182 dumpComment(fout, labelq->data,
11183 NULL, dictinfo->rolname,
11184 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11186 destroyPQExpBuffer(q);
11187 destroyPQExpBuffer(delq);
11188 destroyPQExpBuffer(labelq);
11189 destroyPQExpBuffer(query);
11194 * write out a single text search template
11197 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11201 PQExpBuffer labelq;
11203 /* Skip if not to be dumped */
11204 if (!tmplinfo->dobj.dump || dataOnly)
11207 q = createPQExpBuffer();
11208 delq = createPQExpBuffer();
11209 labelq = createPQExpBuffer();
11211 /* Make sure we are in proper schema */
11212 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11214 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11215 fmtId(tmplinfo->dobj.name));
11217 if (tmplinfo->tmplinit != InvalidOid)
11218 appendPQExpBuffer(q, " INIT = %s,\n",
11219 convertTSFunction(fout, tmplinfo->tmplinit));
11220 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11221 convertTSFunction(fout, tmplinfo->tmpllexize));
11224 * DROP must be fully qualified in case same name appears in pg_catalog
11226 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11227 fmtId(tmplinfo->dobj.namespace->dobj.name));
11228 appendPQExpBuffer(delq, ".%s;\n",
11229 fmtId(tmplinfo->dobj.name));
11231 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11232 fmtId(tmplinfo->dobj.name));
11234 if (binary_upgrade)
11235 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11237 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11238 tmplinfo->dobj.name,
11239 tmplinfo->dobj.namespace->dobj.name,
11242 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11243 q->data, delq->data, NULL,
11244 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11247 /* Dump Template Comments */
11248 dumpComment(fout, labelq->data,
11250 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11252 destroyPQExpBuffer(q);
11253 destroyPQExpBuffer(delq);
11254 destroyPQExpBuffer(labelq);
11259 * write out a single text search configuration
11262 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11266 PQExpBuffer labelq;
11276 /* Skip if not to be dumped */
11277 if (!cfginfo->dobj.dump || dataOnly)
11280 q = createPQExpBuffer();
11281 delq = createPQExpBuffer();
11282 labelq = createPQExpBuffer();
11283 query = createPQExpBuffer();
11285 /* Fetch name and namespace of the config's parser */
11286 selectSourceSchema(fout, "pg_catalog");
11287 appendPQExpBuffer(query, "SELECT nspname, prsname "
11288 "FROM pg_ts_parser p, pg_namespace n "
11289 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11290 cfginfo->cfgparser);
11291 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11292 nspname = PQgetvalue(res, 0, 0);
11293 prsname = PQgetvalue(res, 0, 1);
11295 /* Make sure we are in proper schema */
11296 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11298 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11299 fmtId(cfginfo->dobj.name));
11301 appendPQExpBuffer(q, " PARSER = ");
11302 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11303 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11304 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11308 resetPQExpBuffer(query);
11309 appendPQExpBuffer(query,
11311 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11312 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11313 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11314 "FROM pg_catalog.pg_ts_config_map AS m \n"
11315 "WHERE m.mapcfg = '%u' \n"
11316 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11317 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11319 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11320 ntups = PQntuples(res);
11322 i_tokenname = PQfnumber(res, "tokenname");
11323 i_dictname = PQfnumber(res, "dictname");
11325 for (i = 0; i < ntups; i++)
11327 char *tokenname = PQgetvalue(res, i, i_tokenname);
11328 char *dictname = PQgetvalue(res, i, i_dictname);
11331 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11333 /* starting a new token type, so start a new command */
11335 appendPQExpBuffer(q, ";\n");
11336 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11337 fmtId(cfginfo->dobj.name));
11338 /* tokenname needs quoting, dictname does NOT */
11339 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11340 fmtId(tokenname), dictname);
11343 appendPQExpBuffer(q, ", %s", dictname);
11347 appendPQExpBuffer(q, ";\n");
11352 * DROP must be fully qualified in case same name appears in pg_catalog
11354 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11355 fmtId(cfginfo->dobj.namespace->dobj.name));
11356 appendPQExpBuffer(delq, ".%s;\n",
11357 fmtId(cfginfo->dobj.name));
11359 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11360 fmtId(cfginfo->dobj.name));
11362 if (binary_upgrade)
11363 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11365 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11366 cfginfo->dobj.name,
11367 cfginfo->dobj.namespace->dobj.name,
11370 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11371 q->data, delq->data, NULL,
11372 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11375 /* Dump Configuration Comments */
11376 dumpComment(fout, labelq->data,
11377 NULL, cfginfo->rolname,
11378 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11380 destroyPQExpBuffer(q);
11381 destroyPQExpBuffer(delq);
11382 destroyPQExpBuffer(labelq);
11383 destroyPQExpBuffer(query);
11387 * dumpForeignDataWrapper
11388 * write out a single foreign-data wrapper definition
11391 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11395 PQExpBuffer labelq;
11398 /* Skip if not to be dumped */
11399 if (!fdwinfo->dobj.dump || dataOnly)
11403 * FDWs that belong to an extension are dumped based on their "dump"
11404 * field. Otherwise omit them if we are only dumping some specific object.
11406 if (!fdwinfo->dobj.ext_member)
11407 if (!include_everything)
11410 q = createPQExpBuffer();
11411 delq = createPQExpBuffer();
11412 labelq = createPQExpBuffer();
11414 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11416 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11419 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11420 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11422 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11423 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11425 if (strlen(fdwinfo->fdwoptions) > 0)
11426 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11428 appendPQExpBuffer(q, ";\n");
11430 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11433 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11436 if (binary_upgrade)
11437 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11439 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11440 fdwinfo->dobj.name,
11444 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11445 q->data, delq->data, NULL,
11446 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11449 /* Handle the ACL */
11450 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11451 "FOREIGN DATA WRAPPER",
11452 qfdwname, NULL, fdwinfo->dobj.name,
11453 NULL, fdwinfo->rolname,
11456 /* Dump Foreign Data Wrapper Comments */
11457 dumpComment(fout, labelq->data,
11458 NULL, fdwinfo->rolname,
11459 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11463 destroyPQExpBuffer(q);
11464 destroyPQExpBuffer(delq);
11465 destroyPQExpBuffer(labelq);
11469 * dumpForeignServer
11470 * write out a foreign server definition
11473 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11477 PQExpBuffer labelq;
11483 /* Skip if not to be dumped */
11484 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11487 q = createPQExpBuffer();
11488 delq = createPQExpBuffer();
11489 labelq = createPQExpBuffer();
11490 query = createPQExpBuffer();
11492 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11494 /* look up the foreign-data wrapper */
11495 selectSourceSchema(fout, "pg_catalog");
11496 appendPQExpBuffer(query, "SELECT fdwname "
11497 "FROM pg_foreign_data_wrapper w "
11498 "WHERE w.oid = '%u'",
11500 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11501 fdwname = PQgetvalue(res, 0, 0);
11503 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11504 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11506 appendPQExpBuffer(q, " TYPE ");
11507 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11509 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11511 appendPQExpBuffer(q, " VERSION ");
11512 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11515 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11516 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11518 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11519 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11521 appendPQExpBuffer(q, ";\n");
11523 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11526 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11528 if (binary_upgrade)
11529 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11531 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11532 srvinfo->dobj.name,
11536 false, "SERVER", SECTION_PRE_DATA,
11537 q->data, delq->data, NULL,
11538 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11541 /* Handle the ACL */
11542 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11544 qsrvname, NULL, srvinfo->dobj.name,
11545 NULL, srvinfo->rolname,
11548 /* Dump user mappings */
11549 dumpUserMappings(fout,
11550 srvinfo->dobj.name, NULL,
11552 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11554 /* Dump Foreign Server Comments */
11555 dumpComment(fout, labelq->data,
11556 NULL, srvinfo->rolname,
11557 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11561 destroyPQExpBuffer(q);
11562 destroyPQExpBuffer(delq);
11563 destroyPQExpBuffer(labelq);
11569 * This routine is used to dump any user mappings associated with the
11570 * server handed to this routine. Should be called after ArchiveEntry()
11574 dumpUserMappings(Archive *fout,
11575 const char *servername, const char *namespace,
11577 CatalogId catalogId, DumpId dumpId)
11589 q = createPQExpBuffer();
11590 tag = createPQExpBuffer();
11591 delq = createPQExpBuffer();
11592 query = createPQExpBuffer();
11595 * We read from the publicly accessible view pg_user_mappings, so as not
11596 * to fail if run by a non-superuser. Note that the view will show
11597 * umoptions as null if the user hasn't got privileges for the associated
11598 * server; this means that pg_dump will dump such a mapping, but with no
11599 * OPTIONS clause. A possible alternative is to skip such mappings
11600 * altogether, but it's not clear that that's an improvement.
11602 selectSourceSchema(fout, "pg_catalog");
11604 appendPQExpBuffer(query,
11606 "array_to_string(ARRAY("
11607 "SELECT quote_ident(option_name) || ' ' || "
11608 "quote_literal(option_value) "
11609 "FROM pg_options_to_table(umoptions) "
11610 "ORDER BY option_name"
11611 "), E',\n ') AS umoptions "
11612 "FROM pg_user_mappings "
11613 "WHERE srvid = '%u' "
11614 "ORDER BY usename",
11617 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11619 ntups = PQntuples(res);
11620 i_usename = PQfnumber(res, "usename");
11621 i_umoptions = PQfnumber(res, "umoptions");
11623 for (i = 0; i < ntups; i++)
11628 usename = PQgetvalue(res, i, i_usename);
11629 umoptions = PQgetvalue(res, i, i_umoptions);
11631 resetPQExpBuffer(q);
11632 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11633 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11635 if (umoptions && strlen(umoptions) > 0)
11636 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11638 appendPQExpBuffer(q, ";\n");
11640 resetPQExpBuffer(delq);
11641 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11642 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11644 resetPQExpBuffer(tag);
11645 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11646 usename, servername);
11648 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11653 "USER MAPPING", SECTION_PRE_DATA,
11654 q->data, delq->data, NULL,
11661 destroyPQExpBuffer(query);
11662 destroyPQExpBuffer(delq);
11663 destroyPQExpBuffer(q);
11667 * Write out default privileges information
11670 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11676 /* Skip if not to be dumped */
11677 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11680 q = createPQExpBuffer();
11681 tag = createPQExpBuffer();
11683 switch (daclinfo->defaclobjtype)
11685 case DEFACLOBJ_RELATION:
11688 case DEFACLOBJ_SEQUENCE:
11689 type = "SEQUENCES";
11691 case DEFACLOBJ_FUNCTION:
11692 type = "FUNCTIONS";
11695 /* shouldn't get here */
11696 exit_horribly(NULL,
11697 "unknown object type (%d) in default privileges\n",
11698 (int) daclinfo->defaclobjtype);
11699 type = ""; /* keep compiler quiet */
11702 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11704 /* build the actual command(s) for this tuple */
11705 if (!buildDefaultACLCommands(type,
11706 daclinfo->dobj.namespace != NULL ?
11707 daclinfo->dobj.namespace->dobj.name : NULL,
11708 daclinfo->defaclacl,
11709 daclinfo->defaclrole,
11710 fout->remoteVersion,
11712 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11713 daclinfo->defaclacl);
11715 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11717 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11719 daclinfo->defaclrole,
11720 false, "DEFAULT ACL", SECTION_NONE,
11722 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11725 destroyPQExpBuffer(tag);
11726 destroyPQExpBuffer(q);
11730 * Write out grant/revoke information
11732 * 'objCatId' is the catalog ID of the underlying object.
11733 * 'objDumpId' is the dump ID of the underlying object.
11734 * 'type' must be one of
11735 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11736 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11737 * 'name' is the formatted name of the object. Must be quoted etc. already.
11738 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11739 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11740 * 'nspname' is the namespace the object is in (NULL if none).
11741 * 'owner' is the owner, NULL if there is no owner (for languages).
11742 * 'acls' is the string read out of the fooacl system catalog field;
11743 * it will be parsed here.
11747 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11748 const char *type, const char *name, const char *subname,
11749 const char *tag, const char *nspname, const char *owner,
11754 /* Do nothing if ACL dump is not enabled */
11758 /* --data-only skips ACLs *except* BLOB ACLs */
11759 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11762 sql = createPQExpBuffer();
11764 if (!buildACLCommands(name, subname, type, acls, owner,
11765 "", fout->remoteVersion, sql))
11766 exit_horribly(NULL,
11767 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11771 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11774 owner ? owner : "",
11775 false, "ACL", SECTION_NONE,
11776 sql->data, "", NULL,
11780 destroyPQExpBuffer(sql);
11786 * This routine is used to dump any security labels associated with the
11787 * object handed to this routine. The routine takes a constant character
11788 * string for the target part of the security-label command, plus
11789 * the namespace and owner of the object (for labeling the ArchiveEntry),
11790 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11791 * plus the dump ID for the object (for setting a dependency).
11792 * If a matching pg_seclabel entry is found, it is dumped.
11794 * Note: although this routine takes a dumpId for dependency purposes,
11795 * that purpose is just to mark the dependency in the emitted dump file
11796 * for possible future use by pg_restore. We do NOT use it for determining
11797 * ordering of the label in the dump file, because this routine is called
11798 * after dependency sorting occurs. This routine should be called just after
11799 * calling ArchiveEntry() for the specified object.
11802 dumpSecLabel(Archive *fout, const char *target,
11803 const char *namespace, const char *owner,
11804 CatalogId catalogId, int subid, DumpId dumpId)
11806 SecLabelItem *labels;
11811 /* do nothing, if --no-security-labels is supplied */
11812 if (no_security_labels)
11815 /* Comments are schema not data ... except blob comments are data */
11816 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11827 /* Search for security labels associated with catalogId, using table */
11828 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11830 query = createPQExpBuffer();
11832 for (i = 0; i < nlabels; i++)
11835 * Ignore label entries for which the subid doesn't match.
11837 if (labels[i].objsubid != subid)
11840 appendPQExpBuffer(query,
11841 "SECURITY LABEL FOR %s ON %s IS ",
11842 fmtId(labels[i].provider), target);
11843 appendStringLiteralAH(query, labels[i].label, fout);
11844 appendPQExpBuffer(query, ";\n");
11847 if (query->len > 0)
11849 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11850 target, namespace, NULL, owner,
11851 false, "SECURITY LABEL", SECTION_NONE,
11852 query->data, "", NULL,
11856 destroyPQExpBuffer(query);
11860 * dumpTableSecLabel
11862 * As above, but dump security label for both the specified table (or view)
11866 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11868 SecLabelItem *labels;
11872 PQExpBuffer target;
11874 /* do nothing, if --no-security-labels is supplied */
11875 if (no_security_labels)
11878 /* SecLabel are SCHEMA not data */
11882 /* Search for comments associated with relation, using table */
11883 nlabels = findSecLabels(fout,
11884 tbinfo->dobj.catId.tableoid,
11885 tbinfo->dobj.catId.oid,
11888 /* If security labels exist, build SECURITY LABEL statements */
11892 query = createPQExpBuffer();
11893 target = createPQExpBuffer();
11895 for (i = 0; i < nlabels; i++)
11897 const char *colname;
11898 const char *provider = labels[i].provider;
11899 const char *label = labels[i].label;
11900 int objsubid = labels[i].objsubid;
11902 resetPQExpBuffer(target);
11905 appendPQExpBuffer(target, "%s %s", reltypename,
11906 fmtId(tbinfo->dobj.name));
11910 colname = getAttrName(objsubid, tbinfo);
11911 /* first fmtId result must be consumed before calling it again */
11912 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11913 appendPQExpBuffer(target, ".%s", fmtId(colname));
11915 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11916 fmtId(provider), target->data);
11917 appendStringLiteralAH(query, label, fout);
11918 appendPQExpBuffer(query, ";\n");
11920 if (query->len > 0)
11922 resetPQExpBuffer(target);
11923 appendPQExpBuffer(target, "%s %s", reltypename,
11924 fmtId(tbinfo->dobj.name));
11925 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11927 tbinfo->dobj.namespace->dobj.name,
11928 NULL, tbinfo->rolname,
11929 false, "SECURITY LABEL", SECTION_NONE,
11930 query->data, "", NULL,
11931 &(tbinfo->dobj.dumpId), 1,
11934 destroyPQExpBuffer(query);
11935 destroyPQExpBuffer(target);
11941 * Find the security label(s), if any, associated with the given object.
11942 * All the objsubid values associated with the given classoid/objoid are
11943 * found with one search.
11946 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11948 /* static storage for table of security labels */
11949 static SecLabelItem *labels = NULL;
11950 static int nlabels = -1;
11952 SecLabelItem *middle = NULL;
11954 SecLabelItem *high;
11957 /* Get security labels if we didn't already */
11959 nlabels = collectSecLabels(fout, &labels);
11961 if (nlabels <= 0) /* no labels, so no match is possible */
11968 * Do binary search to find some item matching the object.
11971 high = &labels[nlabels - 1];
11972 while (low <= high)
11974 middle = low + (high - low) / 2;
11976 if (classoid < middle->classoid)
11978 else if (classoid > middle->classoid)
11980 else if (objoid < middle->objoid)
11982 else if (objoid > middle->objoid)
11985 break; /* found a match */
11988 if (low > high) /* no matches */
11995 * Now determine how many items match the object. The search loop
11996 * invariant still holds: only items between low and high inclusive could
12000 while (middle > low)
12002 if (classoid != middle[-1].classoid ||
12003 objoid != middle[-1].objoid)
12012 while (middle <= high)
12014 if (classoid != middle->classoid ||
12015 objoid != middle->objoid)
12027 * Construct a table of all security labels available for database objects.
12028 * It's much faster to pull them all at once.
12030 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12033 collectSecLabels(Archive *fout, SecLabelItem **items)
12044 SecLabelItem *labels;
12046 query = createPQExpBuffer();
12048 appendPQExpBuffer(query,
12049 "SELECT label, provider, classoid, objoid, objsubid "
12050 "FROM pg_catalog.pg_seclabel "
12051 "ORDER BY classoid, objoid, objsubid");
12053 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12055 /* Construct lookup table containing OIDs in numeric form */
12056 i_label = PQfnumber(res, "label");
12057 i_provider = PQfnumber(res, "provider");
12058 i_classoid = PQfnumber(res, "classoid");
12059 i_objoid = PQfnumber(res, "objoid");
12060 i_objsubid = PQfnumber(res, "objsubid");
12062 ntups = PQntuples(res);
12064 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12066 for (i = 0; i < ntups; i++)
12068 labels[i].label = PQgetvalue(res, i, i_label);
12069 labels[i].provider = PQgetvalue(res, i, i_provider);
12070 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12071 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12072 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12075 /* Do NOT free the PGresult since we are keeping pointers into it */
12076 destroyPQExpBuffer(query);
12084 * write out to fout the declarations (not data) of a user-defined table
12087 dumpTable(Archive *fout, TableInfo *tbinfo)
12089 if (tbinfo->dobj.dump)
12093 if (tbinfo->relkind == RELKIND_SEQUENCE)
12094 dumpSequence(fout, tbinfo);
12095 else if (!dataOnly)
12096 dumpTableSchema(fout, tbinfo);
12098 /* Handle the ACL here */
12099 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12100 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12101 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12103 namecopy, NULL, tbinfo->dobj.name,
12104 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12108 * Handle column ACLs, if any. Note: we pull these with a separate
12109 * query rather than trying to fetch them during getTableAttrs, so
12110 * that we won't miss ACLs on system columns.
12112 if (fout->remoteVersion >= 80400)
12114 PQExpBuffer query = createPQExpBuffer();
12118 appendPQExpBuffer(query,
12119 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12120 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12122 tbinfo->dobj.catId.oid);
12123 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12125 for (i = 0; i < PQntuples(res); i++)
12127 char *attname = PQgetvalue(res, i, 0);
12128 char *attacl = PQgetvalue(res, i, 1);
12132 attnamecopy = pg_strdup(fmtId(attname));
12133 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12134 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12135 /* Column's GRANT type is always TABLE */
12136 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12137 namecopy, attnamecopy, acltag,
12138 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12144 destroyPQExpBuffer(query);
12153 * write the declaration (not data) of one user-defined table or view
12156 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12158 PQExpBuffer query = createPQExpBuffer();
12159 PQExpBuffer q = createPQExpBuffer();
12160 PQExpBuffer delq = createPQExpBuffer();
12161 PQExpBuffer labelq = createPQExpBuffer();
12164 TableInfo **parents;
12165 int actual_atts; /* number of attrs in this CREATE statment */
12166 const char *reltypename;
12173 /* Make sure we are in proper schema */
12174 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12176 if (binary_upgrade)
12177 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12178 tbinfo->dobj.catId.oid);
12180 /* Is it a table or a view? */
12181 if (tbinfo->relkind == RELKIND_VIEW)
12185 reltypename = "VIEW";
12187 /* Fetch the view definition */
12188 if (fout->remoteVersion >= 70300)
12190 /* Beginning in 7.3, viewname is not unique; rely on OID */
12191 appendPQExpBuffer(query,
12192 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12193 tbinfo->dobj.catId.oid);
12197 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12198 "FROM pg_views WHERE viewname = ");
12199 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12200 appendPQExpBuffer(query, ";");
12203 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12205 if (PQntuples(res) != 1)
12207 if (PQntuples(res) < 1)
12208 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12209 tbinfo->dobj.name);
12211 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12212 tbinfo->dobj.name);
12215 viewdef = PQgetvalue(res, 0, 0);
12217 if (strlen(viewdef) == 0)
12218 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12219 tbinfo->dobj.name);
12222 * DROP must be fully qualified in case same name appears in
12225 appendPQExpBuffer(delq, "DROP VIEW %s.",
12226 fmtId(tbinfo->dobj.namespace->dobj.name));
12227 appendPQExpBuffer(delq, "%s;\n",
12228 fmtId(tbinfo->dobj.name));
12230 if (binary_upgrade)
12231 binary_upgrade_set_pg_class_oids(fout, q,
12232 tbinfo->dobj.catId.oid, false);
12234 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12235 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12236 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12237 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12239 appendPQExpBuffer(labelq, "VIEW %s",
12240 fmtId(tbinfo->dobj.name));
12246 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12251 reltypename = "FOREIGN TABLE";
12253 /* retrieve name of foreign server and generic options */
12254 appendPQExpBuffer(query,
12255 "SELECT fs.srvname, "
12256 "pg_catalog.array_to_string(ARRAY("
12257 "SELECT pg_catalog.quote_ident(option_name) || "
12258 "' ' || pg_catalog.quote_literal(option_value) "
12259 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12260 "ORDER BY option_name"
12261 "), E',\n ') AS ftoptions "
12262 "FROM pg_catalog.pg_foreign_table ft "
12263 "JOIN pg_catalog.pg_foreign_server fs "
12264 "ON (fs.oid = ft.ftserver) "
12265 "WHERE ft.ftrelid = '%u'",
12266 tbinfo->dobj.catId.oid);
12267 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12268 i_srvname = PQfnumber(res, "srvname");
12269 i_ftoptions = PQfnumber(res, "ftoptions");
12270 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12271 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12276 reltypename = "TABLE";
12280 numParents = tbinfo->numParents;
12281 parents = tbinfo->parents;
12284 * DROP must be fully qualified in case same name appears in
12287 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12288 fmtId(tbinfo->dobj.namespace->dobj.name));
12289 appendPQExpBuffer(delq, "%s;\n",
12290 fmtId(tbinfo->dobj.name));
12292 appendPQExpBuffer(labelq, "%s %s", reltypename,
12293 fmtId(tbinfo->dobj.name));
12295 if (binary_upgrade)
12296 binary_upgrade_set_pg_class_oids(fout, q,
12297 tbinfo->dobj.catId.oid, false);
12299 appendPQExpBuffer(q, "CREATE %s%s %s",
12300 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12303 fmtId(tbinfo->dobj.name));
12306 * Attach to type, if reloftype; except in case of a binary upgrade,
12307 * we dump the table normally and attach it to the type afterward.
12309 if (tbinfo->reloftype && !binary_upgrade)
12310 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12312 /* Dump the attributes */
12314 for (j = 0; j < tbinfo->numatts; j++)
12317 * Normally, dump if it's locally defined in this table, and not
12318 * dropped. But for binary upgrade, we'll dump all the columns,
12319 * and then fix up the dropped and nonlocal cases below.
12321 if (shouldPrintColumn(tbinfo, j))
12324 * Default value --- suppress if to be printed separately.
12326 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12327 !tbinfo->attrdefs[j]->separate);
12330 * Not Null constraint --- suppress if inherited, except in
12331 * binary-upgrade case where that won't work.
12333 bool has_notnull = (tbinfo->notnull[j] &&
12334 (!tbinfo->inhNotNull[j] ||
12337 /* Skip column if fully defined by reloftype */
12338 if (tbinfo->reloftype &&
12339 !has_default && !has_notnull && !binary_upgrade)
12342 /* Format properly if not first attr */
12343 if (actual_atts == 0)
12344 appendPQExpBuffer(q, " (");
12346 appendPQExpBuffer(q, ",");
12347 appendPQExpBuffer(q, "\n ");
12350 /* Attribute name */
12351 appendPQExpBuffer(q, "%s ",
12352 fmtId(tbinfo->attnames[j]));
12354 if (tbinfo->attisdropped[j])
12357 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12358 * so we will not have gotten a valid type name; insert
12359 * INTEGER as a stopgap. We'll clean things up later.
12361 appendPQExpBuffer(q, "INTEGER /* dummy */");
12362 /* Skip all the rest, too */
12366 /* Attribute type */
12367 if (tbinfo->reloftype && !binary_upgrade)
12369 appendPQExpBuffer(q, "WITH OPTIONS");
12371 else if (fout->remoteVersion >= 70100)
12373 appendPQExpBuffer(q, "%s",
12374 tbinfo->atttypnames[j]);
12378 /* If no format_type, fake it */
12379 appendPQExpBuffer(q, "%s",
12380 myFormatType(tbinfo->atttypnames[j],
12381 tbinfo->atttypmod[j]));
12384 /* Add collation if not default for the type */
12385 if (OidIsValid(tbinfo->attcollation[j]))
12389 coll = findCollationByOid(tbinfo->attcollation[j]);
12392 /* always schema-qualify, don't try to be smart */
12393 appendPQExpBuffer(q, " COLLATE %s.",
12394 fmtId(coll->dobj.namespace->dobj.name));
12395 appendPQExpBuffer(q, "%s",
12396 fmtId(coll->dobj.name));
12401 appendPQExpBuffer(q, " DEFAULT %s",
12402 tbinfo->attrdefs[j]->adef_expr);
12405 appendPQExpBuffer(q, " NOT NULL");
12410 * Add non-inherited CHECK constraints, if any.
12412 for (j = 0; j < tbinfo->ncheck; j++)
12414 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12416 if (constr->separate || !constr->conislocal)
12419 if (actual_atts == 0)
12420 appendPQExpBuffer(q, " (\n ");
12422 appendPQExpBuffer(q, ",\n ");
12424 appendPQExpBuffer(q, "CONSTRAINT %s ",
12425 fmtId(constr->dobj.name));
12426 appendPQExpBuffer(q, "%s", constr->condef);
12432 appendPQExpBuffer(q, "\n)");
12433 else if (!(tbinfo->reloftype && !binary_upgrade))
12436 * We must have a parenthesized attribute list, even though empty,
12437 * when not using the OF TYPE syntax.
12439 appendPQExpBuffer(q, " (\n)");
12442 if (numParents > 0 && !binary_upgrade)
12444 appendPQExpBuffer(q, "\nINHERITS (");
12445 for (k = 0; k < numParents; k++)
12447 TableInfo *parentRel = parents[k];
12450 appendPQExpBuffer(q, ", ");
12451 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12452 appendPQExpBuffer(q, "%s.",
12453 fmtId(parentRel->dobj.namespace->dobj.name));
12454 appendPQExpBuffer(q, "%s",
12455 fmtId(parentRel->dobj.name));
12457 appendPQExpBuffer(q, ")");
12460 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12461 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12463 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12464 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12466 bool addcomma = false;
12468 appendPQExpBuffer(q, "\nWITH (");
12469 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12472 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12474 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12476 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12477 tbinfo->toast_reloptions);
12479 appendPQExpBuffer(q, ")");
12482 /* Dump generic options if any */
12483 if (ftoptions && ftoptions[0])
12484 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12486 appendPQExpBuffer(q, ";\n");
12489 * To create binary-compatible heap files, we have to ensure the same
12490 * physical column order, including dropped columns, as in the
12491 * original. Therefore, we create dropped columns above and drop them
12492 * here, also updating their attlen/attalign values so that the
12493 * dropped column can be skipped properly. (We do not bother with
12494 * restoring the original attbyval setting.) Also, inheritance
12495 * relationships are set up by doing ALTER INHERIT rather than using
12496 * an INHERITS clause --- the latter would possibly mess up the column
12497 * order. That also means we have to take care about setting
12498 * attislocal correctly, plus fix up any inherited CHECK constraints.
12499 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12501 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12503 for (j = 0; j < tbinfo->numatts; j++)
12505 if (tbinfo->attisdropped[j])
12507 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12508 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12509 "SET attlen = %d, "
12510 "attalign = '%c', attbyval = false\n"
12511 "WHERE attname = ",
12513 tbinfo->attalign[j]);
12514 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12515 appendPQExpBuffer(q, "\n AND attrelid = ");
12516 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12517 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12519 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12520 fmtId(tbinfo->dobj.name));
12521 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12522 fmtId(tbinfo->attnames[j]));
12524 else if (!tbinfo->attislocal[j])
12526 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12527 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12528 "SET attislocal = false\n"
12529 "WHERE attname = ");
12530 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12531 appendPQExpBuffer(q, "\n AND attrelid = ");
12532 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12533 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12537 for (k = 0; k < tbinfo->ncheck; k++)
12539 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12541 if (constr->separate || constr->conislocal)
12544 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12545 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12546 fmtId(tbinfo->dobj.name));
12547 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12548 fmtId(constr->dobj.name));
12549 appendPQExpBuffer(q, "%s;\n", constr->condef);
12550 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12551 "SET conislocal = false\n"
12552 "WHERE contype = 'c' AND conname = ");
12553 appendStringLiteralAH(q, constr->dobj.name, fout);
12554 appendPQExpBuffer(q, "\n AND conrelid = ");
12555 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12556 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12559 if (numParents > 0)
12561 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12562 for (k = 0; k < numParents; k++)
12564 TableInfo *parentRel = parents[k];
12566 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12567 fmtId(tbinfo->dobj.name));
12568 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12569 appendPQExpBuffer(q, "%s.",
12570 fmtId(parentRel->dobj.namespace->dobj.name));
12571 appendPQExpBuffer(q, "%s;\n",
12572 fmtId(parentRel->dobj.name));
12576 if (tbinfo->reloftype)
12578 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12579 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12580 fmtId(tbinfo->dobj.name),
12581 tbinfo->reloftype);
12584 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12585 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12586 "SET relfrozenxid = '%u'\n"
12588 tbinfo->frozenxid);
12589 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12590 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12592 if (tbinfo->toast_oid)
12594 /* We preserve the toast oids, so we can use it during restore */
12595 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12596 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12597 "SET relfrozenxid = '%u'\n"
12598 "WHERE oid = '%u';\n",
12599 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12604 * Dump additional per-column properties that we can't handle in the
12605 * main CREATE TABLE command.
12607 for (j = 0; j < tbinfo->numatts; j++)
12609 /* None of this applies to dropped columns */
12610 if (tbinfo->attisdropped[j])
12614 * If we didn't dump the column definition explicitly above, and
12615 * it is NOT NULL and did not inherit that property from a parent,
12616 * we have to mark it separately.
12618 if (!shouldPrintColumn(tbinfo, j) &&
12619 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12621 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12622 fmtId(tbinfo->dobj.name));
12623 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12624 fmtId(tbinfo->attnames[j]));
12628 * Dump per-column statistics information. We only issue an ALTER
12629 * TABLE statement if the attstattarget entry for this column is
12630 * non-negative (i.e. it's not the default value)
12632 if (tbinfo->attstattarget[j] >= 0)
12634 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12635 fmtId(tbinfo->dobj.name));
12636 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12637 fmtId(tbinfo->attnames[j]));
12638 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12639 tbinfo->attstattarget[j]);
12643 * Dump per-column storage information. The statement is only
12644 * dumped if the storage has been changed from the type's default.
12646 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12648 switch (tbinfo->attstorage[j])
12654 storage = "EXTERNAL";
12660 storage = "EXTENDED";
12667 * Only dump the statement if it's a storage type we recognize
12669 if (storage != NULL)
12671 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12672 fmtId(tbinfo->dobj.name));
12673 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12674 fmtId(tbinfo->attnames[j]));
12675 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12681 * Dump per-column attributes.
12683 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12685 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12686 fmtId(tbinfo->dobj.name));
12687 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12688 fmtId(tbinfo->attnames[j]));
12689 appendPQExpBuffer(q, "SET (%s);\n",
12690 tbinfo->attoptions[j]);
12694 * Dump per-column fdw options.
12696 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12697 tbinfo->attfdwoptions[j] &&
12698 tbinfo->attfdwoptions[j][0] != '\0')
12700 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12701 fmtId(tbinfo->dobj.name));
12702 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12703 fmtId(tbinfo->attnames[j]));
12704 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12705 tbinfo->attfdwoptions[j]);
12710 if (binary_upgrade)
12711 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12713 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12715 tbinfo->dobj.namespace->dobj.name,
12716 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12718 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12719 reltypename, SECTION_PRE_DATA,
12720 q->data, delq->data, NULL,
12721 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12725 /* Dump Table Comments */
12726 dumpTableComment(fout, tbinfo, reltypename);
12728 /* Dump Table Security Labels */
12729 dumpTableSecLabel(fout, tbinfo, reltypename);
12731 /* Dump comments on inlined table constraints */
12732 for (j = 0; j < tbinfo->ncheck; j++)
12734 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12736 if (constr->separate || !constr->conislocal)
12739 dumpTableConstraintComment(fout, constr);
12742 destroyPQExpBuffer(query);
12743 destroyPQExpBuffer(q);
12744 destroyPQExpBuffer(delq);
12745 destroyPQExpBuffer(labelq);
12749 * dumpAttrDef --- dump an attribute's default-value declaration
12752 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12754 TableInfo *tbinfo = adinfo->adtable;
12755 int adnum = adinfo->adnum;
12759 /* Skip if table definition not to be dumped */
12760 if (!tbinfo->dobj.dump || dataOnly)
12763 /* Skip if not "separate"; it was dumped in the table's definition */
12764 if (!adinfo->separate)
12767 q = createPQExpBuffer();
12768 delq = createPQExpBuffer();
12770 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12771 fmtId(tbinfo->dobj.name));
12772 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12773 fmtId(tbinfo->attnames[adnum - 1]),
12774 adinfo->adef_expr);
12777 * DROP must be fully qualified in case same name appears in pg_catalog
12779 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12780 fmtId(tbinfo->dobj.namespace->dobj.name));
12781 appendPQExpBuffer(delq, "%s ",
12782 fmtId(tbinfo->dobj.name));
12783 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12784 fmtId(tbinfo->attnames[adnum - 1]));
12786 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12787 tbinfo->attnames[adnum - 1],
12788 tbinfo->dobj.namespace->dobj.name,
12791 false, "DEFAULT", SECTION_PRE_DATA,
12792 q->data, delq->data, NULL,
12793 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12796 destroyPQExpBuffer(q);
12797 destroyPQExpBuffer(delq);
12801 * getAttrName: extract the correct name for an attribute
12803 * The array tblInfo->attnames[] only provides names of user attributes;
12804 * if a system attribute number is supplied, we have to fake it.
12805 * We also do a little bit of bounds checking for safety's sake.
12807 static const char *
12808 getAttrName(int attrnum, TableInfo *tblInfo)
12810 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12811 return tblInfo->attnames[attrnum - 1];
12814 case SelfItemPointerAttributeNumber:
12816 case ObjectIdAttributeNumber:
12818 case MinTransactionIdAttributeNumber:
12820 case MinCommandIdAttributeNumber:
12822 case MaxTransactionIdAttributeNumber:
12824 case MaxCommandIdAttributeNumber:
12826 case TableOidAttributeNumber:
12829 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12830 attrnum, tblInfo->dobj.name);
12831 return NULL; /* keep compiler quiet */
12836 * write out to fout a user-defined index
12839 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12841 TableInfo *tbinfo = indxinfo->indextable;
12844 PQExpBuffer labelq;
12849 q = createPQExpBuffer();
12850 delq = createPQExpBuffer();
12851 labelq = createPQExpBuffer();
12853 appendPQExpBuffer(labelq, "INDEX %s",
12854 fmtId(indxinfo->dobj.name));
12857 * If there's an associated constraint, don't dump the index per se, but
12858 * do dump any comment for it. (This is safe because dependency ordering
12859 * will have ensured the constraint is emitted first.)
12861 if (indxinfo->indexconstraint == 0)
12863 if (binary_upgrade)
12864 binary_upgrade_set_pg_class_oids(fout, q,
12865 indxinfo->dobj.catId.oid, true);
12867 /* Plain secondary index */
12868 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12870 /* If the index is clustered, we need to record that. */
12871 if (indxinfo->indisclustered)
12873 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12874 fmtId(tbinfo->dobj.name));
12875 appendPQExpBuffer(q, " ON %s;\n",
12876 fmtId(indxinfo->dobj.name));
12880 * DROP must be fully qualified in case same name appears in
12883 appendPQExpBuffer(delq, "DROP INDEX %s.",
12884 fmtId(tbinfo->dobj.namespace->dobj.name));
12885 appendPQExpBuffer(delq, "%s;\n",
12886 fmtId(indxinfo->dobj.name));
12888 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12889 indxinfo->dobj.name,
12890 tbinfo->dobj.namespace->dobj.name,
12891 indxinfo->tablespace,
12892 tbinfo->rolname, false,
12893 "INDEX", SECTION_POST_DATA,
12894 q->data, delq->data, NULL,
12895 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12899 /* Dump Index Comments */
12900 dumpComment(fout, labelq->data,
12901 tbinfo->dobj.namespace->dobj.name,
12903 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12905 destroyPQExpBuffer(q);
12906 destroyPQExpBuffer(delq);
12907 destroyPQExpBuffer(labelq);
12912 * write out to fout a user-defined constraint
12915 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12917 TableInfo *tbinfo = coninfo->contable;
12921 /* Skip if not to be dumped */
12922 if (!coninfo->dobj.dump || dataOnly)
12925 q = createPQExpBuffer();
12926 delq = createPQExpBuffer();
12928 if (coninfo->contype == 'p' ||
12929 coninfo->contype == 'u' ||
12930 coninfo->contype == 'x')
12932 /* Index-related constraint */
12933 IndxInfo *indxinfo;
12936 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12938 if (indxinfo == NULL)
12939 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12940 coninfo->dobj.name);
12942 if (binary_upgrade)
12943 binary_upgrade_set_pg_class_oids(fout, q,
12944 indxinfo->dobj.catId.oid, true);
12946 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12947 fmtId(tbinfo->dobj.name));
12948 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12949 fmtId(coninfo->dobj.name));
12951 if (coninfo->condef)
12953 /* pg_get_constraintdef should have provided everything */
12954 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12958 appendPQExpBuffer(q, "%s (",
12959 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12960 for (k = 0; k < indxinfo->indnkeys; k++)
12962 int indkey = (int) indxinfo->indkeys[k];
12963 const char *attname;
12965 if (indkey == InvalidAttrNumber)
12967 attname = getAttrName(indkey, tbinfo);
12969 appendPQExpBuffer(q, "%s%s",
12970 (k == 0) ? "" : ", ",
12974 appendPQExpBuffer(q, ")");
12976 if (indxinfo->options && strlen(indxinfo->options) > 0)
12977 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12979 if (coninfo->condeferrable)
12981 appendPQExpBuffer(q, " DEFERRABLE");
12982 if (coninfo->condeferred)
12983 appendPQExpBuffer(q, " INITIALLY DEFERRED");
12986 appendPQExpBuffer(q, ";\n");
12989 /* If the index is clustered, we need to record that. */
12990 if (indxinfo->indisclustered)
12992 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12993 fmtId(tbinfo->dobj.name));
12994 appendPQExpBuffer(q, " ON %s;\n",
12995 fmtId(indxinfo->dobj.name));
12999 * DROP must be fully qualified in case same name appears in
13002 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13003 fmtId(tbinfo->dobj.namespace->dobj.name));
13004 appendPQExpBuffer(delq, "%s ",
13005 fmtId(tbinfo->dobj.name));
13006 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13007 fmtId(coninfo->dobj.name));
13009 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13010 coninfo->dobj.name,
13011 tbinfo->dobj.namespace->dobj.name,
13012 indxinfo->tablespace,
13013 tbinfo->rolname, false,
13014 "CONSTRAINT", SECTION_POST_DATA,
13015 q->data, delq->data, NULL,
13016 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13019 else if (coninfo->contype == 'f')
13022 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13023 * current table data is not processed
13025 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13026 fmtId(tbinfo->dobj.name));
13027 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13028 fmtId(coninfo->dobj.name),
13032 * DROP must be fully qualified in case same name appears in
13035 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13036 fmtId(tbinfo->dobj.namespace->dobj.name));
13037 appendPQExpBuffer(delq, "%s ",
13038 fmtId(tbinfo->dobj.name));
13039 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13040 fmtId(coninfo->dobj.name));
13042 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13043 coninfo->dobj.name,
13044 tbinfo->dobj.namespace->dobj.name,
13046 tbinfo->rolname, false,
13047 "FK CONSTRAINT", SECTION_POST_DATA,
13048 q->data, delq->data, NULL,
13049 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13052 else if (coninfo->contype == 'c' && tbinfo)
13054 /* CHECK constraint on a table */
13056 /* Ignore if not to be dumped separately */
13057 if (coninfo->separate)
13059 /* add ONLY if we do not want it to propagate to children */
13060 appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13061 coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13062 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13063 fmtId(coninfo->dobj.name),
13067 * DROP must be fully qualified in case same name appears in
13070 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13071 fmtId(tbinfo->dobj.namespace->dobj.name));
13072 appendPQExpBuffer(delq, "%s ",
13073 fmtId(tbinfo->dobj.name));
13074 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13075 fmtId(coninfo->dobj.name));
13077 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13078 coninfo->dobj.name,
13079 tbinfo->dobj.namespace->dobj.name,
13081 tbinfo->rolname, false,
13082 "CHECK CONSTRAINT", SECTION_POST_DATA,
13083 q->data, delq->data, NULL,
13084 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13088 else if (coninfo->contype == 'c' && tbinfo == NULL)
13090 /* CHECK constraint on a domain */
13091 TypeInfo *tyinfo = coninfo->condomain;
13093 /* Ignore if not to be dumped separately */
13094 if (coninfo->separate)
13096 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13097 fmtId(tyinfo->dobj.name));
13098 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13099 fmtId(coninfo->dobj.name),
13103 * DROP must be fully qualified in case same name appears in
13106 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13107 fmtId(tyinfo->dobj.namespace->dobj.name));
13108 appendPQExpBuffer(delq, "%s ",
13109 fmtId(tyinfo->dobj.name));
13110 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13111 fmtId(coninfo->dobj.name));
13113 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13114 coninfo->dobj.name,
13115 tyinfo->dobj.namespace->dobj.name,
13117 tyinfo->rolname, false,
13118 "CHECK CONSTRAINT", SECTION_POST_DATA,
13119 q->data, delq->data, NULL,
13120 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13126 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13130 /* Dump Constraint Comments --- only works for table constraints */
13131 if (tbinfo && coninfo->separate)
13132 dumpTableConstraintComment(fout, coninfo);
13134 destroyPQExpBuffer(q);
13135 destroyPQExpBuffer(delq);
13139 * dumpTableConstraintComment --- dump a constraint's comment if any
13141 * This is split out because we need the function in two different places
13142 * depending on whether the constraint is dumped as part of CREATE TABLE
13143 * or as a separate ALTER command.
13146 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13148 TableInfo *tbinfo = coninfo->contable;
13149 PQExpBuffer labelq = createPQExpBuffer();
13151 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13152 fmtId(coninfo->dobj.name));
13153 appendPQExpBuffer(labelq, "ON %s",
13154 fmtId(tbinfo->dobj.name));
13155 dumpComment(fout, labelq->data,
13156 tbinfo->dobj.namespace->dobj.name,
13158 coninfo->dobj.catId, 0,
13159 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13161 destroyPQExpBuffer(labelq);
13165 * findLastBuiltInOid -
13166 * find the last built in oid
13168 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13169 * pg_database entry for the current database
13172 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13176 PQExpBuffer query = createPQExpBuffer();
13178 resetPQExpBuffer(query);
13179 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13180 appendStringLiteralAH(query, dbname, fout);
13182 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13183 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13185 destroyPQExpBuffer(query);
13190 * findLastBuiltInOid -
13191 * find the last built in oid
13193 * For 7.0, we do this by assuming that the last thing that initdb does is to
13194 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13195 * initdb won't be changing anymore, it'll do.
13198 findLastBuiltinOid_V70(Archive *fout)
13203 res = ExecuteSqlQueryForSingleRow(fout,
13204 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13205 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13211 dumpSequence(Archive *fout, TableInfo *tbinfo)
13224 PQExpBuffer query = createPQExpBuffer();
13225 PQExpBuffer delqry = createPQExpBuffer();
13226 PQExpBuffer labelq = createPQExpBuffer();
13228 /* Make sure we are in proper schema */
13229 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13231 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13232 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13234 if (fout->remoteVersion >= 80400)
13236 appendPQExpBuffer(query,
13237 "SELECT sequence_name, "
13238 "start_value, last_value, increment_by, "
13239 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13240 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13242 "END AS max_value, "
13243 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13244 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13246 "END AS min_value, "
13247 "cache_value, is_cycled, is_called from %s",
13249 fmtId(tbinfo->dobj.name));
13253 appendPQExpBuffer(query,
13254 "SELECT sequence_name, "
13255 "0 AS start_value, last_value, increment_by, "
13256 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13257 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13259 "END AS max_value, "
13260 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13261 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13263 "END AS min_value, "
13264 "cache_value, is_cycled, is_called from %s",
13266 fmtId(tbinfo->dobj.name));
13269 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13271 if (PQntuples(res) != 1)
13273 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13274 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13276 tbinfo->dobj.name, PQntuples(res));
13280 /* Disable this check: it fails if sequence has been renamed */
13282 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13284 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13285 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13290 startv = PQgetvalue(res, 0, 1);
13291 last = PQgetvalue(res, 0, 2);
13292 incby = PQgetvalue(res, 0, 3);
13293 if (!PQgetisnull(res, 0, 4))
13294 maxv = PQgetvalue(res, 0, 4);
13295 if (!PQgetisnull(res, 0, 5))
13296 minv = PQgetvalue(res, 0, 5);
13297 cache = PQgetvalue(res, 0, 6);
13298 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13299 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13302 * The logic we use for restoring sequences is as follows:
13304 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13305 * last_val for start if called is false, else use min_val for start_val).
13306 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13307 * BY command for it.
13309 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13314 * DROP must be fully qualified in case same name appears in
13317 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13318 fmtId(tbinfo->dobj.namespace->dobj.name));
13319 appendPQExpBuffer(delqry, "%s;\n",
13320 fmtId(tbinfo->dobj.name));
13322 resetPQExpBuffer(query);
13324 if (binary_upgrade)
13326 binary_upgrade_set_pg_class_oids(fout, query,
13327 tbinfo->dobj.catId.oid, false);
13328 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13329 tbinfo->dobj.catId.oid);
13332 appendPQExpBuffer(query,
13333 "CREATE SEQUENCE %s\n",
13334 fmtId(tbinfo->dobj.name));
13336 if (fout->remoteVersion >= 80400)
13337 appendPQExpBuffer(query, " START WITH %s\n", startv);
13341 * Versions before 8.4 did not remember the true start value. If
13342 * is_called is false then the sequence has never been incremented
13343 * so we can use last_val. Otherwise punt and let it default.
13346 appendPQExpBuffer(query, " START WITH %s\n", last);
13349 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13352 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13354 appendPQExpBuffer(query, " NO MINVALUE\n");
13357 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13359 appendPQExpBuffer(query, " NO MAXVALUE\n");
13361 appendPQExpBuffer(query,
13363 cache, (cycled ? "\n CYCLE" : ""));
13365 appendPQExpBuffer(query, ";\n");
13367 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13369 /* binary_upgrade: no need to clear TOAST table oid */
13371 if (binary_upgrade)
13372 binary_upgrade_extension_member(query, &tbinfo->dobj,
13375 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13377 tbinfo->dobj.namespace->dobj.name,
13380 false, "SEQUENCE", SECTION_PRE_DATA,
13381 query->data, delqry->data, NULL,
13382 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13386 * If the sequence is owned by a table column, emit the ALTER for it
13387 * as a separate TOC entry immediately following the sequence's own
13388 * entry. It's OK to do this rather than using full sorting logic,
13389 * because the dependency that tells us it's owned will have forced
13390 * the table to be created first. We can't just include the ALTER in
13391 * the TOC entry because it will fail if we haven't reassigned the
13392 * sequence owner to match the table's owner.
13394 * We need not schema-qualify the table reference because both
13395 * sequence and table must be in the same schema.
13397 if (OidIsValid(tbinfo->owning_tab))
13399 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13401 if (owning_tab && owning_tab->dobj.dump)
13403 resetPQExpBuffer(query);
13404 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13405 fmtId(tbinfo->dobj.name));
13406 appendPQExpBuffer(query, " OWNED BY %s",
13407 fmtId(owning_tab->dobj.name));
13408 appendPQExpBuffer(query, ".%s;\n",
13409 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13411 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13413 tbinfo->dobj.namespace->dobj.name,
13416 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13417 query->data, "", NULL,
13418 &(tbinfo->dobj.dumpId), 1,
13423 /* Dump Sequence Comments and Security Labels */
13424 dumpComment(fout, labelq->data,
13425 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13426 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13427 dumpSecLabel(fout, labelq->data,
13428 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13429 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13434 resetPQExpBuffer(query);
13435 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13436 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13437 appendPQExpBuffer(query, ", %s, %s);\n",
13438 last, (called ? "true" : "false"));
13440 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13442 tbinfo->dobj.namespace->dobj.name,
13445 false, "SEQUENCE SET", SECTION_PRE_DATA,
13446 query->data, "", NULL,
13447 &(tbinfo->dobj.dumpId), 1,
13453 destroyPQExpBuffer(query);
13454 destroyPQExpBuffer(delqry);
13455 destroyPQExpBuffer(labelq);
13459 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13461 TableInfo *tbinfo = tginfo->tgtable;
13463 PQExpBuffer delqry;
13464 PQExpBuffer labelq;
13473 query = createPQExpBuffer();
13474 delqry = createPQExpBuffer();
13475 labelq = createPQExpBuffer();
13478 * DROP must be fully qualified in case same name appears in pg_catalog
13480 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13481 fmtId(tginfo->dobj.name));
13482 appendPQExpBuffer(delqry, "ON %s.",
13483 fmtId(tbinfo->dobj.namespace->dobj.name));
13484 appendPQExpBuffer(delqry, "%s;\n",
13485 fmtId(tbinfo->dobj.name));
13489 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13493 if (tginfo->tgisconstraint)
13495 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13496 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13500 appendPQExpBuffer(query, "CREATE TRIGGER ");
13501 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13503 appendPQExpBuffer(query, "\n ");
13506 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13507 appendPQExpBuffer(query, "BEFORE");
13508 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13509 appendPQExpBuffer(query, "AFTER");
13510 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13511 appendPQExpBuffer(query, "INSTEAD OF");
13514 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13519 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13521 appendPQExpBuffer(query, " INSERT");
13524 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13527 appendPQExpBuffer(query, " OR DELETE");
13529 appendPQExpBuffer(query, " DELETE");
13532 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13535 appendPQExpBuffer(query, " OR UPDATE");
13537 appendPQExpBuffer(query, " UPDATE");
13540 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13543 appendPQExpBuffer(query, " OR TRUNCATE");
13545 appendPQExpBuffer(query, " TRUNCATE");
13548 appendPQExpBuffer(query, " ON %s\n",
13549 fmtId(tbinfo->dobj.name));
13551 if (tginfo->tgisconstraint)
13553 if (OidIsValid(tginfo->tgconstrrelid))
13555 /* If we are using regclass, name is already quoted */
13556 if (fout->remoteVersion >= 70300)
13557 appendPQExpBuffer(query, " FROM %s\n ",
13558 tginfo->tgconstrrelname);
13560 appendPQExpBuffer(query, " FROM %s\n ",
13561 fmtId(tginfo->tgconstrrelname));
13563 if (!tginfo->tgdeferrable)
13564 appendPQExpBuffer(query, "NOT ");
13565 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13566 if (tginfo->tginitdeferred)
13567 appendPQExpBuffer(query, "DEFERRED\n");
13569 appendPQExpBuffer(query, "IMMEDIATE\n");
13572 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13573 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13575 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13577 /* In 7.3, result of regproc is already quoted */
13578 if (fout->remoteVersion >= 70300)
13579 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13582 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13583 fmtId(tginfo->tgfname));
13585 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13588 for (findx = 0; findx < tginfo->tgnargs; findx++)
13590 /* find the embedded null that terminates this trigger argument */
13591 size_t tlen = strlen(p);
13593 if (p + tlen >= tgargs + lentgargs)
13595 /* hm, not found before end of bytea value... */
13596 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13599 tbinfo->dobj.name);
13604 appendPQExpBuffer(query, ", ");
13605 appendStringLiteralAH(query, p, fout);
13609 appendPQExpBuffer(query, ");\n");
13612 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13614 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13615 fmtId(tbinfo->dobj.name));
13616 switch (tginfo->tgenabled)
13620 appendPQExpBuffer(query, "DISABLE");
13623 appendPQExpBuffer(query, "ENABLE ALWAYS");
13626 appendPQExpBuffer(query, "ENABLE REPLICA");
13629 appendPQExpBuffer(query, "ENABLE");
13632 appendPQExpBuffer(query, " TRIGGER %s;\n",
13633 fmtId(tginfo->dobj.name));
13636 appendPQExpBuffer(labelq, "TRIGGER %s ",
13637 fmtId(tginfo->dobj.name));
13638 appendPQExpBuffer(labelq, "ON %s",
13639 fmtId(tbinfo->dobj.name));
13641 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13643 tbinfo->dobj.namespace->dobj.name,
13645 tbinfo->rolname, false,
13646 "TRIGGER", SECTION_POST_DATA,
13647 query->data, delqry->data, NULL,
13648 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13651 dumpComment(fout, labelq->data,
13652 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13653 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13655 destroyPQExpBuffer(query);
13656 destroyPQExpBuffer(delqry);
13657 destroyPQExpBuffer(labelq);
13665 dumpRule(Archive *fout, RuleInfo *rinfo)
13667 TableInfo *tbinfo = rinfo->ruletable;
13670 PQExpBuffer delcmd;
13671 PQExpBuffer labelq;
13674 /* Skip if not to be dumped */
13675 if (!rinfo->dobj.dump || dataOnly)
13679 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13680 * we do not want to dump it as a separate object.
13682 if (!rinfo->separate)
13686 * Make sure we are in proper schema.
13688 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13690 query = createPQExpBuffer();
13691 cmd = createPQExpBuffer();
13692 delcmd = createPQExpBuffer();
13693 labelq = createPQExpBuffer();
13695 if (fout->remoteVersion >= 70300)
13697 appendPQExpBuffer(query,
13698 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13699 rinfo->dobj.catId.oid);
13703 /* Rule name was unique before 7.3 ... */
13704 appendPQExpBuffer(query,
13705 "SELECT pg_get_ruledef('%s') AS definition",
13709 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13711 if (PQntuples(res) != 1)
13713 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13714 rinfo->dobj.name, tbinfo->dobj.name);
13718 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13721 * Add the command to alter the rules replication firing semantics if it
13722 * differs from the default.
13724 if (rinfo->ev_enabled != 'O')
13726 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13727 fmtId(tbinfo->dobj.namespace->dobj.name));
13728 appendPQExpBuffer(cmd, "%s ",
13729 fmtId(tbinfo->dobj.name));
13730 switch (rinfo->ev_enabled)
13733 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13734 fmtId(rinfo->dobj.name));
13737 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13738 fmtId(rinfo->dobj.name));
13741 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13742 fmtId(rinfo->dobj.name));
13748 * DROP must be fully qualified in case same name appears in pg_catalog
13750 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13751 fmtId(rinfo->dobj.name));
13752 appendPQExpBuffer(delcmd, "ON %s.",
13753 fmtId(tbinfo->dobj.namespace->dobj.name));
13754 appendPQExpBuffer(delcmd, "%s;\n",
13755 fmtId(tbinfo->dobj.name));
13757 appendPQExpBuffer(labelq, "RULE %s",
13758 fmtId(rinfo->dobj.name));
13759 appendPQExpBuffer(labelq, " ON %s",
13760 fmtId(tbinfo->dobj.name));
13762 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13764 tbinfo->dobj.namespace->dobj.name,
13766 tbinfo->rolname, false,
13767 "RULE", SECTION_POST_DATA,
13768 cmd->data, delcmd->data, NULL,
13769 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13772 /* Dump rule comments */
13773 dumpComment(fout, labelq->data,
13774 tbinfo->dobj.namespace->dobj.name,
13776 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13780 destroyPQExpBuffer(query);
13781 destroyPQExpBuffer(cmd);
13782 destroyPQExpBuffer(delcmd);
13783 destroyPQExpBuffer(labelq);
13787 * getExtensionMembership --- obtain extension membership data
13790 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13801 DumpableObject *dobj,
13804 /* Nothing to do if no extensions */
13805 if (numExtensions == 0)
13808 /* Make sure we are in proper schema */
13809 selectSourceSchema(fout, "pg_catalog");
13811 query = createPQExpBuffer();
13813 /* refclassid constraint is redundant but may speed the search */
13814 appendPQExpBuffer(query, "SELECT "
13815 "classid, objid, refclassid, refobjid "
13817 "WHERE refclassid = 'pg_extension'::regclass "
13818 "AND deptype = 'e' "
13821 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13823 ntups = PQntuples(res);
13825 i_classid = PQfnumber(res, "classid");
13826 i_objid = PQfnumber(res, "objid");
13827 i_refclassid = PQfnumber(res, "refclassid");
13828 i_refobjid = PQfnumber(res, "refobjid");
13831 * Since we ordered the SELECT by referenced ID, we can expect that
13832 * multiple entries for the same extension will appear together; this
13833 * saves on searches.
13837 for (i = 0; i < ntups; i++)
13840 CatalogId refobjId;
13842 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13843 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13844 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13845 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13847 if (refdobj == NULL ||
13848 refdobj->catId.tableoid != refobjId.tableoid ||
13849 refdobj->catId.oid != refobjId.oid)
13850 refdobj = findObjectByCatalogId(refobjId);
13853 * Failure to find objects mentioned in pg_depend is not unexpected,
13854 * since for example we don't collect info about TOAST tables.
13856 if (refdobj == NULL)
13859 fprintf(stderr, "no referenced object %u %u\n",
13860 refobjId.tableoid, refobjId.oid);
13865 dobj = findObjectByCatalogId(objId);
13870 fprintf(stderr, "no referencing object %u %u\n",
13871 objId.tableoid, objId.oid);
13876 /* Record dependency so that getDependencies needn't repeat this */
13877 addObjectDependency(dobj, refdobj->dumpId);
13879 dobj->ext_member = true;
13882 * Normally, mark the member object as not to be dumped. But in
13883 * binary upgrades, we still dump the members individually, since the
13884 * idea is to exactly reproduce the database contents rather than
13885 * replace the extension contents with something different.
13887 if (!binary_upgrade)
13888 dobj->dump = false;
13890 dobj->dump = refdobj->dump;
13896 * Now identify extension configuration tables and create TableDataInfo
13897 * objects for them, ensuring their data will be dumped even though the
13898 * tables themselves won't be.
13900 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13901 * user data in a configuration table is treated like schema data. This
13902 * seems appropriate since system data in a config table would get
13903 * reloaded by CREATE EXTENSION.
13905 for (i = 0; i < numExtensions; i++)
13907 ExtensionInfo *curext = &(extinfo[i]);
13908 char *extconfig = curext->extconfig;
13909 char *extcondition = curext->extcondition;
13910 char **extconfigarray = NULL;
13911 char **extconditionarray = NULL;
13913 int nconditionitems;
13915 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13916 if (!curext->dobj.dump)
13919 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13920 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13921 nconfigitems == nconditionitems)
13925 for (j = 0; j < nconfigitems; j++)
13927 TableInfo *configtbl;
13929 configtbl = findTableByOid(atooid(extconfigarray[j]));
13930 if (configtbl == NULL)
13934 * Note: config tables are dumped without OIDs regardless
13935 * of the --oids setting. This is because row filtering
13936 * conditions aren't compatible with dumping OIDs.
13938 makeTableDataInfo(configtbl, false);
13939 if (configtbl->dataObj != NULL)
13941 if (strlen(extconditionarray[j]) > 0)
13942 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13946 if (extconfigarray)
13947 free(extconfigarray);
13948 if (extconditionarray)
13949 free(extconditionarray);
13952 destroyPQExpBuffer(query);
13956 * getDependencies --- obtain available dependency data
13959 getDependencies(Archive *fout)
13970 DumpableObject *dobj,
13973 /* No dependency info available before 7.3 */
13974 if (fout->remoteVersion < 70300)
13978 write_msg(NULL, "reading dependency data\n");
13980 /* Make sure we are in proper schema */
13981 selectSourceSchema(fout, "pg_catalog");
13983 query = createPQExpBuffer();
13986 * PIN dependencies aren't interesting, and EXTENSION dependencies were
13987 * already processed by getExtensionMembership.
13989 appendPQExpBuffer(query, "SELECT "
13990 "classid, objid, refclassid, refobjid, deptype "
13992 "WHERE deptype != 'p' AND deptype != 'e' "
13995 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13997 ntups = PQntuples(res);
13999 i_classid = PQfnumber(res, "classid");
14000 i_objid = PQfnumber(res, "objid");
14001 i_refclassid = PQfnumber(res, "refclassid");
14002 i_refobjid = PQfnumber(res, "refobjid");
14003 i_deptype = PQfnumber(res, "deptype");
14006 * Since we ordered the SELECT by referencing ID, we can expect that
14007 * multiple entries for the same object will appear together; this saves
14012 for (i = 0; i < ntups; i++)
14015 CatalogId refobjId;
14018 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14019 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14020 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14021 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14022 deptype = *(PQgetvalue(res, i, i_deptype));
14024 if (dobj == NULL ||
14025 dobj->catId.tableoid != objId.tableoid ||
14026 dobj->catId.oid != objId.oid)
14027 dobj = findObjectByCatalogId(objId);
14030 * Failure to find objects mentioned in pg_depend is not unexpected,
14031 * since for example we don't collect info about TOAST tables.
14036 fprintf(stderr, "no referencing object %u %u\n",
14037 objId.tableoid, objId.oid);
14042 refdobj = findObjectByCatalogId(refobjId);
14044 if (refdobj == NULL)
14047 fprintf(stderr, "no referenced object %u %u\n",
14048 refobjId.tableoid, refobjId.oid);
14054 * Ordinarily, table rowtypes have implicit dependencies on their
14055 * tables. However, for a composite type the implicit dependency goes
14056 * the other way in pg_depend; which is the right thing for DROP but
14057 * it doesn't produce the dependency ordering we need. So in that one
14058 * case, we reverse the direction of the dependency.
14060 if (deptype == 'i' &&
14061 dobj->objType == DO_TABLE &&
14062 refdobj->objType == DO_TYPE)
14063 addObjectDependency(refdobj, dobj->dumpId);
14066 addObjectDependency(dobj, refdobj->dumpId);
14071 destroyPQExpBuffer(query);
14076 * selectSourceSchema - make the specified schema the active search path
14077 * in the source database.
14079 * NB: pg_catalog is explicitly searched after the specified schema;
14080 * so user names are only qualified if they are cross-schema references,
14081 * and system names are only qualified if they conflict with a user name
14082 * in the current schema.
14084 * Whenever the selected schema is not pg_catalog, be careful to qualify
14085 * references to system catalogs and types in our emitted commands!
14088 selectSourceSchema(Archive *fout, const char *schemaName)
14090 static char *curSchemaName = NULL;
14093 /* Not relevant if fetching from pre-7.3 DB */
14094 if (fout->remoteVersion < 70300)
14096 /* Ignore null schema names */
14097 if (schemaName == NULL || *schemaName == '\0')
14099 /* Optimize away repeated selection of same schema */
14100 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14103 query = createPQExpBuffer();
14104 appendPQExpBuffer(query, "SET search_path = %s",
14105 fmtId(schemaName));
14106 if (strcmp(schemaName, "pg_catalog") != 0)
14107 appendPQExpBuffer(query, ", pg_catalog");
14109 ExecuteSqlStatement(fout, query->data);
14111 destroyPQExpBuffer(query);
14113 free(curSchemaName);
14114 curSchemaName = pg_strdup(schemaName);
14118 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14121 * NB: in 7.3 and up the result may depend on the currently-selected
14122 * schema; this is why we don't try to cache the names.
14125 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14133 if ((opts & zeroAsOpaque) != 0)
14134 return pg_strdup(g_opaque_type);
14135 else if ((opts & zeroAsAny) != 0)
14136 return pg_strdup("'any'");
14137 else if ((opts & zeroAsStar) != 0)
14138 return pg_strdup("*");
14139 else if ((opts & zeroAsNone) != 0)
14140 return pg_strdup("NONE");
14143 query = createPQExpBuffer();
14144 if (fout->remoteVersion >= 70300)
14146 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14149 else if (fout->remoteVersion >= 70100)
14151 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14156 appendPQExpBuffer(query, "SELECT typname "
14158 "WHERE oid = '%u'::oid",
14162 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14164 if (fout->remoteVersion >= 70100)
14166 /* already quoted */
14167 result = pg_strdup(PQgetvalue(res, 0, 0));
14171 /* may need to quote it */
14172 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14176 destroyPQExpBuffer(query);
14182 * myFormatType --- local implementation of format_type for use with 7.0.
14185 myFormatType(const char *typname, int32 typmod)
14188 bool isarray = false;
14189 PQExpBuffer buf = createPQExpBuffer();
14191 /* Handle array types */
14192 if (typname[0] == '_')
14198 /* Show lengths on bpchar and varchar */
14199 if (strcmp(typname, "bpchar") == 0)
14201 int len = (typmod - VARHDRSZ);
14203 appendPQExpBuffer(buf, "character");
14205 appendPQExpBuffer(buf, "(%d)",
14206 typmod - VARHDRSZ);
14208 else if (strcmp(typname, "varchar") == 0)
14210 appendPQExpBuffer(buf, "character varying");
14212 appendPQExpBuffer(buf, "(%d)",
14213 typmod - VARHDRSZ);
14215 else if (strcmp(typname, "numeric") == 0)
14217 appendPQExpBuffer(buf, "numeric");
14224 tmp_typmod = typmod - VARHDRSZ;
14225 precision = (tmp_typmod >> 16) & 0xffff;
14226 scale = tmp_typmod & 0xffff;
14227 appendPQExpBuffer(buf, "(%d,%d)",
14233 * char is an internal single-byte data type; Let's make sure we force it
14234 * through with quotes. - thomas 1998-12-13
14236 else if (strcmp(typname, "char") == 0)
14237 appendPQExpBuffer(buf, "\"char\"");
14239 appendPQExpBuffer(buf, "%s", fmtId(typname));
14241 /* Append array qualifier for array types */
14243 appendPQExpBuffer(buf, "[]");
14245 result = pg_strdup(buf->data);
14246 destroyPQExpBuffer(buf);
14252 * fmtQualifiedId - convert a qualified name to the proper format for
14253 * the source database.
14255 * Like fmtId, use the result before calling again.
14257 static const char *
14258 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14260 static PQExpBuffer id_return = NULL;
14262 if (id_return) /* first time through? */
14263 resetPQExpBuffer(id_return);
14265 id_return = createPQExpBuffer();
14267 /* Suppress schema name if fetching from pre-7.3 DB */
14268 if (fout->remoteVersion >= 70300 && schema && *schema)
14270 appendPQExpBuffer(id_return, "%s.",
14273 appendPQExpBuffer(id_return, "%s",
14276 return id_return->data;
14280 * Return a column list clause for the given relation.
14282 * Special case: if there are no undropped columns in the relation, return
14283 * "", not an invalid "()" column list.
14285 static const char *
14286 fmtCopyColumnList(const TableInfo *ti)
14288 static PQExpBuffer q = NULL;
14289 int numatts = ti->numatts;
14290 char **attnames = ti->attnames;
14291 bool *attisdropped = ti->attisdropped;
14295 if (q) /* first time through? */
14296 resetPQExpBuffer(q);
14298 q = createPQExpBuffer();
14300 appendPQExpBuffer(q, "(");
14302 for (i = 0; i < numatts; i++)
14304 if (attisdropped[i])
14307 appendPQExpBuffer(q, ", ");
14308 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14313 return ""; /* no undropped columns */
14315 appendPQExpBuffer(q, ")");
14320 * Execute an SQL query and verify that we got exactly one row back.
14323 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14328 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14330 /* Expecting a single result only */
14331 ntups = PQntuples(res);
14333 exit_horribly(NULL,
14334 ngettext("query returned %d row instead of one: %s\n",
14335 "query returned %d rows instead of one: %s\n",