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 setup_connection(Archive *AH, const char *dumpencoding,
149 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
150 static void expand_schema_name_patterns(Archive *fout,
151 SimpleStringList *patterns,
152 SimpleOidList *oids);
153 static void expand_table_name_patterns(Archive *fout,
154 SimpleStringList *patterns,
155 SimpleOidList *oids);
156 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
157 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
158 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
159 static void dumpComment(Archive *fout, const char *target,
160 const char *namespace, const char *owner,
161 CatalogId catalogId, int subid, DumpId dumpId);
162 static int findComments(Archive *fout, Oid classoid, Oid objoid,
163 CommentItem **items);
164 static int collectComments(Archive *fout, CommentItem **items);
165 static void dumpSecLabel(Archive *fout, const char *target,
166 const char *namespace, const char *owner,
167 CatalogId catalogId, int subid, DumpId dumpId);
168 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
169 SecLabelItem **items);
170 static int collectSecLabels(Archive *fout, SecLabelItem **items);
171 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
172 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
173 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
174 static void dumpType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
179 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
181 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
182 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
183 static void dumpFunc(Archive *fout, FuncInfo *finfo);
184 static void dumpCast(Archive *fout, CastInfo *cast);
185 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
186 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
187 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
188 static void dumpCollation(Archive *fout, CollInfo *convinfo);
189 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
190 static void dumpRule(Archive *fout, RuleInfo *rinfo);
191 static void dumpAgg(Archive *fout, AggInfo *agginfo);
192 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
193 static void dumpTable(Archive *fout, TableInfo *tbinfo);
194 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
195 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
196 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
197 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
198 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
199 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
201 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
202 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
203 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
204 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
205 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
206 static void dumpUserMappings(Archive *fout,
207 const char *servername, const char *namespace,
208 const char *owner, CatalogId catalogId, DumpId dumpId);
209 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
211 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
212 const char *type, const char *name, const char *subname,
213 const char *tag, const char *nspname, const char *owner,
216 static void getDependencies(Archive *fout);
217 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
218 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
219 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
220 static void getTableDataFKConstraints(void);
221 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
222 static char *format_function_arguments_old(Archive *fout,
223 FuncInfo *finfo, int nallargs,
227 static char *format_function_signature(Archive *fout,
228 FuncInfo *finfo, bool honor_quotes);
229 static const char *convertRegProcReference(Archive *fout,
231 static const char *convertOperatorReference(Archive *fout, const char *opr);
232 static const char *convertTSFunction(Archive *fout, Oid funcOid);
233 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
234 static Oid findLastBuiltinOid_V70(Archive *fout);
235 static void selectSourceSchema(Archive *fout, const char *schemaName);
236 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
237 static char *myFormatType(const char *typname, int32 typmod);
238 static const char *fmtQualifiedId(Archive *fout,
239 const char *schema, const char *id);
240 static void getBlobs(Archive *fout);
241 static void dumpBlob(Archive *fout, BlobInfo *binfo);
242 static int dumpBlobs(Archive *fout, void *arg);
243 static void dumpDatabase(Archive *AH);
244 static void dumpEncoding(Archive *AH);
245 static void dumpStdStrings(Archive *AH);
246 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
247 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
248 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
249 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
250 static void binary_upgrade_set_pg_class_oids(Archive *fout,
251 PQExpBuffer upgrade_buffer,
252 Oid pg_class_oid, bool is_index);
253 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
254 DumpableObject *dobj,
255 const char *objlabel);
256 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
257 static const char *fmtCopyColumnList(const TableInfo *ti);
258 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
261 main(int argc, char **argv)
264 const char *filename = NULL;
265 const char *format = "p";
266 const char *dbname = NULL;
267 const char *pghost = NULL;
268 const char *pgport = NULL;
269 const char *username = NULL;
270 const char *dumpencoding = NULL;
274 DumpableObject **dobjs;
277 enum trivalue prompt_password = TRI_DEFAULT;
278 int compressLevel = -1;
281 int outputCreateDB = 0;
282 bool outputBlobs = false;
283 int outputNoOwner = 0;
284 char *outputSuperuser = NULL;
285 char *use_role = NULL;
288 RestoreOptions *ropt;
289 ArchiveFormat archiveFormat = archUnknown;
290 ArchiveMode archiveMode;
291 Archive *fout; /* the script file */
293 static int disable_triggers = 0;
294 static int outputNoTablespaces = 0;
295 static int use_setsessauth = 0;
297 static struct option long_options[] = {
298 {"data-only", no_argument, NULL, 'a'},
299 {"blobs", no_argument, NULL, 'b'},
300 {"clean", no_argument, NULL, 'c'},
301 {"create", no_argument, NULL, 'C'},
302 {"file", required_argument, NULL, 'f'},
303 {"format", required_argument, NULL, 'F'},
304 {"host", required_argument, NULL, 'h'},
305 {"ignore-version", no_argument, NULL, 'i'},
306 {"no-reconnect", no_argument, NULL, 'R'},
307 {"oids", no_argument, NULL, 'o'},
308 {"no-owner", no_argument, NULL, 'O'},
309 {"port", required_argument, NULL, 'p'},
310 {"schema", required_argument, NULL, 'n'},
311 {"exclude-schema", required_argument, NULL, 'N'},
312 {"schema-only", no_argument, NULL, 's'},
313 {"superuser", required_argument, NULL, 'S'},
314 {"table", required_argument, NULL, 't'},
315 {"exclude-table", required_argument, NULL, 'T'},
316 {"no-password", no_argument, NULL, 'w'},
317 {"password", no_argument, NULL, 'W'},
318 {"username", required_argument, NULL, 'U'},
319 {"verbose", no_argument, NULL, 'v'},
320 {"no-privileges", no_argument, NULL, 'x'},
321 {"no-acl", no_argument, NULL, 'x'},
322 {"compress", required_argument, NULL, 'Z'},
323 {"encoding", required_argument, NULL, 'E'},
324 {"help", no_argument, NULL, '?'},
325 {"version", no_argument, NULL, 'V'},
328 * the following options don't have an equivalent short option letter
330 {"attribute-inserts", no_argument, &column_inserts, 1},
331 {"binary-upgrade", no_argument, &binary_upgrade, 1},
332 {"column-inserts", no_argument, &column_inserts, 1},
333 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
334 {"disable-triggers", no_argument, &disable_triggers, 1},
335 {"exclude-table-data", required_argument, NULL, 4},
336 {"inserts", no_argument, &dump_inserts, 1},
337 {"lock-wait-timeout", required_argument, NULL, 2},
338 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
339 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
340 {"role", required_argument, NULL, 3},
341 {"section", required_argument, NULL, 5},
342 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
343 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
344 {"no-security-labels", no_argument, &no_security_labels, 1},
345 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
350 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
354 strcpy(g_comment_start, "-- ");
355 g_comment_end[0] = '\0';
356 strcpy(g_opaque_type, "opaque");
358 dataOnly = schemaOnly = false;
359 dumpSections = DUMP_UNSECTIONED;
360 lockWaitTimeout = NULL;
362 progname = get_progname(argv[0]);
364 /* Set default options based on progname */
365 if (strcmp(progname, "pg_backup") == 0)
370 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
375 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
377 puts("pg_dump (PostgreSQL) " PG_VERSION);
382 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
383 long_options, &optindex)) != -1)
387 case 'a': /* Dump data only */
391 case 'b': /* Dump blobs */
395 case 'c': /* clean (i.e., drop) schema prior to create */
399 case 'C': /* Create DB */
403 case 'E': /* Dump encoding */
404 dumpencoding = optarg;
415 case 'h': /* server host */
420 /* ignored, deprecated option */
423 case 'n': /* include schema(s) */
424 simple_string_list_append(&schema_include_patterns, optarg);
425 include_everything = false;
428 case 'N': /* exclude schema(s) */
429 simple_string_list_append(&schema_exclude_patterns, optarg);
432 case 'o': /* Dump oids */
436 case 'O': /* Don't reconnect to match owner */
440 case 'p': /* server port */
445 /* no-op, still accepted for backwards compatibility */
448 case 's': /* dump schema only */
452 case 'S': /* Username for superuser in plain text output */
453 outputSuperuser = pg_strdup(optarg);
456 case 't': /* include table(s) */
457 simple_string_list_append(&table_include_patterns, optarg);
458 include_everything = false;
461 case 'T': /* exclude table(s) */
462 simple_string_list_append(&table_exclude_patterns, optarg);
469 case 'v': /* verbose */
474 prompt_password = TRI_NO;
478 prompt_password = TRI_YES;
481 case 'x': /* skip ACL dump */
485 case 'Z': /* Compression Level */
486 compressLevel = atoi(optarg);
490 /* This covers the long options. */
493 case 2: /* lock-wait-timeout */
494 lockWaitTimeout = optarg;
497 case 3: /* SET ROLE */
501 case 4: /* exclude table(s) data */
502 simple_string_list_append(&tabledata_exclude_patterns, optarg);
505 case 5: /* section */
506 set_section(optarg, &dumpSections);
510 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
515 /* Get database name from command line */
517 dbname = argv[optind++];
519 /* Complain if any arguments remain */
522 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
523 progname, argv[optind]);
524 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
529 /* --column-inserts implies --inserts */
533 if (dataOnly && schemaOnly)
534 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
536 if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
537 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
540 dumpSections = DUMP_DATA;
542 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
543 else if ( dumpSections != DUMP_UNSECTIONED)
545 dataOnly = dumpSections == DUMP_DATA;
546 schemaOnly = !(dumpSections & DUMP_DATA);
549 if (dataOnly && outputClean)
550 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
552 if (dump_inserts && oids)
554 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
555 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
559 /* Identify archive format to emit */
560 archiveFormat = parseArchiveFormat(format, &archiveMode);
562 /* archiveFormat specific setup */
563 if (archiveFormat == archNull)
566 /* Custom and directory formats are compressed by default, others not */
567 if (compressLevel == -1)
569 if (archiveFormat == archCustom || archiveFormat == archDirectory)
570 compressLevel = Z_DEFAULT_COMPRESSION;
575 /* Open the output file */
576 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
578 /* Register the cleanup hook */
579 on_exit_close_archive(fout);
582 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
584 /* Let the archiver know how noisy to be */
585 fout->verbose = g_verbose;
587 my_version = parse_version(PG_VERSION);
589 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
592 * We allow the server to be back to 7.0, and up to any minor release of
593 * our own major version. (See also version check in pg_dumpall.c.)
595 fout->minRemoteVersion = 70000;
596 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
599 * Open the database using the Archiver, so it knows about it. Errors mean
602 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
603 setup_connection(fout, dumpencoding, use_role);
606 * Disable security label support if server version < v9.1.x (prevents
607 * access to nonexistent pg_seclabel catalog)
609 if (fout->remoteVersion < 90100)
610 no_security_labels = 1;
613 * Start transaction-snapshot mode transaction to dump consistent data.
615 ExecuteSqlStatement(fout, "BEGIN");
616 if (fout->remoteVersion >= 90100)
618 if (serializable_deferrable)
619 ExecuteSqlStatement(fout,
620 "SET TRANSACTION ISOLATION LEVEL "
621 "SERIALIZABLE, READ ONLY, DEFERRABLE");
623 ExecuteSqlStatement(fout,
624 "SET TRANSACTION ISOLATION LEVEL "
628 ExecuteSqlStatement(fout,
629 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
631 /* Select the appropriate subquery to convert user IDs to names */
632 if (fout->remoteVersion >= 80100)
633 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
634 else if (fout->remoteVersion >= 70300)
635 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
637 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
639 /* Find the last built-in OID, if needed */
640 if (fout->remoteVersion < 70300)
642 if (fout->remoteVersion >= 70100)
643 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
644 PQdb(GetConnection(fout)));
646 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
648 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
651 /* Expand schema selection patterns into OID lists */
652 if (schema_include_patterns.head != NULL)
654 expand_schema_name_patterns(fout, &schema_include_patterns,
655 &schema_include_oids);
656 if (schema_include_oids.head == NULL)
657 exit_horribly(NULL, "No matching schemas were found\n");
659 expand_schema_name_patterns(fout, &schema_exclude_patterns,
660 &schema_exclude_oids);
661 /* non-matching exclusion patterns aren't an error */
663 /* Expand table selection patterns into OID lists */
664 if (table_include_patterns.head != NULL)
666 expand_table_name_patterns(fout, &table_include_patterns,
667 &table_include_oids);
668 if (table_include_oids.head == NULL)
669 exit_horribly(NULL, "No matching tables were found\n");
671 expand_table_name_patterns(fout, &table_exclude_patterns,
672 &table_exclude_oids);
674 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
675 &tabledata_exclude_oids);
677 /* non-matching exclusion patterns aren't an error */
680 * Dumping blobs is now default unless we saw an inclusion switch or -s
681 * ... but even if we did see one of these, -b turns it back on.
683 if (include_everything && !schemaOnly)
687 * Now scan the database and create DumpableObject structs for all the
688 * objects we intend to dump.
690 tblinfo = getSchemaData(fout, &numTables);
692 if (fout->remoteVersion < 80400)
693 guessConstraintInheritance(tblinfo, numTables);
697 getTableData(tblinfo, numTables, oids);
699 getTableDataFKConstraints();
706 * Collect dependency data to assist in ordering the objects.
708 getDependencies(fout);
711 * Sort the objects into a safe dump order (no forward references).
713 * In 7.3 or later, we can rely on dependency information to help us
714 * determine a safe order, so the initial sort is mostly for cosmetic
715 * purposes: we sort by name to ensure that logically identical schemas
716 * will dump identically. Before 7.3 we don't have dependencies and we
717 * use OID ordering as an (unreliable) guide to creation order.
719 getDumpableObjects(&dobjs, &numObjs);
721 if (fout->remoteVersion >= 70300)
722 sortDumpableObjectsByTypeName(dobjs, numObjs);
724 sortDumpableObjectsByTypeOid(dobjs, numObjs);
726 sortDumpableObjects(dobjs, numObjs);
729 * Create archive TOC entries for all the objects to be dumped, in a safe
733 /* First the special ENCODING and STDSTRINGS entries. */
735 dumpStdStrings(fout);
737 /* The database item is always next, unless we don't want it at all */
738 if (include_everything && !dataOnly)
741 /* Now the rearrangeable objects. */
742 for (i = 0; i < numObjs; i++)
743 dumpDumpableObject(fout, dobjs[i]);
746 * And finally we can do the actual output.
750 ropt = NewRestoreOptions();
751 ropt->filename = filename;
752 ropt->dropSchema = outputClean;
753 ropt->aclsSkip = aclsSkip;
754 ropt->superuser = outputSuperuser;
755 ropt->createDB = outputCreateDB;
756 ropt->noOwner = outputNoOwner;
757 ropt->noTablespace = outputNoTablespaces;
758 ropt->disable_triggers = disable_triggers;
759 ropt->use_setsessauth = use_setsessauth;
760 ropt->dataOnly = dataOnly;
762 if (compressLevel == -1)
763 ropt->compression = 0;
765 ropt->compression = compressLevel;
767 ropt->suppressDumpWarnings = true; /* We've already shown them */
769 RestoreArchive(fout, ropt);
779 help(const char *progname)
781 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
782 printf(_("Usage:\n"));
783 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
785 printf(_("\nGeneral options:\n"));
786 printf(_(" -f, --file=FILENAME output file or directory name\n"));
787 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
788 " plain text (default))\n"));
789 printf(_(" -v, --verbose verbose mode\n"));
790 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
791 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
792 printf(_(" --help show this help, then exit\n"));
793 printf(_(" --version output version information, then exit\n"));
795 printf(_("\nOptions controlling the output content:\n"));
796 printf(_(" -a, --data-only dump only the data, not the schema\n"));
797 printf(_(" -b, --blobs include large objects in dump\n"));
798 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
799 printf(_(" -C, --create include commands to create database in dump\n"));
800 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
801 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
802 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
803 printf(_(" -o, --oids include OIDs in dump\n"));
804 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
805 " plain-text format\n"));
806 printf(_(" -s, --schema-only dump only the schema, no data\n"));
807 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
808 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
809 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
810 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
811 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
812 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
813 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
814 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
815 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
816 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
817 printf(_(" --no-security-labels do not dump security label assignments\n"));
818 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
819 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
820 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
821 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
822 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
823 printf(_(" --use-set-session-authorization\n"
824 " use SET SESSION AUTHORIZATION commands instead of\n"
825 " ALTER OWNER commands to set ownership\n"));
827 printf(_("\nConnection options:\n"));
828 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
829 printf(_(" -p, --port=PORT database server port number\n"));
830 printf(_(" -U, --username=NAME connect as specified database user\n"));
831 printf(_(" -w, --no-password never prompt for password\n"));
832 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
833 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
835 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
836 "variable value is used.\n\n"));
837 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
841 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
843 PGconn *conn = GetConnection(AH);
844 const char *std_strings;
846 /* Set the client encoding if requested */
849 if (PQsetClientEncoding(conn, dumpencoding) < 0)
850 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
855 * Get the active encoding and the standard_conforming_strings setting, so
856 * we know how to escape strings.
858 AH->encoding = PQclientEncoding(conn);
860 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
861 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
863 /* Set the role if requested */
864 if (use_role && AH->remoteVersion >= 80100)
866 PQExpBuffer query = createPQExpBuffer();
868 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
869 ExecuteSqlStatement(AH, query->data);
870 destroyPQExpBuffer(query);
873 /* Set the datestyle to ISO to ensure the dump's portability */
874 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
876 /* Likewise, avoid using sql_standard intervalstyle */
877 if (AH->remoteVersion >= 80400)
878 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
881 * If supported, set extra_float_digits so that we can dump float data
882 * exactly (given correctly implemented float I/O code, anyway)
884 if (AH->remoteVersion >= 90000)
885 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
886 else if (AH->remoteVersion >= 70400)
887 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
890 * If synchronized scanning is supported, disable it, to prevent
891 * unpredictable changes in row ordering across a dump and reload.
893 if (AH->remoteVersion >= 80300)
894 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
897 * Disable timeouts if supported.
899 if (AH->remoteVersion >= 70300)
900 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
903 * Quote all identifiers, if requested.
905 if (quote_all_identifiers && AH->remoteVersion >= 90100)
906 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
910 parseArchiveFormat(const char *format, ArchiveMode *mode)
912 ArchiveFormat archiveFormat;
914 *mode = archModeWrite;
916 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
918 /* This is used by pg_dumpall, and is not documented */
919 archiveFormat = archNull;
920 *mode = archModeAppend;
922 else if (pg_strcasecmp(format, "c") == 0)
923 archiveFormat = archCustom;
924 else if (pg_strcasecmp(format, "custom") == 0)
925 archiveFormat = archCustom;
926 else if (pg_strcasecmp(format, "d") == 0)
927 archiveFormat = archDirectory;
928 else if (pg_strcasecmp(format, "directory") == 0)
929 archiveFormat = archDirectory;
930 else if (pg_strcasecmp(format, "p") == 0)
931 archiveFormat = archNull;
932 else if (pg_strcasecmp(format, "plain") == 0)
933 archiveFormat = archNull;
934 else if (pg_strcasecmp(format, "t") == 0)
935 archiveFormat = archTar;
936 else if (pg_strcasecmp(format, "tar") == 0)
937 archiveFormat = archTar;
939 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
940 return archiveFormat;
944 * Find the OIDs of all schemas matching the given list of patterns,
945 * and append them to the given OID list.
948 expand_schema_name_patterns(Archive *fout,
949 SimpleStringList *patterns,
954 SimpleStringListCell *cell;
957 if (patterns->head == NULL)
958 return; /* nothing to do */
960 if (fout->remoteVersion < 70300)
961 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
963 query = createPQExpBuffer();
966 * We use UNION ALL rather than UNION; this might sometimes result in
967 * duplicate entries in the OID list, but we don't care.
970 for (cell = patterns->head; cell; cell = cell->next)
972 if (cell != patterns->head)
973 appendPQExpBuffer(query, "UNION ALL\n");
974 appendPQExpBuffer(query,
975 "SELECT oid FROM pg_catalog.pg_namespace n\n");
976 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
977 false, NULL, "n.nspname", NULL, NULL);
980 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
982 for (i = 0; i < PQntuples(res); i++)
984 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
988 destroyPQExpBuffer(query);
992 * Find the OIDs of all tables matching the given list of patterns,
993 * and append them to the given OID list.
996 expand_table_name_patterns(Archive *fout,
997 SimpleStringList *patterns, SimpleOidList *oids)
1001 SimpleStringListCell *cell;
1004 if (patterns->head == NULL)
1005 return; /* nothing to do */
1007 query = createPQExpBuffer();
1010 * We use UNION ALL rather than UNION; this might sometimes result in
1011 * duplicate entries in the OID list, but we don't care.
1014 for (cell = patterns->head; cell; cell = cell->next)
1016 if (cell != patterns->head)
1017 appendPQExpBuffer(query, "UNION ALL\n");
1018 appendPQExpBuffer(query,
1020 "\nFROM pg_catalog.pg_class c"
1021 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1022 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1023 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1024 RELKIND_FOREIGN_TABLE);
1025 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1026 false, "n.nspname", "c.relname", NULL,
1027 "pg_catalog.pg_table_is_visible(c.oid)");
1030 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1032 for (i = 0; i < PQntuples(res); i++)
1034 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1038 destroyPQExpBuffer(query);
1042 * selectDumpableNamespace: policy-setting subroutine
1043 * Mark a namespace as to be dumped or not
1046 selectDumpableNamespace(NamespaceInfo *nsinfo)
1049 * If specific tables are being dumped, do not dump any complete
1050 * namespaces. If specific namespaces are being dumped, dump just those
1051 * namespaces. Otherwise, dump all non-system namespaces.
1053 if (table_include_oids.head != NULL)
1054 nsinfo->dobj.dump = false;
1055 else if (schema_include_oids.head != NULL)
1056 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1057 nsinfo->dobj.catId.oid);
1058 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1059 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1060 nsinfo->dobj.dump = false;
1062 nsinfo->dobj.dump = true;
1065 * In any case, a namespace can be excluded by an exclusion switch
1067 if (nsinfo->dobj.dump &&
1068 simple_oid_list_member(&schema_exclude_oids,
1069 nsinfo->dobj.catId.oid))
1070 nsinfo->dobj.dump = false;
1074 * selectDumpableTable: policy-setting subroutine
1075 * Mark a table as to be dumped or not
1078 selectDumpableTable(TableInfo *tbinfo)
1081 * If specific tables are being dumped, dump just those tables; else, dump
1082 * according to the parent namespace's dump flag.
1084 if (table_include_oids.head != NULL)
1085 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1086 tbinfo->dobj.catId.oid);
1088 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1091 * In any case, a table can be excluded by an exclusion switch
1093 if (tbinfo->dobj.dump &&
1094 simple_oid_list_member(&table_exclude_oids,
1095 tbinfo->dobj.catId.oid))
1096 tbinfo->dobj.dump = false;
1100 * selectDumpableType: policy-setting subroutine
1101 * Mark a type as to be dumped or not
1103 * If it's a table's rowtype or an autogenerated array type, we also apply a
1104 * special type code to facilitate sorting into the desired order. (We don't
1105 * want to consider those to be ordinary types because that would bring tables
1106 * up into the datatype part of the dump order.) We still set the object's
1107 * dump flag; that's not going to cause the dummy type to be dumped, but we
1108 * need it so that casts involving such types will be dumped correctly -- see
1109 * dumpCast. This means the flag should be set the same as for the underlying
1110 * object (the table or base type).
1113 selectDumpableType(TypeInfo *tyinfo)
1115 /* skip complex types, except for standalone composite types */
1116 if (OidIsValid(tyinfo->typrelid) &&
1117 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1119 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1121 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1122 if (tytable != NULL)
1123 tyinfo->dobj.dump = tytable->dobj.dump;
1125 tyinfo->dobj.dump = false;
1129 /* skip auto-generated array types */
1130 if (tyinfo->isArray)
1132 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1134 * Fall through to set the dump flag; we assume that the subsequent
1135 * rules will do the same thing as they would for the array's base
1136 * type. (We cannot reliably look up the base type here, since
1137 * getTypes may not have processed it yet.)
1141 /* dump only types in dumpable namespaces */
1142 if (!tyinfo->dobj.namespace->dobj.dump)
1143 tyinfo->dobj.dump = false;
1145 /* skip undefined placeholder types */
1146 else if (!tyinfo->isDefined)
1147 tyinfo->dobj.dump = false;
1150 tyinfo->dobj.dump = true;
1154 * selectDumpableDefaultACL: policy-setting subroutine
1155 * Mark a default ACL as to be dumped or not
1157 * For per-schema default ACLs, dump if the schema is to be dumped.
1158 * Otherwise dump if we are dumping "everything". Note that dataOnly
1159 * and aclsSkip are checked separately.
1162 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1164 if (dinfo->dobj.namespace)
1165 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1167 dinfo->dobj.dump = include_everything;
1171 * selectDumpableExtension: policy-setting subroutine
1172 * Mark an extension as to be dumped or not
1174 * Normally, we dump all extensions, or none of them if include_everything
1175 * is false (i.e., a --schema or --table switch was given). However, in
1176 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1177 * assume those will already be installed in the target database. We identify
1178 * such extensions by their having OIDs in the range reserved for initdb.
1181 selectDumpableExtension(ExtensionInfo *extinfo)
1183 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1184 extinfo->dobj.dump = false;
1186 extinfo->dobj.dump = include_everything;
1190 * selectDumpableObject: policy-setting subroutine
1191 * Mark a generic dumpable object as to be dumped or not
1193 * Use this only for object types without a special-case routine above.
1196 selectDumpableObject(DumpableObject *dobj)
1199 * Default policy is to dump if parent namespace is dumpable, or always
1200 * for non-namespace-associated items.
1202 if (dobj->namespace)
1203 dobj->dump = dobj->namespace->dobj.dump;
1209 * Dump a table's contents for loading using the COPY command
1210 * - this routine is called by the Archiver when it wants the table
1215 dumpTableData_copy(Archive *fout, void *dcontext)
1217 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1218 TableInfo *tbinfo = tdinfo->tdtable;
1219 const char *classname = tbinfo->dobj.name;
1220 const bool hasoids = tbinfo->hasoids;
1221 const bool oids = tdinfo->oids;
1222 PQExpBuffer q = createPQExpBuffer();
1223 PGconn *conn = GetConnection(fout);
1227 const char *column_list;
1230 write_msg(NULL, "dumping contents of table %s\n", classname);
1233 * Make sure we are in proper schema. We will qualify the table name
1234 * below anyway (in case its name conflicts with a pg_catalog table); but
1235 * this ensures reproducible results in case the table contains regproc,
1236 * regclass, etc columns.
1238 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1241 * If possible, specify the column list explicitly so that we have no
1242 * possibility of retrieving data in the wrong column order. (The default
1243 * column ordering of COPY will not be what we want in certain corner
1244 * cases involving ADD COLUMN and inheritance.)
1246 if (fout->remoteVersion >= 70300)
1247 column_list = fmtCopyColumnList(tbinfo);
1249 column_list = ""; /* can't select columns in COPY */
1251 if (oids && hasoids)
1253 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1254 fmtQualifiedId(fout,
1255 tbinfo->dobj.namespace->dobj.name,
1259 else if (tdinfo->filtercond)
1261 /* Note: this syntax is only supported in 8.2 and up */
1262 appendPQExpBufferStr(q, "COPY (SELECT ");
1263 /* klugery to get rid of parens in column list */
1264 if (strlen(column_list) > 2)
1266 appendPQExpBufferStr(q, column_list + 1);
1267 q->data[q->len - 1] = ' ';
1270 appendPQExpBufferStr(q, "* ");
1271 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1272 fmtQualifiedId(fout,
1273 tbinfo->dobj.namespace->dobj.name,
1275 tdinfo->filtercond);
1279 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1280 fmtQualifiedId(fout,
1281 tbinfo->dobj.namespace->dobj.name,
1285 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1290 ret = PQgetCopyData(conn, ©buf, 0);
1293 break; /* done or error */
1297 WriteData(fout, copybuf, ret);
1304 * There was considerable discussion in late July, 2000 regarding
1305 * slowing down pg_dump when backing up large tables. Users with both
1306 * slow & fast (multi-processor) machines experienced performance
1307 * degradation when doing a backup.
1309 * Initial attempts based on sleeping for a number of ms for each ms
1310 * of work were deemed too complex, then a simple 'sleep in each loop'
1311 * implementation was suggested. The latter failed because the loop
1312 * was too tight. Finally, the following was implemented:
1314 * If throttle is non-zero, then
1315 * See how long since the last sleep.
1316 * Work out how long to sleep (based on ratio).
1317 * If sleep is more than 100ms, then
1323 * where the throttle value was the number of ms to sleep per ms of
1324 * work. The calculation was done in each loop.
1326 * Most of the hard work is done in the backend, and this solution
1327 * still did not work particularly well: on slow machines, the ratio
1328 * was 50:1, and on medium paced machines, 1:1, and on fast
1329 * multi-processor machines, it had little or no effect, for reasons
1330 * that were unclear.
1332 * Further discussion ensued, and the proposal was dropped.
1334 * For those people who want this feature, it can be implemented using
1335 * gettimeofday in each loop, calculating the time since last sleep,
1336 * multiplying that by the sleep ratio, then if the result is more
1337 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1338 * function to sleep for a subsecond period ie.
1340 * select(0, NULL, NULL, NULL, &tvi);
1342 * This will return after the interval specified in the structure tvi.
1343 * Finally, call gettimeofday again to save the 'last sleep time'.
1347 archprintf(fout, "\\.\n\n\n");
1351 /* copy data transfer failed */
1352 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1353 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1354 write_msg(NULL, "The command was: %s\n", q->data);
1358 /* Check command status and return to normal libpq state */
1359 res = PQgetResult(conn);
1360 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1362 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1363 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1364 write_msg(NULL, "The command was: %s\n", q->data);
1369 destroyPQExpBuffer(q);
1374 * Dump table data using INSERT commands.
1376 * Caution: when we restore from an archive file direct to database, the
1377 * INSERT commands emitted by this function have to be parsed by
1378 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1379 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1382 dumpTableData_insert(Archive *fout, void *dcontext)
1384 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1385 TableInfo *tbinfo = tdinfo->tdtable;
1386 const char *classname = tbinfo->dobj.name;
1387 PQExpBuffer q = createPQExpBuffer();
1394 * Make sure we are in proper schema. We will qualify the table name
1395 * below anyway (in case its name conflicts with a pg_catalog table); but
1396 * this ensures reproducible results in case the table contains regproc,
1397 * regclass, etc columns.
1399 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1401 if (fout->remoteVersion >= 70100)
1403 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1404 "SELECT * FROM ONLY %s",
1405 fmtQualifiedId(fout,
1406 tbinfo->dobj.namespace->dobj.name,
1411 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1413 fmtQualifiedId(fout,
1414 tbinfo->dobj.namespace->dobj.name,
1417 if (tdinfo->filtercond)
1418 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1420 ExecuteSqlStatement(fout, q->data);
1424 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1426 nfields = PQnfields(res);
1427 for (tuple = 0; tuple < PQntuples(res); tuple++)
1429 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1432 /* corner case for zero-column table */
1433 archprintf(fout, "DEFAULT VALUES;\n");
1438 resetPQExpBuffer(q);
1439 appendPQExpBuffer(q, "(");
1440 for (field = 0; field < nfields; field++)
1443 appendPQExpBuffer(q, ", ");
1444 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1446 appendPQExpBuffer(q, ") ");
1447 archputs(q->data, fout);
1449 archprintf(fout, "VALUES (");
1450 for (field = 0; field < nfields; field++)
1453 archprintf(fout, ", ");
1454 if (PQgetisnull(res, tuple, field))
1456 archprintf(fout, "NULL");
1460 /* XXX This code is partially duplicated in ruleutils.c */
1461 switch (PQftype(res, field))
1472 * These types are printed without quotes unless
1473 * they contain values that aren't accepted by the
1474 * scanner unquoted (e.g., 'NaN'). Note that
1475 * strtod() and friends might accept NaN, so we
1476 * can't use that to test.
1478 * In reality we only need to defend against
1479 * infinity and NaN, so we need not get too crazy
1480 * about pattern matching here.
1482 const char *s = PQgetvalue(res, tuple, field);
1484 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1485 archprintf(fout, "%s", s);
1487 archprintf(fout, "'%s'", s);
1493 archprintf(fout, "B'%s'",
1494 PQgetvalue(res, tuple, field));
1498 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1499 archprintf(fout, "true");
1501 archprintf(fout, "false");
1505 /* All other types are printed as string literals. */
1506 resetPQExpBuffer(q);
1507 appendStringLiteralAH(q,
1508 PQgetvalue(res, tuple, field),
1510 archputs(q->data, fout);
1514 archprintf(fout, ");\n");
1517 if (PQntuples(res) <= 0)
1525 archprintf(fout, "\n\n");
1527 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1529 destroyPQExpBuffer(q);
1536 * dump the contents of a single table
1538 * Actually, this just makes an ArchiveEntry for the table contents.
1541 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1543 TableInfo *tbinfo = tdinfo->tdtable;
1544 PQExpBuffer copyBuf = createPQExpBuffer();
1545 DataDumperPtr dumpFn;
1550 /* Dump/restore using COPY */
1551 dumpFn = dumpTableData_copy;
1552 /* must use 2 steps here 'cause fmtId is nonreentrant */
1553 appendPQExpBuffer(copyBuf, "COPY %s ",
1554 fmtId(tbinfo->dobj.name));
1555 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1556 fmtCopyColumnList(tbinfo),
1557 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1558 copyStmt = copyBuf->data;
1562 /* Restore using INSERT */
1563 dumpFn = dumpTableData_insert;
1567 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1568 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1569 NULL, tbinfo->rolname,
1570 false, "TABLE DATA", SECTION_DATA,
1572 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1575 destroyPQExpBuffer(copyBuf);
1580 * set up dumpable objects representing the contents of tables
1583 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1587 for (i = 0; i < numTables; i++)
1589 if (tblinfo[i].dobj.dump)
1590 makeTableDataInfo(&(tblinfo[i]), oids);
1595 * Make a dumpable object for the data of this specific table
1597 * Note: we make a TableDataInfo if and only if we are going to dump the
1598 * table data; the "dump" flag in such objects isn't used.
1601 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1603 TableDataInfo *tdinfo;
1606 * Nothing to do if we already decided to dump the table. This will
1607 * happen for "config" tables.
1609 if (tbinfo->dataObj != NULL)
1612 /* Skip VIEWs (no data to dump) */
1613 if (tbinfo->relkind == RELKIND_VIEW)
1615 /* Skip SEQUENCEs (handled elsewhere) */
1616 if (tbinfo->relkind == RELKIND_SEQUENCE)
1618 /* Skip FOREIGN TABLEs (no data to dump) */
1619 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1622 /* Don't dump data in unlogged tables, if so requested */
1623 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1624 no_unlogged_table_data)
1627 /* Check that the data is not explicitly excluded */
1628 if (simple_oid_list_member(&tabledata_exclude_oids,
1629 tbinfo->dobj.catId.oid))
1632 /* OK, let's dump it */
1633 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1635 tdinfo->dobj.objType = DO_TABLE_DATA;
1638 * Note: use tableoid 0 so that this object won't be mistaken for
1639 * something that pg_depend entries apply to.
1641 tdinfo->dobj.catId.tableoid = 0;
1642 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1643 AssignDumpId(&tdinfo->dobj);
1644 tdinfo->dobj.name = tbinfo->dobj.name;
1645 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1646 tdinfo->tdtable = tbinfo;
1647 tdinfo->oids = oids;
1648 tdinfo->filtercond = NULL; /* might get set later */
1649 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1651 tbinfo->dataObj = tdinfo;
1655 * getTableDataFKConstraints -
1656 * add dump-order dependencies reflecting foreign key constraints
1658 * This code is executed only in a data-only dump --- in schema+data dumps
1659 * we handle foreign key issues by not creating the FK constraints until
1660 * after the data is loaded. In a data-only dump, however, we want to
1661 * order the table data objects in such a way that a table's referenced
1662 * tables are restored first. (In the presence of circular references or
1663 * self-references this may be impossible; we'll detect and complain about
1664 * that during the dependency sorting step.)
1667 getTableDataFKConstraints(void)
1669 DumpableObject **dobjs;
1673 /* Search through all the dumpable objects for FK constraints */
1674 getDumpableObjects(&dobjs, &numObjs);
1675 for (i = 0; i < numObjs; i++)
1677 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1679 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1682 /* Not interesting unless both tables are to be dumped */
1683 if (cinfo->contable == NULL ||
1684 cinfo->contable->dataObj == NULL)
1686 ftable = findTableByOid(cinfo->confrelid);
1687 if (ftable == NULL ||
1688 ftable->dataObj == NULL)
1692 * Okay, make referencing table's TABLE_DATA object depend on the
1693 * referenced table's TABLE_DATA object.
1695 addObjectDependency(&cinfo->contable->dataObj->dobj,
1696 ftable->dataObj->dobj.dumpId);
1704 * guessConstraintInheritance:
1705 * In pre-8.4 databases, we can't tell for certain which constraints
1706 * are inherited. We assume a CHECK constraint is inherited if its name
1707 * matches the name of any constraint in the parent. Originally this code
1708 * tried to compare the expression texts, but that can fail for various
1709 * reasons --- for example, if the parent and child tables are in different
1710 * schemas, reverse-listing of function calls may produce different text
1711 * (schema-qualified or not) depending on search path.
1713 * In 8.4 and up we can rely on the conislocal field to decide which
1714 * constraints must be dumped; much safer.
1716 * This function assumes all conislocal flags were initialized to TRUE.
1717 * It clears the flag on anything that seems to be inherited.
1720 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1726 for (i = 0; i < numTables; i++)
1728 TableInfo *tbinfo = &(tblinfo[i]);
1730 TableInfo **parents;
1733 /* Sequences and views never have parents */
1734 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1735 tbinfo->relkind == RELKIND_VIEW)
1738 /* Don't bother computing anything for non-target tables, either */
1739 if (!tbinfo->dobj.dump)
1742 numParents = tbinfo->numParents;
1743 parents = tbinfo->parents;
1745 if (numParents == 0)
1746 continue; /* nothing to see here, move along */
1748 /* scan for inherited CHECK constraints */
1749 for (j = 0; j < tbinfo->ncheck; j++)
1751 ConstraintInfo *constr;
1753 constr = &(tbinfo->checkexprs[j]);
1755 for (k = 0; k < numParents; k++)
1759 parent = parents[k];
1760 for (l = 0; l < parent->ncheck; l++)
1762 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1764 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1766 constr->conislocal = false;
1770 if (!constr->conislocal)
1780 * dump the database definition
1783 dumpDatabase(Archive *fout)
1785 PQExpBuffer dbQry = createPQExpBuffer();
1786 PQExpBuffer delQry = createPQExpBuffer();
1787 PQExpBuffer creaQry = createPQExpBuffer();
1788 PGconn *conn = GetConnection(fout);
1800 const char *datname,
1808 datname = PQdb(conn);
1811 write_msg(NULL, "saving database definition\n");
1813 /* Make sure we are in proper schema */
1814 selectSourceSchema(fout, "pg_catalog");
1816 /* Get the database owner and parameters from pg_database */
1817 if (fout->remoteVersion >= 80400)
1819 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1820 "(%s datdba) AS dba, "
1821 "pg_encoding_to_char(encoding) AS encoding, "
1822 "datcollate, datctype, datfrozenxid, "
1823 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1824 "shobj_description(oid, 'pg_database') AS description "
1829 appendStringLiteralAH(dbQry, datname, fout);
1831 else if (fout->remoteVersion >= 80200)
1833 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1834 "(%s datdba) AS dba, "
1835 "pg_encoding_to_char(encoding) AS encoding, "
1836 "NULL AS datcollate, NULL AS 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 >= 80000)
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 "
1855 appendStringLiteralAH(dbQry, datname, fout);
1857 else if (fout->remoteVersion >= 70100)
1859 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1860 "(%s datdba) AS dba, "
1861 "pg_encoding_to_char(encoding) AS encoding, "
1862 "NULL AS datcollate, NULL AS datctype, "
1863 "0 AS datfrozenxid, "
1864 "NULL AS tablespace "
1868 appendStringLiteralAH(dbQry, datname, fout);
1872 appendPQExpBuffer(dbQry, "SELECT "
1873 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1875 "(%s datdba) AS dba, "
1876 "pg_encoding_to_char(encoding) AS encoding, "
1877 "NULL AS datcollate, NULL AS datctype, "
1878 "0 AS datfrozenxid, "
1879 "NULL AS tablespace "
1883 appendStringLiteralAH(dbQry, datname, fout);
1886 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1888 i_tableoid = PQfnumber(res, "tableoid");
1889 i_oid = PQfnumber(res, "oid");
1890 i_dba = PQfnumber(res, "dba");
1891 i_encoding = PQfnumber(res, "encoding");
1892 i_collate = PQfnumber(res, "datcollate");
1893 i_ctype = PQfnumber(res, "datctype");
1894 i_frozenxid = PQfnumber(res, "datfrozenxid");
1895 i_tablespace = PQfnumber(res, "tablespace");
1897 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1898 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1899 dba = PQgetvalue(res, 0, i_dba);
1900 encoding = PQgetvalue(res, 0, i_encoding);
1901 collate = PQgetvalue(res, 0, i_collate);
1902 ctype = PQgetvalue(res, 0, i_ctype);
1903 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1904 tablespace = PQgetvalue(res, 0, i_tablespace);
1906 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1908 if (strlen(encoding) > 0)
1910 appendPQExpBuffer(creaQry, " ENCODING = ");
1911 appendStringLiteralAH(creaQry, encoding, fout);
1913 if (strlen(collate) > 0)
1915 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1916 appendStringLiteralAH(creaQry, collate, fout);
1918 if (strlen(ctype) > 0)
1920 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1921 appendStringLiteralAH(creaQry, ctype, fout);
1923 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1924 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1926 appendPQExpBuffer(creaQry, ";\n");
1930 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1931 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1932 "SET datfrozenxid = '%u'\n"
1935 appendStringLiteralAH(creaQry, datname, fout);
1936 appendPQExpBuffer(creaQry, ";\n");
1940 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1943 dbDumpId = createDumpId();
1946 dbCatId, /* catalog ID */
1947 dbDumpId, /* dump ID */
1949 NULL, /* Namespace */
1950 NULL, /* Tablespace */
1952 false, /* with oids */
1953 "DATABASE", /* Desc */
1954 SECTION_PRE_DATA, /* Section */
1955 creaQry->data, /* Create */
1956 delQry->data, /* Del */
1961 NULL); /* Dumper Arg */
1964 * pg_largeobject and pg_largeobject_metadata come from the old system
1965 * intact, so set their relfrozenxids.
1970 PQExpBuffer loFrozenQry = createPQExpBuffer();
1971 PQExpBuffer loOutQry = createPQExpBuffer();
1977 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1978 "FROM pg_catalog.pg_class\n"
1979 "WHERE oid = %u;\n",
1980 LargeObjectRelationId);
1982 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1984 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1986 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
1987 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1988 "SET relfrozenxid = '%u'\n"
1989 "WHERE oid = %u;\n",
1990 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1991 LargeObjectRelationId);
1992 ArchiveEntry(fout, nilCatalogId, createDumpId(),
1993 "pg_largeobject", NULL, NULL, "",
1994 false, "pg_largeobject", SECTION_PRE_DATA,
1995 loOutQry->data, "", NULL,
2002 * pg_largeobject_metadata
2004 if (fout->remoteVersion >= 90000)
2006 resetPQExpBuffer(loFrozenQry);
2007 resetPQExpBuffer(loOutQry);
2009 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2010 "FROM pg_catalog.pg_class\n"
2011 "WHERE oid = %u;\n",
2012 LargeObjectMetadataRelationId);
2014 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2016 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2018 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2019 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2020 "SET relfrozenxid = '%u'\n"
2021 "WHERE oid = %u;\n",
2022 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2023 LargeObjectMetadataRelationId);
2024 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2025 "pg_largeobject_metadata", NULL, NULL, "",
2026 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2027 loOutQry->data, "", NULL,
2034 destroyPQExpBuffer(loFrozenQry);
2035 destroyPQExpBuffer(loOutQry);
2038 /* Dump DB comment if any */
2039 if (fout->remoteVersion >= 80200)
2042 * 8.2 keeps comments on shared objects in a shared table, so we
2043 * cannot use the dumpComment used for other database objects.
2045 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2047 if (comment && strlen(comment))
2049 resetPQExpBuffer(dbQry);
2052 * Generates warning when loaded into a differently-named
2055 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2056 appendStringLiteralAH(dbQry, comment, fout);
2057 appendPQExpBuffer(dbQry, ";\n");
2059 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2060 dba, false, "COMMENT", SECTION_NONE,
2061 dbQry->data, "", NULL,
2062 &dbDumpId, 1, NULL, NULL);
2067 resetPQExpBuffer(dbQry);
2068 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2069 dumpComment(fout, dbQry->data, NULL, "",
2070 dbCatId, 0, dbDumpId);
2075 /* Dump shared security label. */
2076 if (!no_security_labels && fout->remoteVersion >= 90200)
2078 PQExpBuffer seclabelQry = createPQExpBuffer();
2080 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2081 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2082 resetPQExpBuffer(seclabelQry);
2083 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2084 if (strlen(seclabelQry->data))
2085 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2086 dba, false, "SECURITY LABEL", SECTION_NONE,
2087 seclabelQry->data, "", NULL,
2088 &dbDumpId, 1, NULL, NULL);
2089 destroyPQExpBuffer(seclabelQry);
2092 destroyPQExpBuffer(dbQry);
2093 destroyPQExpBuffer(delQry);
2094 destroyPQExpBuffer(creaQry);
2099 * dumpEncoding: put the correct encoding into the archive
2102 dumpEncoding(Archive *AH)
2104 const char *encname = pg_encoding_to_char(AH->encoding);
2105 PQExpBuffer qry = createPQExpBuffer();
2108 write_msg(NULL, "saving encoding = %s\n", encname);
2110 appendPQExpBuffer(qry, "SET client_encoding = ");
2111 appendStringLiteralAH(qry, encname, AH);
2112 appendPQExpBuffer(qry, ";\n");
2114 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2115 "ENCODING", NULL, NULL, "",
2116 false, "ENCODING", SECTION_PRE_DATA,
2117 qry->data, "", NULL,
2121 destroyPQExpBuffer(qry);
2126 * dumpStdStrings: put the correct escape string behavior into the archive
2129 dumpStdStrings(Archive *AH)
2131 const char *stdstrings = AH->std_strings ? "on" : "off";
2132 PQExpBuffer qry = createPQExpBuffer();
2135 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2138 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2141 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2142 "STDSTRINGS", NULL, NULL, "",
2143 false, "STDSTRINGS", SECTION_PRE_DATA,
2144 qry->data, "", NULL,
2148 destroyPQExpBuffer(qry);
2154 * Collect schema-level data about large objects
2157 getBlobs(Archive *fout)
2159 PQExpBuffer blobQry = createPQExpBuffer();
2161 DumpableObject *bdata;
2166 /* Verbose message */
2168 write_msg(NULL, "reading large objects\n");
2170 /* Make sure we are in proper schema */
2171 selectSourceSchema(fout, "pg_catalog");
2173 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2174 if (fout->remoteVersion >= 90000)
2175 appendPQExpBuffer(blobQry,
2176 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2177 " FROM pg_largeobject_metadata",
2179 else if (fout->remoteVersion >= 70100)
2180 appendPQExpBuffer(blobQry,
2181 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2182 " FROM pg_largeobject");
2184 appendPQExpBuffer(blobQry,
2185 "SELECT oid, NULL::oid, NULL::oid"
2186 " FROM pg_class WHERE relkind = 'l'");
2188 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2190 ntups = PQntuples(res);
2194 * Each large object has its own BLOB archive entry.
2196 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2198 for (i = 0; i < ntups; i++)
2200 binfo[i].dobj.objType = DO_BLOB;
2201 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2202 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2203 AssignDumpId(&binfo[i].dobj);
2205 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2206 if (!PQgetisnull(res, i, 1))
2207 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2209 binfo[i].rolname = "";
2210 if (!PQgetisnull(res, i, 2))
2211 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2213 binfo[i].blobacl = NULL;
2217 * If we have any large objects, a "BLOBS" archive entry is needed.
2218 * This is just a placeholder for sorting; it carries no data now.
2220 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2221 bdata->objType = DO_BLOB_DATA;
2222 bdata->catId = nilCatalogId;
2223 AssignDumpId(bdata);
2224 bdata->name = pg_strdup("BLOBS");
2228 destroyPQExpBuffer(blobQry);
2234 * dump the definition (metadata) of the given large object
2237 dumpBlob(Archive *fout, BlobInfo *binfo)
2239 PQExpBuffer cquery = createPQExpBuffer();
2240 PQExpBuffer dquery = createPQExpBuffer();
2242 appendPQExpBuffer(cquery,
2243 "SELECT pg_catalog.lo_create('%s');\n",
2246 appendPQExpBuffer(dquery,
2247 "SELECT pg_catalog.lo_unlink('%s');\n",
2250 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2253 binfo->rolname, false,
2254 "BLOB", SECTION_PRE_DATA,
2255 cquery->data, dquery->data, NULL,
2256 binfo->dobj.dependencies, binfo->dobj.nDeps,
2259 /* set up tag for comment and/or ACL */
2260 resetPQExpBuffer(cquery);
2261 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2263 /* Dump comment if any */
2264 dumpComment(fout, cquery->data,
2265 NULL, binfo->rolname,
2266 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2268 /* Dump security label if any */
2269 dumpSecLabel(fout, cquery->data,
2270 NULL, binfo->rolname,
2271 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2273 /* Dump ACL if any */
2275 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2276 binfo->dobj.name, NULL, cquery->data,
2277 NULL, binfo->rolname, binfo->blobacl);
2279 destroyPQExpBuffer(cquery);
2280 destroyPQExpBuffer(dquery);
2285 * dump the data contents of all large objects
2288 dumpBlobs(Archive *fout, void *arg)
2290 const char *blobQry;
2291 const char *blobFetchQry;
2292 PGconn *conn = GetConnection(fout);
2294 char buf[LOBBUFSIZE];
2300 write_msg(NULL, "saving large objects\n");
2302 /* Make sure we are in proper schema */
2303 selectSourceSchema(fout, "pg_catalog");
2306 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2307 * the already-in-memory dumpable objects instead...
2309 if (fout->remoteVersion >= 90000)
2310 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2311 else if (fout->remoteVersion >= 70100)
2312 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2314 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2316 ExecuteSqlStatement(fout, blobQry);
2318 /* Command to fetch from cursor */
2319 blobFetchQry = "FETCH 1000 IN bloboid";
2324 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2326 /* Process the tuples, if any */
2327 ntups = PQntuples(res);
2328 for (i = 0; i < ntups; i++)
2333 blobOid = atooid(PQgetvalue(res, i, 0));
2335 loFd = lo_open(conn, blobOid, INV_READ);
2337 exit_horribly(NULL, "could not open large object %u: %s",
2338 blobOid, PQerrorMessage(conn));
2340 StartBlob(fout, blobOid);
2342 /* Now read it in chunks, sending data to archive */
2345 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2347 exit_horribly(NULL, "error reading large object %u: %s",
2348 blobOid, PQerrorMessage(conn));
2350 WriteData(fout, buf, cnt);
2353 lo_close(conn, loFd);
2355 EndBlob(fout, blobOid);
2359 } while (ntups > 0);
2365 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2366 PQExpBuffer upgrade_buffer,
2369 PQExpBuffer upgrade_query = createPQExpBuffer();
2370 PGresult *upgrade_res;
2371 Oid pg_type_array_oid;
2373 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2374 appendPQExpBuffer(upgrade_buffer,
2375 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2378 /* we only support old >= 8.3 for binary upgrades */
2379 appendPQExpBuffer(upgrade_query,
2381 "FROM pg_catalog.pg_type "
2382 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2385 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2387 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2389 if (OidIsValid(pg_type_array_oid))
2391 appendPQExpBuffer(upgrade_buffer,
2392 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2393 appendPQExpBuffer(upgrade_buffer,
2394 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2398 PQclear(upgrade_res);
2399 destroyPQExpBuffer(upgrade_query);
2403 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2404 PQExpBuffer upgrade_buffer,
2407 PQExpBuffer upgrade_query = createPQExpBuffer();
2408 PGresult *upgrade_res;
2410 bool toast_set = false;
2412 /* we only support old >= 8.3 for binary upgrades */
2413 appendPQExpBuffer(upgrade_query,
2414 "SELECT c.reltype AS crel, t.reltype AS trel "
2415 "FROM pg_catalog.pg_class c "
2416 "LEFT JOIN pg_catalog.pg_class t ON "
2417 " (c.reltoastrelid = t.oid) "
2418 "WHERE c.oid = '%u'::pg_catalog.oid;",
2421 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2423 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2425 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2428 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2430 /* Toast tables do not have pg_type array rows */
2431 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2432 PQfnumber(upgrade_res, "trel")));
2434 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2435 appendPQExpBuffer(upgrade_buffer,
2436 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2442 PQclear(upgrade_res);
2443 destroyPQExpBuffer(upgrade_query);
2449 binary_upgrade_set_pg_class_oids(Archive *fout,
2450 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2453 PQExpBuffer upgrade_query = createPQExpBuffer();
2454 PGresult *upgrade_res;
2455 Oid pg_class_reltoastrelid;
2456 Oid pg_class_reltoastidxid;
2458 appendPQExpBuffer(upgrade_query,
2459 "SELECT c.reltoastrelid, t.reltoastidxid "
2460 "FROM pg_catalog.pg_class c LEFT JOIN "
2461 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2462 "WHERE c.oid = '%u'::pg_catalog.oid;",
2465 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2467 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2468 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2470 appendPQExpBuffer(upgrade_buffer,
2471 "\n-- For binary upgrade, must preserve pg_class oids\n");
2475 appendPQExpBuffer(upgrade_buffer,
2476 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2478 /* only tables have toast tables, not indexes */
2479 if (OidIsValid(pg_class_reltoastrelid))
2482 * One complexity is that the table definition might not require
2483 * the creation of a TOAST table, and the TOAST table might have
2484 * been created long after table creation, when the table was
2485 * loaded with wide data. By setting the TOAST oid we force
2486 * creation of the TOAST heap and TOAST index by the backend so we
2487 * can cleanly copy the files during binary upgrade.
2490 appendPQExpBuffer(upgrade_buffer,
2491 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2492 pg_class_reltoastrelid);
2494 /* every toast table has an index */
2495 appendPQExpBuffer(upgrade_buffer,
2496 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2497 pg_class_reltoastidxid);
2501 appendPQExpBuffer(upgrade_buffer,
2502 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2505 appendPQExpBuffer(upgrade_buffer, "\n");
2507 PQclear(upgrade_res);
2508 destroyPQExpBuffer(upgrade_query);
2512 * If the DumpableObject is a member of an extension, add a suitable
2513 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2516 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2517 DumpableObject *dobj,
2518 const char *objlabel)
2520 DumpableObject *extobj = NULL;
2523 if (!dobj->ext_member)
2527 * Find the parent extension. We could avoid this search if we wanted to
2528 * add a link field to DumpableObject, but the space costs of that would
2529 * be considerable. We assume that member objects could only have a
2530 * direct dependency on their own extension, not any others.
2532 for (i = 0; i < dobj->nDeps; i++)
2534 extobj = findObjectByDumpId(dobj->dependencies[i]);
2535 if (extobj && extobj->objType == DO_EXTENSION)
2540 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2542 appendPQExpBuffer(upgrade_buffer,
2543 "\n-- For binary upgrade, handle extension membership the hard way\n");
2544 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2545 fmtId(extobj->name),
2551 * read all namespaces in the system catalogs and return them in the
2552 * NamespaceInfo* structure
2554 * numNamespaces is set to the number of namespaces read in
2557 getNamespaces(Archive *fout, int *numNamespaces)
2563 NamespaceInfo *nsinfo;
2571 * Before 7.3, there are no real namespaces; create two dummy entries, one
2572 * for user stuff and one for system stuff.
2574 if (fout->remoteVersion < 70300)
2576 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2578 nsinfo[0].dobj.objType = DO_NAMESPACE;
2579 nsinfo[0].dobj.catId.tableoid = 0;
2580 nsinfo[0].dobj.catId.oid = 0;
2581 AssignDumpId(&nsinfo[0].dobj);
2582 nsinfo[0].dobj.name = pg_strdup("public");
2583 nsinfo[0].rolname = pg_strdup("");
2584 nsinfo[0].nspacl = pg_strdup("");
2586 selectDumpableNamespace(&nsinfo[0]);
2588 nsinfo[1].dobj.objType = DO_NAMESPACE;
2589 nsinfo[1].dobj.catId.tableoid = 0;
2590 nsinfo[1].dobj.catId.oid = 1;
2591 AssignDumpId(&nsinfo[1].dobj);
2592 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2593 nsinfo[1].rolname = pg_strdup("");
2594 nsinfo[1].nspacl = pg_strdup("");
2596 selectDumpableNamespace(&nsinfo[1]);
2598 g_namespaces = nsinfo;
2599 g_numNamespaces = *numNamespaces = 2;
2604 query = createPQExpBuffer();
2606 /* Make sure we are in proper schema */
2607 selectSourceSchema(fout, "pg_catalog");
2610 * we fetch all namespaces including system ones, so that every object we
2611 * read in can be linked to a containing namespace.
2613 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2614 "(%s nspowner) AS rolname, "
2615 "nspacl FROM pg_namespace",
2618 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2620 ntups = PQntuples(res);
2622 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2624 i_tableoid = PQfnumber(res, "tableoid");
2625 i_oid = PQfnumber(res, "oid");
2626 i_nspname = PQfnumber(res, "nspname");
2627 i_rolname = PQfnumber(res, "rolname");
2628 i_nspacl = PQfnumber(res, "nspacl");
2630 for (i = 0; i < ntups; i++)
2632 nsinfo[i].dobj.objType = DO_NAMESPACE;
2633 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2634 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2635 AssignDumpId(&nsinfo[i].dobj);
2636 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2637 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2638 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2640 /* Decide whether to dump this namespace */
2641 selectDumpableNamespace(&nsinfo[i]);
2643 if (strlen(nsinfo[i].rolname) == 0)
2644 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2645 nsinfo[i].dobj.name);
2649 destroyPQExpBuffer(query);
2651 g_namespaces = nsinfo;
2652 g_numNamespaces = *numNamespaces = ntups;
2659 * given a namespace OID and an object OID, look up the info read by
2662 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2663 * a system object or not. In 7.3 and later there is no guessing.
2665 static NamespaceInfo *
2666 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2670 if (fout->remoteVersion >= 70300)
2672 for (i = 0; i < g_numNamespaces; i++)
2674 NamespaceInfo *nsinfo = &g_namespaces[i];
2676 if (nsoid == nsinfo->dobj.catId.oid)
2679 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2683 /* This code depends on the layout set up by getNamespaces. */
2684 if (objoid > g_last_builtin_oid)
2685 i = 0; /* user object */
2687 i = 1; /* system object */
2688 return &g_namespaces[i];
2691 return NULL; /* keep compiler quiet */
2696 * read all extensions in the system catalogs and return them in the
2697 * ExtensionInfo* structure
2699 * numExtensions is set to the number of extensions read in
2702 getExtensions(Archive *fout, int *numExtensions)
2708 ExtensionInfo *extinfo;
2713 int i_extrelocatable;
2719 * Before 9.1, there are no extensions.
2721 if (fout->remoteVersion < 90100)
2727 query = createPQExpBuffer();
2729 /* Make sure we are in proper schema */
2730 selectSourceSchema(fout, "pg_catalog");
2732 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2733 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2734 "FROM pg_extension x "
2735 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2737 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2739 ntups = PQntuples(res);
2741 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2743 i_tableoid = PQfnumber(res, "tableoid");
2744 i_oid = PQfnumber(res, "oid");
2745 i_extname = PQfnumber(res, "extname");
2746 i_nspname = PQfnumber(res, "nspname");
2747 i_extrelocatable = PQfnumber(res, "extrelocatable");
2748 i_extversion = PQfnumber(res, "extversion");
2749 i_extconfig = PQfnumber(res, "extconfig");
2750 i_extcondition = PQfnumber(res, "extcondition");
2752 for (i = 0; i < ntups; i++)
2754 extinfo[i].dobj.objType = DO_EXTENSION;
2755 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2756 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2757 AssignDumpId(&extinfo[i].dobj);
2758 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2759 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2760 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2761 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2762 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2763 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2765 /* Decide whether we want to dump it */
2766 selectDumpableExtension(&(extinfo[i]));
2770 destroyPQExpBuffer(query);
2772 *numExtensions = ntups;
2779 * read all types in the system catalogs and return them in the
2780 * TypeInfo* structure
2782 * numTypes is set to the number of types read in
2784 * NB: this must run after getFuncs() because we assume we can do
2788 getTypes(Archive *fout, int *numTypes)
2793 PQExpBuffer query = createPQExpBuffer();
2795 ShellTypeInfo *stinfo;
2811 * we include even the built-in types because those may be used as array
2812 * elements by user-defined types
2814 * we filter out the built-in types when we dump out the types
2816 * same approach for undefined (shell) types and array types
2818 * Note: as of 8.3 we can reliably detect whether a type is an
2819 * auto-generated array type by checking the element type's typarray.
2820 * (Before that the test is capable of generating false positives.) We
2821 * still check for name beginning with '_', though, so as to avoid the
2822 * cost of the subselect probe for all standard types. This would have to
2823 * be revisited if the backend ever allows renaming of array types.
2826 /* Make sure we are in proper schema */
2827 selectSourceSchema(fout, "pg_catalog");
2829 if (fout->remoteVersion >= 80300)
2831 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2833 "(%s typowner) AS rolname, "
2834 "typinput::oid AS typinput, "
2835 "typoutput::oid AS typoutput, typelem, typrelid, "
2836 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2837 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2838 "typtype, typisdefined, "
2839 "typname[0] = '_' AND typelem != 0 AND "
2840 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2844 else if (fout->remoteVersion >= 70300)
2846 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2848 "(%s typowner) AS rolname, "
2849 "typinput::oid AS typinput, "
2850 "typoutput::oid AS typoutput, typelem, typrelid, "
2851 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2852 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2853 "typtype, typisdefined, "
2854 "typname[0] = '_' AND typelem != 0 AS isarray "
2858 else if (fout->remoteVersion >= 70100)
2860 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2861 "0::oid AS typnamespace, "
2862 "(%s typowner) AS rolname, "
2863 "typinput::oid AS typinput, "
2864 "typoutput::oid AS typoutput, typelem, typrelid, "
2865 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2866 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2867 "typtype, typisdefined, "
2868 "typname[0] = '_' AND typelem != 0 AS isarray "
2874 appendPQExpBuffer(query, "SELECT "
2875 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
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 "
2889 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2891 ntups = PQntuples(res);
2893 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2895 i_tableoid = PQfnumber(res, "tableoid");
2896 i_oid = PQfnumber(res, "oid");
2897 i_typname = PQfnumber(res, "typname");
2898 i_typnamespace = PQfnumber(res, "typnamespace");
2899 i_rolname = PQfnumber(res, "rolname");
2900 i_typinput = PQfnumber(res, "typinput");
2901 i_typoutput = PQfnumber(res, "typoutput");
2902 i_typelem = PQfnumber(res, "typelem");
2903 i_typrelid = PQfnumber(res, "typrelid");
2904 i_typrelkind = PQfnumber(res, "typrelkind");
2905 i_typtype = PQfnumber(res, "typtype");
2906 i_typisdefined = PQfnumber(res, "typisdefined");
2907 i_isarray = PQfnumber(res, "isarray");
2909 for (i = 0; i < ntups; i++)
2911 tyinfo[i].dobj.objType = DO_TYPE;
2912 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2913 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2914 AssignDumpId(&tyinfo[i].dobj);
2915 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2916 tyinfo[i].dobj.namespace =
2918 atooid(PQgetvalue(res, i, i_typnamespace)),
2919 tyinfo[i].dobj.catId.oid);
2920 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2921 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2922 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2923 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2924 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2925 tyinfo[i].shellType = NULL;
2927 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2928 tyinfo[i].isDefined = true;
2930 tyinfo[i].isDefined = false;
2932 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2933 tyinfo[i].isArray = true;
2935 tyinfo[i].isArray = false;
2937 /* Decide whether we want to dump it */
2938 selectDumpableType(&tyinfo[i]);
2941 * If it's a domain, fetch info about its constraints, if any
2943 tyinfo[i].nDomChecks = 0;
2944 tyinfo[i].domChecks = NULL;
2945 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2946 getDomainConstraints(fout, &(tyinfo[i]));
2949 * If it's a base type, make a DumpableObject representing a shell
2950 * definition of the type. We will need to dump that ahead of the I/O
2951 * functions for the type. Similarly, range types need a shell
2952 * definition in case they have a canonicalize function.
2954 * Note: the shell type doesn't have a catId. You might think it
2955 * should copy the base type's catId, but then it might capture the
2956 * pg_depend entries for the type, which we don't want.
2958 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2959 tyinfo[i].typtype == TYPTYPE_RANGE))
2961 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2962 stinfo->dobj.objType = DO_SHELL_TYPE;
2963 stinfo->dobj.catId = nilCatalogId;
2964 AssignDumpId(&stinfo->dobj);
2965 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2966 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2967 stinfo->baseType = &(tyinfo[i]);
2968 tyinfo[i].shellType = stinfo;
2971 * Initially mark the shell type as not to be dumped. We'll only
2972 * dump it if the I/O or canonicalize functions need to be dumped;
2973 * this is taken care of while sorting dependencies.
2975 stinfo->dobj.dump = false;
2978 * However, if dumping from pre-7.3, there will be no dependency
2979 * info so we have to fake it here. We only need to worry about
2980 * typinput and typoutput since the other functions only exist
2983 if (fout->remoteVersion < 70300)
2989 typinput = atooid(PQgetvalue(res, i, i_typinput));
2990 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
2992 funcInfo = findFuncByOid(typinput);
2993 if (funcInfo && funcInfo->dobj.dump)
2995 /* base type depends on function */
2996 addObjectDependency(&tyinfo[i].dobj,
2997 funcInfo->dobj.dumpId);
2998 /* function depends on shell type */
2999 addObjectDependency(&funcInfo->dobj,
3000 stinfo->dobj.dumpId);
3001 /* mark shell type as to be dumped */
3002 stinfo->dobj.dump = true;
3005 funcInfo = findFuncByOid(typoutput);
3006 if (funcInfo && funcInfo->dobj.dump)
3008 /* base type depends on function */
3009 addObjectDependency(&tyinfo[i].dobj,
3010 funcInfo->dobj.dumpId);
3011 /* function depends on shell type */
3012 addObjectDependency(&funcInfo->dobj,
3013 stinfo->dobj.dumpId);
3014 /* mark shell type as to be dumped */
3015 stinfo->dobj.dump = true;
3020 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3021 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3022 tyinfo[i].dobj.name);
3029 destroyPQExpBuffer(query);
3036 * read all operators in the system catalogs and return them in the
3037 * OprInfo* structure
3039 * numOprs is set to the number of operators read in
3042 getOperators(Archive *fout, int *numOprs)
3047 PQExpBuffer query = createPQExpBuffer();
3058 * find all operators, including builtin operators; we filter out
3059 * system-defined operators at dump-out time.
3062 /* Make sure we are in proper schema */
3063 selectSourceSchema(fout, "pg_catalog");
3065 if (fout->remoteVersion >= 70300)
3067 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3069 "(%s oprowner) AS rolname, "
3071 "oprcode::oid AS oprcode "
3075 else if (fout->remoteVersion >= 70100)
3077 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3078 "0::oid AS oprnamespace, "
3079 "(%s oprowner) AS rolname, "
3081 "oprcode::oid AS oprcode "
3087 appendPQExpBuffer(query, "SELECT "
3088 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3090 "0::oid AS oprnamespace, "
3091 "(%s oprowner) AS rolname, "
3093 "oprcode::oid AS oprcode "
3098 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3100 ntups = PQntuples(res);
3103 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3105 i_tableoid = PQfnumber(res, "tableoid");
3106 i_oid = PQfnumber(res, "oid");
3107 i_oprname = PQfnumber(res, "oprname");
3108 i_oprnamespace = PQfnumber(res, "oprnamespace");
3109 i_rolname = PQfnumber(res, "rolname");
3110 i_oprkind = PQfnumber(res, "oprkind");
3111 i_oprcode = PQfnumber(res, "oprcode");
3113 for (i = 0; i < ntups; i++)
3115 oprinfo[i].dobj.objType = DO_OPERATOR;
3116 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3117 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3118 AssignDumpId(&oprinfo[i].dobj);
3119 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3120 oprinfo[i].dobj.namespace =
3122 atooid(PQgetvalue(res, i, i_oprnamespace)),
3123 oprinfo[i].dobj.catId.oid);
3124 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3125 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3126 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3128 /* Decide whether we want to dump it */
3129 selectDumpableObject(&(oprinfo[i].dobj));
3131 if (strlen(oprinfo[i].rolname) == 0)
3132 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3133 oprinfo[i].dobj.name);
3138 destroyPQExpBuffer(query);
3145 * read all collations in the system catalogs and return them in the
3146 * CollInfo* structure
3148 * numCollations is set to the number of collations read in
3151 getCollations(Archive *fout, int *numCollations)
3161 int i_collnamespace;
3164 /* Collations didn't exist pre-9.1 */
3165 if (fout->remoteVersion < 90100)
3171 query = createPQExpBuffer();
3174 * find all collations, including builtin collations; we filter out
3175 * system-defined collations at dump-out time.
3178 /* Make sure we are in proper schema */
3179 selectSourceSchema(fout, "pg_catalog");
3181 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3183 "(%s collowner) AS rolname "
3184 "FROM pg_collation",
3187 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3189 ntups = PQntuples(res);
3190 *numCollations = ntups;
3192 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3194 i_tableoid = PQfnumber(res, "tableoid");
3195 i_oid = PQfnumber(res, "oid");
3196 i_collname = PQfnumber(res, "collname");
3197 i_collnamespace = PQfnumber(res, "collnamespace");
3198 i_rolname = PQfnumber(res, "rolname");
3200 for (i = 0; i < ntups; i++)
3202 collinfo[i].dobj.objType = DO_COLLATION;
3203 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3204 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3205 AssignDumpId(&collinfo[i].dobj);
3206 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3207 collinfo[i].dobj.namespace =
3209 atooid(PQgetvalue(res, i, i_collnamespace)),
3210 collinfo[i].dobj.catId.oid);
3211 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3213 /* Decide whether we want to dump it */
3214 selectDumpableObject(&(collinfo[i].dobj));
3219 destroyPQExpBuffer(query);
3226 * read all conversions in the system catalogs and return them in the
3227 * ConvInfo* structure
3229 * numConversions is set to the number of conversions read in
3232 getConversions(Archive *fout, int *numConversions)
3237 PQExpBuffer query = createPQExpBuffer();
3245 /* Conversions didn't exist pre-7.3 */
3246 if (fout->remoteVersion < 70300)
3248 *numConversions = 0;
3253 * find all conversions, including builtin conversions; we filter out
3254 * system-defined conversions at dump-out time.
3257 /* Make sure we are in proper schema */
3258 selectSourceSchema(fout, "pg_catalog");
3260 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3262 "(%s conowner) AS rolname "
3263 "FROM pg_conversion",
3266 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3268 ntups = PQntuples(res);
3269 *numConversions = ntups;
3271 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3273 i_tableoid = PQfnumber(res, "tableoid");
3274 i_oid = PQfnumber(res, "oid");
3275 i_conname = PQfnumber(res, "conname");
3276 i_connamespace = PQfnumber(res, "connamespace");
3277 i_rolname = PQfnumber(res, "rolname");
3279 for (i = 0; i < ntups; i++)
3281 convinfo[i].dobj.objType = DO_CONVERSION;
3282 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3283 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3284 AssignDumpId(&convinfo[i].dobj);
3285 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3286 convinfo[i].dobj.namespace =
3288 atooid(PQgetvalue(res, i, i_connamespace)),
3289 convinfo[i].dobj.catId.oid);
3290 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3292 /* Decide whether we want to dump it */
3293 selectDumpableObject(&(convinfo[i].dobj));
3298 destroyPQExpBuffer(query);
3305 * read all opclasses in the system catalogs and return them in the
3306 * OpclassInfo* structure
3308 * numOpclasses is set to the number of opclasses read in
3311 getOpclasses(Archive *fout, int *numOpclasses)
3316 PQExpBuffer query = createPQExpBuffer();
3317 OpclassInfo *opcinfo;
3325 * find all opclasses, including builtin opclasses; we filter out
3326 * system-defined opclasses at dump-out time.
3329 /* Make sure we are in proper schema */
3330 selectSourceSchema(fout, "pg_catalog");
3332 if (fout->remoteVersion >= 70300)
3334 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3336 "(%s opcowner) AS rolname "
3340 else if (fout->remoteVersion >= 70100)
3342 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3343 "0::oid AS opcnamespace, "
3344 "''::name AS rolname "
3349 appendPQExpBuffer(query, "SELECT "
3350 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3352 "0::oid AS opcnamespace, "
3353 "''::name AS rolname "
3357 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3359 ntups = PQntuples(res);
3360 *numOpclasses = ntups;
3362 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3364 i_tableoid = PQfnumber(res, "tableoid");
3365 i_oid = PQfnumber(res, "oid");
3366 i_opcname = PQfnumber(res, "opcname");
3367 i_opcnamespace = PQfnumber(res, "opcnamespace");
3368 i_rolname = PQfnumber(res, "rolname");
3370 for (i = 0; i < ntups; i++)
3372 opcinfo[i].dobj.objType = DO_OPCLASS;
3373 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3374 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3375 AssignDumpId(&opcinfo[i].dobj);
3376 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3377 opcinfo[i].dobj.namespace =
3379 atooid(PQgetvalue(res, i, i_opcnamespace)),
3380 opcinfo[i].dobj.catId.oid);
3381 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3383 /* Decide whether we want to dump it */
3384 selectDumpableObject(&(opcinfo[i].dobj));
3386 if (fout->remoteVersion >= 70300)
3388 if (strlen(opcinfo[i].rolname) == 0)
3389 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3390 opcinfo[i].dobj.name);
3396 destroyPQExpBuffer(query);
3403 * read all opfamilies in the system catalogs and return them in the
3404 * OpfamilyInfo* structure
3406 * numOpfamilies is set to the number of opfamilies read in
3409 getOpfamilies(Archive *fout, int *numOpfamilies)
3415 OpfamilyInfo *opfinfo;
3422 /* Before 8.3, there is no separate concept of opfamilies */
3423 if (fout->remoteVersion < 80300)
3429 query = createPQExpBuffer();
3432 * find all opfamilies, including builtin opfamilies; we filter out
3433 * system-defined opfamilies at dump-out time.
3436 /* Make sure we are in proper schema */
3437 selectSourceSchema(fout, "pg_catalog");
3439 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3441 "(%s opfowner) AS rolname "
3445 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3447 ntups = PQntuples(res);
3448 *numOpfamilies = ntups;
3450 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3452 i_tableoid = PQfnumber(res, "tableoid");
3453 i_oid = PQfnumber(res, "oid");
3454 i_opfname = PQfnumber(res, "opfname");
3455 i_opfnamespace = PQfnumber(res, "opfnamespace");
3456 i_rolname = PQfnumber(res, "rolname");
3458 for (i = 0; i < ntups; i++)
3460 opfinfo[i].dobj.objType = DO_OPFAMILY;
3461 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3462 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3463 AssignDumpId(&opfinfo[i].dobj);
3464 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3465 opfinfo[i].dobj.namespace =
3467 atooid(PQgetvalue(res, i, i_opfnamespace)),
3468 opfinfo[i].dobj.catId.oid);
3469 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3471 /* Decide whether we want to dump it */
3472 selectDumpableObject(&(opfinfo[i].dobj));
3474 if (fout->remoteVersion >= 70300)
3476 if (strlen(opfinfo[i].rolname) == 0)
3477 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3478 opfinfo[i].dobj.name);
3484 destroyPQExpBuffer(query);
3491 * read all the user-defined aggregates in the system catalogs and
3492 * return them in the AggInfo* structure
3494 * numAggs is set to the number of aggregates read in
3497 getAggregates(Archive *fout, int *numAggs)
3502 PQExpBuffer query = createPQExpBuffer();
3513 /* Make sure we are in proper schema */
3514 selectSourceSchema(fout, "pg_catalog");
3517 * Find all user-defined aggregates. See comment in getFuncs() for the
3518 * rationale behind the filtering logic.
3521 if (fout->remoteVersion >= 80200)
3523 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3524 "pronamespace AS aggnamespace, "
3525 "pronargs, proargtypes, "
3526 "(%s proowner) AS rolname, "
3529 "WHERE proisagg AND ("
3531 "(SELECT oid FROM pg_namespace "
3532 "WHERE nspname = 'pg_catalog')",
3534 if (binary_upgrade && fout->remoteVersion >= 90100)
3535 appendPQExpBuffer(query,
3536 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3537 "classid = 'pg_proc'::regclass AND "
3538 "objid = p.oid AND "
3539 "refclassid = 'pg_extension'::regclass AND "
3541 appendPQExpBuffer(query, ")");
3543 else if (fout->remoteVersion >= 70300)
3545 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3546 "pronamespace AS aggnamespace, "
3547 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3549 "(%s proowner) AS rolname, "
3553 "AND pronamespace != "
3554 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3557 else if (fout->remoteVersion >= 70100)
3559 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3560 "0::oid AS aggnamespace, "
3561 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3562 "aggbasetype AS proargtypes, "
3563 "(%s aggowner) AS rolname, "
3565 "FROM pg_aggregate "
3566 "where oid > '%u'::oid",
3568 g_last_builtin_oid);
3572 appendPQExpBuffer(query, "SELECT "
3573 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3575 "0::oid AS aggnamespace, "
3576 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3577 "aggbasetype AS proargtypes, "
3578 "(%s aggowner) AS rolname, "
3580 "FROM pg_aggregate "
3581 "where oid > '%u'::oid",
3583 g_last_builtin_oid);
3586 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3588 ntups = PQntuples(res);
3591 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3593 i_tableoid = PQfnumber(res, "tableoid");
3594 i_oid = PQfnumber(res, "oid");
3595 i_aggname = PQfnumber(res, "aggname");
3596 i_aggnamespace = PQfnumber(res, "aggnamespace");
3597 i_pronargs = PQfnumber(res, "pronargs");
3598 i_proargtypes = PQfnumber(res, "proargtypes");
3599 i_rolname = PQfnumber(res, "rolname");
3600 i_aggacl = PQfnumber(res, "aggacl");
3602 for (i = 0; i < ntups; i++)
3604 agginfo[i].aggfn.dobj.objType = DO_AGG;
3605 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3606 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3607 AssignDumpId(&agginfo[i].aggfn.dobj);
3608 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3609 agginfo[i].aggfn.dobj.namespace =
3611 atooid(PQgetvalue(res, i, i_aggnamespace)),
3612 agginfo[i].aggfn.dobj.catId.oid);
3613 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3614 if (strlen(agginfo[i].aggfn.rolname) == 0)
3615 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3616 agginfo[i].aggfn.dobj.name);
3617 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3618 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3619 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3620 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3621 if (agginfo[i].aggfn.nargs == 0)
3622 agginfo[i].aggfn.argtypes = NULL;
3625 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3626 if (fout->remoteVersion >= 70300)
3627 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3628 agginfo[i].aggfn.argtypes,
3629 agginfo[i].aggfn.nargs);
3631 /* it's just aggbasetype */
3632 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3635 /* Decide whether we want to dump it */
3636 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3641 destroyPQExpBuffer(query);
3648 * read all the user-defined functions in the system catalogs and
3649 * return them in the FuncInfo* structure
3651 * numFuncs is set to the number of functions read in
3654 getFuncs(Archive *fout, int *numFuncs)
3659 PQExpBuffer query = createPQExpBuffer();
3672 /* Make sure we are in proper schema */
3673 selectSourceSchema(fout, "pg_catalog");
3676 * Find all user-defined functions. Normally we can exclude functions in
3677 * pg_catalog, which is worth doing since there are several thousand of
3678 * 'em. However, there are some extensions that create functions in
3679 * pg_catalog. In normal dumps we can still ignore those --- but in
3680 * binary-upgrade mode, we must dump the member objects of the extension,
3681 * so be sure to fetch any such functions.
3683 * Also, in 9.2 and up, exclude functions that are internally dependent on
3684 * something else, since presumably those will be created as a result of
3685 * creating the something else. This currently only acts to suppress
3686 * constructor functions for range types. Note that this is OK only
3687 * because the constructors don't have any dependencies the range type
3688 * doesn't have; otherwise we might not get creation ordering correct.
3691 if (fout->remoteVersion >= 70300)
3693 appendPQExpBuffer(query,
3694 "SELECT tableoid, oid, proname, prolang, "
3695 "pronargs, proargtypes, prorettype, proacl, "
3697 "(%s proowner) AS rolname "
3699 "WHERE NOT proisagg AND ("
3701 "(SELECT oid FROM pg_namespace "
3702 "WHERE nspname = 'pg_catalog')",
3704 if (fout->remoteVersion >= 90200)
3705 appendPQExpBuffer(query,
3706 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3707 "WHERE classid = 'pg_proc'::regclass AND "
3708 "objid = p.oid AND deptype = 'i')");
3709 if (binary_upgrade && fout->remoteVersion >= 90100)
3710 appendPQExpBuffer(query,
3711 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3712 "classid = 'pg_proc'::regclass AND "
3713 "objid = p.oid AND "
3714 "refclassid = 'pg_extension'::regclass AND "
3716 appendPQExpBuffer(query, ")");
3718 else if (fout->remoteVersion >= 70100)
3720 appendPQExpBuffer(query,
3721 "SELECT tableoid, oid, proname, prolang, "
3722 "pronargs, proargtypes, prorettype, "
3723 "'{=X}' AS proacl, "
3724 "0::oid AS pronamespace, "
3725 "(%s proowner) AS rolname "
3727 "WHERE pg_proc.oid > '%u'::oid",
3729 g_last_builtin_oid);
3733 appendPQExpBuffer(query,
3735 "(SELECT oid FROM pg_class "
3736 " WHERE relname = 'pg_proc') AS tableoid, "
3737 "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);
3748 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3750 ntups = PQntuples(res);
3754 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3756 i_tableoid = PQfnumber(res, "tableoid");
3757 i_oid = PQfnumber(res, "oid");
3758 i_proname = PQfnumber(res, "proname");
3759 i_pronamespace = PQfnumber(res, "pronamespace");
3760 i_rolname = PQfnumber(res, "rolname");
3761 i_prolang = PQfnumber(res, "prolang");
3762 i_pronargs = PQfnumber(res, "pronargs");
3763 i_proargtypes = PQfnumber(res, "proargtypes");
3764 i_prorettype = PQfnumber(res, "prorettype");
3765 i_proacl = PQfnumber(res, "proacl");
3767 for (i = 0; i < ntups; i++)
3769 finfo[i].dobj.objType = DO_FUNC;
3770 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3771 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3772 AssignDumpId(&finfo[i].dobj);
3773 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3774 finfo[i].dobj.namespace =
3776 atooid(PQgetvalue(res, i, i_pronamespace)),
3777 finfo[i].dobj.catId.oid);
3778 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3779 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3780 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3781 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3782 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3783 if (finfo[i].nargs == 0)
3784 finfo[i].argtypes = NULL;
3787 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3788 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3789 finfo[i].argtypes, finfo[i].nargs);
3792 /* Decide whether we want to dump it */
3793 selectDumpableObject(&(finfo[i].dobj));
3795 if (strlen(finfo[i].rolname) == 0)
3797 "WARNING: owner of function \"%s\" appears to be invalid\n",
3798 finfo[i].dobj.name);
3803 destroyPQExpBuffer(query);
3810 * read all the user-defined tables (no indexes, no catalogs)
3811 * in the system catalogs return them in the TableInfo* structure
3813 * numTables is set to the number of tables read in
3816 getTables(Archive *fout, int *numTables)
3821 PQExpBuffer query = createPQExpBuffer();
3831 int i_relhastriggers;
3837 int i_toastfrozenxid;
3838 int i_relpersistence;
3841 int i_reltablespace;
3843 int i_toastreloptions;
3846 /* Make sure we are in proper schema */
3847 selectSourceSchema(fout, "pg_catalog");
3850 * Find all the tables and table-like objects.
3852 * We include system catalogs, so that we can work if a user table is
3853 * defined to inherit from a system catalog (pretty weird, but...)
3855 * We ignore relations that are not ordinary tables, sequences, views,
3856 * composite types, or foreign tables.
3858 * Composite-type table entries won't be dumped as such, but we have to
3859 * make a DumpableObject for them so that we can track dependencies of the
3860 * composite type (pg_depend entries for columns of the composite type
3861 * link to the pg_class entry not the pg_type entry).
3863 * Note: in this phase we should collect only a minimal amount of
3864 * information about each table, basically just enough to decide if it is
3865 * interesting. We must fetch all tables in this phase because otherwise
3866 * we cannot correctly identify inherited columns, owned sequences, etc.
3869 if (fout->remoteVersion >= 90100)
3872 * Left join to pick up dependency info linking sequences to their
3873 * owning column, if any (note this dependency is AUTO as of 8.2)
3875 appendPQExpBuffer(query,
3876 "SELECT c.tableoid, c.oid, c.relname, "
3877 "c.relacl, c.relkind, c.relnamespace, "
3878 "(%s c.relowner) AS rolname, "
3879 "c.relchecks, c.relhastriggers, "
3880 "c.relhasindex, c.relhasrules, c.relhasoids, "
3881 "c.relfrozenxid, tc.oid AS toid, "
3882 "tc.relfrozenxid AS tfrozenxid, "
3883 "c.relpersistence, "
3884 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3885 "d.refobjid AS owning_tab, "
3886 "d.refobjsubid AS owning_col, "
3887 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3888 "array_to_string(c.reloptions, ', ') AS reloptions, "
3889 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3891 "LEFT JOIN pg_depend d ON "
3892 "(c.relkind = '%c' AND "
3893 "d.classid = c.tableoid AND d.objid = c.oid AND "
3894 "d.objsubid = 0 AND "
3895 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3896 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3897 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3901 RELKIND_RELATION, RELKIND_SEQUENCE,
3902 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3903 RELKIND_FOREIGN_TABLE);
3905 else if (fout->remoteVersion >= 90000)
3908 * Left join to pick up dependency info linking sequences to their
3909 * owning column, if any (note this dependency is AUTO as of 8.2)
3911 appendPQExpBuffer(query,
3912 "SELECT c.tableoid, c.oid, c.relname, "
3913 "c.relacl, c.relkind, c.relnamespace, "
3914 "(%s c.relowner) AS rolname, "
3915 "c.relchecks, c.relhastriggers, "
3916 "c.relhasindex, c.relhasrules, c.relhasoids, "
3917 "c.relfrozenxid, tc.oid AS toid, "
3918 "tc.relfrozenxid AS tfrozenxid, "
3919 "'p' AS relpersistence, "
3920 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3921 "d.refobjid AS owning_tab, "
3922 "d.refobjsubid AS owning_col, "
3923 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3924 "array_to_string(c.reloptions, ', ') AS reloptions, "
3925 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3927 "LEFT JOIN pg_depend d ON "
3928 "(c.relkind = '%c' AND "
3929 "d.classid = c.tableoid AND d.objid = c.oid AND "
3930 "d.objsubid = 0 AND "
3931 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3932 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3933 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3937 RELKIND_RELATION, RELKIND_SEQUENCE,
3938 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3940 else if (fout->remoteVersion >= 80400)
3943 * Left join to pick up dependency info linking sequences to their
3944 * owning column, if any (note this dependency is AUTO as of 8.2)
3946 appendPQExpBuffer(query,
3947 "SELECT c.tableoid, c.oid, c.relname, "
3948 "c.relacl, c.relkind, c.relnamespace, "
3949 "(%s c.relowner) AS rolname, "
3950 "c.relchecks, c.relhastriggers, "
3951 "c.relhasindex, c.relhasrules, c.relhasoids, "
3952 "c.relfrozenxid, tc.oid AS toid, "
3953 "tc.relfrozenxid AS tfrozenxid, "
3954 "'p' AS relpersistence, "
3955 "NULL AS reloftype, "
3956 "d.refobjid AS owning_tab, "
3957 "d.refobjsubid AS owning_col, "
3958 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3959 "array_to_string(c.reloptions, ', ') AS reloptions, "
3960 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3962 "LEFT JOIN pg_depend d ON "
3963 "(c.relkind = '%c' AND "
3964 "d.classid = c.tableoid AND d.objid = c.oid AND "
3965 "d.objsubid = 0 AND "
3966 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3967 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3968 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3972 RELKIND_RELATION, RELKIND_SEQUENCE,
3973 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3975 else if (fout->remoteVersion >= 80200)
3978 * Left join to pick up dependency info linking sequences to their
3979 * owning column, if any (note this dependency is AUTO as of 8.2)
3981 appendPQExpBuffer(query,
3982 "SELECT c.tableoid, c.oid, c.relname, "
3983 "c.relacl, c.relkind, c.relnamespace, "
3984 "(%s c.relowner) AS rolname, "
3985 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
3986 "c.relhasindex, c.relhasrules, c.relhasoids, "
3987 "c.relfrozenxid, tc.oid AS toid, "
3988 "tc.relfrozenxid AS tfrozenxid, "
3989 "'p' AS relpersistence, "
3990 "NULL AS reloftype, "
3991 "d.refobjid AS owning_tab, "
3992 "d.refobjsubid AS owning_col, "
3993 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3994 "array_to_string(c.reloptions, ', ') AS reloptions, "
3995 "NULL AS toast_reloptions "
3997 "LEFT JOIN pg_depend d ON "
3998 "(c.relkind = '%c' AND "
3999 "d.classid = c.tableoid AND d.objid = c.oid AND "
4000 "d.objsubid = 0 AND "
4001 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4002 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4003 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4007 RELKIND_RELATION, RELKIND_SEQUENCE,
4008 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4010 else if (fout->remoteVersion >= 80000)
4013 * Left join to pick up dependency info linking sequences to their
4014 * owning column, if any
4016 appendPQExpBuffer(query,
4017 "SELECT c.tableoid, c.oid, relname, "
4018 "relacl, relkind, relnamespace, "
4019 "(%s relowner) AS rolname, "
4020 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4021 "relhasindex, relhasrules, relhasoids, "
4022 "0 AS relfrozenxid, "
4025 "'p' AS relpersistence, "
4026 "NULL AS reloftype, "
4027 "d.refobjid AS owning_tab, "
4028 "d.refobjsubid AS owning_col, "
4029 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4030 "NULL AS reloptions, "
4031 "NULL AS toast_reloptions "
4033 "LEFT JOIN pg_depend d ON "
4034 "(c.relkind = '%c' AND "
4035 "d.classid = c.tableoid AND d.objid = c.oid AND "
4036 "d.objsubid = 0 AND "
4037 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4038 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4042 RELKIND_RELATION, RELKIND_SEQUENCE,
4043 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4045 else if (fout->remoteVersion >= 70300)
4048 * Left join to pick up dependency info linking sequences to their
4049 * owning column, if any
4051 appendPQExpBuffer(query,
4052 "SELECT c.tableoid, c.oid, relname, "
4053 "relacl, relkind, relnamespace, "
4054 "(%s relowner) AS rolname, "
4055 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4056 "relhasindex, relhasrules, relhasoids, "
4057 "0 AS relfrozenxid, "
4060 "'p' AS relpersistence, "
4061 "NULL AS reloftype, "
4062 "d.refobjid AS owning_tab, "
4063 "d.refobjsubid AS owning_col, "
4064 "NULL AS reltablespace, "
4065 "NULL AS reloptions, "
4066 "NULL AS toast_reloptions "
4068 "LEFT JOIN pg_depend d ON "
4069 "(c.relkind = '%c' AND "
4070 "d.classid = c.tableoid AND d.objid = c.oid AND "
4071 "d.objsubid = 0 AND "
4072 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4073 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4077 RELKIND_RELATION, RELKIND_SEQUENCE,
4078 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4080 else if (fout->remoteVersion >= 70200)
4082 appendPQExpBuffer(query,
4083 "SELECT tableoid, oid, relname, relacl, relkind, "
4084 "0::oid AS relnamespace, "
4085 "(%s relowner) AS rolname, "
4086 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4087 "relhasindex, relhasrules, relhasoids, "
4088 "0 AS relfrozenxid, "
4091 "'p' AS relpersistence, "
4092 "NULL AS reloftype, "
4093 "NULL::oid AS owning_tab, "
4094 "NULL::int4 AS owning_col, "
4095 "NULL AS reltablespace, "
4096 "NULL AS reloptions, "
4097 "NULL AS toast_reloptions "
4099 "WHERE relkind IN ('%c', '%c', '%c') "
4102 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4104 else if (fout->remoteVersion >= 70100)
4106 /* all tables have oids in 7.1 */
4107 appendPQExpBuffer(query,
4108 "SELECT tableoid, oid, relname, relacl, relkind, "
4109 "0::oid AS relnamespace, "
4110 "(%s relowner) AS rolname, "
4111 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4112 "relhasindex, relhasrules, "
4113 "'t'::bool AS relhasoids, "
4114 "0 AS relfrozenxid, "
4117 "'p' AS relpersistence, "
4118 "NULL AS reloftype, "
4119 "NULL::oid AS owning_tab, "
4120 "NULL::int4 AS owning_col, "
4121 "NULL AS reltablespace, "
4122 "NULL AS reloptions, "
4123 "NULL AS toast_reloptions "
4125 "WHERE relkind IN ('%c', '%c', '%c') "
4128 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4133 * Before 7.1, view relkind was not set to 'v', so we must check if we
4134 * have a view by looking for a rule in pg_rewrite.
4136 appendPQExpBuffer(query,
4138 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4139 "oid, relname, relacl, "
4140 "CASE WHEN relhasrules and relkind = 'r' "
4141 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4142 " r.ev_class = c.oid AND r.ev_type = '1') "
4143 "THEN '%c'::\"char\" "
4144 "ELSE relkind END AS relkind,"
4145 "0::oid AS relnamespace, "
4146 "(%s relowner) AS rolname, "
4147 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4148 "relhasindex, relhasrules, "
4149 "'t'::bool AS relhasoids, "
4150 "0 as relfrozenxid, "
4153 "'p' AS relpersistence, "
4154 "NULL AS reloftype, "
4155 "NULL::oid AS owning_tab, "
4156 "NULL::int4 AS owning_col, "
4157 "NULL AS reltablespace, "
4158 "NULL AS reloptions, "
4159 "NULL AS toast_reloptions "
4161 "WHERE relkind IN ('%c', '%c') "
4165 RELKIND_RELATION, RELKIND_SEQUENCE);
4168 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4170 ntups = PQntuples(res);
4175 * Extract data from result and lock dumpable tables. We do the locking
4176 * before anything else, to minimize the window wherein a table could
4177 * disappear under us.
4179 * Note that we have to save info about all tables here, even when dumping
4180 * only one, because we don't yet know which tables might be inheritance
4181 * ancestors of the target table.
4183 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4185 i_reltableoid = PQfnumber(res, "tableoid");
4186 i_reloid = PQfnumber(res, "oid");
4187 i_relname = PQfnumber(res, "relname");
4188 i_relnamespace = PQfnumber(res, "relnamespace");
4189 i_relacl = PQfnumber(res, "relacl");
4190 i_relkind = PQfnumber(res, "relkind");
4191 i_rolname = PQfnumber(res, "rolname");
4192 i_relchecks = PQfnumber(res, "relchecks");
4193 i_relhastriggers = PQfnumber(res, "relhastriggers");
4194 i_relhasindex = PQfnumber(res, "relhasindex");
4195 i_relhasrules = PQfnumber(res, "relhasrules");
4196 i_relhasoids = PQfnumber(res, "relhasoids");
4197 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4198 i_toastoid = PQfnumber(res, "toid");
4199 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4200 i_relpersistence = PQfnumber(res, "relpersistence");
4201 i_owning_tab = PQfnumber(res, "owning_tab");
4202 i_owning_col = PQfnumber(res, "owning_col");
4203 i_reltablespace = PQfnumber(res, "reltablespace");
4204 i_reloptions = PQfnumber(res, "reloptions");
4205 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4206 i_reloftype = PQfnumber(res, "reloftype");
4208 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4211 * Arrange to fail instead of waiting forever for a table lock.
4213 * NB: this coding assumes that the only queries issued within the
4214 * following loop are LOCK TABLEs; else the timeout may be undesirably
4215 * applied to other things too.
4217 resetPQExpBuffer(query);
4218 appendPQExpBuffer(query, "SET statement_timeout = ");
4219 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4220 ExecuteSqlStatement(fout, query->data);
4223 for (i = 0; i < ntups; i++)
4225 tblinfo[i].dobj.objType = DO_TABLE;
4226 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4227 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4228 AssignDumpId(&tblinfo[i].dobj);
4229 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4230 tblinfo[i].dobj.namespace =
4232 atooid(PQgetvalue(res, i, i_relnamespace)),
4233 tblinfo[i].dobj.catId.oid);
4234 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4235 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4236 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4237 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4238 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4239 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4240 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4241 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4242 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4243 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4244 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4245 if (PQgetisnull(res, i, i_reloftype))
4246 tblinfo[i].reloftype = NULL;
4248 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4249 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4250 if (PQgetisnull(res, i, i_owning_tab))
4252 tblinfo[i].owning_tab = InvalidOid;
4253 tblinfo[i].owning_col = 0;
4257 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4258 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4260 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4261 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4262 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4264 /* other fields were zeroed above */
4267 * Decide whether we want to dump this table.
4269 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4270 tblinfo[i].dobj.dump = false;
4272 selectDumpableTable(&tblinfo[i]);
4273 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4276 * Read-lock target tables to make sure they aren't DROPPED or altered
4277 * in schema before we get around to dumping them.
4279 * Note that we don't explicitly lock parents of the target tables; we
4280 * assume our lock on the child is enough to prevent schema
4281 * alterations to parent tables.
4283 * NOTE: it'd be kinda nice to lock other relations too, not only
4284 * plain tables, but the backend doesn't presently allow that.
4286 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4288 resetPQExpBuffer(query);
4289 appendPQExpBuffer(query,
4290 "LOCK TABLE %s IN ACCESS SHARE MODE",
4291 fmtQualifiedId(fout,
4292 tblinfo[i].dobj.namespace->dobj.name,
4293 tblinfo[i].dobj.name));
4294 ExecuteSqlStatement(fout, query->data);
4297 /* Emit notice if join for owner failed */
4298 if (strlen(tblinfo[i].rolname) == 0)
4299 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4300 tblinfo[i].dobj.name);
4303 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4305 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4310 destroyPQExpBuffer(query);
4317 * identify owned sequences and mark them as dumpable if owning table is
4319 * We used to do this in getTables(), but it's better to do it after the
4320 * index used by findTableByOid() has been set up.
4323 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4328 * Force sequences that are "owned" by table columns to be dumped whenever
4329 * their owning table is being dumped.
4331 for (i = 0; i < numTables; i++)
4333 TableInfo *seqinfo = &tblinfo[i];
4334 TableInfo *owning_tab;
4336 if (!OidIsValid(seqinfo->owning_tab))
4337 continue; /* not an owned sequence */
4338 if (seqinfo->dobj.dump)
4339 continue; /* no need to search */
4340 owning_tab = findTableByOid(seqinfo->owning_tab);
4341 if (owning_tab && owning_tab->dobj.dump)
4343 seqinfo->interesting = true;
4344 seqinfo->dobj.dump = true;
4351 * read all the inheritance information
4352 * from the system catalogs return them in the InhInfo* structure
4354 * numInherits is set to the number of pairs read in
4357 getInherits(Archive *fout, int *numInherits)
4362 PQExpBuffer query = createPQExpBuffer();
4368 /* Make sure we are in proper schema */
4369 selectSourceSchema(fout, "pg_catalog");
4371 /* find all the inheritance information */
4373 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4375 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4377 ntups = PQntuples(res);
4379 *numInherits = ntups;
4381 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4383 i_inhrelid = PQfnumber(res, "inhrelid");
4384 i_inhparent = PQfnumber(res, "inhparent");
4386 for (i = 0; i < ntups; i++)
4388 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4389 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4394 destroyPQExpBuffer(query);
4401 * get information about every index on a dumpable table
4403 * Note: index data is not returned directly to the caller, but it
4404 * does get entered into the DumpableObject tables.
4407 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4411 PQExpBuffer query = createPQExpBuffer();
4414 ConstraintInfo *constrinfo;
4433 for (i = 0; i < numTables; i++)
4435 TableInfo *tbinfo = &tblinfo[i];
4437 /* Only plain tables have indexes */
4438 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4441 /* Ignore indexes of tables not to be dumped */
4442 if (!tbinfo->dobj.dump)
4446 write_msg(NULL, "reading indexes for table \"%s\"\n",
4449 /* Make sure we are in proper schema so indexdef is right */
4450 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4453 * The point of the messy-looking outer join is to find a constraint
4454 * that is related by an internal dependency link to the index. If we
4455 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4456 * assume an index won't have more than one internal dependency.
4458 * As of 9.0 we don't need to look at pg_depend but can check for a
4459 * match to pg_constraint.conindid. The check on conrelid is
4460 * redundant but useful because that column is indexed while conindid
4463 resetPQExpBuffer(query);
4464 if (fout->remoteVersion >= 90000)
4466 appendPQExpBuffer(query,
4467 "SELECT t.tableoid, t.oid, "
4468 "t.relname AS indexname, "
4469 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4470 "t.relnatts AS indnkeys, "
4471 "i.indkey, i.indisclustered, "
4472 "c.contype, c.conname, "
4473 "c.condeferrable, c.condeferred, "
4474 "c.tableoid AS contableoid, "
4476 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4477 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4478 "array_to_string(t.reloptions, ', ') AS options "
4479 "FROM pg_catalog.pg_index i "
4480 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4481 "LEFT JOIN pg_catalog.pg_constraint c "
4482 "ON (i.indrelid = c.conrelid AND "
4483 "i.indexrelid = c.conindid AND "
4484 "c.contype IN ('p','u','x')) "
4485 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4486 "ORDER BY indexname",
4487 tbinfo->dobj.catId.oid);
4489 else if (fout->remoteVersion >= 80200)
4491 appendPQExpBuffer(query,
4492 "SELECT t.tableoid, t.oid, "
4493 "t.relname AS indexname, "
4494 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4495 "t.relnatts AS indnkeys, "
4496 "i.indkey, i.indisclustered, "
4497 "c.contype, c.conname, "
4498 "c.condeferrable, c.condeferred, "
4499 "c.tableoid AS contableoid, "
4502 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4503 "array_to_string(t.reloptions, ', ') AS options "
4504 "FROM pg_catalog.pg_index i "
4505 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4506 "LEFT JOIN pg_catalog.pg_depend d "
4507 "ON (d.classid = t.tableoid "
4508 "AND d.objid = t.oid "
4509 "AND d.deptype = 'i') "
4510 "LEFT JOIN pg_catalog.pg_constraint c "
4511 "ON (d.refclassid = c.tableoid "
4512 "AND d.refobjid = c.oid) "
4513 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4514 "ORDER BY indexname",
4515 tbinfo->dobj.catId.oid);
4517 else if (fout->remoteVersion >= 80000)
4519 appendPQExpBuffer(query,
4520 "SELECT t.tableoid, t.oid, "
4521 "t.relname AS indexname, "
4522 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4523 "t.relnatts AS indnkeys, "
4524 "i.indkey, i.indisclustered, "
4525 "c.contype, c.conname, "
4526 "c.condeferrable, c.condeferred, "
4527 "c.tableoid AS contableoid, "
4530 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4532 "FROM pg_catalog.pg_index i "
4533 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4534 "LEFT JOIN pg_catalog.pg_depend d "
4535 "ON (d.classid = t.tableoid "
4536 "AND d.objid = t.oid "
4537 "AND d.deptype = 'i') "
4538 "LEFT JOIN pg_catalog.pg_constraint c "
4539 "ON (d.refclassid = c.tableoid "
4540 "AND d.refobjid = c.oid) "
4541 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4542 "ORDER BY indexname",
4543 tbinfo->dobj.catId.oid);
4545 else if (fout->remoteVersion >= 70300)
4547 appendPQExpBuffer(query,
4548 "SELECT t.tableoid, t.oid, "
4549 "t.relname AS indexname, "
4550 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4551 "t.relnatts AS indnkeys, "
4552 "i.indkey, i.indisclustered, "
4553 "c.contype, c.conname, "
4554 "c.condeferrable, c.condeferred, "
4555 "c.tableoid AS contableoid, "
4558 "NULL AS tablespace, "
4560 "FROM pg_catalog.pg_index i "
4561 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4562 "LEFT JOIN pg_catalog.pg_depend d "
4563 "ON (d.classid = t.tableoid "
4564 "AND d.objid = t.oid "
4565 "AND d.deptype = 'i') "
4566 "LEFT JOIN pg_catalog.pg_constraint c "
4567 "ON (d.refclassid = c.tableoid "
4568 "AND d.refobjid = c.oid) "
4569 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4570 "ORDER BY indexname",
4571 tbinfo->dobj.catId.oid);
4573 else if (fout->remoteVersion >= 70100)
4575 appendPQExpBuffer(query,
4576 "SELECT t.tableoid, t.oid, "
4577 "t.relname AS indexname, "
4578 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4579 "t.relnatts AS indnkeys, "
4580 "i.indkey, false AS indisclustered, "
4581 "CASE WHEN i.indisprimary THEN 'p'::char "
4582 "ELSE '0'::char END AS contype, "
4583 "t.relname AS conname, "
4584 "false AS condeferrable, "
4585 "false AS condeferred, "
4586 "0::oid AS contableoid, "
4589 "NULL AS tablespace, "
4591 "FROM pg_index i, pg_class t "
4592 "WHERE t.oid = i.indexrelid "
4593 "AND i.indrelid = '%u'::oid "
4594 "ORDER BY indexname",
4595 tbinfo->dobj.catId.oid);
4599 appendPQExpBuffer(query,
4601 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4603 "t.relname AS indexname, "
4604 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4605 "t.relnatts AS indnkeys, "
4606 "i.indkey, false AS indisclustered, "
4607 "CASE WHEN i.indisprimary THEN 'p'::char "
4608 "ELSE '0'::char END AS contype, "
4609 "t.relname AS conname, "
4610 "false AS condeferrable, "
4611 "false AS condeferred, "
4612 "0::oid AS contableoid, "
4615 "NULL AS tablespace, "
4617 "FROM pg_index i, pg_class t "
4618 "WHERE t.oid = i.indexrelid "
4619 "AND i.indrelid = '%u'::oid "
4620 "ORDER BY indexname",
4621 tbinfo->dobj.catId.oid);
4624 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4626 ntups = PQntuples(res);
4628 i_tableoid = PQfnumber(res, "tableoid");
4629 i_oid = PQfnumber(res, "oid");
4630 i_indexname = PQfnumber(res, "indexname");
4631 i_indexdef = PQfnumber(res, "indexdef");
4632 i_indnkeys = PQfnumber(res, "indnkeys");
4633 i_indkey = PQfnumber(res, "indkey");
4634 i_indisclustered = PQfnumber(res, "indisclustered");
4635 i_contype = PQfnumber(res, "contype");
4636 i_conname = PQfnumber(res, "conname");
4637 i_condeferrable = PQfnumber(res, "condeferrable");
4638 i_condeferred = PQfnumber(res, "condeferred");
4639 i_contableoid = PQfnumber(res, "contableoid");
4640 i_conoid = PQfnumber(res, "conoid");
4641 i_condef = PQfnumber(res, "condef");
4642 i_tablespace = PQfnumber(res, "tablespace");
4643 i_options = PQfnumber(res, "options");
4645 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4646 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4648 for (j = 0; j < ntups; j++)
4652 indxinfo[j].dobj.objType = DO_INDEX;
4653 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4654 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4655 AssignDumpId(&indxinfo[j].dobj);
4656 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4657 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4658 indxinfo[j].indextable = tbinfo;
4659 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4660 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4661 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4662 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4665 * In pre-7.4 releases, indkeys may contain more entries than
4666 * indnkeys says (since indnkeys will be 1 for a functional
4667 * index). We don't actually care about this case since we don't
4668 * examine indkeys except for indexes associated with PRIMARY and
4669 * UNIQUE constraints, which are never functional indexes. But we
4670 * have to allocate enough space to keep parseOidArray from
4673 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4674 parseOidArray(PQgetvalue(res, j, i_indkey),
4675 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4676 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4677 contype = *(PQgetvalue(res, j, i_contype));
4679 if (contype == 'p' || contype == 'u' || contype == 'x')
4682 * If we found a constraint matching the index, create an
4685 * In a pre-7.3 database, we take this path iff the index was
4686 * marked indisprimary.
4688 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4689 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4690 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4691 AssignDumpId(&constrinfo[j].dobj);
4692 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4693 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4694 constrinfo[j].contable = tbinfo;
4695 constrinfo[j].condomain = NULL;
4696 constrinfo[j].contype = contype;
4698 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4700 constrinfo[j].condef = NULL;
4701 constrinfo[j].confrelid = InvalidOid;
4702 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4703 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4704 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4705 constrinfo[j].conislocal = true;
4706 constrinfo[j].separate = true;
4708 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4710 /* If pre-7.3 DB, better make sure table comes first */
4711 addObjectDependency(&constrinfo[j].dobj,
4712 tbinfo->dobj.dumpId);
4716 /* Plain secondary index */
4717 indxinfo[j].indexconstraint = 0;
4724 destroyPQExpBuffer(query);
4730 * Get info about constraints on dumpable tables.
4732 * Currently handles foreign keys only.
4733 * Unique and primary key constraints are handled with indexes,
4734 * while check constraints are processed in getTableAttrs().
4737 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4741 ConstraintInfo *constrinfo;
4751 /* pg_constraint was created in 7.3, so nothing to do if older */
4752 if (fout->remoteVersion < 70300)
4755 query = createPQExpBuffer();
4757 for (i = 0; i < numTables; i++)
4759 TableInfo *tbinfo = &tblinfo[i];
4761 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4765 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4769 * select table schema to ensure constraint expr is qualified if
4772 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4774 resetPQExpBuffer(query);
4775 appendPQExpBuffer(query,
4776 "SELECT tableoid, oid, conname, confrelid, "
4777 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4778 "FROM pg_catalog.pg_constraint "
4779 "WHERE conrelid = '%u'::pg_catalog.oid "
4780 "AND contype = 'f'",
4781 tbinfo->dobj.catId.oid);
4782 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4784 ntups = PQntuples(res);
4786 i_contableoid = PQfnumber(res, "tableoid");
4787 i_conoid = PQfnumber(res, "oid");
4788 i_conname = PQfnumber(res, "conname");
4789 i_confrelid = PQfnumber(res, "confrelid");
4790 i_condef = PQfnumber(res, "condef");
4792 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4794 for (j = 0; j < ntups; j++)
4796 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4797 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4798 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4799 AssignDumpId(&constrinfo[j].dobj);
4800 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4801 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4802 constrinfo[j].contable = tbinfo;
4803 constrinfo[j].condomain = NULL;
4804 constrinfo[j].contype = 'f';
4805 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4806 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4807 constrinfo[j].conindex = 0;
4808 constrinfo[j].condeferrable = false;
4809 constrinfo[j].condeferred = false;
4810 constrinfo[j].conislocal = true;
4811 constrinfo[j].separate = true;
4817 destroyPQExpBuffer(query);
4821 * getDomainConstraints
4823 * Get info about constraints on a domain.
4826 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4829 ConstraintInfo *constrinfo;
4838 /* pg_constraint was created in 7.3, so nothing to do if older */
4839 if (fout->remoteVersion < 70300)
4843 * select appropriate schema to ensure names in constraint are properly
4846 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4848 query = createPQExpBuffer();
4850 if (fout->remoteVersion >= 90100)
4851 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4852 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4854 "FROM pg_catalog.pg_constraint "
4855 "WHERE contypid = '%u'::pg_catalog.oid "
4857 tyinfo->dobj.catId.oid);
4859 else if (fout->remoteVersion >= 70400)
4860 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4861 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4862 "true as convalidated "
4863 "FROM pg_catalog.pg_constraint "
4864 "WHERE contypid = '%u'::pg_catalog.oid "
4866 tyinfo->dobj.catId.oid);
4868 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4869 "'CHECK (' || consrc || ')' AS consrc, "
4870 "true as convalidated "
4871 "FROM pg_catalog.pg_constraint "
4872 "WHERE contypid = '%u'::pg_catalog.oid "
4874 tyinfo->dobj.catId.oid);
4876 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4878 ntups = PQntuples(res);
4880 i_tableoid = PQfnumber(res, "tableoid");
4881 i_oid = PQfnumber(res, "oid");
4882 i_conname = PQfnumber(res, "conname");
4883 i_consrc = PQfnumber(res, "consrc");
4885 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4887 tyinfo->nDomChecks = ntups;
4888 tyinfo->domChecks = constrinfo;
4890 for (i = 0; i < ntups; i++)
4892 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4894 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4895 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4896 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4897 AssignDumpId(&constrinfo[i].dobj);
4898 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4899 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4900 constrinfo[i].contable = NULL;
4901 constrinfo[i].condomain = tyinfo;
4902 constrinfo[i].contype = 'c';
4903 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4904 constrinfo[i].confrelid = InvalidOid;
4905 constrinfo[i].conindex = 0;
4906 constrinfo[i].condeferrable = false;
4907 constrinfo[i].condeferred = false;
4908 constrinfo[i].conislocal = true;
4910 constrinfo[i].separate = !validated;
4913 * Make the domain depend on the constraint, ensuring it won't be
4914 * output till any constraint dependencies are OK. If the constraint
4915 * has not been validated, it's going to be dumped after the domain
4916 * anyway, so this doesn't matter.
4919 addObjectDependency(&tyinfo->dobj,
4920 constrinfo[i].dobj.dumpId);
4925 destroyPQExpBuffer(query);
4930 * get basic information about every rule in the system
4932 * numRules is set to the number of rules read in
4935 getRules(Archive *fout, int *numRules)
4940 PQExpBuffer query = createPQExpBuffer();
4950 /* Make sure we are in proper schema */
4951 selectSourceSchema(fout, "pg_catalog");
4953 if (fout->remoteVersion >= 80300)
4955 appendPQExpBuffer(query, "SELECT "
4956 "tableoid, oid, rulename, "
4957 "ev_class AS ruletable, ev_type, is_instead, "
4962 else if (fout->remoteVersion >= 70100)
4964 appendPQExpBuffer(query, "SELECT "
4965 "tableoid, oid, rulename, "
4966 "ev_class AS ruletable, ev_type, is_instead, "
4967 "'O'::char AS ev_enabled "
4973 appendPQExpBuffer(query, "SELECT "
4974 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4976 "ev_class AS ruletable, ev_type, is_instead, "
4977 "'O'::char AS ev_enabled "
4982 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4984 ntups = PQntuples(res);
4988 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
4990 i_tableoid = PQfnumber(res, "tableoid");
4991 i_oid = PQfnumber(res, "oid");
4992 i_rulename = PQfnumber(res, "rulename");
4993 i_ruletable = PQfnumber(res, "ruletable");
4994 i_ev_type = PQfnumber(res, "ev_type");
4995 i_is_instead = PQfnumber(res, "is_instead");
4996 i_ev_enabled = PQfnumber(res, "ev_enabled");
4998 for (i = 0; i < ntups; i++)
5002 ruleinfo[i].dobj.objType = DO_RULE;
5003 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5004 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5005 AssignDumpId(&ruleinfo[i].dobj);
5006 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5007 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5008 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5009 if (ruleinfo[i].ruletable == NULL)
5010 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5011 ruletableoid, ruleinfo[i].dobj.catId.oid);
5012 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5013 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5014 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5015 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5016 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5017 if (ruleinfo[i].ruletable)
5020 * If the table is a view, force its ON SELECT rule to be sorted
5021 * before the view itself --- this ensures that any dependencies
5022 * for the rule affect the table's positioning. Other rules are
5023 * forced to appear after their table.
5025 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5026 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5028 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5029 ruleinfo[i].dobj.dumpId);
5030 /* We'll merge the rule into CREATE VIEW, if possible */
5031 ruleinfo[i].separate = false;
5035 addObjectDependency(&ruleinfo[i].dobj,
5036 ruleinfo[i].ruletable->dobj.dumpId);
5037 ruleinfo[i].separate = true;
5041 ruleinfo[i].separate = true;
5046 destroyPQExpBuffer(query);
5053 * get information about every trigger on a dumpable table
5055 * Note: trigger data is not returned directly to the caller, but it
5056 * does get entered into the DumpableObject tables.
5059 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5063 PQExpBuffer query = createPQExpBuffer();
5065 TriggerInfo *tginfo;
5083 for (i = 0; i < numTables; i++)
5085 TableInfo *tbinfo = &tblinfo[i];
5087 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5091 write_msg(NULL, "reading triggers for table \"%s\"\n",
5095 * select table schema to ensure regproc name is qualified if needed
5097 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5099 resetPQExpBuffer(query);
5100 if (fout->remoteVersion >= 90000)
5103 * NB: think not to use pretty=true in pg_get_triggerdef. It
5104 * could result in non-forward-compatible dumps of WHEN clauses
5105 * due to under-parenthesization.
5107 appendPQExpBuffer(query,
5109 "tgfoid::pg_catalog.regproc AS tgfname, "
5110 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5111 "tgenabled, tableoid, oid "
5112 "FROM pg_catalog.pg_trigger t "
5113 "WHERE tgrelid = '%u'::pg_catalog.oid "
5114 "AND NOT tgisinternal",
5115 tbinfo->dobj.catId.oid);
5117 else if (fout->remoteVersion >= 80300)
5120 * We ignore triggers that are tied to a foreign-key constraint
5122 appendPQExpBuffer(query,
5124 "tgfoid::pg_catalog.regproc AS tgfname, "
5125 "tgtype, tgnargs, tgargs, tgenabled, "
5126 "tgisconstraint, tgconstrname, tgdeferrable, "
5127 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5128 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5129 "FROM pg_catalog.pg_trigger t "
5130 "WHERE tgrelid = '%u'::pg_catalog.oid "
5131 "AND tgconstraint = 0",
5132 tbinfo->dobj.catId.oid);
5134 else if (fout->remoteVersion >= 70300)
5137 * We ignore triggers that are tied to a foreign-key constraint,
5138 * but in these versions we have to grovel through pg_constraint
5141 appendPQExpBuffer(query,
5143 "tgfoid::pg_catalog.regproc AS tgfname, "
5144 "tgtype, tgnargs, tgargs, tgenabled, "
5145 "tgisconstraint, tgconstrname, tgdeferrable, "
5146 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5147 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5148 "FROM pg_catalog.pg_trigger t "
5149 "WHERE tgrelid = '%u'::pg_catalog.oid "
5150 "AND (NOT tgisconstraint "
5152 " (SELECT 1 FROM pg_catalog.pg_depend d "
5153 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5154 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5155 tbinfo->dobj.catId.oid);
5157 else if (fout->remoteVersion >= 70100)
5159 appendPQExpBuffer(query,
5160 "SELECT tgname, tgfoid::regproc AS tgfname, "
5161 "tgtype, tgnargs, tgargs, tgenabled, "
5162 "tgisconstraint, tgconstrname, tgdeferrable, "
5163 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5164 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5165 " AS tgconstrrelname "
5167 "WHERE tgrelid = '%u'::oid",
5168 tbinfo->dobj.catId.oid);
5172 appendPQExpBuffer(query,
5173 "SELECT tgname, tgfoid::regproc AS tgfname, "
5174 "tgtype, tgnargs, tgargs, tgenabled, "
5175 "tgisconstraint, tgconstrname, tgdeferrable, "
5176 "tgconstrrelid, tginitdeferred, "
5177 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5179 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5180 " AS tgconstrrelname "
5182 "WHERE tgrelid = '%u'::oid",
5183 tbinfo->dobj.catId.oid);
5185 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5187 ntups = PQntuples(res);
5189 i_tableoid = PQfnumber(res, "tableoid");
5190 i_oid = PQfnumber(res, "oid");
5191 i_tgname = PQfnumber(res, "tgname");
5192 i_tgfname = PQfnumber(res, "tgfname");
5193 i_tgtype = PQfnumber(res, "tgtype");
5194 i_tgnargs = PQfnumber(res, "tgnargs");
5195 i_tgargs = PQfnumber(res, "tgargs");
5196 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5197 i_tgconstrname = PQfnumber(res, "tgconstrname");
5198 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5199 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5200 i_tgenabled = PQfnumber(res, "tgenabled");
5201 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5202 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5203 i_tgdef = PQfnumber(res, "tgdef");
5205 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5207 for (j = 0; j < ntups; j++)
5209 tginfo[j].dobj.objType = DO_TRIGGER;
5210 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5211 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5212 AssignDumpId(&tginfo[j].dobj);
5213 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5214 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5215 tginfo[j].tgtable = tbinfo;
5216 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5219 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5221 /* remaining fields are not valid if we have tgdef */
5222 tginfo[j].tgfname = NULL;
5223 tginfo[j].tgtype = 0;
5224 tginfo[j].tgnargs = 0;
5225 tginfo[j].tgargs = NULL;
5226 tginfo[j].tgisconstraint = false;
5227 tginfo[j].tgdeferrable = false;
5228 tginfo[j].tginitdeferred = false;
5229 tginfo[j].tgconstrname = NULL;
5230 tginfo[j].tgconstrrelid = InvalidOid;
5231 tginfo[j].tgconstrrelname = NULL;
5235 tginfo[j].tgdef = NULL;
5237 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5238 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5239 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5240 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5241 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5242 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5243 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5245 if (tginfo[j].tgisconstraint)
5247 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5248 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5249 if (OidIsValid(tginfo[j].tgconstrrelid))
5251 if (PQgetisnull(res, j, i_tgconstrrelname))
5252 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5253 tginfo[j].dobj.name,
5255 tginfo[j].tgconstrrelid);
5256 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5259 tginfo[j].tgconstrrelname = NULL;
5263 tginfo[j].tgconstrname = NULL;
5264 tginfo[j].tgconstrrelid = InvalidOid;
5265 tginfo[j].tgconstrrelname = NULL;
5273 destroyPQExpBuffer(query);
5278 * get basic information about every procedural language in the system
5280 * numProcLangs is set to the number of langs read in
5282 * NB: this must run after getFuncs() because we assume we can do
5286 getProcLangs(Archive *fout, int *numProcLangs)
5291 PQExpBuffer query = createPQExpBuffer();
5292 ProcLangInfo *planginfo;
5297 int i_lanplcallfoid;
5303 /* Make sure we are in proper schema */
5304 selectSourceSchema(fout, "pg_catalog");
5306 if (fout->remoteVersion >= 90000)
5308 /* pg_language has a laninline column */
5309 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5310 "lanname, lanpltrusted, lanplcallfoid, "
5311 "laninline, lanvalidator, lanacl, "
5312 "(%s lanowner) AS lanowner "
5318 else if (fout->remoteVersion >= 80300)
5320 /* pg_language has a lanowner column */
5321 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5322 "lanname, lanpltrusted, lanplcallfoid, "
5323 "lanvalidator, lanacl, "
5324 "(%s lanowner) AS lanowner "
5330 else if (fout->remoteVersion >= 80100)
5332 /* Languages are owned by the bootstrap superuser, OID 10 */
5333 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5334 "(%s '10') AS lanowner "
5340 else if (fout->remoteVersion >= 70400)
5342 /* Languages are owned by the bootstrap superuser, sysid 1 */
5343 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5344 "(%s '1') AS lanowner "
5350 else if (fout->remoteVersion >= 70100)
5352 /* No clear notion of an owner at all before 7.4 ... */
5353 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5359 appendPQExpBuffer(query, "SELECT "
5360 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5361 "oid, * FROM pg_language "
5366 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5368 ntups = PQntuples(res);
5370 *numProcLangs = ntups;
5372 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5374 i_tableoid = PQfnumber(res, "tableoid");
5375 i_oid = PQfnumber(res, "oid");
5376 i_lanname = PQfnumber(res, "lanname");
5377 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5378 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5379 /* these may fail and return -1: */
5380 i_laninline = PQfnumber(res, "laninline");
5381 i_lanvalidator = PQfnumber(res, "lanvalidator");
5382 i_lanacl = PQfnumber(res, "lanacl");
5383 i_lanowner = PQfnumber(res, "lanowner");
5385 for (i = 0; i < ntups; i++)
5387 planginfo[i].dobj.objType = DO_PROCLANG;
5388 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5389 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5390 AssignDumpId(&planginfo[i].dobj);
5392 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5393 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5394 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5395 if (i_laninline >= 0)
5396 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5398 planginfo[i].laninline = InvalidOid;
5399 if (i_lanvalidator >= 0)
5400 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5402 planginfo[i].lanvalidator = InvalidOid;
5404 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5406 planginfo[i].lanacl = pg_strdup("{=U}");
5407 if (i_lanowner >= 0)
5408 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5410 planginfo[i].lanowner = pg_strdup("");
5412 if (fout->remoteVersion < 70300)
5415 * We need to make a dependency to ensure the function will be
5416 * dumped first. (In 7.3 and later the regular dependency
5417 * mechanism will handle this for us.)
5419 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5422 addObjectDependency(&planginfo[i].dobj,
5423 funcInfo->dobj.dumpId);
5429 destroyPQExpBuffer(query);
5436 * get basic information about every cast in the system
5438 * numCasts is set to the number of casts read in
5441 getCasts(Archive *fout, int *numCasts)
5446 PQExpBuffer query = createPQExpBuffer();
5456 /* Make sure we are in proper schema */
5457 selectSourceSchema(fout, "pg_catalog");
5459 if (fout->remoteVersion >= 80400)
5461 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5462 "castsource, casttarget, castfunc, castcontext, "
5464 "FROM pg_cast ORDER BY 3,4");
5466 else if (fout->remoteVersion >= 70300)
5468 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5469 "castsource, casttarget, castfunc, castcontext, "
5470 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5471 "FROM pg_cast ORDER BY 3,4");
5475 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5476 "t1.oid AS castsource, t2.oid AS casttarget, "
5477 "p.oid AS castfunc, 'e' AS castcontext, "
5478 "'f' AS castmethod "
5479 "FROM pg_type t1, pg_type t2, pg_proc p "
5480 "WHERE p.pronargs = 1 AND "
5481 "p.proargtypes[0] = t1.oid AND "
5482 "p.prorettype = t2.oid AND p.proname = t2.typname "
5486 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5488 ntups = PQntuples(res);
5492 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5494 i_tableoid = PQfnumber(res, "tableoid");
5495 i_oid = PQfnumber(res, "oid");
5496 i_castsource = PQfnumber(res, "castsource");
5497 i_casttarget = PQfnumber(res, "casttarget");
5498 i_castfunc = PQfnumber(res, "castfunc");
5499 i_castcontext = PQfnumber(res, "castcontext");
5500 i_castmethod = PQfnumber(res, "castmethod");
5502 for (i = 0; i < ntups; i++)
5504 PQExpBufferData namebuf;
5505 TypeInfo *sTypeInfo;
5506 TypeInfo *tTypeInfo;
5508 castinfo[i].dobj.objType = DO_CAST;
5509 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5510 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5511 AssignDumpId(&castinfo[i].dobj);
5512 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5513 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5514 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5515 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5516 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5519 * Try to name cast as concatenation of typnames. This is only used
5520 * for purposes of sorting. If we fail to find either type, the name
5521 * will be an empty string.
5523 initPQExpBuffer(&namebuf);
5524 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5525 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5526 if (sTypeInfo && tTypeInfo)
5527 appendPQExpBuffer(&namebuf, "%s %s",
5528 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5529 castinfo[i].dobj.name = namebuf.data;
5531 if (OidIsValid(castinfo[i].castfunc))
5534 * We need to make a dependency to ensure the function will be
5535 * dumped first. (In 7.3 and later the regular dependency
5536 * mechanism will handle this for us.)
5540 funcInfo = findFuncByOid(castinfo[i].castfunc);
5542 addObjectDependency(&castinfo[i].dobj,
5543 funcInfo->dobj.dumpId);
5549 destroyPQExpBuffer(query);
5556 * for each interesting table, read info about its attributes
5557 * (names, types, default values, CHECK constraints, etc)
5559 * This is implemented in a very inefficient way right now, looping
5560 * through the tblinfo and doing a join per table to find the attrs and their
5561 * types. However, because we want type names and so forth to be named
5562 * relative to the schema of each table, we couldn't do it in just one
5563 * query. (Maybe one query per schema?)
5568 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5572 PQExpBuffer q = createPQExpBuffer();
5577 int i_attstattarget;
5588 int i_attfdwoptions;
5593 for (i = 0; i < numTables; i++)
5595 TableInfo *tbinfo = &tblinfo[i];
5597 /* Don't bother to collect info for sequences */
5598 if (tbinfo->relkind == RELKIND_SEQUENCE)
5601 /* Don't bother with uninteresting tables, either */
5602 if (!tbinfo->interesting)
5606 * Make sure we are in proper schema for this table; this allows
5607 * correct retrieval of formatted type names and default exprs
5609 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5611 /* find all the user attributes and their types */
5614 * we must read the attribute names in attribute number order! because
5615 * we will use the attnum to index into the attnames array later. We
5616 * actually ask to order by "attrelid, attnum" because (at least up to
5617 * 7.3) the planner is not smart enough to realize it needn't re-sort
5618 * the output of an indexscan on pg_attribute_relid_attnum_index.
5621 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5624 resetPQExpBuffer(q);
5626 if (fout->remoteVersion >= 90200)
5629 * attfdwoptions is new in 9.2.
5631 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5632 "a.attstattarget, a.attstorage, t.typstorage, "
5633 "a.attnotnull, a.atthasdef, a.attisdropped, "
5634 "a.attlen, a.attalign, a.attislocal, "
5635 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5636 "array_to_string(a.attoptions, ', ') AS attoptions, "
5637 "CASE WHEN a.attcollation <> t.typcollation "
5638 "THEN a.attcollation ELSE 0 END AS attcollation, "
5639 "pg_catalog.array_to_string(ARRAY("
5640 "SELECT pg_catalog.quote_ident(option_name) || "
5641 "' ' || pg_catalog.quote_literal(option_value) "
5642 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5643 "ORDER BY option_name"
5644 "), E',\n ') AS attfdwoptions "
5645 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5646 "ON a.atttypid = t.oid "
5647 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5648 "AND a.attnum > 0::pg_catalog.int2 "
5649 "ORDER BY a.attrelid, a.attnum",
5650 tbinfo->dobj.catId.oid);
5652 else if (fout->remoteVersion >= 90100)
5655 * attcollation is new in 9.1. Since we only want to dump COLLATE
5656 * clauses for attributes whose collation is different from their
5657 * type's default, we use a CASE here to suppress uninteresting
5658 * attcollations cheaply.
5660 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5661 "a.attstattarget, a.attstorage, t.typstorage, "
5662 "a.attnotnull, a.atthasdef, a.attisdropped, "
5663 "a.attlen, a.attalign, a.attislocal, "
5664 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5665 "array_to_string(a.attoptions, ', ') AS attoptions, "
5666 "CASE WHEN a.attcollation <> t.typcollation "
5667 "THEN a.attcollation ELSE 0 END AS attcollation, "
5668 "NULL AS attfdwoptions "
5669 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5670 "ON a.atttypid = t.oid "
5671 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5672 "AND a.attnum > 0::pg_catalog.int2 "
5673 "ORDER BY a.attrelid, a.attnum",
5674 tbinfo->dobj.catId.oid);
5676 else if (fout->remoteVersion >= 90000)
5678 /* attoptions is new in 9.0 */
5679 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5680 "a.attstattarget, a.attstorage, t.typstorage, "
5681 "a.attnotnull, a.atthasdef, a.attisdropped, "
5682 "a.attlen, a.attalign, a.attislocal, "
5683 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5684 "array_to_string(a.attoptions, ', ') AS attoptions, "
5685 "0 AS attcollation, "
5686 "NULL AS attfdwoptions "
5687 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5688 "ON a.atttypid = t.oid "
5689 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5690 "AND a.attnum > 0::pg_catalog.int2 "
5691 "ORDER BY a.attrelid, a.attnum",
5692 tbinfo->dobj.catId.oid);
5694 else if (fout->remoteVersion >= 70300)
5696 /* need left join here to not fail on dropped columns ... */
5697 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5698 "a.attstattarget, a.attstorage, t.typstorage, "
5699 "a.attnotnull, a.atthasdef, a.attisdropped, "
5700 "a.attlen, a.attalign, a.attislocal, "
5701 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5702 "'' AS attoptions, 0 AS attcollation, "
5703 "NULL AS attfdwoptions "
5704 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5705 "ON a.atttypid = t.oid "
5706 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5707 "AND a.attnum > 0::pg_catalog.int2 "
5708 "ORDER BY a.attrelid, a.attnum",
5709 tbinfo->dobj.catId.oid);
5711 else if (fout->remoteVersion >= 70100)
5714 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5715 * we don't dump it because we can't tell whether it's been
5716 * explicitly set or was just a default.
5718 * attislocal doesn't exist before 7.3, either; in older databases
5719 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5721 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5722 "-1 AS attstattarget, a.attstorage, "
5723 "t.typstorage, a.attnotnull, a.atthasdef, "
5724 "false AS attisdropped, a.attlen, "
5725 "a.attalign, true AS attislocal, "
5726 "format_type(t.oid,a.atttypmod) AS atttypname, "
5727 "'' AS attoptions, 0 AS attcollation, "
5728 "NULL AS attfdwoptions "
5729 "FROM pg_attribute a LEFT JOIN pg_type t "
5730 "ON a.atttypid = t.oid "
5731 "WHERE a.attrelid = '%u'::oid "
5732 "AND a.attnum > 0::int2 "
5733 "ORDER BY a.attrelid, a.attnum",
5734 tbinfo->dobj.catId.oid);
5738 /* format_type not available before 7.1 */
5739 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5740 "-1 AS attstattarget, "
5741 "attstorage, attstorage AS typstorage, "
5742 "attnotnull, atthasdef, false AS attisdropped, "
5743 "attlen, attalign, "
5744 "true AS attislocal, "
5745 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5746 "'' AS attoptions, 0 AS attcollation, "
5747 "NULL AS attfdwoptions "
5748 "FROM pg_attribute a "
5749 "WHERE attrelid = '%u'::oid "
5750 "AND attnum > 0::int2 "
5751 "ORDER BY attrelid, attnum",
5752 tbinfo->dobj.catId.oid);
5755 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5757 ntups = PQntuples(res);
5759 i_attnum = PQfnumber(res, "attnum");
5760 i_attname = PQfnumber(res, "attname");
5761 i_atttypname = PQfnumber(res, "atttypname");
5762 i_atttypmod = PQfnumber(res, "atttypmod");
5763 i_attstattarget = PQfnumber(res, "attstattarget");
5764 i_attstorage = PQfnumber(res, "attstorage");
5765 i_typstorage = PQfnumber(res, "typstorage");
5766 i_attnotnull = PQfnumber(res, "attnotnull");
5767 i_atthasdef = PQfnumber(res, "atthasdef");
5768 i_attisdropped = PQfnumber(res, "attisdropped");
5769 i_attlen = PQfnumber(res, "attlen");
5770 i_attalign = PQfnumber(res, "attalign");
5771 i_attislocal = PQfnumber(res, "attislocal");
5772 i_attoptions = PQfnumber(res, "attoptions");
5773 i_attcollation = PQfnumber(res, "attcollation");
5774 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5776 tbinfo->numatts = ntups;
5777 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5778 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5779 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5780 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5781 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5782 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5783 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5784 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5785 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5786 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5787 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5788 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5789 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5790 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5791 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5792 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5793 hasdefaults = false;
5795 for (j = 0; j < ntups; j++)
5797 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5799 "invalid column numbering in table \"%s\"\n",
5801 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5802 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5803 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5804 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5805 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5806 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5807 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5808 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5809 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5810 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5811 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5812 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5813 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5814 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5815 tbinfo->attrdefs[j] = NULL; /* fix below */
5816 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5818 /* these flags will be set in flagInhAttrs() */
5819 tbinfo->inhNotNull[j] = false;
5825 * Get info about column defaults
5829 AttrDefInfo *attrdefs;
5833 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5836 resetPQExpBuffer(q);
5837 if (fout->remoteVersion >= 70300)
5839 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5840 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5841 "FROM pg_catalog.pg_attrdef "
5842 "WHERE adrelid = '%u'::pg_catalog.oid",
5843 tbinfo->dobj.catId.oid);
5845 else if (fout->remoteVersion >= 70200)
5847 /* 7.2 did not have OIDs in pg_attrdef */
5848 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5849 "pg_get_expr(adbin, adrelid) AS adsrc "
5851 "WHERE adrelid = '%u'::oid",
5852 tbinfo->dobj.catId.oid);
5854 else if (fout->remoteVersion >= 70100)
5856 /* no pg_get_expr, so must rely on adsrc */
5857 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5859 "WHERE adrelid = '%u'::oid",
5860 tbinfo->dobj.catId.oid);
5864 /* no pg_get_expr, no tableoid either */
5865 appendPQExpBuffer(q, "SELECT "
5866 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5867 "oid, adnum, adsrc "
5869 "WHERE adrelid = '%u'::oid",
5870 tbinfo->dobj.catId.oid);
5872 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5874 numDefaults = PQntuples(res);
5875 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5877 for (j = 0; j < numDefaults; j++)
5881 adnum = atoi(PQgetvalue(res, j, 2));
5883 if (adnum <= 0 || adnum > ntups)
5885 "invalid adnum value %d for table \"%s\"\n",
5886 adnum, tbinfo->dobj.name);
5889 * dropped columns shouldn't have defaults, but just in case,
5892 if (tbinfo->attisdropped[adnum - 1])
5895 attrdefs[j].dobj.objType = DO_ATTRDEF;
5896 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5897 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5898 AssignDumpId(&attrdefs[j].dobj);
5899 attrdefs[j].adtable = tbinfo;
5900 attrdefs[j].adnum = adnum;
5901 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5903 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5904 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5906 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5909 * Defaults on a VIEW must always be dumped as separate ALTER
5910 * TABLE commands. Defaults on regular tables are dumped as
5911 * part of the CREATE TABLE if possible, which it won't be
5912 * if the column is not going to be emitted explicitly.
5914 if (tbinfo->relkind == RELKIND_VIEW)
5916 attrdefs[j].separate = true;
5917 /* needed in case pre-7.3 DB: */
5918 addObjectDependency(&attrdefs[j].dobj,
5919 tbinfo->dobj.dumpId);
5921 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5923 /* column will be suppressed, print default separately */
5924 attrdefs[j].separate = true;
5925 /* needed in case pre-7.3 DB: */
5926 addObjectDependency(&attrdefs[j].dobj,
5927 tbinfo->dobj.dumpId);
5931 attrdefs[j].separate = false;
5933 * Mark the default as needing to appear before the table,
5934 * so that any dependencies it has must be emitted before
5935 * the CREATE TABLE. If this is not possible, we'll
5936 * change to "separate" mode while sorting dependencies.
5938 addObjectDependency(&tbinfo->dobj,
5939 attrdefs[j].dobj.dumpId);
5942 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5948 * Get info about table CHECK constraints
5950 if (tbinfo->ncheck > 0)
5952 ConstraintInfo *constrs;
5956 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5959 resetPQExpBuffer(q);
5960 if (fout->remoteVersion >= 90200)
5963 * convalidated is new in 9.2 (actually, it is there in 9.1,
5964 * but it wasn't ever false for check constraints until 9.2).
5966 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5967 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5968 "conislocal, convalidated "
5969 "FROM pg_catalog.pg_constraint "
5970 "WHERE conrelid = '%u'::pg_catalog.oid "
5971 " AND contype = 'c' "
5973 tbinfo->dobj.catId.oid);
5975 else if (fout->remoteVersion >= 80400)
5977 /* conislocal is new in 8.4 */
5978 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5979 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5980 "conislocal, true AS convalidated "
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 >= 70400)
5989 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5990 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5991 "true AS conislocal, true AS convalidated "
5992 "FROM pg_catalog.pg_constraint "
5993 "WHERE conrelid = '%u'::pg_catalog.oid "
5994 " AND contype = 'c' "
5996 tbinfo->dobj.catId.oid);
5998 else if (fout->remoteVersion >= 70300)
6000 /* no pg_get_constraintdef, must use consrc */
6001 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6002 "'CHECK (' || consrc || ')' AS consrc, "
6003 "true AS conislocal, true AS convalidated "
6004 "FROM pg_catalog.pg_constraint "
6005 "WHERE conrelid = '%u'::pg_catalog.oid "
6006 " AND contype = 'c' "
6008 tbinfo->dobj.catId.oid);
6010 else if (fout->remoteVersion >= 70200)
6012 /* 7.2 did not have OIDs in pg_relcheck */
6013 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6014 "rcname AS conname, "
6015 "'CHECK (' || rcsrc || ')' AS consrc, "
6016 "true AS conislocal, true AS convalidated "
6018 "WHERE rcrelid = '%u'::oid "
6020 tbinfo->dobj.catId.oid);
6022 else if (fout->remoteVersion >= 70100)
6024 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6025 "rcname AS conname, "
6026 "'CHECK (' || rcsrc || ')' AS consrc, "
6027 "true AS conislocal, true AS convalidated "
6029 "WHERE rcrelid = '%u'::oid "
6031 tbinfo->dobj.catId.oid);
6035 /* no tableoid in 7.0 */
6036 appendPQExpBuffer(q, "SELECT "
6037 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6038 "oid, rcname AS conname, "
6039 "'CHECK (' || rcsrc || ')' AS consrc, "
6040 "true AS conislocal, true AS convalidated "
6042 "WHERE rcrelid = '%u'::oid "
6044 tbinfo->dobj.catId.oid);
6046 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6048 numConstrs = PQntuples(res);
6049 if (numConstrs != tbinfo->ncheck)
6051 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6052 "expected %d check constraints on table \"%s\" but found %d\n",
6054 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6055 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6059 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6060 tbinfo->checkexprs = constrs;
6062 for (j = 0; j < numConstrs; j++)
6064 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6066 constrs[j].dobj.objType = DO_CONSTRAINT;
6067 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6068 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6069 AssignDumpId(&constrs[j].dobj);
6070 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6071 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6072 constrs[j].contable = tbinfo;
6073 constrs[j].condomain = NULL;
6074 constrs[j].contype = 'c';
6075 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6076 constrs[j].confrelid = InvalidOid;
6077 constrs[j].conindex = 0;
6078 constrs[j].condeferrable = false;
6079 constrs[j].condeferred = false;
6080 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6082 * An unvalidated constraint needs to be dumped separately, so
6083 * that potentially-violating existing data is loaded before
6086 constrs[j].separate = !validated;
6088 constrs[j].dobj.dump = tbinfo->dobj.dump;
6091 * Mark the constraint as needing to appear before the table
6092 * --- this is so that any other dependencies of the
6093 * constraint will be emitted before we try to create the
6094 * table. If the constraint is to be dumped separately, it will be
6095 * dumped after data is loaded anyway, so don't do it. (There's
6096 * an automatic dependency in the opposite direction anyway, so
6097 * don't need to add one manually here.)
6099 if (!constrs[j].separate)
6100 addObjectDependency(&tbinfo->dobj,
6101 constrs[j].dobj.dumpId);
6104 * If the constraint is inherited, this will be detected later
6105 * (in pre-8.4 databases). We also detect later if the
6106 * constraint must be split out from the table definition.
6113 destroyPQExpBuffer(q);
6117 * Test whether a column should be printed as part of table's CREATE TABLE.
6118 * Column number is zero-based.
6120 * Normally this is always true, but it's false for dropped columns, as well
6121 * as those that were inherited without any local definition. (If we print
6122 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6123 * However, in binary_upgrade mode, we must print all such columns anyway and
6124 * fix the attislocal/attisdropped state later, so as to keep control of the
6125 * physical column order.
6127 * This function exists because there are scattered nonobvious places that
6128 * must be kept in sync with this decision.
6131 shouldPrintColumn(TableInfo *tbinfo, int colno)
6135 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6141 * read all text search parsers in the system catalogs and return them
6142 * in the TSParserInfo* structure
6144 * numTSParsers is set to the number of parsers read in
6147 getTSParsers(Archive *fout, int *numTSParsers)
6153 TSParserInfo *prsinfo;
6164 /* Before 8.3, there is no built-in text search support */
6165 if (fout->remoteVersion < 80300)
6171 query = createPQExpBuffer();
6174 * find all text search objects, including builtin ones; we filter out
6175 * system-defined objects at dump-out time.
6178 /* Make sure we are in proper schema */
6179 selectSourceSchema(fout, "pg_catalog");
6181 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6182 "prsstart::oid, prstoken::oid, "
6183 "prsend::oid, prsheadline::oid, prslextype::oid "
6184 "FROM pg_ts_parser");
6186 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6188 ntups = PQntuples(res);
6189 *numTSParsers = ntups;
6191 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6193 i_tableoid = PQfnumber(res, "tableoid");
6194 i_oid = PQfnumber(res, "oid");
6195 i_prsname = PQfnumber(res, "prsname");
6196 i_prsnamespace = PQfnumber(res, "prsnamespace");
6197 i_prsstart = PQfnumber(res, "prsstart");
6198 i_prstoken = PQfnumber(res, "prstoken");
6199 i_prsend = PQfnumber(res, "prsend");
6200 i_prsheadline = PQfnumber(res, "prsheadline");
6201 i_prslextype = PQfnumber(res, "prslextype");
6203 for (i = 0; i < ntups; i++)
6205 prsinfo[i].dobj.objType = DO_TSPARSER;
6206 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6207 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6208 AssignDumpId(&prsinfo[i].dobj);
6209 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6210 prsinfo[i].dobj.namespace =
6212 atooid(PQgetvalue(res, i, i_prsnamespace)),
6213 prsinfo[i].dobj.catId.oid);
6214 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6215 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6216 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6217 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6218 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6220 /* Decide whether we want to dump it */
6221 selectDumpableObject(&(prsinfo[i].dobj));
6226 destroyPQExpBuffer(query);
6232 * getTSDictionaries:
6233 * read all text search dictionaries in the system catalogs and return them
6234 * in the TSDictInfo* structure
6236 * numTSDicts is set to the number of dictionaries read in
6239 getTSDictionaries(Archive *fout, int *numTSDicts)
6245 TSDictInfo *dictinfo;
6249 int i_dictnamespace;
6252 int i_dictinitoption;
6254 /* Before 8.3, there is no built-in text search support */
6255 if (fout->remoteVersion < 80300)
6261 query = createPQExpBuffer();
6263 /* Make sure we are in proper schema */
6264 selectSourceSchema(fout, "pg_catalog");
6266 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6267 "dictnamespace, (%s dictowner) AS rolname, "
6268 "dicttemplate, dictinitoption "
6272 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6274 ntups = PQntuples(res);
6275 *numTSDicts = ntups;
6277 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6279 i_tableoid = PQfnumber(res, "tableoid");
6280 i_oid = PQfnumber(res, "oid");
6281 i_dictname = PQfnumber(res, "dictname");
6282 i_dictnamespace = PQfnumber(res, "dictnamespace");
6283 i_rolname = PQfnumber(res, "rolname");
6284 i_dictinitoption = PQfnumber(res, "dictinitoption");
6285 i_dicttemplate = PQfnumber(res, "dicttemplate");
6287 for (i = 0; i < ntups; i++)
6289 dictinfo[i].dobj.objType = DO_TSDICT;
6290 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6291 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6292 AssignDumpId(&dictinfo[i].dobj);
6293 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6294 dictinfo[i].dobj.namespace =
6296 atooid(PQgetvalue(res, i, i_dictnamespace)),
6297 dictinfo[i].dobj.catId.oid);
6298 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6299 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6300 if (PQgetisnull(res, i, i_dictinitoption))
6301 dictinfo[i].dictinitoption = NULL;
6303 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6305 /* Decide whether we want to dump it */
6306 selectDumpableObject(&(dictinfo[i].dobj));
6311 destroyPQExpBuffer(query);
6318 * read all text search templates in the system catalogs and return them
6319 * in the TSTemplateInfo* structure
6321 * numTSTemplates is set to the number of templates read in
6324 getTSTemplates(Archive *fout, int *numTSTemplates)
6330 TSTemplateInfo *tmplinfo;
6334 int i_tmplnamespace;
6338 /* Before 8.3, there is no built-in text search support */
6339 if (fout->remoteVersion < 80300)
6341 *numTSTemplates = 0;
6345 query = createPQExpBuffer();
6347 /* Make sure we are in proper schema */
6348 selectSourceSchema(fout, "pg_catalog");
6350 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6351 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6352 "FROM pg_ts_template");
6354 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6356 ntups = PQntuples(res);
6357 *numTSTemplates = ntups;
6359 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6361 i_tableoid = PQfnumber(res, "tableoid");
6362 i_oid = PQfnumber(res, "oid");
6363 i_tmplname = PQfnumber(res, "tmplname");
6364 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6365 i_tmplinit = PQfnumber(res, "tmplinit");
6366 i_tmpllexize = PQfnumber(res, "tmpllexize");
6368 for (i = 0; i < ntups; i++)
6370 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6371 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6372 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6373 AssignDumpId(&tmplinfo[i].dobj);
6374 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6375 tmplinfo[i].dobj.namespace =
6377 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6378 tmplinfo[i].dobj.catId.oid);
6379 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6380 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6382 /* Decide whether we want to dump it */
6383 selectDumpableObject(&(tmplinfo[i].dobj));
6388 destroyPQExpBuffer(query);
6394 * getTSConfigurations:
6395 * read all text search configurations in the system catalogs and return
6396 * them in the TSConfigInfo* structure
6398 * numTSConfigs is set to the number of configurations read in
6401 getTSConfigurations(Archive *fout, int *numTSConfigs)
6407 TSConfigInfo *cfginfo;
6415 /* Before 8.3, there is no built-in text search support */
6416 if (fout->remoteVersion < 80300)
6422 query = createPQExpBuffer();
6424 /* Make sure we are in proper schema */
6425 selectSourceSchema(fout, "pg_catalog");
6427 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6428 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6429 "FROM pg_ts_config",
6432 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6434 ntups = PQntuples(res);
6435 *numTSConfigs = ntups;
6437 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6439 i_tableoid = PQfnumber(res, "tableoid");
6440 i_oid = PQfnumber(res, "oid");
6441 i_cfgname = PQfnumber(res, "cfgname");
6442 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6443 i_rolname = PQfnumber(res, "rolname");
6444 i_cfgparser = PQfnumber(res, "cfgparser");
6446 for (i = 0; i < ntups; i++)
6448 cfginfo[i].dobj.objType = DO_TSCONFIG;
6449 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6450 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6451 AssignDumpId(&cfginfo[i].dobj);
6452 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6453 cfginfo[i].dobj.namespace =
6455 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6456 cfginfo[i].dobj.catId.oid);
6457 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6458 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6460 /* Decide whether we want to dump it */
6461 selectDumpableObject(&(cfginfo[i].dobj));
6466 destroyPQExpBuffer(query);
6472 * getForeignDataWrappers:
6473 * read all foreign-data wrappers in the system catalogs and return
6474 * them in the FdwInfo* structure
6476 * numForeignDataWrappers is set to the number of fdws read in
6479 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6484 PQExpBuffer query = createPQExpBuffer();
6495 /* Before 8.4, there are no foreign-data wrappers */
6496 if (fout->remoteVersion < 80400)
6498 *numForeignDataWrappers = 0;
6502 /* Make sure we are in proper schema */
6503 selectSourceSchema(fout, "pg_catalog");
6505 if (fout->remoteVersion >= 90100)
6507 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6508 "(%s fdwowner) AS rolname, "
6509 "fdwhandler::pg_catalog.regproc, "
6510 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6511 "array_to_string(ARRAY("
6512 "SELECT quote_ident(option_name) || ' ' || "
6513 "quote_literal(option_value) "
6514 "FROM pg_options_to_table(fdwoptions) "
6515 "ORDER BY option_name"
6516 "), E',\n ') AS fdwoptions "
6517 "FROM pg_foreign_data_wrapper",
6522 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6523 "(%s fdwowner) AS rolname, "
6524 "'-' AS fdwhandler, "
6525 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6526 "array_to_string(ARRAY("
6527 "SELECT quote_ident(option_name) || ' ' || "
6528 "quote_literal(option_value) "
6529 "FROM pg_options_to_table(fdwoptions) "
6530 "ORDER BY option_name"
6531 "), E',\n ') AS fdwoptions "
6532 "FROM pg_foreign_data_wrapper",
6536 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6538 ntups = PQntuples(res);
6539 *numForeignDataWrappers = ntups;
6541 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6543 i_tableoid = PQfnumber(res, "tableoid");
6544 i_oid = PQfnumber(res, "oid");
6545 i_fdwname = PQfnumber(res, "fdwname");
6546 i_rolname = PQfnumber(res, "rolname");
6547 i_fdwhandler = PQfnumber(res, "fdwhandler");
6548 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6549 i_fdwacl = PQfnumber(res, "fdwacl");
6550 i_fdwoptions = PQfnumber(res, "fdwoptions");
6552 for (i = 0; i < ntups; i++)
6554 fdwinfo[i].dobj.objType = DO_FDW;
6555 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6556 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6557 AssignDumpId(&fdwinfo[i].dobj);
6558 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6559 fdwinfo[i].dobj.namespace = NULL;
6560 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6561 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6562 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6563 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6564 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6566 /* Decide whether we want to dump it */
6567 selectDumpableObject(&(fdwinfo[i].dobj));
6572 destroyPQExpBuffer(query);
6578 * getForeignServers:
6579 * read all foreign servers in the system catalogs and return
6580 * them in the ForeignServerInfo * structure
6582 * numForeignServers is set to the number of servers read in
6585 getForeignServers(Archive *fout, int *numForeignServers)
6590 PQExpBuffer query = createPQExpBuffer();
6591 ForeignServerInfo *srvinfo;
6602 /* Before 8.4, there are no foreign servers */
6603 if (fout->remoteVersion < 80400)
6605 *numForeignServers = 0;
6609 /* Make sure we are in proper schema */
6610 selectSourceSchema(fout,"pg_catalog");
6612 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6613 "(%s srvowner) AS rolname, "
6614 "srvfdw, srvtype, srvversion, srvacl,"
6615 "array_to_string(ARRAY("
6616 "SELECT quote_ident(option_name) || ' ' || "
6617 "quote_literal(option_value) "
6618 "FROM pg_options_to_table(srvoptions) "
6619 "ORDER BY option_name"
6620 "), E',\n ') AS srvoptions "
6621 "FROM pg_foreign_server",
6624 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6626 ntups = PQntuples(res);
6627 *numForeignServers = ntups;
6629 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6631 i_tableoid = PQfnumber(res, "tableoid");
6632 i_oid = PQfnumber(res, "oid");
6633 i_srvname = PQfnumber(res, "srvname");
6634 i_rolname = PQfnumber(res, "rolname");
6635 i_srvfdw = PQfnumber(res, "srvfdw");
6636 i_srvtype = PQfnumber(res, "srvtype");
6637 i_srvversion = PQfnumber(res, "srvversion");
6638 i_srvacl = PQfnumber(res, "srvacl");
6639 i_srvoptions = PQfnumber(res, "srvoptions");
6641 for (i = 0; i < ntups; i++)
6643 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6644 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6645 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6646 AssignDumpId(&srvinfo[i].dobj);
6647 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6648 srvinfo[i].dobj.namespace = NULL;
6649 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6650 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6651 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6652 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6653 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6654 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6656 /* Decide whether we want to dump it */
6657 selectDumpableObject(&(srvinfo[i].dobj));
6662 destroyPQExpBuffer(query);
6669 * read all default ACL information in the system catalogs and return
6670 * them in the DefaultACLInfo structure
6672 * numDefaultACLs is set to the number of ACLs read in
6675 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6677 DefaultACLInfo *daclinfo;
6683 int i_defaclnamespace;
6684 int i_defaclobjtype;
6689 if (fout->remoteVersion < 90000)
6691 *numDefaultACLs = 0;
6695 query = createPQExpBuffer();
6697 /* Make sure we are in proper schema */
6698 selectSourceSchema(fout, "pg_catalog");
6700 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6701 "(%s defaclrole) AS defaclrole, "
6705 "FROM pg_default_acl",
6708 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6710 ntups = PQntuples(res);
6711 *numDefaultACLs = ntups;
6713 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6715 i_oid = PQfnumber(res, "oid");
6716 i_tableoid = PQfnumber(res, "tableoid");
6717 i_defaclrole = PQfnumber(res, "defaclrole");
6718 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6719 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6720 i_defaclacl = PQfnumber(res, "defaclacl");
6722 for (i = 0; i < ntups; i++)
6724 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6726 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6727 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6728 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6729 AssignDumpId(&daclinfo[i].dobj);
6730 /* cheesy ... is it worth coming up with a better object name? */
6731 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6733 if (nspid != InvalidOid)
6734 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6735 daclinfo[i].dobj.catId.oid);
6737 daclinfo[i].dobj.namespace = NULL;
6739 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6740 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6741 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6743 /* Decide whether we want to dump it */
6744 selectDumpableDefaultACL(&(daclinfo[i]));
6749 destroyPQExpBuffer(query);
6757 * This routine is used to dump any comments associated with the
6758 * object handed to this routine. The routine takes a constant character
6759 * string for the target part of the comment-creation command, plus
6760 * the namespace and owner of the object (for labeling the ArchiveEntry),
6761 * plus catalog ID and subid which are the lookup key for pg_description,
6762 * plus the dump ID for the object (for setting a dependency).
6763 * If a matching pg_description entry is found, it is dumped.
6765 * Note: although this routine takes a dumpId for dependency purposes,
6766 * that purpose is just to mark the dependency in the emitted dump file
6767 * for possible future use by pg_restore. We do NOT use it for determining
6768 * ordering of the comment in the dump file, because this routine is called
6769 * after dependency sorting occurs. This routine should be called just after
6770 * calling ArchiveEntry() for the specified object.
6773 dumpComment(Archive *fout, const char *target,
6774 const char *namespace, const char *owner,
6775 CatalogId catalogId, int subid, DumpId dumpId)
6777 CommentItem *comments;
6780 /* Comments are schema not data ... except blob comments are data */
6781 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6792 /* Search for comments associated with catalogId, using table */
6793 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6796 /* Is there one matching the subid? */
6797 while (ncomments > 0)
6799 if (comments->objsubid == subid)
6805 /* If a comment exists, build COMMENT ON statement */
6808 PQExpBuffer query = createPQExpBuffer();
6810 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6811 appendStringLiteralAH(query, comments->descr, fout);
6812 appendPQExpBuffer(query, ";\n");
6815 * We mark comments as SECTION_NONE because they really belong in the
6816 * same section as their parent, whether that is pre-data or
6819 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6820 target, namespace, NULL, owner,
6821 false, "COMMENT", SECTION_NONE,
6822 query->data, "", NULL,
6826 destroyPQExpBuffer(query);
6831 * dumpTableComment --
6833 * As above, but dump comments for both the specified table (or view)
6837 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6838 const char *reltypename)
6840 CommentItem *comments;
6845 /* Comments are SCHEMA not data */
6849 /* Search for comments associated with relation, using table */
6850 ncomments = findComments(fout,
6851 tbinfo->dobj.catId.tableoid,
6852 tbinfo->dobj.catId.oid,
6855 /* If comments exist, build COMMENT ON statements */
6859 query = createPQExpBuffer();
6860 target = createPQExpBuffer();
6862 while (ncomments > 0)
6864 const char *descr = comments->descr;
6865 int objsubid = comments->objsubid;
6869 resetPQExpBuffer(target);
6870 appendPQExpBuffer(target, "%s %s", reltypename,
6871 fmtId(tbinfo->dobj.name));
6873 resetPQExpBuffer(query);
6874 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6875 appendStringLiteralAH(query, descr, fout);
6876 appendPQExpBuffer(query, ";\n");
6878 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6880 tbinfo->dobj.namespace->dobj.name,
6881 NULL, tbinfo->rolname,
6882 false, "COMMENT", SECTION_NONE,
6883 query->data, "", NULL,
6884 &(tbinfo->dobj.dumpId), 1,
6887 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6889 resetPQExpBuffer(target);
6890 appendPQExpBuffer(target, "COLUMN %s.",
6891 fmtId(tbinfo->dobj.name));
6892 appendPQExpBuffer(target, "%s",
6893 fmtId(tbinfo->attnames[objsubid - 1]));
6895 resetPQExpBuffer(query);
6896 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6897 appendStringLiteralAH(query, descr, fout);
6898 appendPQExpBuffer(query, ";\n");
6900 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6902 tbinfo->dobj.namespace->dobj.name,
6903 NULL, tbinfo->rolname,
6904 false, "COMMENT", SECTION_NONE,
6905 query->data, "", NULL,
6906 &(tbinfo->dobj.dumpId), 1,
6914 destroyPQExpBuffer(query);
6915 destroyPQExpBuffer(target);
6921 * Find the comment(s), if any, associated with the given object. All the
6922 * objsubid values associated with the given classoid/objoid are found with
6926 findComments(Archive *fout, Oid classoid, Oid objoid,
6927 CommentItem **items)
6929 /* static storage for table of comments */
6930 static CommentItem *comments = NULL;
6931 static int ncomments = -1;
6933 CommentItem *middle = NULL;
6938 /* Get comments if we didn't already */
6940 ncomments = collectComments(fout, &comments);
6943 * Pre-7.2, pg_description does not contain classoid, so collectComments
6944 * just stores a zero. If there's a collision on object OID, well, you
6945 * get duplicate comments.
6947 if (fout->remoteVersion < 70200)
6951 * Do binary search to find some item matching the object.
6954 high = &comments[ncomments - 1];
6957 middle = low + (high - low) / 2;
6959 if (classoid < middle->classoid)
6961 else if (classoid > middle->classoid)
6963 else if (objoid < middle->objoid)
6965 else if (objoid > middle->objoid)
6968 break; /* found a match */
6971 if (low > high) /* no matches */
6978 * Now determine how many items match the object. The search loop
6979 * invariant still holds: only items between low and high inclusive could
6983 while (middle > low)
6985 if (classoid != middle[-1].classoid ||
6986 objoid != middle[-1].objoid)
6995 while (middle <= high)
6997 if (classoid != middle->classoid ||
6998 objoid != middle->objoid)
7008 * collectComments --
7010 * Construct a table of all comments available for database objects.
7011 * We used to do per-object queries for the comments, but it's much faster
7012 * to pull them all over at once, and on most databases the memory cost
7015 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7018 collectComments(Archive *fout, CommentItem **items)
7028 CommentItem *comments;
7031 * Note we do NOT change source schema here; preserve the caller's
7035 query = createPQExpBuffer();
7037 if (fout->remoteVersion >= 70300)
7039 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7040 "FROM pg_catalog.pg_description "
7041 "ORDER BY classoid, objoid, objsubid");
7043 else if (fout->remoteVersion >= 70200)
7045 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7046 "FROM pg_description "
7047 "ORDER BY classoid, objoid, objsubid");
7051 /* Note: this will fail to find attribute comments in pre-7.2... */
7052 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7053 "FROM pg_description "
7057 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7059 /* Construct lookup table containing OIDs in numeric form */
7061 i_description = PQfnumber(res, "description");
7062 i_classoid = PQfnumber(res, "classoid");
7063 i_objoid = PQfnumber(res, "objoid");
7064 i_objsubid = PQfnumber(res, "objsubid");
7066 ntups = PQntuples(res);
7068 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7070 for (i = 0; i < ntups; i++)
7072 comments[i].descr = PQgetvalue(res, i, i_description);
7073 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7074 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7075 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7078 /* Do NOT free the PGresult since we are keeping pointers into it */
7079 destroyPQExpBuffer(query);
7086 * dumpDumpableObject
7088 * This routine and its subsidiaries are responsible for creating
7089 * ArchiveEntries (TOC objects) for each object to be dumped.
7092 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7097 switch (dobj->objType)
7102 case DO_FK_CONSTRAINT:
7104 skip = !(dumpSections & DUMP_POST_DATA);
7107 skip = !(dumpSections & DUMP_DATA);
7110 skip = !(dumpSections & DUMP_PRE_DATA);
7116 switch (dobj->objType)
7119 dumpNamespace(fout, (NamespaceInfo *) dobj);
7122 dumpExtension(fout, (ExtensionInfo *) dobj);
7125 dumpType(fout, (TypeInfo *) dobj);
7128 dumpShellType(fout, (ShellTypeInfo *) dobj);
7131 dumpFunc(fout, (FuncInfo *) dobj);
7134 dumpAgg(fout, (AggInfo *) dobj);
7137 dumpOpr(fout, (OprInfo *) dobj);
7140 dumpOpclass(fout, (OpclassInfo *) dobj);
7143 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7146 dumpCollation(fout, (CollInfo *) dobj);
7149 dumpConversion(fout, (ConvInfo *) dobj);
7152 dumpTable(fout, (TableInfo *) dobj);
7155 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7158 dumpIndex(fout, (IndxInfo *) dobj);
7161 dumpRule(fout, (RuleInfo *) dobj);
7164 dumpTrigger(fout, (TriggerInfo *) dobj);
7167 dumpConstraint(fout, (ConstraintInfo *) dobj);
7169 case DO_FK_CONSTRAINT:
7170 dumpConstraint(fout, (ConstraintInfo *) dobj);
7173 dumpProcLang(fout, (ProcLangInfo *) dobj);
7176 dumpCast(fout, (CastInfo *) dobj);
7179 dumpTableData(fout, (TableDataInfo *) dobj);
7182 /* table rowtypes and array types are never dumped separately */
7185 dumpTSParser(fout, (TSParserInfo *) dobj);
7188 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7191 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7194 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7197 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7199 case DO_FOREIGN_SERVER:
7200 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7202 case DO_DEFAULT_ACL:
7203 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7206 dumpBlob(fout, (BlobInfo *) dobj);
7209 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7210 dobj->name, NULL, NULL, "",
7211 false, "BLOBS", SECTION_DATA,
7213 dobj->dependencies, dobj->nDeps,
7221 * writes out to fout the queries to recreate a user-defined namespace
7224 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7231 /* Skip if not to be dumped */
7232 if (!nspinfo->dobj.dump || dataOnly)
7235 /* don't dump dummy namespace from pre-7.3 source */
7236 if (strlen(nspinfo->dobj.name) == 0)
7239 q = createPQExpBuffer();
7240 delq = createPQExpBuffer();
7241 labelq = createPQExpBuffer();
7243 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7245 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7247 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7249 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7252 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7254 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7258 false, "SCHEMA", SECTION_PRE_DATA,
7259 q->data, delq->data, NULL,
7260 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7263 /* Dump Schema Comments and Security Labels */
7264 dumpComment(fout, labelq->data,
7265 NULL, nspinfo->rolname,
7266 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7267 dumpSecLabel(fout, labelq->data,
7268 NULL, nspinfo->rolname,
7269 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7271 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7272 qnspname, NULL, nspinfo->dobj.name, NULL,
7273 nspinfo->rolname, nspinfo->nspacl);
7277 destroyPQExpBuffer(q);
7278 destroyPQExpBuffer(delq);
7279 destroyPQExpBuffer(labelq);
7284 * writes out to fout the queries to recreate an extension
7287 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7294 /* Skip if not to be dumped */
7295 if (!extinfo->dobj.dump || dataOnly)
7298 q = createPQExpBuffer();
7299 delq = createPQExpBuffer();
7300 labelq = createPQExpBuffer();
7302 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7304 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7306 if (!binary_upgrade)
7309 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7310 * problem if the extension already exists in the target database;
7311 * this is essential for installed-by-default extensions such as
7314 * In binary-upgrade mode, that doesn't work well, so instead we skip
7315 * built-in extensions based on their OIDs; see
7316 * selectDumpableExtension.
7318 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7319 qextname, fmtId(extinfo->namespace));
7326 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7327 appendPQExpBuffer(q,
7328 "SELECT binary_upgrade.create_empty_extension(");
7329 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7330 appendPQExpBuffer(q, ", ");
7331 appendStringLiteralAH(q, extinfo->namespace, fout);
7332 appendPQExpBuffer(q, ", ");
7333 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7334 appendStringLiteralAH(q, extinfo->extversion, fout);
7335 appendPQExpBuffer(q, ", ");
7338 * Note that we're pushing extconfig (an OID array) back into
7339 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7340 * preserved in binary upgrade.
7342 if (strlen(extinfo->extconfig) > 2)
7343 appendStringLiteralAH(q, extinfo->extconfig, fout);
7345 appendPQExpBuffer(q, "NULL");
7346 appendPQExpBuffer(q, ", ");
7347 if (strlen(extinfo->extcondition) > 2)
7348 appendStringLiteralAH(q, extinfo->extcondition, fout);
7350 appendPQExpBuffer(q, "NULL");
7351 appendPQExpBuffer(q, ", ");
7352 appendPQExpBuffer(q, "ARRAY[");
7354 for (i = 0; i < extinfo->dobj.nDeps; i++)
7356 DumpableObject *extobj;
7358 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7359 if (extobj && extobj->objType == DO_EXTENSION)
7362 appendPQExpBuffer(q, ",");
7363 appendStringLiteralAH(q, extobj->name, fout);
7366 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7367 appendPQExpBuffer(q, ");\n");
7370 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7372 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7376 false, "EXTENSION", SECTION_PRE_DATA,
7377 q->data, delq->data, NULL,
7378 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7381 /* Dump Extension Comments and Security Labels */
7382 dumpComment(fout, labelq->data,
7384 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7385 dumpSecLabel(fout, labelq->data,
7387 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7391 destroyPQExpBuffer(q);
7392 destroyPQExpBuffer(delq);
7393 destroyPQExpBuffer(labelq);
7398 * writes out to fout the queries to recreate a user-defined type
7401 dumpType(Archive *fout, TypeInfo *tyinfo)
7403 /* Skip if not to be dumped */
7404 if (!tyinfo->dobj.dump || dataOnly)
7407 /* Dump out in proper style */
7408 if (tyinfo->typtype == TYPTYPE_BASE)
7409 dumpBaseType(fout, tyinfo);
7410 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7411 dumpDomain(fout, tyinfo);
7412 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7413 dumpCompositeType(fout, tyinfo);
7414 else if (tyinfo->typtype == TYPTYPE_ENUM)
7415 dumpEnumType(fout, tyinfo);
7416 else if (tyinfo->typtype == TYPTYPE_RANGE)
7417 dumpRangeType(fout, tyinfo);
7419 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7425 * writes out to fout the queries to recreate a user-defined enum type
7428 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7430 PQExpBuffer q = createPQExpBuffer();
7431 PQExpBuffer delq = createPQExpBuffer();
7432 PQExpBuffer labelq = createPQExpBuffer();
7433 PQExpBuffer query = createPQExpBuffer();
7440 /* Set proper schema search path */
7441 selectSourceSchema(fout, "pg_catalog");
7443 if (fout->remoteVersion >= 90100)
7444 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7445 "FROM pg_catalog.pg_enum "
7446 "WHERE enumtypid = '%u'"
7447 "ORDER BY enumsortorder",
7448 tyinfo->dobj.catId.oid);
7450 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7451 "FROM pg_catalog.pg_enum "
7452 "WHERE enumtypid = '%u'"
7454 tyinfo->dobj.catId.oid);
7456 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7458 num = PQntuples(res);
7461 * DROP must be fully qualified in case same name appears in pg_catalog.
7462 * CASCADE shouldn't be required here as for normal types since the I/O
7463 * functions are generic and do not get dropped.
7465 appendPQExpBuffer(delq, "DROP TYPE %s.",
7466 fmtId(tyinfo->dobj.namespace->dobj.name));
7467 appendPQExpBuffer(delq, "%s;\n",
7468 fmtId(tyinfo->dobj.name));
7471 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7472 tyinfo->dobj.catId.oid);
7474 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7475 fmtId(tyinfo->dobj.name));
7477 if (!binary_upgrade)
7479 /* Labels with server-assigned oids */
7480 for (i = 0; i < num; i++)
7482 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7484 appendPQExpBuffer(q, ",");
7485 appendPQExpBuffer(q, "\n ");
7486 appendStringLiteralAH(q, label, fout);
7490 appendPQExpBuffer(q, "\n);\n");
7494 /* Labels with dump-assigned (preserved) oids */
7495 for (i = 0; i < num; i++)
7497 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7498 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7501 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7502 appendPQExpBuffer(q,
7503 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7505 appendPQExpBuffer(q, "ALTER TYPE %s.",
7506 fmtId(tyinfo->dobj.namespace->dobj.name));
7507 appendPQExpBuffer(q, "%s ADD VALUE ",
7508 fmtId(tyinfo->dobj.name));
7509 appendStringLiteralAH(q, label, fout);
7510 appendPQExpBuffer(q, ";\n\n");
7514 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7517 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7519 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7521 tyinfo->dobj.namespace->dobj.name,
7523 tyinfo->rolname, false,
7524 "TYPE", SECTION_PRE_DATA,
7525 q->data, delq->data, NULL,
7526 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7529 /* Dump Type Comments and Security Labels */
7530 dumpComment(fout, labelq->data,
7531 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7532 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7533 dumpSecLabel(fout, labelq->data,
7534 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7535 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7538 destroyPQExpBuffer(q);
7539 destroyPQExpBuffer(delq);
7540 destroyPQExpBuffer(labelq);
7541 destroyPQExpBuffer(query);
7546 * writes out to fout the queries to recreate a user-defined range type
7549 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7551 PQExpBuffer q = createPQExpBuffer();
7552 PQExpBuffer delq = createPQExpBuffer();
7553 PQExpBuffer labelq = createPQExpBuffer();
7554 PQExpBuffer query = createPQExpBuffer();
7560 * select appropriate schema to ensure names in CREATE are properly
7563 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7565 appendPQExpBuffer(query,
7566 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7567 "opc.opcname AS opcname, "
7568 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7569 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7571 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7572 " ELSE rngcollation END AS collation, "
7573 "rngcanonical, rngsubdiff "
7574 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7575 " pg_catalog.pg_opclass opc "
7576 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7578 tyinfo->dobj.catId.oid);
7580 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7583 * DROP must be fully qualified in case same name appears in pg_catalog.
7584 * CASCADE shouldn't be required here as for normal types since the I/O
7585 * functions are generic and do not get dropped.
7587 appendPQExpBuffer(delq, "DROP TYPE %s.",
7588 fmtId(tyinfo->dobj.namespace->dobj.name));
7589 appendPQExpBuffer(delq, "%s;\n",
7590 fmtId(tyinfo->dobj.name));
7593 binary_upgrade_set_type_oids_by_type_oid(fout,
7594 q, tyinfo->dobj.catId.oid);
7596 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7597 fmtId(tyinfo->dobj.name));
7599 appendPQExpBuffer(q, "\n subtype = %s",
7600 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7602 /* print subtype_opclass only if not default for subtype */
7603 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7605 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7606 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7608 /* always schema-qualify, don't try to be smart */
7609 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7611 appendPQExpBuffer(q, "%s", fmtId(opcname));
7614 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7615 if (OidIsValid(collationOid))
7617 CollInfo *coll = findCollationByOid(collationOid);
7621 /* always schema-qualify, don't try to be smart */
7622 appendPQExpBuffer(q, ",\n collation = %s.",
7623 fmtId(coll->dobj.namespace->dobj.name));
7624 appendPQExpBuffer(q, "%s",
7625 fmtId(coll->dobj.name));
7629 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7630 if (strcmp(procname, "-") != 0)
7631 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7633 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7634 if (strcmp(procname, "-") != 0)
7635 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7637 appendPQExpBuffer(q, "\n);\n");
7639 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7642 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7644 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7646 tyinfo->dobj.namespace->dobj.name,
7648 tyinfo->rolname, false,
7649 "TYPE", SECTION_PRE_DATA,
7650 q->data, delq->data, NULL,
7651 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7654 /* Dump Type Comments and Security Labels */
7655 dumpComment(fout, labelq->data,
7656 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7657 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7658 dumpSecLabel(fout, labelq->data,
7659 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7660 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7663 destroyPQExpBuffer(q);
7664 destroyPQExpBuffer(delq);
7665 destroyPQExpBuffer(labelq);
7666 destroyPQExpBuffer(query);
7671 * writes out to fout the queries to recreate a user-defined base type
7674 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7676 PQExpBuffer q = createPQExpBuffer();
7677 PQExpBuffer delq = createPQExpBuffer();
7678 PQExpBuffer labelq = createPQExpBuffer();
7679 PQExpBuffer query = createPQExpBuffer();
7695 char *typispreferred;
7700 char *typcollatable;
7702 bool typdefault_is_literal = false;
7704 /* Set proper schema search path so regproc references list correctly */
7705 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7707 /* Fetch type-specific details */
7708 if (fout->remoteVersion >= 90100)
7710 appendPQExpBuffer(query, "SELECT typlen, "
7711 "typinput, typoutput, typreceive, typsend, "
7712 "typmodin, typmodout, typanalyze, "
7713 "typreceive::pg_catalog.oid AS typreceiveoid, "
7714 "typsend::pg_catalog.oid AS typsendoid, "
7715 "typmodin::pg_catalog.oid AS typmodinoid, "
7716 "typmodout::pg_catalog.oid AS typmodoutoid, "
7717 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7718 "typcategory, typispreferred, "
7719 "typdelim, typbyval, typalign, typstorage, "
7720 "(typcollation <> 0) AS typcollatable, "
7721 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7722 "FROM pg_catalog.pg_type "
7723 "WHERE oid = '%u'::pg_catalog.oid",
7724 tyinfo->dobj.catId.oid);
7726 else if (fout->remoteVersion >= 80400)
7728 appendPQExpBuffer(query, "SELECT typlen, "
7729 "typinput, typoutput, typreceive, typsend, "
7730 "typmodin, typmodout, typanalyze, "
7731 "typreceive::pg_catalog.oid AS typreceiveoid, "
7732 "typsend::pg_catalog.oid AS typsendoid, "
7733 "typmodin::pg_catalog.oid AS typmodinoid, "
7734 "typmodout::pg_catalog.oid AS typmodoutoid, "
7735 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7736 "typcategory, typispreferred, "
7737 "typdelim, typbyval, typalign, typstorage, "
7738 "false AS typcollatable, "
7739 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7740 "FROM pg_catalog.pg_type "
7741 "WHERE oid = '%u'::pg_catalog.oid",
7742 tyinfo->dobj.catId.oid);
7744 else if (fout->remoteVersion >= 80300)
7746 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7747 appendPQExpBuffer(query, "SELECT typlen, "
7748 "typinput, typoutput, typreceive, typsend, "
7749 "typmodin, typmodout, typanalyze, "
7750 "typreceive::pg_catalog.oid AS typreceiveoid, "
7751 "typsend::pg_catalog.oid AS typsendoid, "
7752 "typmodin::pg_catalog.oid AS typmodinoid, "
7753 "typmodout::pg_catalog.oid AS typmodoutoid, "
7754 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7755 "'U' AS typcategory, false AS typispreferred, "
7756 "typdelim, typbyval, typalign, typstorage, "
7757 "false AS typcollatable, "
7758 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7759 "FROM pg_catalog.pg_type "
7760 "WHERE oid = '%u'::pg_catalog.oid",
7761 tyinfo->dobj.catId.oid);
7763 else if (fout->remoteVersion >= 80000)
7765 appendPQExpBuffer(query, "SELECT typlen, "
7766 "typinput, typoutput, typreceive, typsend, "
7767 "'-' AS typmodin, '-' AS typmodout, "
7769 "typreceive::pg_catalog.oid AS typreceiveoid, "
7770 "typsend::pg_catalog.oid AS typsendoid, "
7771 "0 AS typmodinoid, 0 AS typmodoutoid, "
7772 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7773 "'U' AS typcategory, false AS typispreferred, "
7774 "typdelim, typbyval, typalign, typstorage, "
7775 "false AS typcollatable, "
7776 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7777 "FROM pg_catalog.pg_type "
7778 "WHERE oid = '%u'::pg_catalog.oid",
7779 tyinfo->dobj.catId.oid);
7781 else if (fout->remoteVersion >= 70400)
7783 appendPQExpBuffer(query, "SELECT typlen, "
7784 "typinput, typoutput, typreceive, typsend, "
7785 "'-' AS typmodin, '-' AS typmodout, "
7786 "'-' AS typanalyze, "
7787 "typreceive::pg_catalog.oid AS typreceiveoid, "
7788 "typsend::pg_catalog.oid AS typsendoid, "
7789 "0 AS typmodinoid, 0 AS typmodoutoid, "
7790 "0 AS typanalyzeoid, "
7791 "'U' AS typcategory, false AS typispreferred, "
7792 "typdelim, typbyval, typalign, typstorage, "
7793 "false AS typcollatable, "
7794 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7795 "FROM pg_catalog.pg_type "
7796 "WHERE oid = '%u'::pg_catalog.oid",
7797 tyinfo->dobj.catId.oid);
7799 else if (fout->remoteVersion >= 70300)
7801 appendPQExpBuffer(query, "SELECT typlen, "
7802 "typinput, typoutput, "
7803 "'-' AS typreceive, '-' AS typsend, "
7804 "'-' AS typmodin, '-' AS typmodout, "
7805 "'-' AS typanalyze, "
7806 "0 AS typreceiveoid, 0 AS typsendoid, "
7807 "0 AS typmodinoid, 0 AS typmodoutoid, "
7808 "0 AS typanalyzeoid, "
7809 "'U' AS typcategory, false AS typispreferred, "
7810 "typdelim, typbyval, typalign, typstorage, "
7811 "false AS typcollatable, "
7812 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7813 "FROM pg_catalog.pg_type "
7814 "WHERE oid = '%u'::pg_catalog.oid",
7815 tyinfo->dobj.catId.oid);
7817 else if (fout->remoteVersion >= 70200)
7820 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7821 * ignore them because they are not right.
7823 appendPQExpBuffer(query, "SELECT typlen, "
7824 "typinput, typoutput, "
7825 "'-' AS typreceive, '-' AS typsend, "
7826 "'-' AS typmodin, '-' AS typmodout, "
7827 "'-' AS typanalyze, "
7828 "0 AS typreceiveoid, 0 AS typsendoid, "
7829 "0 AS typmodinoid, 0 AS typmodoutoid, "
7830 "0 AS typanalyzeoid, "
7831 "'U' AS typcategory, false AS typispreferred, "
7832 "typdelim, typbyval, typalign, typstorage, "
7833 "false AS typcollatable, "
7834 "NULL AS typdefaultbin, typdefault "
7836 "WHERE oid = '%u'::oid",
7837 tyinfo->dobj.catId.oid);
7839 else if (fout->remoteVersion >= 70100)
7842 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7845 appendPQExpBuffer(query, "SELECT typlen, "
7846 "typinput, typoutput, "
7847 "'-' AS typreceive, '-' AS typsend, "
7848 "'-' AS typmodin, '-' AS typmodout, "
7849 "'-' AS typanalyze, "
7850 "0 AS typreceiveoid, 0 AS typsendoid, "
7851 "0 AS typmodinoid, 0 AS typmodoutoid, "
7852 "0 AS typanalyzeoid, "
7853 "'U' AS typcategory, false AS typispreferred, "
7854 "typdelim, typbyval, typalign, typstorage, "
7855 "false AS typcollatable, "
7856 "NULL AS typdefaultbin, NULL AS typdefault "
7858 "WHERE oid = '%u'::oid",
7859 tyinfo->dobj.catId.oid);
7863 appendPQExpBuffer(query, "SELECT typlen, "
7864 "typinput, typoutput, "
7865 "'-' AS typreceive, '-' AS typsend, "
7866 "'-' AS typmodin, '-' AS typmodout, "
7867 "'-' AS typanalyze, "
7868 "0 AS typreceiveoid, 0 AS typsendoid, "
7869 "0 AS typmodinoid, 0 AS typmodoutoid, "
7870 "0 AS typanalyzeoid, "
7871 "'U' AS typcategory, false AS typispreferred, "
7872 "typdelim, typbyval, typalign, "
7873 "'p'::char AS typstorage, "
7874 "false AS typcollatable, "
7875 "NULL AS typdefaultbin, NULL AS typdefault "
7877 "WHERE oid = '%u'::oid",
7878 tyinfo->dobj.catId.oid);
7881 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7883 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7884 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7885 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7886 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7887 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7888 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7889 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7890 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7891 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7892 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7893 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7894 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7895 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7896 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7897 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7898 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7899 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7900 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7901 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7902 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7903 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7904 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7905 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7907 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7908 typdefault_is_literal = true; /* it needs quotes */
7914 * DROP must be fully qualified in case same name appears in pg_catalog.
7915 * The reason we include CASCADE is that the circular dependency between
7916 * the type and its I/O functions makes it impossible to drop the type any
7919 appendPQExpBuffer(delq, "DROP TYPE %s.",
7920 fmtId(tyinfo->dobj.namespace->dobj.name));
7921 appendPQExpBuffer(delq, "%s CASCADE;\n",
7922 fmtId(tyinfo->dobj.name));
7924 /* We might already have a shell type, but setting pg_type_oid is harmless */
7926 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7927 tyinfo->dobj.catId.oid);
7929 appendPQExpBuffer(q,
7930 "CREATE TYPE %s (\n"
7931 " INTERNALLENGTH = %s",
7932 fmtId(tyinfo->dobj.name),
7933 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7935 if (fout->remoteVersion >= 70300)
7937 /* regproc result is correctly quoted as of 7.3 */
7938 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7939 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7940 if (OidIsValid(typreceiveoid))
7941 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7942 if (OidIsValid(typsendoid))
7943 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7944 if (OidIsValid(typmodinoid))
7945 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7946 if (OidIsValid(typmodoutoid))
7947 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7948 if (OidIsValid(typanalyzeoid))
7949 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7953 /* regproc delivers an unquoted name before 7.3 */
7954 /* cannot combine these because fmtId uses static result area */
7955 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7956 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7957 /* receive/send/typmodin/typmodout/analyze need not be printed */
7960 if (strcmp(typcollatable, "t") == 0)
7961 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7963 if (typdefault != NULL)
7965 appendPQExpBuffer(q, ",\n DEFAULT = ");
7966 if (typdefault_is_literal)
7967 appendStringLiteralAH(q, typdefault, fout);
7969 appendPQExpBufferStr(q, typdefault);
7972 if (OidIsValid(tyinfo->typelem))
7976 /* reselect schema in case changed by function dump */
7977 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7978 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7979 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
7983 if (strcmp(typcategory, "U") != 0)
7985 appendPQExpBuffer(q, ",\n CATEGORY = ");
7986 appendStringLiteralAH(q, typcategory, fout);
7989 if (strcmp(typispreferred, "t") == 0)
7990 appendPQExpBuffer(q, ",\n PREFERRED = true");
7992 if (typdelim && strcmp(typdelim, ",") != 0)
7994 appendPQExpBuffer(q, ",\n DELIMITER = ");
7995 appendStringLiteralAH(q, typdelim, fout);
7998 if (strcmp(typalign, "c") == 0)
7999 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8000 else if (strcmp(typalign, "s") == 0)
8001 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8002 else if (strcmp(typalign, "i") == 0)
8003 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8004 else if (strcmp(typalign, "d") == 0)
8005 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8007 if (strcmp(typstorage, "p") == 0)
8008 appendPQExpBuffer(q, ",\n STORAGE = plain");
8009 else if (strcmp(typstorage, "e") == 0)
8010 appendPQExpBuffer(q, ",\n STORAGE = external");
8011 else if (strcmp(typstorage, "x") == 0)
8012 appendPQExpBuffer(q, ",\n STORAGE = extended");
8013 else if (strcmp(typstorage, "m") == 0)
8014 appendPQExpBuffer(q, ",\n STORAGE = main");
8016 if (strcmp(typbyval, "t") == 0)
8017 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8019 appendPQExpBuffer(q, "\n);\n");
8021 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8024 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8026 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8028 tyinfo->dobj.namespace->dobj.name,
8030 tyinfo->rolname, false,
8031 "TYPE", SECTION_PRE_DATA,
8032 q->data, delq->data, NULL,
8033 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8036 /* Dump Type Comments and Security Labels */
8037 dumpComment(fout, labelq->data,
8038 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8039 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8040 dumpSecLabel(fout, labelq->data,
8041 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8042 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8045 destroyPQExpBuffer(q);
8046 destroyPQExpBuffer(delq);
8047 destroyPQExpBuffer(labelq);
8048 destroyPQExpBuffer(query);
8053 * writes out to fout the queries to recreate a user-defined domain
8056 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8058 PQExpBuffer q = createPQExpBuffer();
8059 PQExpBuffer delq = createPQExpBuffer();
8060 PQExpBuffer labelq = createPQExpBuffer();
8061 PQExpBuffer query = createPQExpBuffer();
8068 bool typdefault_is_literal = false;
8070 /* Set proper schema search path so type references list correctly */
8071 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8073 /* Fetch domain specific details */
8074 if (fout->remoteVersion >= 90100)
8076 /* typcollation is new in 9.1 */
8077 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8078 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8079 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8081 "CASE WHEN t.typcollation <> u.typcollation "
8082 "THEN t.typcollation ELSE 0 END AS typcollation "
8083 "FROM pg_catalog.pg_type t "
8084 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8085 "WHERE t.oid = '%u'::pg_catalog.oid",
8086 tyinfo->dobj.catId.oid);
8090 /* We assume here that remoteVersion must be at least 70300 */
8091 appendPQExpBuffer(query, "SELECT typnotnull, "
8092 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8093 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8094 "typdefault, 0 AS typcollation "
8095 "FROM pg_catalog.pg_type "
8096 "WHERE oid = '%u'::pg_catalog.oid",
8097 tyinfo->dobj.catId.oid);
8100 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8102 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8103 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8104 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8105 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8106 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8108 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8109 typdefault_is_literal = true; /* it needs quotes */
8113 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8116 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8117 tyinfo->dobj.catId.oid);
8119 appendPQExpBuffer(q,
8120 "CREATE DOMAIN %s AS %s",
8121 fmtId(tyinfo->dobj.name),
8124 /* Print collation only if different from base type's collation */
8125 if (OidIsValid(typcollation))
8129 coll = findCollationByOid(typcollation);
8132 /* always schema-qualify, don't try to be smart */
8133 appendPQExpBuffer(q, " COLLATE %s.",
8134 fmtId(coll->dobj.namespace->dobj.name));
8135 appendPQExpBuffer(q, "%s",
8136 fmtId(coll->dobj.name));
8140 if (typnotnull[0] == 't')
8141 appendPQExpBuffer(q, " NOT NULL");
8143 if (typdefault != NULL)
8145 appendPQExpBuffer(q, " DEFAULT ");
8146 if (typdefault_is_literal)
8147 appendStringLiteralAH(q, typdefault, fout);
8149 appendPQExpBufferStr(q, typdefault);
8155 * Add any CHECK constraints for the domain
8157 for (i = 0; i < tyinfo->nDomChecks; i++)
8159 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8161 if (!domcheck->separate)
8162 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8163 fmtId(domcheck->dobj.name), domcheck->condef);
8166 appendPQExpBuffer(q, ";\n");
8169 * DROP must be fully qualified in case same name appears in pg_catalog
8171 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8172 fmtId(tyinfo->dobj.namespace->dobj.name));
8173 appendPQExpBuffer(delq, "%s;\n",
8174 fmtId(tyinfo->dobj.name));
8176 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8179 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8181 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8183 tyinfo->dobj.namespace->dobj.name,
8185 tyinfo->rolname, false,
8186 "DOMAIN", SECTION_PRE_DATA,
8187 q->data, delq->data, NULL,
8188 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8191 /* Dump Domain Comments and Security Labels */
8192 dumpComment(fout, labelq->data,
8193 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8194 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8195 dumpSecLabel(fout, labelq->data,
8196 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8197 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8199 destroyPQExpBuffer(q);
8200 destroyPQExpBuffer(delq);
8201 destroyPQExpBuffer(labelq);
8202 destroyPQExpBuffer(query);
8207 * writes out to fout the queries to recreate a user-defined stand-alone
8211 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8213 PQExpBuffer q = createPQExpBuffer();
8214 PQExpBuffer dropped = createPQExpBuffer();
8215 PQExpBuffer delq = createPQExpBuffer();
8216 PQExpBuffer labelq = createPQExpBuffer();
8217 PQExpBuffer query = createPQExpBuffer();
8230 /* Set proper schema search path so type references list correctly */
8231 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8233 /* Fetch type specific details */
8234 if (fout->remoteVersion >= 90100)
8237 * attcollation is new in 9.1. Since we only want to dump COLLATE
8238 * clauses for attributes whose collation is different from their
8239 * type's default, we use a CASE here to suppress uninteresting
8240 * attcollations cheaply. atttypid will be 0 for dropped columns;
8241 * collation does not matter for those.
8243 appendPQExpBuffer(query, "SELECT a.attname, "
8244 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8245 "a.attlen, a.attalign, a.attisdropped, "
8246 "CASE WHEN a.attcollation <> at.typcollation "
8247 "THEN a.attcollation ELSE 0 END AS attcollation, "
8249 "FROM pg_catalog.pg_type ct "
8250 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8251 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8252 "WHERE ct.oid = '%u'::pg_catalog.oid "
8253 "ORDER BY a.attnum ",
8254 tyinfo->dobj.catId.oid);
8259 * We assume here that remoteVersion must be at least 70300. Since
8260 * ALTER TYPE could not drop columns until 9.1, attisdropped should
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 "0 AS attcollation, "
8268 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8269 "WHERE ct.oid = '%u'::pg_catalog.oid "
8270 "AND a.attrelid = ct.typrelid "
8271 "ORDER BY a.attnum ",
8272 tyinfo->dobj.catId.oid);
8275 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8277 ntups = PQntuples(res);
8279 i_attname = PQfnumber(res, "attname");
8280 i_atttypdefn = PQfnumber(res, "atttypdefn");
8281 i_attlen = PQfnumber(res, "attlen");
8282 i_attalign = PQfnumber(res, "attalign");
8283 i_attisdropped = PQfnumber(res, "attisdropped");
8284 i_attcollation = PQfnumber(res, "attcollation");
8285 i_typrelid = PQfnumber(res, "typrelid");
8289 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8291 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8292 tyinfo->dobj.catId.oid);
8293 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8296 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8297 fmtId(tyinfo->dobj.name));
8300 for (i = 0; i < ntups; i++)
8309 attname = PQgetvalue(res, i, i_attname);
8310 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8311 attlen = PQgetvalue(res, i, i_attlen);
8312 attalign = PQgetvalue(res, i, i_attalign);
8313 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8314 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8316 if (attisdropped && !binary_upgrade)
8319 /* Format properly if not first attr */
8320 if (actual_atts++ > 0)
8321 appendPQExpBuffer(q, ",");
8322 appendPQExpBuffer(q, "\n\t");
8326 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8328 /* Add collation if not default for the column type */
8329 if (OidIsValid(attcollation))
8333 coll = findCollationByOid(attcollation);
8336 /* always schema-qualify, don't try to be smart */
8337 appendPQExpBuffer(q, " COLLATE %s.",
8338 fmtId(coll->dobj.namespace->dobj.name));
8339 appendPQExpBuffer(q, "%s",
8340 fmtId(coll->dobj.name));
8347 * This is a dropped attribute and we're in binary_upgrade mode.
8348 * Insert a placeholder for it in the CREATE TYPE command, and set
8349 * length and alignment with direct UPDATE to the catalogs
8350 * afterwards. See similar code in dumpTableSchema().
8352 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8354 /* stash separately for insertion after the CREATE TYPE */
8355 appendPQExpBuffer(dropped,
8356 "\n-- For binary upgrade, recreate dropped column.\n");
8357 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8359 "attalign = '%s', attbyval = false\n"
8360 "WHERE attname = ", attlen, attalign);
8361 appendStringLiteralAH(dropped, attname, fout);
8362 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8363 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8364 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8366 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8367 fmtId(tyinfo->dobj.name));
8368 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8372 appendPQExpBuffer(q, "\n);\n");
8373 appendPQExpBufferStr(q, dropped->data);
8376 * DROP must be fully qualified in case same name appears in pg_catalog
8378 appendPQExpBuffer(delq, "DROP TYPE %s.",
8379 fmtId(tyinfo->dobj.namespace->dobj.name));
8380 appendPQExpBuffer(delq, "%s;\n",
8381 fmtId(tyinfo->dobj.name));
8383 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8386 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8388 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8390 tyinfo->dobj.namespace->dobj.name,
8392 tyinfo->rolname, false,
8393 "TYPE", SECTION_PRE_DATA,
8394 q->data, delq->data, NULL,
8395 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8399 /* Dump Type Comments and Security Labels */
8400 dumpComment(fout, labelq->data,
8401 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8402 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8403 dumpSecLabel(fout, labelq->data,
8404 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8405 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8408 destroyPQExpBuffer(q);
8409 destroyPQExpBuffer(dropped);
8410 destroyPQExpBuffer(delq);
8411 destroyPQExpBuffer(labelq);
8412 destroyPQExpBuffer(query);
8414 /* Dump any per-column comments */
8415 dumpCompositeTypeColComments(fout, tyinfo);
8419 * dumpCompositeTypeColComments
8420 * writes out to fout the queries to recreate comments on the columns of
8421 * a user-defined stand-alone composite type
8424 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8426 CommentItem *comments;
8437 query = createPQExpBuffer();
8439 /* We assume here that remoteVersion must be at least 70300 */
8440 appendPQExpBuffer(query,
8441 "SELECT c.tableoid, a.attname, a.attnum "
8442 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8443 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8444 " AND NOT a.attisdropped "
8445 "ORDER BY a.attnum ",
8448 /* Fetch column attnames */
8449 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8451 ntups = PQntuples(res);
8455 destroyPQExpBuffer(query);
8459 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8461 /* Search for comments associated with type's pg_class OID */
8462 ncomments = findComments(fout,
8467 /* If no comments exist, we're done */
8471 destroyPQExpBuffer(query);
8475 /* Build COMMENT ON statements */
8476 target = createPQExpBuffer();
8478 i_attnum = PQfnumber(res, "attnum");
8479 i_attname = PQfnumber(res, "attname");
8480 while (ncomments > 0)
8482 const char *attname;
8485 for (i = 0; i < ntups; i++)
8487 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8489 attname = PQgetvalue(res, i, i_attname);
8493 if (attname) /* just in case we don't find it */
8495 const char *descr = comments->descr;
8497 resetPQExpBuffer(target);
8498 appendPQExpBuffer(target, "COLUMN %s.",
8499 fmtId(tyinfo->dobj.name));
8500 appendPQExpBuffer(target, "%s",
8503 resetPQExpBuffer(query);
8504 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8505 appendStringLiteralAH(query, descr, fout);
8506 appendPQExpBuffer(query, ";\n");
8508 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8510 tyinfo->dobj.namespace->dobj.name,
8511 NULL, tyinfo->rolname,
8512 false, "COMMENT", SECTION_NONE,
8513 query->data, "", NULL,
8514 &(tyinfo->dobj.dumpId), 1,
8523 destroyPQExpBuffer(query);
8524 destroyPQExpBuffer(target);
8529 * writes out to fout the queries to create a shell type
8531 * We dump a shell definition in advance of the I/O functions for the type.
8534 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8538 /* Skip if not to be dumped */
8539 if (!stinfo->dobj.dump || dataOnly)
8542 q = createPQExpBuffer();
8545 * Note the lack of a DROP command for the shell type; any required DROP
8546 * is driven off the base type entry, instead. This interacts with
8547 * _printTocEntry()'s use of the presence of a DROP command to decide
8548 * whether an entry needs an ALTER OWNER command. We don't want to alter
8549 * the shell type's owner immediately on creation; that should happen only
8550 * after it's filled in, otherwise the backend complains.
8554 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8555 stinfo->baseType->dobj.catId.oid);
8557 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8558 fmtId(stinfo->dobj.name));
8560 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8562 stinfo->dobj.namespace->dobj.name,
8564 stinfo->baseType->rolname, false,
8565 "SHELL TYPE", SECTION_PRE_DATA,
8567 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8570 destroyPQExpBuffer(q);
8574 * Determine whether we want to dump definitions for procedural languages.
8575 * Since the languages themselves don't have schemas, we can't rely on
8576 * the normal schema-based selection mechanism. We choose to dump them
8577 * whenever neither --schema nor --table was given. (Before 8.1, we used
8578 * the dump flag of the PL's call handler function, but in 8.1 this will
8579 * probably always be false since call handlers are created in pg_catalog.)
8581 * For some backwards compatibility with the older behavior, we forcibly
8582 * dump a PL if its handler function (and validator if any) are in a
8583 * dumpable namespace. That case is not checked here.
8585 * Also, if the PL belongs to an extension, we do not use this heuristic.
8586 * That case isn't checked here either.
8589 shouldDumpProcLangs(void)
8591 if (!include_everything)
8593 /* And they're schema not data */
8601 * writes out to fout the queries to recreate a user-defined
8602 * procedural language
8605 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8614 FuncInfo *inlineInfo = NULL;
8615 FuncInfo *validatorInfo = NULL;
8617 /* Skip if not to be dumped */
8618 if (!plang->dobj.dump || dataOnly)
8622 * Try to find the support function(s). It is not an error if we don't
8623 * find them --- if the functions are in the pg_catalog schema, as is
8624 * standard in 8.1 and up, then we won't have loaded them. (In this case
8625 * we will emit a parameterless CREATE LANGUAGE command, which will
8626 * require PL template knowledge in the backend to reload.)
8629 funcInfo = findFuncByOid(plang->lanplcallfoid);
8630 if (funcInfo != NULL && !funcInfo->dobj.dump)
8631 funcInfo = NULL; /* treat not-dumped same as not-found */
8633 if (OidIsValid(plang->laninline))
8635 inlineInfo = findFuncByOid(plang->laninline);
8636 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8640 if (OidIsValid(plang->lanvalidator))
8642 validatorInfo = findFuncByOid(plang->lanvalidator);
8643 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8644 validatorInfo = NULL;
8648 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8649 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8652 * However, for a language that belongs to an extension, we must not use
8653 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8654 * told to (via dobj.dump). Generally the support functions will belong
8655 * to the same extension and so have the same dump flags ... if they
8656 * don't, this might not work terribly nicely.
8658 useParams = (funcInfo != NULL &&
8659 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8660 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8662 if (!plang->dobj.ext_member)
8664 if (!useParams && !shouldDumpProcLangs())
8668 defqry = createPQExpBuffer();
8669 delqry = createPQExpBuffer();
8670 labelq = createPQExpBuffer();
8672 qlanname = pg_strdup(fmtId(plang->dobj.name));
8675 * If dumping a HANDLER clause, treat the language as being in the handler
8676 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8677 * it doesn't really have a schema.
8680 lanschema = funcInfo->dobj.namespace->dobj.name;
8684 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8689 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8690 plang->lanpltrusted ? "TRUSTED " : "",
8692 appendPQExpBuffer(defqry, " HANDLER %s",
8693 fmtId(funcInfo->dobj.name));
8694 if (OidIsValid(plang->laninline))
8696 appendPQExpBuffer(defqry, " INLINE ");
8697 /* Cope with possibility that inline is in different schema */
8698 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8699 appendPQExpBuffer(defqry, "%s.",
8700 fmtId(inlineInfo->dobj.namespace->dobj.name));
8701 appendPQExpBuffer(defqry, "%s",
8702 fmtId(inlineInfo->dobj.name));
8704 if (OidIsValid(plang->lanvalidator))
8706 appendPQExpBuffer(defqry, " VALIDATOR ");
8707 /* Cope with possibility that validator is in different schema */
8708 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8709 appendPQExpBuffer(defqry, "%s.",
8710 fmtId(validatorInfo->dobj.namespace->dobj.name));
8711 appendPQExpBuffer(defqry, "%s",
8712 fmtId(validatorInfo->dobj.name));
8718 * If not dumping parameters, then use CREATE OR REPLACE so that the
8719 * command will not fail if the language is preinstalled in the target
8720 * database. We restrict the use of REPLACE to this case so as to
8721 * eliminate the risk of replacing a language with incompatible
8722 * parameter settings: this command will only succeed at all if there
8723 * is a pg_pltemplate entry, and if there is one, the existing entry
8724 * must match it too.
8726 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8729 appendPQExpBuffer(defqry, ";\n");
8731 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8734 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8736 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8738 lanschema, NULL, plang->lanowner,
8739 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8740 defqry->data, delqry->data, NULL,
8741 plang->dobj.dependencies, plang->dobj.nDeps,
8744 /* Dump Proc Lang Comments and Security Labels */
8745 dumpComment(fout, labelq->data,
8747 plang->dobj.catId, 0, plang->dobj.dumpId);
8748 dumpSecLabel(fout, labelq->data,
8750 plang->dobj.catId, 0, plang->dobj.dumpId);
8752 if (plang->lanpltrusted)
8753 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8754 qlanname, NULL, plang->dobj.name,
8756 plang->lanowner, plang->lanacl);
8760 destroyPQExpBuffer(defqry);
8761 destroyPQExpBuffer(delqry);
8762 destroyPQExpBuffer(labelq);
8766 * format_function_arguments: generate function name and argument list
8768 * This is used when we can rely on pg_get_function_arguments to format
8769 * the argument list.
8772 format_function_arguments(FuncInfo *finfo, char *funcargs)
8776 initPQExpBuffer(&fn);
8777 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8782 * format_function_arguments_old: generate function name and argument list
8784 * The argument type names are qualified if needed. The function name
8785 * is never qualified.
8787 * This is used only with pre-8.4 servers, so we aren't expecting to see
8788 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8790 * Any or all of allargtypes, argmodes, argnames may be NULL.
8793 format_function_arguments_old(Archive *fout,
8794 FuncInfo *finfo, int nallargs,
8802 initPQExpBuffer(&fn);
8803 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8804 for (j = 0; j < nallargs; j++)
8808 const char *argmode;
8809 const char *argname;
8811 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8812 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8816 switch (argmodes[j][0])
8821 case PROARGMODE_OUT:
8824 case PROARGMODE_INOUT:
8828 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8836 argname = argnames ? argnames[j] : (char *) NULL;
8837 if (argname && argname[0] == '\0')
8840 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8841 (j > 0) ? ", " : "",
8843 argname ? fmtId(argname) : "",
8848 appendPQExpBuffer(&fn, ")");
8853 * format_function_signature: generate function name and argument list
8855 * This is like format_function_arguments_old except that only a minimal
8856 * list of input argument types is generated; this is sufficient to
8857 * reference the function, but not to define it.
8859 * If honor_quotes is false then the function name is never quoted.
8860 * This is appropriate for use in TOC tags, but not in SQL commands.
8863 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8868 initPQExpBuffer(&fn);
8870 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8872 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8873 for (j = 0; j < finfo->nargs; j++)
8877 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8880 appendPQExpBuffer(&fn, "%s%s",
8881 (j > 0) ? ", " : "",
8885 appendPQExpBuffer(&fn, ")");
8892 * dump out one function
8895 dumpFunc(Archive *fout, FuncInfo *finfo)
8903 char *funcsig; /* identity signature */
8904 char *funcfullsig; /* full signature */
8912 char *proallargtypes;
8926 char **allargtypes = NULL;
8927 char **argmodes = NULL;
8928 char **argnames = NULL;
8929 char **configitems = NULL;
8930 int nconfigitems = 0;
8933 /* Skip if not to be dumped */
8934 if (!finfo->dobj.dump || dataOnly)
8937 query = createPQExpBuffer();
8938 q = createPQExpBuffer();
8939 delqry = createPQExpBuffer();
8940 labelq = createPQExpBuffer();
8941 asPart = createPQExpBuffer();
8943 /* Set proper schema search path so type references list correctly */
8944 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8946 /* Fetch function-specific details */
8947 if (fout->remoteVersion >= 90200)
8950 * proleakproof was added at v9.2
8952 appendPQExpBuffer(query,
8953 "SELECT proretset, prosrc, probin, "
8954 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8955 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8956 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8957 "proiswindow, provolatile, proisstrict, prosecdef, "
8958 "proleakproof, proconfig, procost, prorows, "
8959 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8960 "FROM pg_catalog.pg_proc "
8961 "WHERE oid = '%u'::pg_catalog.oid",
8962 finfo->dobj.catId.oid);
8964 else if (fout->remoteVersion >= 80400)
8967 * In 8.4 and up we rely on pg_get_function_arguments and
8968 * pg_get_function_result instead of examining proallargtypes etc.
8970 appendPQExpBuffer(query,
8971 "SELECT proretset, prosrc, probin, "
8972 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8973 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8974 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8975 "proiswindow, provolatile, proisstrict, prosecdef, "
8976 "false AS proleakproof, "
8977 " proconfig, procost, prorows, "
8978 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8979 "FROM pg_catalog.pg_proc "
8980 "WHERE oid = '%u'::pg_catalog.oid",
8981 finfo->dobj.catId.oid);
8983 else if (fout->remoteVersion >= 80300)
8985 appendPQExpBuffer(query,
8986 "SELECT proretset, prosrc, probin, "
8987 "proallargtypes, proargmodes, proargnames, "
8988 "false AS proiswindow, "
8989 "provolatile, proisstrict, prosecdef, "
8990 "false AS proleakproof, "
8991 "proconfig, procost, prorows, "
8992 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8993 "FROM pg_catalog.pg_proc "
8994 "WHERE oid = '%u'::pg_catalog.oid",
8995 finfo->dobj.catId.oid);
8997 else if (fout->remoteVersion >= 80100)
8999 appendPQExpBuffer(query,
9000 "SELECT proretset, prosrc, probin, "
9001 "proallargtypes, proargmodes, proargnames, "
9002 "false AS proiswindow, "
9003 "provolatile, proisstrict, prosecdef, "
9004 "false AS proleakproof, "
9005 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9006 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9007 "FROM pg_catalog.pg_proc "
9008 "WHERE oid = '%u'::pg_catalog.oid",
9009 finfo->dobj.catId.oid);
9011 else if (fout->remoteVersion >= 80000)
9013 appendPQExpBuffer(query,
9014 "SELECT proretset, prosrc, probin, "
9015 "null AS proallargtypes, "
9016 "null AS proargmodes, "
9018 "false AS proiswindow, "
9019 "provolatile, proisstrict, prosecdef, "
9020 "false AS proleakproof, "
9021 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9022 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9023 "FROM pg_catalog.pg_proc "
9024 "WHERE oid = '%u'::pg_catalog.oid",
9025 finfo->dobj.catId.oid);
9027 else if (fout->remoteVersion >= 70300)
9029 appendPQExpBuffer(query,
9030 "SELECT proretset, prosrc, probin, "
9031 "null AS proallargtypes, "
9032 "null AS proargmodes, "
9033 "null AS proargnames, "
9034 "false AS proiswindow, "
9035 "provolatile, proisstrict, prosecdef, "
9036 "false AS proleakproof, "
9037 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9038 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9039 "FROM pg_catalog.pg_proc "
9040 "WHERE oid = '%u'::pg_catalog.oid",
9041 finfo->dobj.catId.oid);
9043 else if (fout->remoteVersion >= 70100)
9045 appendPQExpBuffer(query,
9046 "SELECT proretset, prosrc, probin, "
9047 "null AS proallargtypes, "
9048 "null AS proargmodes, "
9049 "null AS proargnames, "
9050 "false AS proiswindow, "
9051 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9053 "false AS prosecdef, "
9054 "false AS proleakproof, "
9055 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9056 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9058 "WHERE oid = '%u'::oid",
9059 finfo->dobj.catId.oid);
9063 appendPQExpBuffer(query,
9064 "SELECT proretset, prosrc, probin, "
9065 "null AS proallargtypes, "
9066 "null AS proargmodes, "
9067 "null AS proargnames, "
9068 "false AS proiswindow, "
9069 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9070 "false AS proisstrict, "
9071 "false AS prosecdef, "
9072 "false AS proleakproof, "
9073 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9074 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9076 "WHERE oid = '%u'::oid",
9077 finfo->dobj.catId.oid);
9080 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9082 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9083 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9084 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9085 if (fout->remoteVersion >= 80400)
9087 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9088 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9089 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9090 proallargtypes = proargmodes = proargnames = NULL;
9094 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9095 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9096 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9097 funcargs = funciargs = funcresult = NULL;
9099 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9100 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9101 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9102 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9103 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9104 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9105 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9106 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9107 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9110 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9111 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9112 * versions would set it to "-". There are no known cases in which prosrc
9113 * is unused, so the tests below for "-" are probably useless.
9115 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9117 appendPQExpBuffer(asPart, "AS ");
9118 appendStringLiteralAH(asPart, probin, fout);
9119 if (strcmp(prosrc, "-") != 0)
9121 appendPQExpBuffer(asPart, ", ");
9124 * where we have bin, use dollar quoting if allowed and src
9125 * contains quote or backslash; else use regular quoting.
9127 if (disable_dollar_quoting ||
9128 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9129 appendStringLiteralAH(asPart, prosrc, fout);
9131 appendStringLiteralDQ(asPart, prosrc, NULL);
9136 if (strcmp(prosrc, "-") != 0)
9138 appendPQExpBuffer(asPart, "AS ");
9139 /* with no bin, dollar quote src unconditionally if allowed */
9140 if (disable_dollar_quoting)
9141 appendStringLiteralAH(asPart, prosrc, fout);
9143 appendStringLiteralDQ(asPart, prosrc, NULL);
9147 nallargs = finfo->nargs; /* unless we learn different from allargs */
9149 if (proallargtypes && *proallargtypes)
9153 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9154 nitems < finfo->nargs)
9156 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9165 if (proargmodes && *proargmodes)
9169 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9172 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9179 if (proargnames && *proargnames)
9183 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9186 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9193 if (proconfig && *proconfig)
9195 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9197 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9207 /* 8.4 or later; we rely on server-side code for most of the work */
9208 funcfullsig = format_function_arguments(finfo, funcargs);
9209 funcsig = format_function_arguments(finfo, funciargs);
9213 /* pre-8.4, do it ourselves */
9214 funcsig = format_function_arguments_old(fout,
9215 finfo, nallargs, allargtypes,
9216 argmodes, argnames);
9217 funcfullsig = funcsig;
9220 funcsig_tag = format_function_signature(fout, finfo, false);
9223 * DROP must be fully qualified in case same name appears in pg_catalog
9225 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9226 fmtId(finfo->dobj.namespace->dobj.name),
9229 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9231 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9234 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9236 appendPQExpBuffer(q, "RETURNS %s%s",
9237 (proretset[0] == 't') ? "SETOF " : "",
9242 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9244 if (proiswindow[0] == 't')
9245 appendPQExpBuffer(q, " WINDOW");
9247 if (provolatile[0] != PROVOLATILE_VOLATILE)
9249 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9250 appendPQExpBuffer(q, " IMMUTABLE");
9251 else if (provolatile[0] == PROVOLATILE_STABLE)
9252 appendPQExpBuffer(q, " STABLE");
9253 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9254 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9258 if (proisstrict[0] == 't')
9259 appendPQExpBuffer(q, " STRICT");
9261 if (prosecdef[0] == 't')
9262 appendPQExpBuffer(q, " SECURITY DEFINER");
9264 if (proleakproof[0] == 't')
9265 appendPQExpBuffer(q, " LEAKPROOF");
9268 * COST and ROWS are emitted only if present and not default, so as not to
9269 * break backwards-compatibility of the dump without need. Keep this code
9270 * in sync with the defaults in functioncmds.c.
9272 if (strcmp(procost, "0") != 0)
9274 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9276 /* default cost is 1 */
9277 if (strcmp(procost, "1") != 0)
9278 appendPQExpBuffer(q, " COST %s", procost);
9282 /* default cost is 100 */
9283 if (strcmp(procost, "100") != 0)
9284 appendPQExpBuffer(q, " COST %s", procost);
9287 if (proretset[0] == 't' &&
9288 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9289 appendPQExpBuffer(q, " ROWS %s", prorows);
9291 for (i = 0; i < nconfigitems; i++)
9293 /* we feel free to scribble on configitems[] here */
9294 char *configitem = configitems[i];
9297 pos = strchr(configitem, '=');
9301 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9304 * Some GUC variable names are 'LIST' type and hence must not be
9307 if (pg_strcasecmp(configitem, "DateStyle") == 0
9308 || pg_strcasecmp(configitem, "search_path") == 0)
9309 appendPQExpBuffer(q, "%s", pos);
9311 appendStringLiteralAH(q, pos, fout);
9314 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9316 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9319 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9321 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9323 finfo->dobj.namespace->dobj.name,
9325 finfo->rolname, false,
9326 "FUNCTION", SECTION_PRE_DATA,
9327 q->data, delqry->data, NULL,
9328 finfo->dobj.dependencies, finfo->dobj.nDeps,
9331 /* Dump Function Comments and Security Labels */
9332 dumpComment(fout, labelq->data,
9333 finfo->dobj.namespace->dobj.name, finfo->rolname,
9334 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9335 dumpSecLabel(fout, labelq->data,
9336 finfo->dobj.namespace->dobj.name, finfo->rolname,
9337 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9339 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9340 funcsig, NULL, funcsig_tag,
9341 finfo->dobj.namespace->dobj.name,
9342 finfo->rolname, finfo->proacl);
9346 destroyPQExpBuffer(query);
9347 destroyPQExpBuffer(q);
9348 destroyPQExpBuffer(delqry);
9349 destroyPQExpBuffer(labelq);
9350 destroyPQExpBuffer(asPart);
9365 * Dump a user-defined cast
9368 dumpCast(Archive *fout, CastInfo *cast)
9373 FuncInfo *funcInfo = NULL;
9375 /* Skip if not to be dumped */
9376 if (!cast->dobj.dump || dataOnly)
9379 /* Cannot dump if we don't have the cast function's info */
9380 if (OidIsValid(cast->castfunc))
9382 funcInfo = findFuncByOid(cast->castfunc);
9383 if (funcInfo == NULL)
9388 * As per discussion we dump casts if one or more of the underlying
9389 * objects (the conversion function and the two data types) are not
9390 * builtin AND if all of the non-builtin objects are included in the dump.
9391 * Builtin meaning, the namespace name does not start with "pg_".
9393 * However, for a cast that belongs to an extension, we must not use this
9394 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9396 if (!cast->dobj.ext_member)
9398 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9399 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9401 if (sourceInfo == NULL || targetInfo == NULL)
9405 * Skip this cast if all objects are from pg_
9407 if ((funcInfo == NULL ||
9408 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9409 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9410 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9414 * Skip cast if function isn't from pg_ and is not to be dumped.
9417 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9418 !funcInfo->dobj.dump)
9422 * Same for the source type
9424 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9425 !sourceInfo->dobj.dump)
9429 * and the target type.
9431 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9432 !targetInfo->dobj.dump)
9436 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9437 selectSourceSchema(fout, "pg_catalog");
9439 defqry = createPQExpBuffer();
9440 delqry = createPQExpBuffer();
9441 labelq = createPQExpBuffer();
9443 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9444 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9445 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9447 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9448 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9449 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9451 switch (cast->castmethod)
9453 case COERCION_METHOD_BINARY:
9454 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9456 case COERCION_METHOD_INOUT:
9457 appendPQExpBuffer(defqry, "WITH INOUT");
9459 case COERCION_METHOD_FUNCTION:
9462 char *fsig = format_function_signature(fout, funcInfo, true);
9465 * Always qualify the function name, in case it is not in
9466 * pg_catalog schema (format_function_signature won't qualify it).
9468 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9469 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9473 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9476 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9479 if (cast->castcontext == 'a')
9480 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9481 else if (cast->castcontext == 'i')
9482 appendPQExpBuffer(defqry, " AS IMPLICIT");
9483 appendPQExpBuffer(defqry, ";\n");
9485 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9486 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9487 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9490 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9492 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9494 "pg_catalog", NULL, "",
9495 false, "CAST", SECTION_PRE_DATA,
9496 defqry->data, delqry->data, NULL,
9497 cast->dobj.dependencies, cast->dobj.nDeps,
9500 /* Dump Cast Comments */
9501 dumpComment(fout, labelq->data,
9503 cast->dobj.catId, 0, cast->dobj.dumpId);
9505 destroyPQExpBuffer(defqry);
9506 destroyPQExpBuffer(delqry);
9507 destroyPQExpBuffer(labelq);
9512 * write out a single operator definition
9515 dumpOpr(Archive *fout, OprInfo *oprinfo)
9522 PQExpBuffer details;
9546 /* Skip if not to be dumped */
9547 if (!oprinfo->dobj.dump || dataOnly)
9551 * some operators are invalid because they were the result of user
9552 * defining operators before commutators exist
9554 if (!OidIsValid(oprinfo->oprcode))
9557 query = createPQExpBuffer();
9558 q = createPQExpBuffer();
9559 delq = createPQExpBuffer();
9560 labelq = createPQExpBuffer();
9561 oprid = createPQExpBuffer();
9562 details = createPQExpBuffer();
9564 /* Make sure we are in proper schema so regoperator works correctly */
9565 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9567 if (fout->remoteVersion >= 80300)
9569 appendPQExpBuffer(query, "SELECT oprkind, "
9570 "oprcode::pg_catalog.regprocedure, "
9571 "oprleft::pg_catalog.regtype, "
9572 "oprright::pg_catalog.regtype, "
9573 "oprcom::pg_catalog.regoperator, "
9574 "oprnegate::pg_catalog.regoperator, "
9575 "oprrest::pg_catalog.regprocedure, "
9576 "oprjoin::pg_catalog.regprocedure, "
9577 "oprcanmerge, oprcanhash "
9578 "FROM pg_catalog.pg_operator "
9579 "WHERE oid = '%u'::pg_catalog.oid",
9580 oprinfo->dobj.catId.oid);
9582 else if (fout->remoteVersion >= 70300)
9584 appendPQExpBuffer(query, "SELECT oprkind, "
9585 "oprcode::pg_catalog.regprocedure, "
9586 "oprleft::pg_catalog.regtype, "
9587 "oprright::pg_catalog.regtype, "
9588 "oprcom::pg_catalog.regoperator, "
9589 "oprnegate::pg_catalog.regoperator, "
9590 "oprrest::pg_catalog.regprocedure, "
9591 "oprjoin::pg_catalog.regprocedure, "
9592 "(oprlsortop != 0) AS oprcanmerge, "
9594 "FROM pg_catalog.pg_operator "
9595 "WHERE oid = '%u'::pg_catalog.oid",
9596 oprinfo->dobj.catId.oid);
9598 else if (fout->remoteVersion >= 70100)
9600 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9601 "CASE WHEN oprleft = 0 THEN '-' "
9602 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9603 "CASE WHEN oprright = 0 THEN '-' "
9604 "ELSE format_type(oprright, NULL) END AS oprright, "
9605 "oprcom, oprnegate, oprrest, oprjoin, "
9606 "(oprlsortop != 0) AS oprcanmerge, "
9609 "WHERE oid = '%u'::oid",
9610 oprinfo->dobj.catId.oid);
9614 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9615 "CASE WHEN oprleft = 0 THEN '-'::name "
9616 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9617 "CASE WHEN oprright = 0 THEN '-'::name "
9618 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9619 "oprcom, oprnegate, oprrest, oprjoin, "
9620 "(oprlsortop != 0) AS oprcanmerge, "
9623 "WHERE oid = '%u'::oid",
9624 oprinfo->dobj.catId.oid);
9627 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9629 i_oprkind = PQfnumber(res, "oprkind");
9630 i_oprcode = PQfnumber(res, "oprcode");
9631 i_oprleft = PQfnumber(res, "oprleft");
9632 i_oprright = PQfnumber(res, "oprright");
9633 i_oprcom = PQfnumber(res, "oprcom");
9634 i_oprnegate = PQfnumber(res, "oprnegate");
9635 i_oprrest = PQfnumber(res, "oprrest");
9636 i_oprjoin = PQfnumber(res, "oprjoin");
9637 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9638 i_oprcanhash = PQfnumber(res, "oprcanhash");
9640 oprkind = PQgetvalue(res, 0, i_oprkind);
9641 oprcode = PQgetvalue(res, 0, i_oprcode);
9642 oprleft = PQgetvalue(res, 0, i_oprleft);
9643 oprright = PQgetvalue(res, 0, i_oprright);
9644 oprcom = PQgetvalue(res, 0, i_oprcom);
9645 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9646 oprrest = PQgetvalue(res, 0, i_oprrest);
9647 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9648 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9649 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9651 appendPQExpBuffer(details, " PROCEDURE = %s",
9652 convertRegProcReference(fout, oprcode));
9654 appendPQExpBuffer(oprid, "%s (",
9655 oprinfo->dobj.name);
9658 * right unary means there's a left arg and left unary means there's a
9661 if (strcmp(oprkind, "r") == 0 ||
9662 strcmp(oprkind, "b") == 0)
9664 if (fout->remoteVersion >= 70100)
9667 name = fmtId(oprleft);
9668 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9669 appendPQExpBuffer(oprid, "%s", name);
9672 appendPQExpBuffer(oprid, "NONE");
9674 if (strcmp(oprkind, "l") == 0 ||
9675 strcmp(oprkind, "b") == 0)
9677 if (fout->remoteVersion >= 70100)
9680 name = fmtId(oprright);
9681 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9682 appendPQExpBuffer(oprid, ", %s)", name);
9685 appendPQExpBuffer(oprid, ", NONE)");
9687 name = convertOperatorReference(fout, oprcom);
9689 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9691 name = convertOperatorReference(fout, oprnegate);
9693 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9695 if (strcmp(oprcanmerge, "t") == 0)
9696 appendPQExpBuffer(details, ",\n MERGES");
9698 if (strcmp(oprcanhash, "t") == 0)
9699 appendPQExpBuffer(details, ",\n HASHES");
9701 name = convertRegProcReference(fout, oprrest);
9703 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9705 name = convertRegProcReference(fout, oprjoin);
9707 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9710 * DROP must be fully qualified in case same name appears in pg_catalog
9712 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9713 fmtId(oprinfo->dobj.namespace->dobj.name),
9716 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9717 oprinfo->dobj.name, details->data);
9719 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9722 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9724 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9726 oprinfo->dobj.namespace->dobj.name,
9729 false, "OPERATOR", SECTION_PRE_DATA,
9730 q->data, delq->data, NULL,
9731 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9734 /* Dump Operator Comments */
9735 dumpComment(fout, labelq->data,
9736 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9737 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9741 destroyPQExpBuffer(query);
9742 destroyPQExpBuffer(q);
9743 destroyPQExpBuffer(delq);
9744 destroyPQExpBuffer(labelq);
9745 destroyPQExpBuffer(oprid);
9746 destroyPQExpBuffer(details);
9750 * Convert a function reference obtained from pg_operator
9752 * Returns what to print, or NULL if function references is InvalidOid
9754 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9755 * argument-types part. In prior versions, the input is a REGPROC display.
9758 convertRegProcReference(Archive *fout, const char *proc)
9760 /* In all cases "-" means a null reference */
9761 if (strcmp(proc, "-") == 0)
9764 if (fout->remoteVersion >= 70300)
9770 name = pg_strdup(proc);
9771 /* find non-double-quoted left paren */
9773 for (paren = name; *paren; paren++)
9775 if (*paren == '(' && !inquote)
9786 /* REGPROC before 7.3 does not quote its result */
9791 * Convert an operator cross-reference obtained from pg_operator
9793 * Returns what to print, or NULL to print nothing
9795 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9796 * argument-types part, and add OPERATOR() decoration if the name is
9797 * schema-qualified. In older versions, the input is just a numeric OID,
9798 * which we search our operator list for.
9801 convertOperatorReference(Archive *fout, const char *opr)
9805 /* In all cases "0" means a null reference */
9806 if (strcmp(opr, "0") == 0)
9809 if (fout->remoteVersion >= 70300)
9817 name = pg_strdup(opr);
9818 /* find non-double-quoted left paren, and check for non-quoted dot */
9821 for (ptr = name; *ptr; ptr++)
9825 else if (*ptr == '.' && !inquote)
9827 else if (*ptr == '(' && !inquote)
9833 /* If not schema-qualified, don't need to add OPERATOR() */
9836 oname = pg_malloc(strlen(name) + 11);
9837 sprintf(oname, "OPERATOR(%s)", name);
9842 oprInfo = findOprByOid(atooid(opr));
9843 if (oprInfo == NULL)
9845 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9849 return oprInfo->dobj.name;
9853 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9855 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9856 * argument lists of these functions are predetermined. Note that the
9857 * caller should ensure we are in the proper schema, because the results
9858 * are search path dependent!
9861 convertTSFunction(Archive *fout, Oid funcOid)
9867 snprintf(query, sizeof(query),
9868 "SELECT '%u'::pg_catalog.regproc", funcOid);
9869 res = ExecuteSqlQueryForSingleRow(fout, query);
9871 result = pg_strdup(PQgetvalue(res, 0, 0));
9881 * write out a single operator class definition
9884 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9896 int i_opcfamilyname;
9903 int i_sortfamilynsp;
9906 int i_amproclefttype;
9907 int i_amprocrighttype;
9912 char *opcfamilyname;
9919 char *sortfamilynsp;
9922 char *amproclefttype;
9923 char *amprocrighttype;
9927 /* Skip if not to be dumped */
9928 if (!opcinfo->dobj.dump || dataOnly)
9932 * XXX currently we do not implement dumping of operator classes from
9933 * pre-7.3 databases. This could be done but it seems not worth the
9936 if (fout->remoteVersion < 70300)
9939 query = createPQExpBuffer();
9940 q = createPQExpBuffer();
9941 delq = createPQExpBuffer();
9942 labelq = createPQExpBuffer();
9944 /* Make sure we are in proper schema so regoperator works correctly */
9945 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9947 /* Get additional fields from the pg_opclass row */
9948 if (fout->remoteVersion >= 80300)
9950 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9951 "opckeytype::pg_catalog.regtype, "
9952 "opcdefault, opcfamily, "
9953 "opfname AS opcfamilyname, "
9954 "nspname AS opcfamilynsp, "
9955 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9956 "FROM pg_catalog.pg_opclass c "
9957 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9958 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9959 "WHERE c.oid = '%u'::pg_catalog.oid",
9960 opcinfo->dobj.catId.oid);
9964 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9965 "opckeytype::pg_catalog.regtype, "
9966 "opcdefault, NULL AS opcfamily, "
9967 "NULL AS opcfamilyname, "
9968 "NULL AS opcfamilynsp, "
9969 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9970 "FROM pg_catalog.pg_opclass "
9971 "WHERE oid = '%u'::pg_catalog.oid",
9972 opcinfo->dobj.catId.oid);
9975 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9977 i_opcintype = PQfnumber(res, "opcintype");
9978 i_opckeytype = PQfnumber(res, "opckeytype");
9979 i_opcdefault = PQfnumber(res, "opcdefault");
9980 i_opcfamily = PQfnumber(res, "opcfamily");
9981 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9982 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9983 i_amname = PQfnumber(res, "amname");
9985 opcintype = PQgetvalue(res, 0, i_opcintype);
9986 opckeytype = PQgetvalue(res, 0, i_opckeytype);
9987 opcdefault = PQgetvalue(res, 0, i_opcdefault);
9988 /* opcfamily will still be needed after we PQclear res */
9989 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9990 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9991 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
9992 /* amname will still be needed after we PQclear res */
9993 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
9996 * DROP must be fully qualified in case same name appears in pg_catalog
9998 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
9999 fmtId(opcinfo->dobj.namespace->dobj.name));
10000 appendPQExpBuffer(delq, ".%s",
10001 fmtId(opcinfo->dobj.name));
10002 appendPQExpBuffer(delq, " USING %s;\n",
10005 /* Build the fixed portion of the CREATE command */
10006 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10007 fmtId(opcinfo->dobj.name));
10008 if (strcmp(opcdefault, "t") == 0)
10009 appendPQExpBuffer(q, "DEFAULT ");
10010 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10013 if (strlen(opcfamilyname) > 0 &&
10014 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10015 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10017 appendPQExpBuffer(q, " FAMILY ");
10018 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10019 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10020 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10022 appendPQExpBuffer(q, " AS\n ");
10026 if (strcmp(opckeytype, "-") != 0)
10028 appendPQExpBuffer(q, "STORAGE %s",
10036 * Now fetch and print the OPERATOR entries (pg_amop rows).
10038 * Print only those opfamily members that are tied to the opclass by
10039 * pg_depend entries.
10041 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10042 * older server's opclass in which it is used. This is to avoid
10043 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10044 * older server and then reload into that old version. This can go away
10045 * once 8.3 is so old as to not be of interest to anyone.
10047 resetPQExpBuffer(query);
10049 if (fout->remoteVersion >= 90100)
10051 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10052 "amopopr::pg_catalog.regoperator, "
10053 "opfname AS sortfamily, "
10054 "nspname AS sortfamilynsp "
10055 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10056 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10057 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10058 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10059 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10060 "AND refobjid = '%u'::pg_catalog.oid "
10061 "AND amopfamily = '%s'::pg_catalog.oid "
10062 "ORDER BY amopstrategy",
10063 opcinfo->dobj.catId.oid,
10066 else if (fout->remoteVersion >= 80400)
10068 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10069 "amopopr::pg_catalog.regoperator, "
10070 "NULL AS sortfamily, "
10071 "NULL AS sortfamilynsp "
10072 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10073 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10074 "AND refobjid = '%u'::pg_catalog.oid "
10075 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10076 "AND objid = ao.oid "
10077 "ORDER BY amopstrategy",
10078 opcinfo->dobj.catId.oid);
10080 else if (fout->remoteVersion >= 80300)
10082 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10083 "amopopr::pg_catalog.regoperator, "
10084 "NULL AS sortfamily, "
10085 "NULL AS sortfamilynsp "
10086 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10087 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10088 "AND refobjid = '%u'::pg_catalog.oid "
10089 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10090 "AND objid = ao.oid "
10091 "ORDER BY amopstrategy",
10092 opcinfo->dobj.catId.oid);
10097 * Here, we print all entries since there are no opfamilies and hence
10098 * no loose operators to worry about.
10100 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10101 "amopopr::pg_catalog.regoperator, "
10102 "NULL AS sortfamily, "
10103 "NULL AS sortfamilynsp "
10104 "FROM pg_catalog.pg_amop "
10105 "WHERE amopclaid = '%u'::pg_catalog.oid "
10106 "ORDER BY amopstrategy",
10107 opcinfo->dobj.catId.oid);
10110 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10112 ntups = PQntuples(res);
10114 i_amopstrategy = PQfnumber(res, "amopstrategy");
10115 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10116 i_amopopr = PQfnumber(res, "amopopr");
10117 i_sortfamily = PQfnumber(res, "sortfamily");
10118 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10120 for (i = 0; i < ntups; i++)
10122 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10123 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10124 amopopr = PQgetvalue(res, i, i_amopopr);
10125 sortfamily = PQgetvalue(res, i, i_sortfamily);
10126 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10129 appendPQExpBuffer(q, " ,\n ");
10131 appendPQExpBuffer(q, "OPERATOR %s %s",
10132 amopstrategy, amopopr);
10134 if (strlen(sortfamily) > 0)
10136 appendPQExpBuffer(q, " FOR ORDER BY ");
10137 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10138 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10139 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10142 if (strcmp(amopreqcheck, "t") == 0)
10143 appendPQExpBuffer(q, " RECHECK");
10151 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10153 * Print only those opfamily members that are tied to the opclass by
10154 * pg_depend entries.
10156 * We print the amproclefttype/amprocrighttype even though in most cases
10157 * the backend could deduce the right values, because of the corner case
10158 * of a btree sort support function for a cross-type comparison. That's
10159 * only allowed in 9.2 and later, but for simplicity print them in all
10160 * versions that have the columns.
10162 resetPQExpBuffer(query);
10164 if (fout->remoteVersion >= 80300)
10166 appendPQExpBuffer(query, "SELECT amprocnum, "
10167 "amproc::pg_catalog.regprocedure, "
10168 "amproclefttype::pg_catalog.regtype, "
10169 "amprocrighttype::pg_catalog.regtype "
10170 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10171 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10172 "AND refobjid = '%u'::pg_catalog.oid "
10173 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10174 "AND objid = ap.oid "
10175 "ORDER BY amprocnum",
10176 opcinfo->dobj.catId.oid);
10180 appendPQExpBuffer(query, "SELECT amprocnum, "
10181 "amproc::pg_catalog.regprocedure, "
10182 "'' AS amproclefttype, "
10183 "'' AS amprocrighttype "
10184 "FROM pg_catalog.pg_amproc "
10185 "WHERE amopclaid = '%u'::pg_catalog.oid "
10186 "ORDER BY amprocnum",
10187 opcinfo->dobj.catId.oid);
10190 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10192 ntups = PQntuples(res);
10194 i_amprocnum = PQfnumber(res, "amprocnum");
10195 i_amproc = PQfnumber(res, "amproc");
10196 i_amproclefttype = PQfnumber(res, "amproclefttype");
10197 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10199 for (i = 0; i < ntups; i++)
10201 amprocnum = PQgetvalue(res, i, i_amprocnum);
10202 amproc = PQgetvalue(res, i, i_amproc);
10203 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10204 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10207 appendPQExpBuffer(q, " ,\n ");
10209 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10211 if (*amproclefttype && *amprocrighttype)
10212 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10214 appendPQExpBuffer(q, " %s", amproc);
10221 appendPQExpBuffer(q, ";\n");
10223 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10224 fmtId(opcinfo->dobj.name));
10225 appendPQExpBuffer(labelq, " USING %s",
10228 if (binary_upgrade)
10229 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10231 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10232 opcinfo->dobj.name,
10233 opcinfo->dobj.namespace->dobj.name,
10236 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10237 q->data, delq->data, NULL,
10238 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10241 /* Dump Operator Class Comments */
10242 dumpComment(fout, labelq->data,
10243 NULL, opcinfo->rolname,
10244 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10247 destroyPQExpBuffer(query);
10248 destroyPQExpBuffer(q);
10249 destroyPQExpBuffer(delq);
10250 destroyPQExpBuffer(labelq);
10255 * write out a single operator family definition
10257 * Note: this also dumps any "loose" operator members that aren't bound to a
10258 * specific opclass within the opfamily.
10261 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10266 PQExpBuffer labelq;
10269 PGresult *res_procs;
10272 int i_amopstrategy;
10273 int i_amopreqcheck;
10276 int i_sortfamilynsp;
10279 int i_amproclefttype;
10280 int i_amprocrighttype;
10282 char *amopstrategy;
10283 char *amopreqcheck;
10286 char *sortfamilynsp;
10289 char *amproclefttype;
10290 char *amprocrighttype;
10294 /* Skip if not to be dumped */
10295 if (!opfinfo->dobj.dump || dataOnly)
10299 * We want to dump the opfamily only if (1) it contains "loose" operators
10300 * or functions, or (2) it contains an opclass with a different name or
10301 * owner. Otherwise it's sufficient to let it be created during creation
10302 * of the contained opclass, and not dumping it improves portability of
10303 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10307 query = createPQExpBuffer();
10308 q = createPQExpBuffer();
10309 delq = createPQExpBuffer();
10310 labelq = createPQExpBuffer();
10312 /* Make sure we are in proper schema so regoperator works correctly */
10313 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10316 * Fetch only those opfamily members that are tied directly to the
10317 * opfamily by pg_depend entries.
10319 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10320 * older server's opclass in which it is used. This is to avoid
10321 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10322 * older server and then reload into that old version. This can go away
10323 * once 8.3 is so old as to not be of interest to anyone.
10325 if (fout->remoteVersion >= 90100)
10327 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10328 "amopopr::pg_catalog.regoperator, "
10329 "opfname AS sortfamily, "
10330 "nspname AS sortfamilynsp "
10331 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10332 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10333 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10334 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10335 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10336 "AND refobjid = '%u'::pg_catalog.oid "
10337 "AND amopfamily = '%u'::pg_catalog.oid "
10338 "ORDER BY amopstrategy",
10339 opfinfo->dobj.catId.oid,
10340 opfinfo->dobj.catId.oid);
10342 else if (fout->remoteVersion >= 80400)
10344 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10345 "amopopr::pg_catalog.regoperator, "
10346 "NULL AS sortfamily, "
10347 "NULL AS sortfamilynsp "
10348 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10349 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10350 "AND refobjid = '%u'::pg_catalog.oid "
10351 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10352 "AND objid = ao.oid "
10353 "ORDER BY amopstrategy",
10354 opfinfo->dobj.catId.oid);
10358 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10359 "amopopr::pg_catalog.regoperator, "
10360 "NULL AS sortfamily, "
10361 "NULL AS sortfamilynsp "
10362 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10363 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10364 "AND refobjid = '%u'::pg_catalog.oid "
10365 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10366 "AND objid = ao.oid "
10367 "ORDER BY amopstrategy",
10368 opfinfo->dobj.catId.oid);
10371 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10373 resetPQExpBuffer(query);
10375 appendPQExpBuffer(query, "SELECT amprocnum, "
10376 "amproc::pg_catalog.regprocedure, "
10377 "amproclefttype::pg_catalog.regtype, "
10378 "amprocrighttype::pg_catalog.regtype "
10379 "FROM pg_catalog.pg_amproc ap, 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_amproc'::pg_catalog.regclass "
10383 "AND objid = ap.oid "
10384 "ORDER BY amprocnum",
10385 opfinfo->dobj.catId.oid);
10387 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10389 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10391 /* No loose members, so check contained opclasses */
10392 resetPQExpBuffer(query);
10394 appendPQExpBuffer(query, "SELECT 1 "
10395 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10396 "WHERE f.oid = '%u'::pg_catalog.oid "
10397 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10398 "AND refobjid = f.oid "
10399 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10400 "AND objid = c.oid "
10401 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10403 opfinfo->dobj.catId.oid);
10405 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10407 if (PQntuples(res) == 0)
10409 /* no need to dump it, so bail out */
10412 PQclear(res_procs);
10413 destroyPQExpBuffer(query);
10414 destroyPQExpBuffer(q);
10415 destroyPQExpBuffer(delq);
10416 destroyPQExpBuffer(labelq);
10423 /* Get additional fields from the pg_opfamily row */
10424 resetPQExpBuffer(query);
10426 appendPQExpBuffer(query, "SELECT "
10427 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10428 "FROM pg_catalog.pg_opfamily "
10429 "WHERE oid = '%u'::pg_catalog.oid",
10430 opfinfo->dobj.catId.oid);
10432 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10434 i_amname = PQfnumber(res, "amname");
10436 /* amname will still be needed after we PQclear res */
10437 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10440 * DROP must be fully qualified in case same name appears in pg_catalog
10442 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10443 fmtId(opfinfo->dobj.namespace->dobj.name));
10444 appendPQExpBuffer(delq, ".%s",
10445 fmtId(opfinfo->dobj.name));
10446 appendPQExpBuffer(delq, " USING %s;\n",
10449 /* Build the fixed portion of the CREATE command */
10450 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10451 fmtId(opfinfo->dobj.name));
10452 appendPQExpBuffer(q, " USING %s;\n",
10457 /* Do we need an ALTER to add loose members? */
10458 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10460 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10461 fmtId(opfinfo->dobj.name));
10462 appendPQExpBuffer(q, " USING %s ADD\n ",
10468 * Now fetch and print the OPERATOR entries (pg_amop rows).
10470 ntups = PQntuples(res_ops);
10472 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10473 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10474 i_amopopr = PQfnumber(res_ops, "amopopr");
10475 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10476 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10478 for (i = 0; i < ntups; i++)
10480 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10481 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10482 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10483 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10484 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10487 appendPQExpBuffer(q, " ,\n ");
10489 appendPQExpBuffer(q, "OPERATOR %s %s",
10490 amopstrategy, amopopr);
10492 if (strlen(sortfamily) > 0)
10494 appendPQExpBuffer(q, " FOR ORDER BY ");
10495 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10496 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10497 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10500 if (strcmp(amopreqcheck, "t") == 0)
10501 appendPQExpBuffer(q, " RECHECK");
10507 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10509 ntups = PQntuples(res_procs);
10511 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10512 i_amproc = PQfnumber(res_procs, "amproc");
10513 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10514 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10516 for (i = 0; i < ntups; i++)
10518 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10519 amproc = PQgetvalue(res_procs, i, i_amproc);
10520 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10521 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10524 appendPQExpBuffer(q, " ,\n ");
10526 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10527 amprocnum, amproclefttype, amprocrighttype,
10533 appendPQExpBuffer(q, ";\n");
10536 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10537 fmtId(opfinfo->dobj.name));
10538 appendPQExpBuffer(labelq, " USING %s",
10541 if (binary_upgrade)
10542 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10544 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10545 opfinfo->dobj.name,
10546 opfinfo->dobj.namespace->dobj.name,
10549 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10550 q->data, delq->data, NULL,
10551 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10554 /* Dump Operator Family Comments */
10555 dumpComment(fout, labelq->data,
10556 NULL, opfinfo->rolname,
10557 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10561 PQclear(res_procs);
10562 destroyPQExpBuffer(query);
10563 destroyPQExpBuffer(q);
10564 destroyPQExpBuffer(delq);
10565 destroyPQExpBuffer(labelq);
10570 * write out a single collation definition
10573 dumpCollation(Archive *fout, CollInfo *collinfo)
10578 PQExpBuffer labelq;
10582 const char *collcollate;
10583 const char *collctype;
10585 /* Skip if not to be dumped */
10586 if (!collinfo->dobj.dump || dataOnly)
10589 query = createPQExpBuffer();
10590 q = createPQExpBuffer();
10591 delq = createPQExpBuffer();
10592 labelq = createPQExpBuffer();
10594 /* Make sure we are in proper schema */
10595 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10597 /* Get conversion-specific details */
10598 appendPQExpBuffer(query, "SELECT "
10601 "FROM pg_catalog.pg_collation c "
10602 "WHERE c.oid = '%u'::pg_catalog.oid",
10603 collinfo->dobj.catId.oid);
10605 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10607 i_collcollate = PQfnumber(res, "collcollate");
10608 i_collctype = PQfnumber(res, "collctype");
10610 collcollate = PQgetvalue(res, 0, i_collcollate);
10611 collctype = PQgetvalue(res, 0, i_collctype);
10614 * DROP must be fully qualified in case same name appears in pg_catalog
10616 appendPQExpBuffer(delq, "DROP COLLATION %s",
10617 fmtId(collinfo->dobj.namespace->dobj.name));
10618 appendPQExpBuffer(delq, ".%s;\n",
10619 fmtId(collinfo->dobj.name));
10621 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10622 fmtId(collinfo->dobj.name));
10623 appendStringLiteralAH(q, collcollate, fout);
10624 appendPQExpBuffer(q, ", lc_ctype = ");
10625 appendStringLiteralAH(q, collctype, fout);
10626 appendPQExpBuffer(q, ");\n");
10628 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10630 if (binary_upgrade)
10631 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10633 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10634 collinfo->dobj.name,
10635 collinfo->dobj.namespace->dobj.name,
10638 false, "COLLATION", SECTION_PRE_DATA,
10639 q->data, delq->data, NULL,
10640 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10643 /* Dump Collation Comments */
10644 dumpComment(fout, labelq->data,
10645 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10646 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10650 destroyPQExpBuffer(query);
10651 destroyPQExpBuffer(q);
10652 destroyPQExpBuffer(delq);
10653 destroyPQExpBuffer(labelq);
10658 * write out a single conversion definition
10661 dumpConversion(Archive *fout, ConvInfo *convinfo)
10666 PQExpBuffer labelq;
10668 int i_conforencoding;
10669 int i_contoencoding;
10672 const char *conforencoding;
10673 const char *contoencoding;
10674 const char *conproc;
10677 /* Skip if not to be dumped */
10678 if (!convinfo->dobj.dump || dataOnly)
10681 query = createPQExpBuffer();
10682 q = createPQExpBuffer();
10683 delq = createPQExpBuffer();
10684 labelq = createPQExpBuffer();
10686 /* Make sure we are in proper schema */
10687 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10689 /* Get conversion-specific details */
10690 appendPQExpBuffer(query, "SELECT "
10691 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10692 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10693 "conproc, condefault "
10694 "FROM pg_catalog.pg_conversion c "
10695 "WHERE c.oid = '%u'::pg_catalog.oid",
10696 convinfo->dobj.catId.oid);
10698 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10700 i_conforencoding = PQfnumber(res, "conforencoding");
10701 i_contoencoding = PQfnumber(res, "contoencoding");
10702 i_conproc = PQfnumber(res, "conproc");
10703 i_condefault = PQfnumber(res, "condefault");
10705 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10706 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10707 conproc = PQgetvalue(res, 0, i_conproc);
10708 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10711 * DROP must be fully qualified in case same name appears in pg_catalog
10713 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10714 fmtId(convinfo->dobj.namespace->dobj.name));
10715 appendPQExpBuffer(delq, ".%s;\n",
10716 fmtId(convinfo->dobj.name));
10718 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10719 (condefault) ? "DEFAULT " : "",
10720 fmtId(convinfo->dobj.name));
10721 appendStringLiteralAH(q, conforencoding, fout);
10722 appendPQExpBuffer(q, " TO ");
10723 appendStringLiteralAH(q, contoencoding, fout);
10724 /* regproc is automatically quoted in 7.3 and above */
10725 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10727 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10729 if (binary_upgrade)
10730 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10732 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10733 convinfo->dobj.name,
10734 convinfo->dobj.namespace->dobj.name,
10737 false, "CONVERSION", SECTION_PRE_DATA,
10738 q->data, delq->data, NULL,
10739 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10742 /* Dump Conversion Comments */
10743 dumpComment(fout, labelq->data,
10744 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10745 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10749 destroyPQExpBuffer(query);
10750 destroyPQExpBuffer(q);
10751 destroyPQExpBuffer(delq);
10752 destroyPQExpBuffer(labelq);
10756 * format_aggregate_signature: generate aggregate name and argument list
10758 * The argument type names are qualified if needed. The aggregate name
10759 * is never qualified.
10762 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10764 PQExpBufferData buf;
10767 initPQExpBuffer(&buf);
10769 appendPQExpBuffer(&buf, "%s",
10770 fmtId(agginfo->aggfn.dobj.name));
10772 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10774 if (agginfo->aggfn.nargs == 0)
10775 appendPQExpBuffer(&buf, "(*)");
10778 appendPQExpBuffer(&buf, "(");
10779 for (j = 0; j < agginfo->aggfn.nargs; j++)
10783 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10786 appendPQExpBuffer(&buf, "%s%s",
10787 (j > 0) ? ", " : "",
10791 appendPQExpBuffer(&buf, ")");
10798 * write out a single aggregate definition
10801 dumpAgg(Archive *fout, AggInfo *agginfo)
10806 PQExpBuffer labelq;
10807 PQExpBuffer details;
10814 int i_aggtranstype;
10817 const char *aggtransfn;
10818 const char *aggfinalfn;
10819 const char *aggsortop;
10820 const char *aggtranstype;
10821 const char *agginitval;
10824 /* Skip if not to be dumped */
10825 if (!agginfo->aggfn.dobj.dump || dataOnly)
10828 query = createPQExpBuffer();
10829 q = createPQExpBuffer();
10830 delq = createPQExpBuffer();
10831 labelq = createPQExpBuffer();
10832 details = createPQExpBuffer();
10834 /* Make sure we are in proper schema */
10835 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10837 /* Get aggregate-specific details */
10838 if (fout->remoteVersion >= 80100)
10840 appendPQExpBuffer(query, "SELECT aggtransfn, "
10841 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10842 "aggsortop::pg_catalog.regoperator, "
10844 "'t'::boolean AS convertok "
10845 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10846 "WHERE a.aggfnoid = p.oid "
10847 "AND p.oid = '%u'::pg_catalog.oid",
10848 agginfo->aggfn.dobj.catId.oid);
10850 else if (fout->remoteVersion >= 70300)
10852 appendPQExpBuffer(query, "SELECT aggtransfn, "
10853 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10856 "'t'::boolean AS convertok "
10857 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10858 "WHERE a.aggfnoid = p.oid "
10859 "AND p.oid = '%u'::pg_catalog.oid",
10860 agginfo->aggfn.dobj.catId.oid);
10862 else if (fout->remoteVersion >= 70100)
10864 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10865 "format_type(aggtranstype, NULL) AS aggtranstype, "
10868 "'t'::boolean AS convertok "
10869 "FROM pg_aggregate "
10870 "WHERE oid = '%u'::oid",
10871 agginfo->aggfn.dobj.catId.oid);
10875 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10877 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10879 "agginitval1 AS agginitval, "
10880 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10881 "FROM pg_aggregate "
10882 "WHERE oid = '%u'::oid",
10883 agginfo->aggfn.dobj.catId.oid);
10886 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10888 i_aggtransfn = PQfnumber(res, "aggtransfn");
10889 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10890 i_aggsortop = PQfnumber(res, "aggsortop");
10891 i_aggtranstype = PQfnumber(res, "aggtranstype");
10892 i_agginitval = PQfnumber(res, "agginitval");
10893 i_convertok = PQfnumber(res, "convertok");
10895 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10896 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10897 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10898 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10899 agginitval = PQgetvalue(res, 0, i_agginitval);
10900 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10902 aggsig = format_aggregate_signature(agginfo, fout, true);
10903 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10907 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10912 if (fout->remoteVersion >= 70300)
10914 /* If using 7.3's regproc or regtype, data is already quoted */
10915 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10919 else if (fout->remoteVersion >= 70100)
10921 /* format_type quotes, regproc does not */
10922 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10928 /* need quotes all around */
10929 appendPQExpBuffer(details, " SFUNC = %s,\n",
10930 fmtId(aggtransfn));
10931 appendPQExpBuffer(details, " STYPE = %s",
10932 fmtId(aggtranstype));
10935 if (!PQgetisnull(res, 0, i_agginitval))
10937 appendPQExpBuffer(details, ",\n INITCOND = ");
10938 appendStringLiteralAH(details, agginitval, fout);
10941 if (strcmp(aggfinalfn, "-") != 0)
10943 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
10947 aggsortop = convertOperatorReference(fout, aggsortop);
10950 appendPQExpBuffer(details, ",\n SORTOP = %s",
10955 * DROP must be fully qualified in case same name appears in pg_catalog
10957 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10958 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10961 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10962 aggsig, details->data);
10964 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10966 if (binary_upgrade)
10967 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10969 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10971 agginfo->aggfn.dobj.namespace->dobj.name,
10973 agginfo->aggfn.rolname,
10974 false, "AGGREGATE", SECTION_PRE_DATA,
10975 q->data, delq->data, NULL,
10976 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10979 /* Dump Aggregate Comments */
10980 dumpComment(fout, labelq->data,
10981 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10982 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10983 dumpSecLabel(fout, labelq->data,
10984 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10985 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10988 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10989 * command look like a function's GRANT; in particular this affects the
10990 * syntax for zero-argument aggregates.
10995 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
10996 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
10998 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11000 aggsig, NULL, aggsig_tag,
11001 agginfo->aggfn.dobj.namespace->dobj.name,
11002 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11009 destroyPQExpBuffer(query);
11010 destroyPQExpBuffer(q);
11011 destroyPQExpBuffer(delq);
11012 destroyPQExpBuffer(labelq);
11013 destroyPQExpBuffer(details);
11018 * write out a single text search parser
11021 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11025 PQExpBuffer labelq;
11027 /* Skip if not to be dumped */
11028 if (!prsinfo->dobj.dump || dataOnly)
11031 q = createPQExpBuffer();
11032 delq = createPQExpBuffer();
11033 labelq = createPQExpBuffer();
11035 /* Make sure we are in proper schema */
11036 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11038 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11039 fmtId(prsinfo->dobj.name));
11041 appendPQExpBuffer(q, " START = %s,\n",
11042 convertTSFunction(fout, prsinfo->prsstart));
11043 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11044 convertTSFunction(fout, prsinfo->prstoken));
11045 appendPQExpBuffer(q, " END = %s,\n",
11046 convertTSFunction(fout, prsinfo->prsend));
11047 if (prsinfo->prsheadline != InvalidOid)
11048 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11049 convertTSFunction(fout, prsinfo->prsheadline));
11050 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11051 convertTSFunction(fout, prsinfo->prslextype));
11054 * DROP must be fully qualified in case same name appears in pg_catalog
11056 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11057 fmtId(prsinfo->dobj.namespace->dobj.name));
11058 appendPQExpBuffer(delq, ".%s;\n",
11059 fmtId(prsinfo->dobj.name));
11061 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11062 fmtId(prsinfo->dobj.name));
11064 if (binary_upgrade)
11065 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11067 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11068 prsinfo->dobj.name,
11069 prsinfo->dobj.namespace->dobj.name,
11072 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11073 q->data, delq->data, NULL,
11074 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11077 /* Dump Parser Comments */
11078 dumpComment(fout, labelq->data,
11080 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11082 destroyPQExpBuffer(q);
11083 destroyPQExpBuffer(delq);
11084 destroyPQExpBuffer(labelq);
11089 * write out a single text search dictionary
11092 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11096 PQExpBuffer labelq;
11102 /* Skip if not to be dumped */
11103 if (!dictinfo->dobj.dump || dataOnly)
11106 q = createPQExpBuffer();
11107 delq = createPQExpBuffer();
11108 labelq = createPQExpBuffer();
11109 query = createPQExpBuffer();
11111 /* Fetch name and namespace of the dictionary's template */
11112 selectSourceSchema(fout, "pg_catalog");
11113 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11114 "FROM pg_ts_template p, pg_namespace n "
11115 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11116 dictinfo->dicttemplate);
11117 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11118 nspname = PQgetvalue(res, 0, 0);
11119 tmplname = PQgetvalue(res, 0, 1);
11121 /* Make sure we are in proper schema */
11122 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11124 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11125 fmtId(dictinfo->dobj.name));
11127 appendPQExpBuffer(q, " TEMPLATE = ");
11128 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11129 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11130 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11134 /* the dictinitoption can be dumped straight into the command */
11135 if (dictinfo->dictinitoption)
11136 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11138 appendPQExpBuffer(q, " );\n");
11141 * DROP must be fully qualified in case same name appears in pg_catalog
11143 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11144 fmtId(dictinfo->dobj.namespace->dobj.name));
11145 appendPQExpBuffer(delq, ".%s;\n",
11146 fmtId(dictinfo->dobj.name));
11148 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11149 fmtId(dictinfo->dobj.name));
11151 if (binary_upgrade)
11152 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11154 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11155 dictinfo->dobj.name,
11156 dictinfo->dobj.namespace->dobj.name,
11159 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11160 q->data, delq->data, NULL,
11161 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11164 /* Dump Dictionary Comments */
11165 dumpComment(fout, labelq->data,
11166 NULL, dictinfo->rolname,
11167 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11169 destroyPQExpBuffer(q);
11170 destroyPQExpBuffer(delq);
11171 destroyPQExpBuffer(labelq);
11172 destroyPQExpBuffer(query);
11177 * write out a single text search template
11180 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11184 PQExpBuffer labelq;
11186 /* Skip if not to be dumped */
11187 if (!tmplinfo->dobj.dump || dataOnly)
11190 q = createPQExpBuffer();
11191 delq = createPQExpBuffer();
11192 labelq = createPQExpBuffer();
11194 /* Make sure we are in proper schema */
11195 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11197 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11198 fmtId(tmplinfo->dobj.name));
11200 if (tmplinfo->tmplinit != InvalidOid)
11201 appendPQExpBuffer(q, " INIT = %s,\n",
11202 convertTSFunction(fout, tmplinfo->tmplinit));
11203 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11204 convertTSFunction(fout, tmplinfo->tmpllexize));
11207 * DROP must be fully qualified in case same name appears in pg_catalog
11209 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11210 fmtId(tmplinfo->dobj.namespace->dobj.name));
11211 appendPQExpBuffer(delq, ".%s;\n",
11212 fmtId(tmplinfo->dobj.name));
11214 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11215 fmtId(tmplinfo->dobj.name));
11217 if (binary_upgrade)
11218 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11220 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11221 tmplinfo->dobj.name,
11222 tmplinfo->dobj.namespace->dobj.name,
11225 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11226 q->data, delq->data, NULL,
11227 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11230 /* Dump Template Comments */
11231 dumpComment(fout, labelq->data,
11233 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11235 destroyPQExpBuffer(q);
11236 destroyPQExpBuffer(delq);
11237 destroyPQExpBuffer(labelq);
11242 * write out a single text search configuration
11245 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11249 PQExpBuffer labelq;
11259 /* Skip if not to be dumped */
11260 if (!cfginfo->dobj.dump || dataOnly)
11263 q = createPQExpBuffer();
11264 delq = createPQExpBuffer();
11265 labelq = createPQExpBuffer();
11266 query = createPQExpBuffer();
11268 /* Fetch name and namespace of the config's parser */
11269 selectSourceSchema(fout, "pg_catalog");
11270 appendPQExpBuffer(query, "SELECT nspname, prsname "
11271 "FROM pg_ts_parser p, pg_namespace n "
11272 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11273 cfginfo->cfgparser);
11274 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11275 nspname = PQgetvalue(res, 0, 0);
11276 prsname = PQgetvalue(res, 0, 1);
11278 /* Make sure we are in proper schema */
11279 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11281 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11282 fmtId(cfginfo->dobj.name));
11284 appendPQExpBuffer(q, " PARSER = ");
11285 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11286 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11287 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11291 resetPQExpBuffer(query);
11292 appendPQExpBuffer(query,
11294 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11295 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11296 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11297 "FROM pg_catalog.pg_ts_config_map AS m \n"
11298 "WHERE m.mapcfg = '%u' \n"
11299 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11300 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11302 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11303 ntups = PQntuples(res);
11305 i_tokenname = PQfnumber(res, "tokenname");
11306 i_dictname = PQfnumber(res, "dictname");
11308 for (i = 0; i < ntups; i++)
11310 char *tokenname = PQgetvalue(res, i, i_tokenname);
11311 char *dictname = PQgetvalue(res, i, i_dictname);
11314 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11316 /* starting a new token type, so start a new command */
11318 appendPQExpBuffer(q, ";\n");
11319 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11320 fmtId(cfginfo->dobj.name));
11321 /* tokenname needs quoting, dictname does NOT */
11322 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11323 fmtId(tokenname), dictname);
11326 appendPQExpBuffer(q, ", %s", dictname);
11330 appendPQExpBuffer(q, ";\n");
11335 * DROP must be fully qualified in case same name appears in pg_catalog
11337 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11338 fmtId(cfginfo->dobj.namespace->dobj.name));
11339 appendPQExpBuffer(delq, ".%s;\n",
11340 fmtId(cfginfo->dobj.name));
11342 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11343 fmtId(cfginfo->dobj.name));
11345 if (binary_upgrade)
11346 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11348 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11349 cfginfo->dobj.name,
11350 cfginfo->dobj.namespace->dobj.name,
11353 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11354 q->data, delq->data, NULL,
11355 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11358 /* Dump Configuration Comments */
11359 dumpComment(fout, labelq->data,
11360 NULL, cfginfo->rolname,
11361 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11363 destroyPQExpBuffer(q);
11364 destroyPQExpBuffer(delq);
11365 destroyPQExpBuffer(labelq);
11366 destroyPQExpBuffer(query);
11370 * dumpForeignDataWrapper
11371 * write out a single foreign-data wrapper definition
11374 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11378 PQExpBuffer labelq;
11381 /* Skip if not to be dumped */
11382 if (!fdwinfo->dobj.dump || dataOnly)
11386 * FDWs that belong to an extension are dumped based on their "dump"
11387 * field. Otherwise omit them if we are only dumping some specific object.
11389 if (!fdwinfo->dobj.ext_member)
11390 if (!include_everything)
11393 q = createPQExpBuffer();
11394 delq = createPQExpBuffer();
11395 labelq = createPQExpBuffer();
11397 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11399 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11402 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11403 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11405 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11406 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11408 if (strlen(fdwinfo->fdwoptions) > 0)
11409 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11411 appendPQExpBuffer(q, ";\n");
11413 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11416 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11419 if (binary_upgrade)
11420 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11422 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11423 fdwinfo->dobj.name,
11427 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11428 q->data, delq->data, NULL,
11429 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11432 /* Handle the ACL */
11433 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11434 "FOREIGN DATA WRAPPER",
11435 qfdwname, NULL, fdwinfo->dobj.name,
11436 NULL, fdwinfo->rolname,
11439 /* Dump Foreign Data Wrapper Comments */
11440 dumpComment(fout, labelq->data,
11441 NULL, fdwinfo->rolname,
11442 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11446 destroyPQExpBuffer(q);
11447 destroyPQExpBuffer(delq);
11448 destroyPQExpBuffer(labelq);
11452 * dumpForeignServer
11453 * write out a foreign server definition
11456 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11460 PQExpBuffer labelq;
11466 /* Skip if not to be dumped */
11467 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11470 q = createPQExpBuffer();
11471 delq = createPQExpBuffer();
11472 labelq = createPQExpBuffer();
11473 query = createPQExpBuffer();
11475 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11477 /* look up the foreign-data wrapper */
11478 selectSourceSchema(fout, "pg_catalog");
11479 appendPQExpBuffer(query, "SELECT fdwname "
11480 "FROM pg_foreign_data_wrapper w "
11481 "WHERE w.oid = '%u'",
11483 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11484 fdwname = PQgetvalue(res, 0, 0);
11486 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11487 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11489 appendPQExpBuffer(q, " TYPE ");
11490 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11492 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11494 appendPQExpBuffer(q, " VERSION ");
11495 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11498 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11499 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11501 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11502 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11504 appendPQExpBuffer(q, ";\n");
11506 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11509 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11511 if (binary_upgrade)
11512 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11514 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11515 srvinfo->dobj.name,
11519 false, "SERVER", SECTION_PRE_DATA,
11520 q->data, delq->data, NULL,
11521 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11524 /* Handle the ACL */
11525 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11527 qsrvname, NULL, srvinfo->dobj.name,
11528 NULL, srvinfo->rolname,
11531 /* Dump user mappings */
11532 dumpUserMappings(fout,
11533 srvinfo->dobj.name, NULL,
11535 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11537 /* Dump Foreign Server Comments */
11538 dumpComment(fout, labelq->data,
11539 NULL, srvinfo->rolname,
11540 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11544 destroyPQExpBuffer(q);
11545 destroyPQExpBuffer(delq);
11546 destroyPQExpBuffer(labelq);
11552 * This routine is used to dump any user mappings associated with the
11553 * server handed to this routine. Should be called after ArchiveEntry()
11557 dumpUserMappings(Archive *fout,
11558 const char *servername, const char *namespace,
11560 CatalogId catalogId, DumpId dumpId)
11572 q = createPQExpBuffer();
11573 tag = createPQExpBuffer();
11574 delq = createPQExpBuffer();
11575 query = createPQExpBuffer();
11578 * We read from the publicly accessible view pg_user_mappings, so as not
11579 * to fail if run by a non-superuser. Note that the view will show
11580 * umoptions as null if the user hasn't got privileges for the associated
11581 * server; this means that pg_dump will dump such a mapping, but with no
11582 * OPTIONS clause. A possible alternative is to skip such mappings
11583 * altogether, but it's not clear that that's an improvement.
11585 selectSourceSchema(fout, "pg_catalog");
11587 appendPQExpBuffer(query,
11589 "array_to_string(ARRAY("
11590 "SELECT quote_ident(option_name) || ' ' || "
11591 "quote_literal(option_value) "
11592 "FROM pg_options_to_table(umoptions) "
11593 "ORDER BY option_name"
11594 "), E',\n ') AS umoptions "
11595 "FROM pg_user_mappings "
11596 "WHERE srvid = '%u' "
11597 "ORDER BY usename",
11600 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11602 ntups = PQntuples(res);
11603 i_usename = PQfnumber(res, "usename");
11604 i_umoptions = PQfnumber(res, "umoptions");
11606 for (i = 0; i < ntups; i++)
11611 usename = PQgetvalue(res, i, i_usename);
11612 umoptions = PQgetvalue(res, i, i_umoptions);
11614 resetPQExpBuffer(q);
11615 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11616 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11618 if (umoptions && strlen(umoptions) > 0)
11619 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11621 appendPQExpBuffer(q, ";\n");
11623 resetPQExpBuffer(delq);
11624 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11625 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11627 resetPQExpBuffer(tag);
11628 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11629 usename, servername);
11631 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11636 "USER MAPPING", SECTION_PRE_DATA,
11637 q->data, delq->data, NULL,
11644 destroyPQExpBuffer(query);
11645 destroyPQExpBuffer(delq);
11646 destroyPQExpBuffer(q);
11650 * Write out default privileges information
11653 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11659 /* Skip if not to be dumped */
11660 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11663 q = createPQExpBuffer();
11664 tag = createPQExpBuffer();
11666 switch (daclinfo->defaclobjtype)
11668 case DEFACLOBJ_RELATION:
11671 case DEFACLOBJ_SEQUENCE:
11672 type = "SEQUENCES";
11674 case DEFACLOBJ_FUNCTION:
11675 type = "FUNCTIONS";
11678 /* shouldn't get here */
11679 exit_horribly(NULL,
11680 "unknown object type (%d) in default privileges\n",
11681 (int) daclinfo->defaclobjtype);
11682 type = ""; /* keep compiler quiet */
11685 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11687 /* build the actual command(s) for this tuple */
11688 if (!buildDefaultACLCommands(type,
11689 daclinfo->dobj.namespace != NULL ?
11690 daclinfo->dobj.namespace->dobj.name : NULL,
11691 daclinfo->defaclacl,
11692 daclinfo->defaclrole,
11693 fout->remoteVersion,
11695 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11696 daclinfo->defaclacl);
11698 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11700 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11702 daclinfo->defaclrole,
11703 false, "DEFAULT ACL", SECTION_NONE,
11705 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11708 destroyPQExpBuffer(tag);
11709 destroyPQExpBuffer(q);
11713 * Write out grant/revoke information
11715 * 'objCatId' is the catalog ID of the underlying object.
11716 * 'objDumpId' is the dump ID of the underlying object.
11717 * 'type' must be one of
11718 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11719 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11720 * 'name' is the formatted name of the object. Must be quoted etc. already.
11721 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11722 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11723 * 'nspname' is the namespace the object is in (NULL if none).
11724 * 'owner' is the owner, NULL if there is no owner (for languages).
11725 * 'acls' is the string read out of the fooacl system catalog field;
11726 * it will be parsed here.
11730 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11731 const char *type, const char *name, const char *subname,
11732 const char *tag, const char *nspname, const char *owner,
11737 /* Do nothing if ACL dump is not enabled */
11741 /* --data-only skips ACLs *except* BLOB ACLs */
11742 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11745 sql = createPQExpBuffer();
11747 if (!buildACLCommands(name, subname, type, acls, owner,
11748 "", fout->remoteVersion, sql))
11749 exit_horribly(NULL,
11750 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11754 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11757 owner ? owner : "",
11758 false, "ACL", SECTION_NONE,
11759 sql->data, "", NULL,
11763 destroyPQExpBuffer(sql);
11769 * This routine is used to dump any security labels associated with the
11770 * object handed to this routine. The routine takes a constant character
11771 * string for the target part of the security-label command, plus
11772 * the namespace and owner of the object (for labeling the ArchiveEntry),
11773 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11774 * plus the dump ID for the object (for setting a dependency).
11775 * If a matching pg_seclabel entry is found, it is dumped.
11777 * Note: although this routine takes a dumpId for dependency purposes,
11778 * that purpose is just to mark the dependency in the emitted dump file
11779 * for possible future use by pg_restore. We do NOT use it for determining
11780 * ordering of the label in the dump file, because this routine is called
11781 * after dependency sorting occurs. This routine should be called just after
11782 * calling ArchiveEntry() for the specified object.
11785 dumpSecLabel(Archive *fout, const char *target,
11786 const char *namespace, const char *owner,
11787 CatalogId catalogId, int subid, DumpId dumpId)
11789 SecLabelItem *labels;
11794 /* do nothing, if --no-security-labels is supplied */
11795 if (no_security_labels)
11798 /* Comments are schema not data ... except blob comments are data */
11799 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11810 /* Search for security labels associated with catalogId, using table */
11811 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11813 query = createPQExpBuffer();
11815 for (i = 0; i < nlabels; i++)
11818 * Ignore label entries for which the subid doesn't match.
11820 if (labels[i].objsubid != subid)
11823 appendPQExpBuffer(query,
11824 "SECURITY LABEL FOR %s ON %s IS ",
11825 fmtId(labels[i].provider), target);
11826 appendStringLiteralAH(query, labels[i].label, fout);
11827 appendPQExpBuffer(query, ";\n");
11830 if (query->len > 0)
11832 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11833 target, namespace, NULL, owner,
11834 false, "SECURITY LABEL", SECTION_NONE,
11835 query->data, "", NULL,
11839 destroyPQExpBuffer(query);
11843 * dumpTableSecLabel
11845 * As above, but dump security label for both the specified table (or view)
11849 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11851 SecLabelItem *labels;
11855 PQExpBuffer target;
11857 /* do nothing, if --no-security-labels is supplied */
11858 if (no_security_labels)
11861 /* SecLabel are SCHEMA not data */
11865 /* Search for comments associated with relation, using table */
11866 nlabels = findSecLabels(fout,
11867 tbinfo->dobj.catId.tableoid,
11868 tbinfo->dobj.catId.oid,
11871 /* If security labels exist, build SECURITY LABEL statements */
11875 query = createPQExpBuffer();
11876 target = createPQExpBuffer();
11878 for (i = 0; i < nlabels; i++)
11880 const char *colname;
11881 const char *provider = labels[i].provider;
11882 const char *label = labels[i].label;
11883 int objsubid = labels[i].objsubid;
11885 resetPQExpBuffer(target);
11888 appendPQExpBuffer(target, "%s %s", reltypename,
11889 fmtId(tbinfo->dobj.name));
11893 colname = getAttrName(objsubid, tbinfo);
11894 /* first fmtId result must be consumed before calling it again */
11895 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11896 appendPQExpBuffer(target, ".%s", fmtId(colname));
11898 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11899 fmtId(provider), target->data);
11900 appendStringLiteralAH(query, label, fout);
11901 appendPQExpBuffer(query, ";\n");
11903 if (query->len > 0)
11905 resetPQExpBuffer(target);
11906 appendPQExpBuffer(target, "%s %s", reltypename,
11907 fmtId(tbinfo->dobj.name));
11908 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11910 tbinfo->dobj.namespace->dobj.name,
11911 NULL, tbinfo->rolname,
11912 false, "SECURITY LABEL", SECTION_NONE,
11913 query->data, "", NULL,
11914 &(tbinfo->dobj.dumpId), 1,
11917 destroyPQExpBuffer(query);
11918 destroyPQExpBuffer(target);
11924 * Find the security label(s), if any, associated with the given object.
11925 * All the objsubid values associated with the given classoid/objoid are
11926 * found with one search.
11929 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11931 /* static storage for table of security labels */
11932 static SecLabelItem *labels = NULL;
11933 static int nlabels = -1;
11935 SecLabelItem *middle = NULL;
11937 SecLabelItem *high;
11940 /* Get security labels if we didn't already */
11942 nlabels = collectSecLabels(fout, &labels);
11944 if (nlabels <= 0) /* no labels, so no match is possible */
11951 * Do binary search to find some item matching the object.
11954 high = &labels[nlabels - 1];
11955 while (low <= high)
11957 middle = low + (high - low) / 2;
11959 if (classoid < middle->classoid)
11961 else if (classoid > middle->classoid)
11963 else if (objoid < middle->objoid)
11965 else if (objoid > middle->objoid)
11968 break; /* found a match */
11971 if (low > high) /* no matches */
11978 * Now determine how many items match the object. The search loop
11979 * invariant still holds: only items between low and high inclusive could
11983 while (middle > low)
11985 if (classoid != middle[-1].classoid ||
11986 objoid != middle[-1].objoid)
11995 while (middle <= high)
11997 if (classoid != middle->classoid ||
11998 objoid != middle->objoid)
12010 * Construct a table of all security labels available for database objects.
12011 * It's much faster to pull them all at once.
12013 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12016 collectSecLabels(Archive *fout, SecLabelItem **items)
12027 SecLabelItem *labels;
12029 query = createPQExpBuffer();
12031 appendPQExpBuffer(query,
12032 "SELECT label, provider, classoid, objoid, objsubid "
12033 "FROM pg_catalog.pg_seclabel "
12034 "ORDER BY classoid, objoid, objsubid");
12036 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12038 /* Construct lookup table containing OIDs in numeric form */
12039 i_label = PQfnumber(res, "label");
12040 i_provider = PQfnumber(res, "provider");
12041 i_classoid = PQfnumber(res, "classoid");
12042 i_objoid = PQfnumber(res, "objoid");
12043 i_objsubid = PQfnumber(res, "objsubid");
12045 ntups = PQntuples(res);
12047 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12049 for (i = 0; i < ntups; i++)
12051 labels[i].label = PQgetvalue(res, i, i_label);
12052 labels[i].provider = PQgetvalue(res, i, i_provider);
12053 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12054 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12055 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12058 /* Do NOT free the PGresult since we are keeping pointers into it */
12059 destroyPQExpBuffer(query);
12067 * write out to fout the declarations (not data) of a user-defined table
12070 dumpTable(Archive *fout, TableInfo *tbinfo)
12072 if (tbinfo->dobj.dump)
12076 if (tbinfo->relkind == RELKIND_SEQUENCE)
12077 dumpSequence(fout, tbinfo);
12078 else if (!dataOnly)
12079 dumpTableSchema(fout, tbinfo);
12081 /* Handle the ACL here */
12082 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12083 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12084 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12086 namecopy, NULL, tbinfo->dobj.name,
12087 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12091 * Handle column ACLs, if any. Note: we pull these with a separate
12092 * query rather than trying to fetch them during getTableAttrs, so
12093 * that we won't miss ACLs on system columns.
12095 if (fout->remoteVersion >= 80400)
12097 PQExpBuffer query = createPQExpBuffer();
12101 appendPQExpBuffer(query,
12102 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12103 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12105 tbinfo->dobj.catId.oid);
12106 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12108 for (i = 0; i < PQntuples(res); i++)
12110 char *attname = PQgetvalue(res, i, 0);
12111 char *attacl = PQgetvalue(res, i, 1);
12115 attnamecopy = pg_strdup(fmtId(attname));
12116 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12117 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12118 /* Column's GRANT type is always TABLE */
12119 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12120 namecopy, attnamecopy, acltag,
12121 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12127 destroyPQExpBuffer(query);
12136 * write the declaration (not data) of one user-defined table or view
12139 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12141 PQExpBuffer query = createPQExpBuffer();
12142 PQExpBuffer q = createPQExpBuffer();
12143 PQExpBuffer delq = createPQExpBuffer();
12144 PQExpBuffer labelq = createPQExpBuffer();
12147 TableInfo **parents;
12148 int actual_atts; /* number of attrs in this CREATE statement */
12149 const char *reltypename;
12156 /* Make sure we are in proper schema */
12157 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12159 if (binary_upgrade)
12160 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12161 tbinfo->dobj.catId.oid);
12163 /* Is it a table or a view? */
12164 if (tbinfo->relkind == RELKIND_VIEW)
12168 reltypename = "VIEW";
12170 /* Fetch the view definition */
12171 if (fout->remoteVersion >= 70300)
12173 /* Beginning in 7.3, viewname is not unique; rely on OID */
12174 appendPQExpBuffer(query,
12175 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12176 tbinfo->dobj.catId.oid);
12180 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12181 "FROM pg_views WHERE viewname = ");
12182 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12183 appendPQExpBuffer(query, ";");
12186 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12188 if (PQntuples(res) != 1)
12190 if (PQntuples(res) < 1)
12191 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12192 tbinfo->dobj.name);
12194 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12195 tbinfo->dobj.name);
12198 viewdef = PQgetvalue(res, 0, 0);
12200 if (strlen(viewdef) == 0)
12201 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12202 tbinfo->dobj.name);
12205 * DROP must be fully qualified in case same name appears in
12208 appendPQExpBuffer(delq, "DROP VIEW %s.",
12209 fmtId(tbinfo->dobj.namespace->dobj.name));
12210 appendPQExpBuffer(delq, "%s;\n",
12211 fmtId(tbinfo->dobj.name));
12213 if (binary_upgrade)
12214 binary_upgrade_set_pg_class_oids(fout, q,
12215 tbinfo->dobj.catId.oid, false);
12217 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12218 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12219 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12220 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12222 appendPQExpBuffer(labelq, "VIEW %s",
12223 fmtId(tbinfo->dobj.name));
12229 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12234 reltypename = "FOREIGN TABLE";
12236 /* retrieve name of foreign server and generic options */
12237 appendPQExpBuffer(query,
12238 "SELECT fs.srvname, "
12239 "pg_catalog.array_to_string(ARRAY("
12240 "SELECT pg_catalog.quote_ident(option_name) || "
12241 "' ' || pg_catalog.quote_literal(option_value) "
12242 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12243 "ORDER BY option_name"
12244 "), E',\n ') AS ftoptions "
12245 "FROM pg_catalog.pg_foreign_table ft "
12246 "JOIN pg_catalog.pg_foreign_server fs "
12247 "ON (fs.oid = ft.ftserver) "
12248 "WHERE ft.ftrelid = '%u'",
12249 tbinfo->dobj.catId.oid);
12250 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12251 i_srvname = PQfnumber(res, "srvname");
12252 i_ftoptions = PQfnumber(res, "ftoptions");
12253 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12254 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12259 reltypename = "TABLE";
12263 numParents = tbinfo->numParents;
12264 parents = tbinfo->parents;
12267 * DROP must be fully qualified in case same name appears in
12270 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12271 fmtId(tbinfo->dobj.namespace->dobj.name));
12272 appendPQExpBuffer(delq, "%s;\n",
12273 fmtId(tbinfo->dobj.name));
12275 appendPQExpBuffer(labelq, "%s %s", reltypename,
12276 fmtId(tbinfo->dobj.name));
12278 if (binary_upgrade)
12279 binary_upgrade_set_pg_class_oids(fout, q,
12280 tbinfo->dobj.catId.oid, false);
12282 appendPQExpBuffer(q, "CREATE %s%s %s",
12283 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12286 fmtId(tbinfo->dobj.name));
12289 * Attach to type, if reloftype; except in case of a binary upgrade,
12290 * we dump the table normally and attach it to the type afterward.
12292 if (tbinfo->reloftype && !binary_upgrade)
12293 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12295 /* Dump the attributes */
12297 for (j = 0; j < tbinfo->numatts; j++)
12300 * Normally, dump if it's locally defined in this table, and not
12301 * dropped. But for binary upgrade, we'll dump all the columns,
12302 * and then fix up the dropped and nonlocal cases below.
12304 if (shouldPrintColumn(tbinfo, j))
12307 * Default value --- suppress if to be printed separately.
12309 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12310 !tbinfo->attrdefs[j]->separate);
12313 * Not Null constraint --- suppress if inherited, except in
12314 * binary-upgrade case where that won't work.
12316 bool has_notnull = (tbinfo->notnull[j] &&
12317 (!tbinfo->inhNotNull[j] ||
12320 /* Skip column if fully defined by reloftype */
12321 if (tbinfo->reloftype &&
12322 !has_default && !has_notnull && !binary_upgrade)
12325 /* Format properly if not first attr */
12326 if (actual_atts == 0)
12327 appendPQExpBuffer(q, " (");
12329 appendPQExpBuffer(q, ",");
12330 appendPQExpBuffer(q, "\n ");
12333 /* Attribute name */
12334 appendPQExpBuffer(q, "%s ",
12335 fmtId(tbinfo->attnames[j]));
12337 if (tbinfo->attisdropped[j])
12340 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12341 * so we will not have gotten a valid type name; insert
12342 * INTEGER as a stopgap. We'll clean things up later.
12344 appendPQExpBuffer(q, "INTEGER /* dummy */");
12345 /* Skip all the rest, too */
12349 /* Attribute type */
12350 if (tbinfo->reloftype && !binary_upgrade)
12352 appendPQExpBuffer(q, "WITH OPTIONS");
12354 else if (fout->remoteVersion >= 70100)
12356 appendPQExpBuffer(q, "%s",
12357 tbinfo->atttypnames[j]);
12361 /* If no format_type, fake it */
12362 appendPQExpBuffer(q, "%s",
12363 myFormatType(tbinfo->atttypnames[j],
12364 tbinfo->atttypmod[j]));
12367 /* Add collation if not default for the type */
12368 if (OidIsValid(tbinfo->attcollation[j]))
12372 coll = findCollationByOid(tbinfo->attcollation[j]);
12375 /* always schema-qualify, don't try to be smart */
12376 appendPQExpBuffer(q, " COLLATE %s.",
12377 fmtId(coll->dobj.namespace->dobj.name));
12378 appendPQExpBuffer(q, "%s",
12379 fmtId(coll->dobj.name));
12384 appendPQExpBuffer(q, " DEFAULT %s",
12385 tbinfo->attrdefs[j]->adef_expr);
12388 appendPQExpBuffer(q, " NOT NULL");
12393 * Add non-inherited CHECK constraints, if any.
12395 for (j = 0; j < tbinfo->ncheck; j++)
12397 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12399 if (constr->separate || !constr->conislocal)
12402 if (actual_atts == 0)
12403 appendPQExpBuffer(q, " (\n ");
12405 appendPQExpBuffer(q, ",\n ");
12407 appendPQExpBuffer(q, "CONSTRAINT %s ",
12408 fmtId(constr->dobj.name));
12409 appendPQExpBuffer(q, "%s", constr->condef);
12415 appendPQExpBuffer(q, "\n)");
12416 else if (!(tbinfo->reloftype && !binary_upgrade))
12419 * We must have a parenthesized attribute list, even though empty,
12420 * when not using the OF TYPE syntax.
12422 appendPQExpBuffer(q, " (\n)");
12425 if (numParents > 0 && !binary_upgrade)
12427 appendPQExpBuffer(q, "\nINHERITS (");
12428 for (k = 0; k < numParents; k++)
12430 TableInfo *parentRel = parents[k];
12433 appendPQExpBuffer(q, ", ");
12434 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12435 appendPQExpBuffer(q, "%s.",
12436 fmtId(parentRel->dobj.namespace->dobj.name));
12437 appendPQExpBuffer(q, "%s",
12438 fmtId(parentRel->dobj.name));
12440 appendPQExpBuffer(q, ")");
12443 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12444 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12446 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12447 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12449 bool addcomma = false;
12451 appendPQExpBuffer(q, "\nWITH (");
12452 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12455 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12457 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12459 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12460 tbinfo->toast_reloptions);
12462 appendPQExpBuffer(q, ")");
12465 /* Dump generic options if any */
12466 if (ftoptions && ftoptions[0])
12467 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12469 appendPQExpBuffer(q, ";\n");
12472 * To create binary-compatible heap files, we have to ensure the same
12473 * physical column order, including dropped columns, as in the
12474 * original. Therefore, we create dropped columns above and drop them
12475 * here, also updating their attlen/attalign values so that the
12476 * dropped column can be skipped properly. (We do not bother with
12477 * restoring the original attbyval setting.) Also, inheritance
12478 * relationships are set up by doing ALTER INHERIT rather than using
12479 * an INHERITS clause --- the latter would possibly mess up the column
12480 * order. That also means we have to take care about setting
12481 * attislocal correctly, plus fix up any inherited CHECK constraints.
12482 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12484 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12486 for (j = 0; j < tbinfo->numatts; j++)
12488 if (tbinfo->attisdropped[j])
12490 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12491 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12492 "SET attlen = %d, "
12493 "attalign = '%c', attbyval = false\n"
12494 "WHERE attname = ",
12496 tbinfo->attalign[j]);
12497 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12498 appendPQExpBuffer(q, "\n AND attrelid = ");
12499 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12500 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12502 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12503 fmtId(tbinfo->dobj.name));
12504 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12505 fmtId(tbinfo->attnames[j]));
12507 else if (!tbinfo->attislocal[j])
12509 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12510 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12511 "SET attislocal = false\n"
12512 "WHERE attname = ");
12513 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12514 appendPQExpBuffer(q, "\n AND attrelid = ");
12515 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12516 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12520 for (k = 0; k < tbinfo->ncheck; k++)
12522 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12524 if (constr->separate || constr->conislocal)
12527 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12528 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12529 fmtId(tbinfo->dobj.name));
12530 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12531 fmtId(constr->dobj.name));
12532 appendPQExpBuffer(q, "%s;\n", constr->condef);
12533 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12534 "SET conislocal = false\n"
12535 "WHERE contype = 'c' AND conname = ");
12536 appendStringLiteralAH(q, constr->dobj.name, fout);
12537 appendPQExpBuffer(q, "\n AND conrelid = ");
12538 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12539 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12542 if (numParents > 0)
12544 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12545 for (k = 0; k < numParents; k++)
12547 TableInfo *parentRel = parents[k];
12549 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12550 fmtId(tbinfo->dobj.name));
12551 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12552 appendPQExpBuffer(q, "%s.",
12553 fmtId(parentRel->dobj.namespace->dobj.name));
12554 appendPQExpBuffer(q, "%s;\n",
12555 fmtId(parentRel->dobj.name));
12559 if (tbinfo->reloftype)
12561 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12562 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12563 fmtId(tbinfo->dobj.name),
12564 tbinfo->reloftype);
12567 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12568 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12569 "SET relfrozenxid = '%u'\n"
12571 tbinfo->frozenxid);
12572 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12573 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12575 if (tbinfo->toast_oid)
12577 /* We preserve the toast oids, so we can use it during restore */
12578 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12579 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12580 "SET relfrozenxid = '%u'\n"
12581 "WHERE oid = '%u';\n",
12582 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12587 * Dump additional per-column properties that we can't handle in the
12588 * main CREATE TABLE command.
12590 for (j = 0; j < tbinfo->numatts; j++)
12592 /* None of this applies to dropped columns */
12593 if (tbinfo->attisdropped[j])
12597 * If we didn't dump the column definition explicitly above, and
12598 * it is NOT NULL and did not inherit that property from a parent,
12599 * we have to mark it separately.
12601 if (!shouldPrintColumn(tbinfo, j) &&
12602 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12604 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12605 fmtId(tbinfo->dobj.name));
12606 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12607 fmtId(tbinfo->attnames[j]));
12611 * Dump per-column statistics information. We only issue an ALTER
12612 * TABLE statement if the attstattarget entry for this column is
12613 * non-negative (i.e. it's not the default value)
12615 if (tbinfo->attstattarget[j] >= 0)
12617 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12618 fmtId(tbinfo->dobj.name));
12619 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12620 fmtId(tbinfo->attnames[j]));
12621 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12622 tbinfo->attstattarget[j]);
12626 * Dump per-column storage information. The statement is only
12627 * dumped if the storage has been changed from the type's default.
12629 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12631 switch (tbinfo->attstorage[j])
12637 storage = "EXTERNAL";
12643 storage = "EXTENDED";
12650 * Only dump the statement if it's a storage type we recognize
12652 if (storage != NULL)
12654 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12655 fmtId(tbinfo->dobj.name));
12656 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12657 fmtId(tbinfo->attnames[j]));
12658 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12664 * Dump per-column attributes.
12666 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12668 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12669 fmtId(tbinfo->dobj.name));
12670 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12671 fmtId(tbinfo->attnames[j]));
12672 appendPQExpBuffer(q, "SET (%s);\n",
12673 tbinfo->attoptions[j]);
12677 * Dump per-column fdw options.
12679 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12680 tbinfo->attfdwoptions[j] &&
12681 tbinfo->attfdwoptions[j][0] != '\0')
12683 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12684 fmtId(tbinfo->dobj.name));
12685 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12686 fmtId(tbinfo->attnames[j]));
12687 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12688 tbinfo->attfdwoptions[j]);
12693 if (binary_upgrade)
12694 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12696 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12698 tbinfo->dobj.namespace->dobj.name,
12699 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12701 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12702 reltypename, SECTION_PRE_DATA,
12703 q->data, delq->data, NULL,
12704 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12708 /* Dump Table Comments */
12709 dumpTableComment(fout, tbinfo, reltypename);
12711 /* Dump Table Security Labels */
12712 dumpTableSecLabel(fout, tbinfo, reltypename);
12714 /* Dump comments on inlined table constraints */
12715 for (j = 0; j < tbinfo->ncheck; j++)
12717 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12719 if (constr->separate || !constr->conislocal)
12722 dumpTableConstraintComment(fout, constr);
12725 destroyPQExpBuffer(query);
12726 destroyPQExpBuffer(q);
12727 destroyPQExpBuffer(delq);
12728 destroyPQExpBuffer(labelq);
12732 * dumpAttrDef --- dump an attribute's default-value declaration
12735 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12737 TableInfo *tbinfo = adinfo->adtable;
12738 int adnum = adinfo->adnum;
12742 /* Skip if table definition not to be dumped */
12743 if (!tbinfo->dobj.dump || dataOnly)
12746 /* Skip if not "separate"; it was dumped in the table's definition */
12747 if (!adinfo->separate)
12750 q = createPQExpBuffer();
12751 delq = createPQExpBuffer();
12753 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12754 fmtId(tbinfo->dobj.name));
12755 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12756 fmtId(tbinfo->attnames[adnum - 1]),
12757 adinfo->adef_expr);
12760 * DROP must be fully qualified in case same name appears in pg_catalog
12762 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12763 fmtId(tbinfo->dobj.namespace->dobj.name));
12764 appendPQExpBuffer(delq, "%s ",
12765 fmtId(tbinfo->dobj.name));
12766 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12767 fmtId(tbinfo->attnames[adnum - 1]));
12769 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12770 tbinfo->attnames[adnum - 1],
12771 tbinfo->dobj.namespace->dobj.name,
12774 false, "DEFAULT", SECTION_PRE_DATA,
12775 q->data, delq->data, NULL,
12776 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12779 destroyPQExpBuffer(q);
12780 destroyPQExpBuffer(delq);
12784 * getAttrName: extract the correct name for an attribute
12786 * The array tblInfo->attnames[] only provides names of user attributes;
12787 * if a system attribute number is supplied, we have to fake it.
12788 * We also do a little bit of bounds checking for safety's sake.
12790 static const char *
12791 getAttrName(int attrnum, TableInfo *tblInfo)
12793 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12794 return tblInfo->attnames[attrnum - 1];
12797 case SelfItemPointerAttributeNumber:
12799 case ObjectIdAttributeNumber:
12801 case MinTransactionIdAttributeNumber:
12803 case MinCommandIdAttributeNumber:
12805 case MaxTransactionIdAttributeNumber:
12807 case MaxCommandIdAttributeNumber:
12809 case TableOidAttributeNumber:
12812 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12813 attrnum, tblInfo->dobj.name);
12814 return NULL; /* keep compiler quiet */
12819 * write out to fout a user-defined index
12822 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12824 TableInfo *tbinfo = indxinfo->indextable;
12827 PQExpBuffer labelq;
12832 q = createPQExpBuffer();
12833 delq = createPQExpBuffer();
12834 labelq = createPQExpBuffer();
12836 appendPQExpBuffer(labelq, "INDEX %s",
12837 fmtId(indxinfo->dobj.name));
12840 * If there's an associated constraint, don't dump the index per se, but
12841 * do dump any comment for it. (This is safe because dependency ordering
12842 * will have ensured the constraint is emitted first.)
12844 if (indxinfo->indexconstraint == 0)
12846 if (binary_upgrade)
12847 binary_upgrade_set_pg_class_oids(fout, q,
12848 indxinfo->dobj.catId.oid, true);
12850 /* Plain secondary index */
12851 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12853 /* If the index is clustered, we need to record that. */
12854 if (indxinfo->indisclustered)
12856 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12857 fmtId(tbinfo->dobj.name));
12858 appendPQExpBuffer(q, " ON %s;\n",
12859 fmtId(indxinfo->dobj.name));
12863 * DROP must be fully qualified in case same name appears in
12866 appendPQExpBuffer(delq, "DROP INDEX %s.",
12867 fmtId(tbinfo->dobj.namespace->dobj.name));
12868 appendPQExpBuffer(delq, "%s;\n",
12869 fmtId(indxinfo->dobj.name));
12871 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12872 indxinfo->dobj.name,
12873 tbinfo->dobj.namespace->dobj.name,
12874 indxinfo->tablespace,
12875 tbinfo->rolname, false,
12876 "INDEX", SECTION_POST_DATA,
12877 q->data, delq->data, NULL,
12878 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12882 /* Dump Index Comments */
12883 dumpComment(fout, labelq->data,
12884 tbinfo->dobj.namespace->dobj.name,
12886 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12888 destroyPQExpBuffer(q);
12889 destroyPQExpBuffer(delq);
12890 destroyPQExpBuffer(labelq);
12895 * write out to fout a user-defined constraint
12898 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12900 TableInfo *tbinfo = coninfo->contable;
12904 /* Skip if not to be dumped */
12905 if (!coninfo->dobj.dump || dataOnly)
12908 q = createPQExpBuffer();
12909 delq = createPQExpBuffer();
12911 if (coninfo->contype == 'p' ||
12912 coninfo->contype == 'u' ||
12913 coninfo->contype == 'x')
12915 /* Index-related constraint */
12916 IndxInfo *indxinfo;
12919 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12921 if (indxinfo == NULL)
12922 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12923 coninfo->dobj.name);
12925 if (binary_upgrade)
12926 binary_upgrade_set_pg_class_oids(fout, q,
12927 indxinfo->dobj.catId.oid, true);
12929 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12930 fmtId(tbinfo->dobj.name));
12931 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12932 fmtId(coninfo->dobj.name));
12934 if (coninfo->condef)
12936 /* pg_get_constraintdef should have provided everything */
12937 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12941 appendPQExpBuffer(q, "%s (",
12942 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12943 for (k = 0; k < indxinfo->indnkeys; k++)
12945 int indkey = (int) indxinfo->indkeys[k];
12946 const char *attname;
12948 if (indkey == InvalidAttrNumber)
12950 attname = getAttrName(indkey, tbinfo);
12952 appendPQExpBuffer(q, "%s%s",
12953 (k == 0) ? "" : ", ",
12957 appendPQExpBuffer(q, ")");
12959 if (indxinfo->options && strlen(indxinfo->options) > 0)
12960 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12962 if (coninfo->condeferrable)
12964 appendPQExpBuffer(q, " DEFERRABLE");
12965 if (coninfo->condeferred)
12966 appendPQExpBuffer(q, " INITIALLY DEFERRED");
12969 appendPQExpBuffer(q, ";\n");
12972 /* If the index is clustered, we need to record that. */
12973 if (indxinfo->indisclustered)
12975 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12976 fmtId(tbinfo->dobj.name));
12977 appendPQExpBuffer(q, " ON %s;\n",
12978 fmtId(indxinfo->dobj.name));
12982 * DROP must be fully qualified in case same name appears in
12985 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12986 fmtId(tbinfo->dobj.namespace->dobj.name));
12987 appendPQExpBuffer(delq, "%s ",
12988 fmtId(tbinfo->dobj.name));
12989 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12990 fmtId(coninfo->dobj.name));
12992 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
12993 coninfo->dobj.name,
12994 tbinfo->dobj.namespace->dobj.name,
12995 indxinfo->tablespace,
12996 tbinfo->rolname, false,
12997 "CONSTRAINT", SECTION_POST_DATA,
12998 q->data, delq->data, NULL,
12999 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13002 else if (coninfo->contype == 'f')
13005 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13006 * current table data is not processed
13008 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13009 fmtId(tbinfo->dobj.name));
13010 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13011 fmtId(coninfo->dobj.name),
13015 * DROP must be fully qualified in case same name appears in
13018 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13019 fmtId(tbinfo->dobj.namespace->dobj.name));
13020 appendPQExpBuffer(delq, "%s ",
13021 fmtId(tbinfo->dobj.name));
13022 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13023 fmtId(coninfo->dobj.name));
13025 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13026 coninfo->dobj.name,
13027 tbinfo->dobj.namespace->dobj.name,
13029 tbinfo->rolname, false,
13030 "FK CONSTRAINT", SECTION_POST_DATA,
13031 q->data, delq->data, NULL,
13032 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13035 else if (coninfo->contype == 'c' && tbinfo)
13037 /* CHECK constraint on a table */
13039 /* Ignore if not to be dumped separately */
13040 if (coninfo->separate)
13042 /* not ONLY since we want it to propagate to children */
13043 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13044 fmtId(tbinfo->dobj.name));
13045 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13046 fmtId(coninfo->dobj.name),
13050 * DROP must be fully qualified in case same name appears in
13053 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13054 fmtId(tbinfo->dobj.namespace->dobj.name));
13055 appendPQExpBuffer(delq, "%s ",
13056 fmtId(tbinfo->dobj.name));
13057 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13058 fmtId(coninfo->dobj.name));
13060 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13061 coninfo->dobj.name,
13062 tbinfo->dobj.namespace->dobj.name,
13064 tbinfo->rolname, false,
13065 "CHECK CONSTRAINT", SECTION_POST_DATA,
13066 q->data, delq->data, NULL,
13067 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13071 else if (coninfo->contype == 'c' && tbinfo == NULL)
13073 /* CHECK constraint on a domain */
13074 TypeInfo *tyinfo = coninfo->condomain;
13076 /* Ignore if not to be dumped separately */
13077 if (coninfo->separate)
13079 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13080 fmtId(tyinfo->dobj.name));
13081 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13082 fmtId(coninfo->dobj.name),
13086 * DROP must be fully qualified in case same name appears in
13089 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13090 fmtId(tyinfo->dobj.namespace->dobj.name));
13091 appendPQExpBuffer(delq, "%s ",
13092 fmtId(tyinfo->dobj.name));
13093 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13094 fmtId(coninfo->dobj.name));
13096 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13097 coninfo->dobj.name,
13098 tyinfo->dobj.namespace->dobj.name,
13100 tyinfo->rolname, false,
13101 "CHECK CONSTRAINT", SECTION_POST_DATA,
13102 q->data, delq->data, NULL,
13103 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13109 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13113 /* Dump Constraint Comments --- only works for table constraints */
13114 if (tbinfo && coninfo->separate)
13115 dumpTableConstraintComment(fout, coninfo);
13117 destroyPQExpBuffer(q);
13118 destroyPQExpBuffer(delq);
13122 * dumpTableConstraintComment --- dump a constraint's comment if any
13124 * This is split out because we need the function in two different places
13125 * depending on whether the constraint is dumped as part of CREATE TABLE
13126 * or as a separate ALTER command.
13129 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13131 TableInfo *tbinfo = coninfo->contable;
13132 PQExpBuffer labelq = createPQExpBuffer();
13134 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13135 fmtId(coninfo->dobj.name));
13136 appendPQExpBuffer(labelq, "ON %s",
13137 fmtId(tbinfo->dobj.name));
13138 dumpComment(fout, labelq->data,
13139 tbinfo->dobj.namespace->dobj.name,
13141 coninfo->dobj.catId, 0,
13142 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13144 destroyPQExpBuffer(labelq);
13148 * findLastBuiltInOid -
13149 * find the last built in oid
13151 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13152 * pg_database entry for the current database
13155 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13159 PQExpBuffer query = createPQExpBuffer();
13161 resetPQExpBuffer(query);
13162 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13163 appendStringLiteralAH(query, dbname, fout);
13165 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13166 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13168 destroyPQExpBuffer(query);
13173 * findLastBuiltInOid -
13174 * find the last built in oid
13176 * For 7.0, we do this by assuming that the last thing that initdb does is to
13177 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13178 * initdb won't be changing anymore, it'll do.
13181 findLastBuiltinOid_V70(Archive *fout)
13186 res = ExecuteSqlQueryForSingleRow(fout,
13187 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13188 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13194 dumpSequence(Archive *fout, TableInfo *tbinfo)
13207 PQExpBuffer query = createPQExpBuffer();
13208 PQExpBuffer delqry = createPQExpBuffer();
13209 PQExpBuffer labelq = createPQExpBuffer();
13211 /* Make sure we are in proper schema */
13212 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13214 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13215 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13217 if (fout->remoteVersion >= 80400)
13219 appendPQExpBuffer(query,
13220 "SELECT sequence_name, "
13221 "start_value, last_value, increment_by, "
13222 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13223 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13225 "END AS max_value, "
13226 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13227 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13229 "END AS min_value, "
13230 "cache_value, is_cycled, is_called from %s",
13232 fmtId(tbinfo->dobj.name));
13236 appendPQExpBuffer(query,
13237 "SELECT sequence_name, "
13238 "0 AS 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));
13252 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13254 if (PQntuples(res) != 1)
13256 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13257 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13259 tbinfo->dobj.name, PQntuples(res));
13263 /* Disable this check: it fails if sequence has been renamed */
13265 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13267 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13268 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13273 startv = PQgetvalue(res, 0, 1);
13274 last = PQgetvalue(res, 0, 2);
13275 incby = PQgetvalue(res, 0, 3);
13276 if (!PQgetisnull(res, 0, 4))
13277 maxv = PQgetvalue(res, 0, 4);
13278 if (!PQgetisnull(res, 0, 5))
13279 minv = PQgetvalue(res, 0, 5);
13280 cache = PQgetvalue(res, 0, 6);
13281 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13282 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13285 * The logic we use for restoring sequences is as follows:
13287 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13288 * last_val for start if called is false, else use min_val for start_val).
13289 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13290 * BY command for it.
13292 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13297 * DROP must be fully qualified in case same name appears in
13300 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13301 fmtId(tbinfo->dobj.namespace->dobj.name));
13302 appendPQExpBuffer(delqry, "%s;\n",
13303 fmtId(tbinfo->dobj.name));
13305 resetPQExpBuffer(query);
13307 if (binary_upgrade)
13309 binary_upgrade_set_pg_class_oids(fout, query,
13310 tbinfo->dobj.catId.oid, false);
13311 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13312 tbinfo->dobj.catId.oid);
13315 appendPQExpBuffer(query,
13316 "CREATE SEQUENCE %s\n",
13317 fmtId(tbinfo->dobj.name));
13319 if (fout->remoteVersion >= 80400)
13320 appendPQExpBuffer(query, " START WITH %s\n", startv);
13324 * Versions before 8.4 did not remember the true start value. If
13325 * is_called is false then the sequence has never been incremented
13326 * so we can use last_val. Otherwise punt and let it default.
13329 appendPQExpBuffer(query, " START WITH %s\n", last);
13332 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13335 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13337 appendPQExpBuffer(query, " NO MINVALUE\n");
13340 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13342 appendPQExpBuffer(query, " NO MAXVALUE\n");
13344 appendPQExpBuffer(query,
13346 cache, (cycled ? "\n CYCLE" : ""));
13348 appendPQExpBuffer(query, ";\n");
13350 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13352 /* binary_upgrade: no need to clear TOAST table oid */
13354 if (binary_upgrade)
13355 binary_upgrade_extension_member(query, &tbinfo->dobj,
13358 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13360 tbinfo->dobj.namespace->dobj.name,
13363 false, "SEQUENCE", SECTION_PRE_DATA,
13364 query->data, delqry->data, NULL,
13365 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13369 * If the sequence is owned by a table column, emit the ALTER for it
13370 * as a separate TOC entry immediately following the sequence's own
13371 * entry. It's OK to do this rather than using full sorting logic,
13372 * because the dependency that tells us it's owned will have forced
13373 * the table to be created first. We can't just include the ALTER in
13374 * the TOC entry because it will fail if we haven't reassigned the
13375 * sequence owner to match the table's owner.
13377 * We need not schema-qualify the table reference because both
13378 * sequence and table must be in the same schema.
13380 if (OidIsValid(tbinfo->owning_tab))
13382 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13384 if (owning_tab && owning_tab->dobj.dump)
13386 resetPQExpBuffer(query);
13387 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13388 fmtId(tbinfo->dobj.name));
13389 appendPQExpBuffer(query, " OWNED BY %s",
13390 fmtId(owning_tab->dobj.name));
13391 appendPQExpBuffer(query, ".%s;\n",
13392 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13394 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13396 tbinfo->dobj.namespace->dobj.name,
13399 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13400 query->data, "", NULL,
13401 &(tbinfo->dobj.dumpId), 1,
13406 /* Dump Sequence Comments and Security Labels */
13407 dumpComment(fout, labelq->data,
13408 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13409 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13410 dumpSecLabel(fout, labelq->data,
13411 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13412 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13417 resetPQExpBuffer(query);
13418 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13419 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13420 appendPQExpBuffer(query, ", %s, %s);\n",
13421 last, (called ? "true" : "false"));
13423 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13425 tbinfo->dobj.namespace->dobj.name,
13428 false, "SEQUENCE SET", SECTION_PRE_DATA,
13429 query->data, "", NULL,
13430 &(tbinfo->dobj.dumpId), 1,
13436 destroyPQExpBuffer(query);
13437 destroyPQExpBuffer(delqry);
13438 destroyPQExpBuffer(labelq);
13442 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13444 TableInfo *tbinfo = tginfo->tgtable;
13446 PQExpBuffer delqry;
13447 PQExpBuffer labelq;
13456 query = createPQExpBuffer();
13457 delqry = createPQExpBuffer();
13458 labelq = createPQExpBuffer();
13461 * DROP must be fully qualified in case same name appears in pg_catalog
13463 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13464 fmtId(tginfo->dobj.name));
13465 appendPQExpBuffer(delqry, "ON %s.",
13466 fmtId(tbinfo->dobj.namespace->dobj.name));
13467 appendPQExpBuffer(delqry, "%s;\n",
13468 fmtId(tbinfo->dobj.name));
13472 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13476 if (tginfo->tgisconstraint)
13478 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13479 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13483 appendPQExpBuffer(query, "CREATE TRIGGER ");
13484 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13486 appendPQExpBuffer(query, "\n ");
13489 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13490 appendPQExpBuffer(query, "BEFORE");
13491 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13492 appendPQExpBuffer(query, "AFTER");
13493 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13494 appendPQExpBuffer(query, "INSTEAD OF");
13497 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13502 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13504 appendPQExpBuffer(query, " INSERT");
13507 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13510 appendPQExpBuffer(query, " OR DELETE");
13512 appendPQExpBuffer(query, " DELETE");
13515 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13518 appendPQExpBuffer(query, " OR UPDATE");
13520 appendPQExpBuffer(query, " UPDATE");
13523 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13526 appendPQExpBuffer(query, " OR TRUNCATE");
13528 appendPQExpBuffer(query, " TRUNCATE");
13531 appendPQExpBuffer(query, " ON %s\n",
13532 fmtId(tbinfo->dobj.name));
13534 if (tginfo->tgisconstraint)
13536 if (OidIsValid(tginfo->tgconstrrelid))
13538 /* If we are using regclass, name is already quoted */
13539 if (fout->remoteVersion >= 70300)
13540 appendPQExpBuffer(query, " FROM %s\n ",
13541 tginfo->tgconstrrelname);
13543 appendPQExpBuffer(query, " FROM %s\n ",
13544 fmtId(tginfo->tgconstrrelname));
13546 if (!tginfo->tgdeferrable)
13547 appendPQExpBuffer(query, "NOT ");
13548 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13549 if (tginfo->tginitdeferred)
13550 appendPQExpBuffer(query, "DEFERRED\n");
13552 appendPQExpBuffer(query, "IMMEDIATE\n");
13555 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13556 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13558 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13560 /* In 7.3, result of regproc is already quoted */
13561 if (fout->remoteVersion >= 70300)
13562 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13565 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13566 fmtId(tginfo->tgfname));
13568 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13571 for (findx = 0; findx < tginfo->tgnargs; findx++)
13573 /* find the embedded null that terminates this trigger argument */
13574 size_t tlen = strlen(p);
13576 if (p + tlen >= tgargs + lentgargs)
13578 /* hm, not found before end of bytea value... */
13579 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13582 tbinfo->dobj.name);
13587 appendPQExpBuffer(query, ", ");
13588 appendStringLiteralAH(query, p, fout);
13592 appendPQExpBuffer(query, ");\n");
13595 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13597 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13598 fmtId(tbinfo->dobj.name));
13599 switch (tginfo->tgenabled)
13603 appendPQExpBuffer(query, "DISABLE");
13606 appendPQExpBuffer(query, "ENABLE ALWAYS");
13609 appendPQExpBuffer(query, "ENABLE REPLICA");
13612 appendPQExpBuffer(query, "ENABLE");
13615 appendPQExpBuffer(query, " TRIGGER %s;\n",
13616 fmtId(tginfo->dobj.name));
13619 appendPQExpBuffer(labelq, "TRIGGER %s ",
13620 fmtId(tginfo->dobj.name));
13621 appendPQExpBuffer(labelq, "ON %s",
13622 fmtId(tbinfo->dobj.name));
13624 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13626 tbinfo->dobj.namespace->dobj.name,
13628 tbinfo->rolname, false,
13629 "TRIGGER", SECTION_POST_DATA,
13630 query->data, delqry->data, NULL,
13631 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13634 dumpComment(fout, labelq->data,
13635 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13636 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13638 destroyPQExpBuffer(query);
13639 destroyPQExpBuffer(delqry);
13640 destroyPQExpBuffer(labelq);
13648 dumpRule(Archive *fout, RuleInfo *rinfo)
13650 TableInfo *tbinfo = rinfo->ruletable;
13653 PQExpBuffer delcmd;
13654 PQExpBuffer labelq;
13657 /* Skip if not to be dumped */
13658 if (!rinfo->dobj.dump || dataOnly)
13662 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13663 * we do not want to dump it as a separate object.
13665 if (!rinfo->separate)
13669 * Make sure we are in proper schema.
13671 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13673 query = createPQExpBuffer();
13674 cmd = createPQExpBuffer();
13675 delcmd = createPQExpBuffer();
13676 labelq = createPQExpBuffer();
13678 if (fout->remoteVersion >= 70300)
13680 appendPQExpBuffer(query,
13681 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13682 rinfo->dobj.catId.oid);
13686 /* Rule name was unique before 7.3 ... */
13687 appendPQExpBuffer(query,
13688 "SELECT pg_get_ruledef('%s') AS definition",
13692 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13694 if (PQntuples(res) != 1)
13696 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13697 rinfo->dobj.name, tbinfo->dobj.name);
13701 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13704 * Add the command to alter the rules replication firing semantics if it
13705 * differs from the default.
13707 if (rinfo->ev_enabled != 'O')
13709 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13710 fmtId(tbinfo->dobj.namespace->dobj.name));
13711 appendPQExpBuffer(cmd, "%s ",
13712 fmtId(tbinfo->dobj.name));
13713 switch (rinfo->ev_enabled)
13716 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13717 fmtId(rinfo->dobj.name));
13720 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13721 fmtId(rinfo->dobj.name));
13724 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13725 fmtId(rinfo->dobj.name));
13731 * DROP must be fully qualified in case same name appears in pg_catalog
13733 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13734 fmtId(rinfo->dobj.name));
13735 appendPQExpBuffer(delcmd, "ON %s.",
13736 fmtId(tbinfo->dobj.namespace->dobj.name));
13737 appendPQExpBuffer(delcmd, "%s;\n",
13738 fmtId(tbinfo->dobj.name));
13740 appendPQExpBuffer(labelq, "RULE %s",
13741 fmtId(rinfo->dobj.name));
13742 appendPQExpBuffer(labelq, " ON %s",
13743 fmtId(tbinfo->dobj.name));
13745 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13747 tbinfo->dobj.namespace->dobj.name,
13749 tbinfo->rolname, false,
13750 "RULE", SECTION_POST_DATA,
13751 cmd->data, delcmd->data, NULL,
13752 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13755 /* Dump rule comments */
13756 dumpComment(fout, labelq->data,
13757 tbinfo->dobj.namespace->dobj.name,
13759 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13763 destroyPQExpBuffer(query);
13764 destroyPQExpBuffer(cmd);
13765 destroyPQExpBuffer(delcmd);
13766 destroyPQExpBuffer(labelq);
13770 * getExtensionMembership --- obtain extension membership data
13773 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13784 DumpableObject *dobj,
13787 /* Nothing to do if no extensions */
13788 if (numExtensions == 0)
13791 /* Make sure we are in proper schema */
13792 selectSourceSchema(fout, "pg_catalog");
13794 query = createPQExpBuffer();
13796 /* refclassid constraint is redundant but may speed the search */
13797 appendPQExpBuffer(query, "SELECT "
13798 "classid, objid, refclassid, refobjid "
13800 "WHERE refclassid = 'pg_extension'::regclass "
13801 "AND deptype = 'e' "
13804 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13806 ntups = PQntuples(res);
13808 i_classid = PQfnumber(res, "classid");
13809 i_objid = PQfnumber(res, "objid");
13810 i_refclassid = PQfnumber(res, "refclassid");
13811 i_refobjid = PQfnumber(res, "refobjid");
13814 * Since we ordered the SELECT by referenced ID, we can expect that
13815 * multiple entries for the same extension will appear together; this
13816 * saves on searches.
13820 for (i = 0; i < ntups; i++)
13823 CatalogId refobjId;
13825 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13826 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13827 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13828 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13830 if (refdobj == NULL ||
13831 refdobj->catId.tableoid != refobjId.tableoid ||
13832 refdobj->catId.oid != refobjId.oid)
13833 refdobj = findObjectByCatalogId(refobjId);
13836 * Failure to find objects mentioned in pg_depend is not unexpected,
13837 * since for example we don't collect info about TOAST tables.
13839 if (refdobj == NULL)
13842 fprintf(stderr, "no referenced object %u %u\n",
13843 refobjId.tableoid, refobjId.oid);
13848 dobj = findObjectByCatalogId(objId);
13853 fprintf(stderr, "no referencing object %u %u\n",
13854 objId.tableoid, objId.oid);
13859 /* Record dependency so that getDependencies needn't repeat this */
13860 addObjectDependency(dobj, refdobj->dumpId);
13862 dobj->ext_member = true;
13865 * Normally, mark the member object as not to be dumped. But in
13866 * binary upgrades, we still dump the members individually, since the
13867 * idea is to exactly reproduce the database contents rather than
13868 * replace the extension contents with something different.
13870 if (!binary_upgrade)
13871 dobj->dump = false;
13873 dobj->dump = refdobj->dump;
13879 * Now identify extension configuration tables and create TableDataInfo
13880 * objects for them, ensuring their data will be dumped even though the
13881 * tables themselves won't be.
13883 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13884 * user data in a configuration table is treated like schema data. This
13885 * seems appropriate since system data in a config table would get
13886 * reloaded by CREATE EXTENSION.
13888 for (i = 0; i < numExtensions; i++)
13890 ExtensionInfo *curext = &(extinfo[i]);
13891 char *extconfig = curext->extconfig;
13892 char *extcondition = curext->extcondition;
13893 char **extconfigarray = NULL;
13894 char **extconditionarray = NULL;
13896 int nconditionitems;
13898 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13899 if (!curext->dobj.dump)
13902 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13903 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13904 nconfigitems == nconditionitems)
13908 for (j = 0; j < nconfigitems; j++)
13910 TableInfo *configtbl;
13912 configtbl = findTableByOid(atooid(extconfigarray[j]));
13913 if (configtbl == NULL)
13917 * Note: config tables are dumped without OIDs regardless
13918 * of the --oids setting. This is because row filtering
13919 * conditions aren't compatible with dumping OIDs.
13921 makeTableDataInfo(configtbl, false);
13922 if (configtbl->dataObj != NULL)
13924 if (strlen(extconditionarray[j]) > 0)
13925 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13929 if (extconfigarray)
13930 free(extconfigarray);
13931 if (extconditionarray)
13932 free(extconditionarray);
13935 destroyPQExpBuffer(query);
13939 * getDependencies --- obtain available dependency data
13942 getDependencies(Archive *fout)
13953 DumpableObject *dobj,
13956 /* No dependency info available before 7.3 */
13957 if (fout->remoteVersion < 70300)
13961 write_msg(NULL, "reading dependency data\n");
13963 /* Make sure we are in proper schema */
13964 selectSourceSchema(fout, "pg_catalog");
13966 query = createPQExpBuffer();
13969 * PIN dependencies aren't interesting, and EXTENSION dependencies were
13970 * already processed by getExtensionMembership.
13972 appendPQExpBuffer(query, "SELECT "
13973 "classid, objid, refclassid, refobjid, deptype "
13975 "WHERE deptype != 'p' AND deptype != 'e' "
13978 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13980 ntups = PQntuples(res);
13982 i_classid = PQfnumber(res, "classid");
13983 i_objid = PQfnumber(res, "objid");
13984 i_refclassid = PQfnumber(res, "refclassid");
13985 i_refobjid = PQfnumber(res, "refobjid");
13986 i_deptype = PQfnumber(res, "deptype");
13989 * Since we ordered the SELECT by referencing ID, we can expect that
13990 * multiple entries for the same object will appear together; this saves
13995 for (i = 0; i < ntups; i++)
13998 CatalogId refobjId;
14001 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14002 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14003 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14004 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14005 deptype = *(PQgetvalue(res, i, i_deptype));
14007 if (dobj == NULL ||
14008 dobj->catId.tableoid != objId.tableoid ||
14009 dobj->catId.oid != objId.oid)
14010 dobj = findObjectByCatalogId(objId);
14013 * Failure to find objects mentioned in pg_depend is not unexpected,
14014 * since for example we don't collect info about TOAST tables.
14019 fprintf(stderr, "no referencing object %u %u\n",
14020 objId.tableoid, objId.oid);
14025 refdobj = findObjectByCatalogId(refobjId);
14027 if (refdobj == NULL)
14030 fprintf(stderr, "no referenced object %u %u\n",
14031 refobjId.tableoid, refobjId.oid);
14037 * Ordinarily, table rowtypes have implicit dependencies on their
14038 * tables. However, for a composite type the implicit dependency goes
14039 * the other way in pg_depend; which is the right thing for DROP but
14040 * it doesn't produce the dependency ordering we need. So in that one
14041 * case, we reverse the direction of the dependency.
14043 if (deptype == 'i' &&
14044 dobj->objType == DO_TABLE &&
14045 refdobj->objType == DO_TYPE)
14046 addObjectDependency(refdobj, dobj->dumpId);
14049 addObjectDependency(dobj, refdobj->dumpId);
14054 destroyPQExpBuffer(query);
14059 * selectSourceSchema - make the specified schema the active search path
14060 * in the source database.
14062 * NB: pg_catalog is explicitly searched after the specified schema;
14063 * so user names are only qualified if they are cross-schema references,
14064 * and system names are only qualified if they conflict with a user name
14065 * in the current schema.
14067 * Whenever the selected schema is not pg_catalog, be careful to qualify
14068 * references to system catalogs and types in our emitted commands!
14071 selectSourceSchema(Archive *fout, const char *schemaName)
14073 static char *curSchemaName = NULL;
14076 /* Not relevant if fetching from pre-7.3 DB */
14077 if (fout->remoteVersion < 70300)
14079 /* Ignore null schema names */
14080 if (schemaName == NULL || *schemaName == '\0')
14082 /* Optimize away repeated selection of same schema */
14083 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14086 query = createPQExpBuffer();
14087 appendPQExpBuffer(query, "SET search_path = %s",
14088 fmtId(schemaName));
14089 if (strcmp(schemaName, "pg_catalog") != 0)
14090 appendPQExpBuffer(query, ", pg_catalog");
14092 ExecuteSqlStatement(fout, query->data);
14094 destroyPQExpBuffer(query);
14096 free(curSchemaName);
14097 curSchemaName = pg_strdup(schemaName);
14101 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14104 * NB: in 7.3 and up the result may depend on the currently-selected
14105 * schema; this is why we don't try to cache the names.
14108 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14116 if ((opts & zeroAsOpaque) != 0)
14117 return pg_strdup(g_opaque_type);
14118 else if ((opts & zeroAsAny) != 0)
14119 return pg_strdup("'any'");
14120 else if ((opts & zeroAsStar) != 0)
14121 return pg_strdup("*");
14122 else if ((opts & zeroAsNone) != 0)
14123 return pg_strdup("NONE");
14126 query = createPQExpBuffer();
14127 if (fout->remoteVersion >= 70300)
14129 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14132 else if (fout->remoteVersion >= 70100)
14134 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14139 appendPQExpBuffer(query, "SELECT typname "
14141 "WHERE oid = '%u'::oid",
14145 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14147 if (fout->remoteVersion >= 70100)
14149 /* already quoted */
14150 result = pg_strdup(PQgetvalue(res, 0, 0));
14154 /* may need to quote it */
14155 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14159 destroyPQExpBuffer(query);
14165 * myFormatType --- local implementation of format_type for use with 7.0.
14168 myFormatType(const char *typname, int32 typmod)
14171 bool isarray = false;
14172 PQExpBuffer buf = createPQExpBuffer();
14174 /* Handle array types */
14175 if (typname[0] == '_')
14181 /* Show lengths on bpchar and varchar */
14182 if (strcmp(typname, "bpchar") == 0)
14184 int len = (typmod - VARHDRSZ);
14186 appendPQExpBuffer(buf, "character");
14188 appendPQExpBuffer(buf, "(%d)",
14189 typmod - VARHDRSZ);
14191 else if (strcmp(typname, "varchar") == 0)
14193 appendPQExpBuffer(buf, "character varying");
14195 appendPQExpBuffer(buf, "(%d)",
14196 typmod - VARHDRSZ);
14198 else if (strcmp(typname, "numeric") == 0)
14200 appendPQExpBuffer(buf, "numeric");
14207 tmp_typmod = typmod - VARHDRSZ;
14208 precision = (tmp_typmod >> 16) & 0xffff;
14209 scale = tmp_typmod & 0xffff;
14210 appendPQExpBuffer(buf, "(%d,%d)",
14216 * char is an internal single-byte data type; Let's make sure we force it
14217 * through with quotes. - thomas 1998-12-13
14219 else if (strcmp(typname, "char") == 0)
14220 appendPQExpBuffer(buf, "\"char\"");
14222 appendPQExpBuffer(buf, "%s", fmtId(typname));
14224 /* Append array qualifier for array types */
14226 appendPQExpBuffer(buf, "[]");
14228 result = pg_strdup(buf->data);
14229 destroyPQExpBuffer(buf);
14235 * fmtQualifiedId - convert a qualified name to the proper format for
14236 * the source database.
14238 * Like fmtId, use the result before calling again.
14240 static const char *
14241 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14243 static PQExpBuffer id_return = NULL;
14245 if (id_return) /* first time through? */
14246 resetPQExpBuffer(id_return);
14248 id_return = createPQExpBuffer();
14250 /* Suppress schema name if fetching from pre-7.3 DB */
14251 if (fout->remoteVersion >= 70300 && schema && *schema)
14253 appendPQExpBuffer(id_return, "%s.",
14256 appendPQExpBuffer(id_return, "%s",
14259 return id_return->data;
14263 * Return a column list clause for the given relation.
14265 * Special case: if there are no undropped columns in the relation, return
14266 * "", not an invalid "()" column list.
14268 static const char *
14269 fmtCopyColumnList(const TableInfo *ti)
14271 static PQExpBuffer q = NULL;
14272 int numatts = ti->numatts;
14273 char **attnames = ti->attnames;
14274 bool *attisdropped = ti->attisdropped;
14278 if (q) /* first time through? */
14279 resetPQExpBuffer(q);
14281 q = createPQExpBuffer();
14283 appendPQExpBuffer(q, "(");
14285 for (i = 0; i < numatts; i++)
14287 if (attisdropped[i])
14290 appendPQExpBuffer(q, ", ");
14291 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14296 return ""; /* no undropped columns */
14298 appendPQExpBuffer(q, ")");
14303 * Execute an SQL query and verify that we got exactly one row back.
14306 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14311 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14313 /* Expecting a single result only */
14314 ntups = PQntuples(res);
14316 exit_horribly(NULL,
14317 ngettext("query returned %d row instead of one: %s\n",
14318 "query returned %d rows instead of one: %s\n",