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 (including views and sequences).
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 tables that are not type 'r' (ordinary relation), 'S'
3856 * (sequence), 'v' (view), or 'c' (composite type).
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 * conisonly and convalidated are new in 9.2 (actually, the latter
5964 * is there in 9.1, but it wasn't ever false for check constraints
5967 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5968 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5969 "conislocal, convalidated, conisonly "
5970 "FROM pg_catalog.pg_constraint "
5971 "WHERE conrelid = '%u'::pg_catalog.oid "
5972 " AND contype = 'c' "
5974 tbinfo->dobj.catId.oid);
5976 else if (fout->remoteVersion >= 80400)
5978 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5979 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5980 "conislocal, true AS convalidated, "
5981 "false as conisonly "
5982 "FROM pg_catalog.pg_constraint "
5983 "WHERE conrelid = '%u'::pg_catalog.oid "
5984 " AND contype = 'c' "
5986 tbinfo->dobj.catId.oid);
5988 else if (fout->remoteVersion >= 70400)
5990 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5991 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5992 "true AS conislocal, true AS convalidated, "
5993 "false as conisonly "
5994 "FROM pg_catalog.pg_constraint "
5995 "WHERE conrelid = '%u'::pg_catalog.oid "
5996 " AND contype = 'c' "
5998 tbinfo->dobj.catId.oid);
6000 else if (fout->remoteVersion >= 70300)
6002 /* no pg_get_constraintdef, must use consrc */
6003 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6004 "'CHECK (' || consrc || ')' AS consrc, "
6005 "true AS conislocal, true AS convalidated, "
6006 "false as conisonly "
6007 "FROM pg_catalog.pg_constraint "
6008 "WHERE conrelid = '%u'::pg_catalog.oid "
6009 " AND contype = 'c' "
6011 tbinfo->dobj.catId.oid);
6013 else if (fout->remoteVersion >= 70200)
6015 /* 7.2 did not have OIDs in pg_relcheck */
6016 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6017 "rcname AS conname, "
6018 "'CHECK (' || rcsrc || ')' AS consrc, "
6019 "true AS conislocal, true AS convalidated, "
6020 "false as conisonly "
6022 "WHERE rcrelid = '%u'::oid "
6024 tbinfo->dobj.catId.oid);
6026 else if (fout->remoteVersion >= 70100)
6028 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6029 "rcname AS conname, "
6030 "'CHECK (' || rcsrc || ')' AS consrc, "
6031 "true AS conislocal, true AS convalidated, "
6032 "false as conisonly "
6034 "WHERE rcrelid = '%u'::oid "
6036 tbinfo->dobj.catId.oid);
6040 /* no tableoid in 7.0 */
6041 appendPQExpBuffer(q, "SELECT "
6042 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6043 "oid, rcname AS conname, "
6044 "'CHECK (' || rcsrc || ')' AS consrc, "
6045 "true AS conislocal, true AS convalidated, "
6046 "false as conisonly "
6048 "WHERE rcrelid = '%u'::oid "
6050 tbinfo->dobj.catId.oid);
6052 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6054 numConstrs = PQntuples(res);
6055 if (numConstrs != tbinfo->ncheck)
6057 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6058 "expected %d check constraints on table \"%s\" but found %d\n",
6060 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6061 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6065 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6066 tbinfo->checkexprs = constrs;
6068 for (j = 0; j < numConstrs; j++)
6070 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6071 bool isonly = PQgetvalue(res, j, 6)[0] == 't';
6073 constrs[j].dobj.objType = DO_CONSTRAINT;
6074 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6075 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6076 AssignDumpId(&constrs[j].dobj);
6077 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6078 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6079 constrs[j].contable = tbinfo;
6080 constrs[j].condomain = NULL;
6081 constrs[j].contype = 'c';
6082 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6083 constrs[j].confrelid = InvalidOid;
6084 constrs[j].conindex = 0;
6085 constrs[j].condeferrable = false;
6086 constrs[j].condeferred = false;
6087 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6088 constrs[j].conisonly = isonly;
6090 * An unvalidated constraint needs to be dumped separately, so
6091 * that potentially-violating existing data is loaded before
6092 * the constraint. An ONLY constraint needs to be dumped
6095 constrs[j].separate = !validated || isonly;
6097 constrs[j].dobj.dump = tbinfo->dobj.dump;
6100 * Mark the constraint as needing to appear before the table
6101 * --- this is so that any other dependencies of the
6102 * constraint will be emitted before we try to create the
6103 * table. If the constraint is to be dumped separately, it will be
6104 * dumped after data is loaded anyway, so don't do it. (There's
6105 * an automatic dependency in the opposite direction anyway, so
6106 * don't need to add one manually here.)
6108 if (!constrs[j].separate)
6109 addObjectDependency(&tbinfo->dobj,
6110 constrs[j].dobj.dumpId);
6113 * If the constraint is inherited, this will be detected later
6114 * (in pre-8.4 databases). We also detect later if the
6115 * constraint must be split out from the table definition.
6122 destroyPQExpBuffer(q);
6126 * Test whether a column should be printed as part of table's CREATE TABLE.
6127 * Column number is zero-based.
6129 * Normally this is always true, but it's false for dropped columns, as well
6130 * as those that were inherited without any local definition. (If we print
6131 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6132 * However, in binary_upgrade mode, we must print all such columns anyway and
6133 * fix the attislocal/attisdropped state later, so as to keep control of the
6134 * physical column order.
6136 * This function exists because there are scattered nonobvious places that
6137 * must be kept in sync with this decision.
6140 shouldPrintColumn(TableInfo *tbinfo, int colno)
6144 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6150 * read all text search parsers in the system catalogs and return them
6151 * in the TSParserInfo* structure
6153 * numTSParsers is set to the number of parsers read in
6156 getTSParsers(Archive *fout, int *numTSParsers)
6162 TSParserInfo *prsinfo;
6173 /* Before 8.3, there is no built-in text search support */
6174 if (fout->remoteVersion < 80300)
6180 query = createPQExpBuffer();
6183 * find all text search objects, including builtin ones; we filter out
6184 * system-defined objects at dump-out time.
6187 /* Make sure we are in proper schema */
6188 selectSourceSchema(fout, "pg_catalog");
6190 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6191 "prsstart::oid, prstoken::oid, "
6192 "prsend::oid, prsheadline::oid, prslextype::oid "
6193 "FROM pg_ts_parser");
6195 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6197 ntups = PQntuples(res);
6198 *numTSParsers = ntups;
6200 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6202 i_tableoid = PQfnumber(res, "tableoid");
6203 i_oid = PQfnumber(res, "oid");
6204 i_prsname = PQfnumber(res, "prsname");
6205 i_prsnamespace = PQfnumber(res, "prsnamespace");
6206 i_prsstart = PQfnumber(res, "prsstart");
6207 i_prstoken = PQfnumber(res, "prstoken");
6208 i_prsend = PQfnumber(res, "prsend");
6209 i_prsheadline = PQfnumber(res, "prsheadline");
6210 i_prslextype = PQfnumber(res, "prslextype");
6212 for (i = 0; i < ntups; i++)
6214 prsinfo[i].dobj.objType = DO_TSPARSER;
6215 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6216 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6217 AssignDumpId(&prsinfo[i].dobj);
6218 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6219 prsinfo[i].dobj.namespace =
6221 atooid(PQgetvalue(res, i, i_prsnamespace)),
6222 prsinfo[i].dobj.catId.oid);
6223 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6224 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6225 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6226 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6227 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6229 /* Decide whether we want to dump it */
6230 selectDumpableObject(&(prsinfo[i].dobj));
6235 destroyPQExpBuffer(query);
6241 * getTSDictionaries:
6242 * read all text search dictionaries in the system catalogs and return them
6243 * in the TSDictInfo* structure
6245 * numTSDicts is set to the number of dictionaries read in
6248 getTSDictionaries(Archive *fout, int *numTSDicts)
6254 TSDictInfo *dictinfo;
6258 int i_dictnamespace;
6261 int i_dictinitoption;
6263 /* Before 8.3, there is no built-in text search support */
6264 if (fout->remoteVersion < 80300)
6270 query = createPQExpBuffer();
6272 /* Make sure we are in proper schema */
6273 selectSourceSchema(fout, "pg_catalog");
6275 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6276 "dictnamespace, (%s dictowner) AS rolname, "
6277 "dicttemplate, dictinitoption "
6281 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6283 ntups = PQntuples(res);
6284 *numTSDicts = ntups;
6286 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6288 i_tableoid = PQfnumber(res, "tableoid");
6289 i_oid = PQfnumber(res, "oid");
6290 i_dictname = PQfnumber(res, "dictname");
6291 i_dictnamespace = PQfnumber(res, "dictnamespace");
6292 i_rolname = PQfnumber(res, "rolname");
6293 i_dictinitoption = PQfnumber(res, "dictinitoption");
6294 i_dicttemplate = PQfnumber(res, "dicttemplate");
6296 for (i = 0; i < ntups; i++)
6298 dictinfo[i].dobj.objType = DO_TSDICT;
6299 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6300 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6301 AssignDumpId(&dictinfo[i].dobj);
6302 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6303 dictinfo[i].dobj.namespace =
6305 atooid(PQgetvalue(res, i, i_dictnamespace)),
6306 dictinfo[i].dobj.catId.oid);
6307 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6308 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6309 if (PQgetisnull(res, i, i_dictinitoption))
6310 dictinfo[i].dictinitoption = NULL;
6312 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6314 /* Decide whether we want to dump it */
6315 selectDumpableObject(&(dictinfo[i].dobj));
6320 destroyPQExpBuffer(query);
6327 * read all text search templates in the system catalogs and return them
6328 * in the TSTemplateInfo* structure
6330 * numTSTemplates is set to the number of templates read in
6333 getTSTemplates(Archive *fout, int *numTSTemplates)
6339 TSTemplateInfo *tmplinfo;
6343 int i_tmplnamespace;
6347 /* Before 8.3, there is no built-in text search support */
6348 if (fout->remoteVersion < 80300)
6350 *numTSTemplates = 0;
6354 query = createPQExpBuffer();
6356 /* Make sure we are in proper schema */
6357 selectSourceSchema(fout, "pg_catalog");
6359 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6360 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6361 "FROM pg_ts_template");
6363 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6365 ntups = PQntuples(res);
6366 *numTSTemplates = ntups;
6368 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6370 i_tableoid = PQfnumber(res, "tableoid");
6371 i_oid = PQfnumber(res, "oid");
6372 i_tmplname = PQfnumber(res, "tmplname");
6373 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6374 i_tmplinit = PQfnumber(res, "tmplinit");
6375 i_tmpllexize = PQfnumber(res, "tmpllexize");
6377 for (i = 0; i < ntups; i++)
6379 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6380 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6381 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6382 AssignDumpId(&tmplinfo[i].dobj);
6383 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6384 tmplinfo[i].dobj.namespace =
6386 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6387 tmplinfo[i].dobj.catId.oid);
6388 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6389 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6391 /* Decide whether we want to dump it */
6392 selectDumpableObject(&(tmplinfo[i].dobj));
6397 destroyPQExpBuffer(query);
6403 * getTSConfigurations:
6404 * read all text search configurations in the system catalogs and return
6405 * them in the TSConfigInfo* structure
6407 * numTSConfigs is set to the number of configurations read in
6410 getTSConfigurations(Archive *fout, int *numTSConfigs)
6416 TSConfigInfo *cfginfo;
6424 /* Before 8.3, there is no built-in text search support */
6425 if (fout->remoteVersion < 80300)
6431 query = createPQExpBuffer();
6433 /* Make sure we are in proper schema */
6434 selectSourceSchema(fout, "pg_catalog");
6436 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6437 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6438 "FROM pg_ts_config",
6441 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6443 ntups = PQntuples(res);
6444 *numTSConfigs = ntups;
6446 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6448 i_tableoid = PQfnumber(res, "tableoid");
6449 i_oid = PQfnumber(res, "oid");
6450 i_cfgname = PQfnumber(res, "cfgname");
6451 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6452 i_rolname = PQfnumber(res, "rolname");
6453 i_cfgparser = PQfnumber(res, "cfgparser");
6455 for (i = 0; i < ntups; i++)
6457 cfginfo[i].dobj.objType = DO_TSCONFIG;
6458 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6459 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6460 AssignDumpId(&cfginfo[i].dobj);
6461 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6462 cfginfo[i].dobj.namespace =
6464 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6465 cfginfo[i].dobj.catId.oid);
6466 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6467 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6469 /* Decide whether we want to dump it */
6470 selectDumpableObject(&(cfginfo[i].dobj));
6475 destroyPQExpBuffer(query);
6481 * getForeignDataWrappers:
6482 * read all foreign-data wrappers in the system catalogs and return
6483 * them in the FdwInfo* structure
6485 * numForeignDataWrappers is set to the number of fdws read in
6488 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6493 PQExpBuffer query = createPQExpBuffer();
6504 /* Before 8.4, there are no foreign-data wrappers */
6505 if (fout->remoteVersion < 80400)
6507 *numForeignDataWrappers = 0;
6511 /* Make sure we are in proper schema */
6512 selectSourceSchema(fout, "pg_catalog");
6514 if (fout->remoteVersion >= 90100)
6516 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6517 "(%s fdwowner) AS rolname, "
6518 "fdwhandler::pg_catalog.regproc, "
6519 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6520 "array_to_string(ARRAY("
6521 "SELECT quote_ident(option_name) || ' ' || "
6522 "quote_literal(option_value) "
6523 "FROM pg_options_to_table(fdwoptions) "
6524 "ORDER BY option_name"
6525 "), E',\n ') AS fdwoptions "
6526 "FROM pg_foreign_data_wrapper",
6531 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6532 "(%s fdwowner) AS rolname, "
6533 "'-' AS fdwhandler, "
6534 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6535 "array_to_string(ARRAY("
6536 "SELECT quote_ident(option_name) || ' ' || "
6537 "quote_literal(option_value) "
6538 "FROM pg_options_to_table(fdwoptions) "
6539 "ORDER BY option_name"
6540 "), E',\n ') AS fdwoptions "
6541 "FROM pg_foreign_data_wrapper",
6545 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6547 ntups = PQntuples(res);
6548 *numForeignDataWrappers = ntups;
6550 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6552 i_tableoid = PQfnumber(res, "tableoid");
6553 i_oid = PQfnumber(res, "oid");
6554 i_fdwname = PQfnumber(res, "fdwname");
6555 i_rolname = PQfnumber(res, "rolname");
6556 i_fdwhandler = PQfnumber(res, "fdwhandler");
6557 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6558 i_fdwacl = PQfnumber(res, "fdwacl");
6559 i_fdwoptions = PQfnumber(res, "fdwoptions");
6561 for (i = 0; i < ntups; i++)
6563 fdwinfo[i].dobj.objType = DO_FDW;
6564 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6565 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6566 AssignDumpId(&fdwinfo[i].dobj);
6567 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6568 fdwinfo[i].dobj.namespace = NULL;
6569 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6570 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6571 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6572 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6573 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6575 /* Decide whether we want to dump it */
6576 selectDumpableObject(&(fdwinfo[i].dobj));
6581 destroyPQExpBuffer(query);
6587 * getForeignServers:
6588 * read all foreign servers in the system catalogs and return
6589 * them in the ForeignServerInfo * structure
6591 * numForeignServers is set to the number of servers read in
6594 getForeignServers(Archive *fout, int *numForeignServers)
6599 PQExpBuffer query = createPQExpBuffer();
6600 ForeignServerInfo *srvinfo;
6611 /* Before 8.4, there are no foreign servers */
6612 if (fout->remoteVersion < 80400)
6614 *numForeignServers = 0;
6618 /* Make sure we are in proper schema */
6619 selectSourceSchema(fout,"pg_catalog");
6621 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6622 "(%s srvowner) AS rolname, "
6623 "srvfdw, srvtype, srvversion, srvacl,"
6624 "array_to_string(ARRAY("
6625 "SELECT quote_ident(option_name) || ' ' || "
6626 "quote_literal(option_value) "
6627 "FROM pg_options_to_table(srvoptions) "
6628 "ORDER BY option_name"
6629 "), E',\n ') AS srvoptions "
6630 "FROM pg_foreign_server",
6633 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6635 ntups = PQntuples(res);
6636 *numForeignServers = ntups;
6638 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6640 i_tableoid = PQfnumber(res, "tableoid");
6641 i_oid = PQfnumber(res, "oid");
6642 i_srvname = PQfnumber(res, "srvname");
6643 i_rolname = PQfnumber(res, "rolname");
6644 i_srvfdw = PQfnumber(res, "srvfdw");
6645 i_srvtype = PQfnumber(res, "srvtype");
6646 i_srvversion = PQfnumber(res, "srvversion");
6647 i_srvacl = PQfnumber(res, "srvacl");
6648 i_srvoptions = PQfnumber(res, "srvoptions");
6650 for (i = 0; i < ntups; i++)
6652 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6653 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6654 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6655 AssignDumpId(&srvinfo[i].dobj);
6656 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6657 srvinfo[i].dobj.namespace = NULL;
6658 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6659 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6660 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6661 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6662 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6663 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6665 /* Decide whether we want to dump it */
6666 selectDumpableObject(&(srvinfo[i].dobj));
6671 destroyPQExpBuffer(query);
6678 * read all default ACL information in the system catalogs and return
6679 * them in the DefaultACLInfo structure
6681 * numDefaultACLs is set to the number of ACLs read in
6684 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6686 DefaultACLInfo *daclinfo;
6692 int i_defaclnamespace;
6693 int i_defaclobjtype;
6698 if (fout->remoteVersion < 90000)
6700 *numDefaultACLs = 0;
6704 query = createPQExpBuffer();
6706 /* Make sure we are in proper schema */
6707 selectSourceSchema(fout, "pg_catalog");
6709 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6710 "(%s defaclrole) AS defaclrole, "
6714 "FROM pg_default_acl",
6717 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6719 ntups = PQntuples(res);
6720 *numDefaultACLs = ntups;
6722 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6724 i_oid = PQfnumber(res, "oid");
6725 i_tableoid = PQfnumber(res, "tableoid");
6726 i_defaclrole = PQfnumber(res, "defaclrole");
6727 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6728 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6729 i_defaclacl = PQfnumber(res, "defaclacl");
6731 for (i = 0; i < ntups; i++)
6733 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6735 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6736 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6737 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6738 AssignDumpId(&daclinfo[i].dobj);
6739 /* cheesy ... is it worth coming up with a better object name? */
6740 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6742 if (nspid != InvalidOid)
6743 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6744 daclinfo[i].dobj.catId.oid);
6746 daclinfo[i].dobj.namespace = NULL;
6748 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6749 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6750 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6752 /* Decide whether we want to dump it */
6753 selectDumpableDefaultACL(&(daclinfo[i]));
6758 destroyPQExpBuffer(query);
6766 * This routine is used to dump any comments associated with the
6767 * object handed to this routine. The routine takes a constant character
6768 * string for the target part of the comment-creation command, plus
6769 * the namespace and owner of the object (for labeling the ArchiveEntry),
6770 * plus catalog ID and subid which are the lookup key for pg_description,
6771 * plus the dump ID for the object (for setting a dependency).
6772 * If a matching pg_description entry is found, it is dumped.
6774 * Note: although this routine takes a dumpId for dependency purposes,
6775 * that purpose is just to mark the dependency in the emitted dump file
6776 * for possible future use by pg_restore. We do NOT use it for determining
6777 * ordering of the comment in the dump file, because this routine is called
6778 * after dependency sorting occurs. This routine should be called just after
6779 * calling ArchiveEntry() for the specified object.
6782 dumpComment(Archive *fout, const char *target,
6783 const char *namespace, const char *owner,
6784 CatalogId catalogId, int subid, DumpId dumpId)
6786 CommentItem *comments;
6789 /* Comments are schema not data ... except blob comments are data */
6790 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6801 /* Search for comments associated with catalogId, using table */
6802 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6805 /* Is there one matching the subid? */
6806 while (ncomments > 0)
6808 if (comments->objsubid == subid)
6814 /* If a comment exists, build COMMENT ON statement */
6817 PQExpBuffer query = createPQExpBuffer();
6819 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6820 appendStringLiteralAH(query, comments->descr, fout);
6821 appendPQExpBuffer(query, ";\n");
6824 * We mark comments as SECTION_NONE because they really belong in the
6825 * same section as their parent, whether that is pre-data or
6828 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6829 target, namespace, NULL, owner,
6830 false, "COMMENT", SECTION_NONE,
6831 query->data, "", NULL,
6835 destroyPQExpBuffer(query);
6840 * dumpTableComment --
6842 * As above, but dump comments for both the specified table (or view)
6846 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6847 const char *reltypename)
6849 CommentItem *comments;
6854 /* Comments are SCHEMA not data */
6858 /* Search for comments associated with relation, using table */
6859 ncomments = findComments(fout,
6860 tbinfo->dobj.catId.tableoid,
6861 tbinfo->dobj.catId.oid,
6864 /* If comments exist, build COMMENT ON statements */
6868 query = createPQExpBuffer();
6869 target = createPQExpBuffer();
6871 while (ncomments > 0)
6873 const char *descr = comments->descr;
6874 int objsubid = comments->objsubid;
6878 resetPQExpBuffer(target);
6879 appendPQExpBuffer(target, "%s %s", reltypename,
6880 fmtId(tbinfo->dobj.name));
6882 resetPQExpBuffer(query);
6883 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6884 appendStringLiteralAH(query, descr, fout);
6885 appendPQExpBuffer(query, ";\n");
6887 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6889 tbinfo->dobj.namespace->dobj.name,
6890 NULL, tbinfo->rolname,
6891 false, "COMMENT", SECTION_NONE,
6892 query->data, "", NULL,
6893 &(tbinfo->dobj.dumpId), 1,
6896 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6898 resetPQExpBuffer(target);
6899 appendPQExpBuffer(target, "COLUMN %s.",
6900 fmtId(tbinfo->dobj.name));
6901 appendPQExpBuffer(target, "%s",
6902 fmtId(tbinfo->attnames[objsubid - 1]));
6904 resetPQExpBuffer(query);
6905 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6906 appendStringLiteralAH(query, descr, fout);
6907 appendPQExpBuffer(query, ";\n");
6909 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6911 tbinfo->dobj.namespace->dobj.name,
6912 NULL, tbinfo->rolname,
6913 false, "COMMENT", SECTION_NONE,
6914 query->data, "", NULL,
6915 &(tbinfo->dobj.dumpId), 1,
6923 destroyPQExpBuffer(query);
6924 destroyPQExpBuffer(target);
6930 * Find the comment(s), if any, associated with the given object. All the
6931 * objsubid values associated with the given classoid/objoid are found with
6935 findComments(Archive *fout, Oid classoid, Oid objoid,
6936 CommentItem **items)
6938 /* static storage for table of comments */
6939 static CommentItem *comments = NULL;
6940 static int ncomments = -1;
6942 CommentItem *middle = NULL;
6947 /* Get comments if we didn't already */
6949 ncomments = collectComments(fout, &comments);
6952 * Pre-7.2, pg_description does not contain classoid, so collectComments
6953 * just stores a zero. If there's a collision on object OID, well, you
6954 * get duplicate comments.
6956 if (fout->remoteVersion < 70200)
6960 * Do binary search to find some item matching the object.
6963 high = &comments[ncomments - 1];
6966 middle = low + (high - low) / 2;
6968 if (classoid < middle->classoid)
6970 else if (classoid > middle->classoid)
6972 else if (objoid < middle->objoid)
6974 else if (objoid > middle->objoid)
6977 break; /* found a match */
6980 if (low > high) /* no matches */
6987 * Now determine how many items match the object. The search loop
6988 * invariant still holds: only items between low and high inclusive could
6992 while (middle > low)
6994 if (classoid != middle[-1].classoid ||
6995 objoid != middle[-1].objoid)
7004 while (middle <= high)
7006 if (classoid != middle->classoid ||
7007 objoid != middle->objoid)
7017 * collectComments --
7019 * Construct a table of all comments available for database objects.
7020 * We used to do per-object queries for the comments, but it's much faster
7021 * to pull them all over at once, and on most databases the memory cost
7024 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7027 collectComments(Archive *fout, CommentItem **items)
7037 CommentItem *comments;
7040 * Note we do NOT change source schema here; preserve the caller's
7044 query = createPQExpBuffer();
7046 if (fout->remoteVersion >= 70300)
7048 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7049 "FROM pg_catalog.pg_description "
7050 "ORDER BY classoid, objoid, objsubid");
7052 else if (fout->remoteVersion >= 70200)
7054 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7055 "FROM pg_description "
7056 "ORDER BY classoid, objoid, objsubid");
7060 /* Note: this will fail to find attribute comments in pre-7.2... */
7061 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7062 "FROM pg_description "
7066 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7068 /* Construct lookup table containing OIDs in numeric form */
7070 i_description = PQfnumber(res, "description");
7071 i_classoid = PQfnumber(res, "classoid");
7072 i_objoid = PQfnumber(res, "objoid");
7073 i_objsubid = PQfnumber(res, "objsubid");
7075 ntups = PQntuples(res);
7077 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7079 for (i = 0; i < ntups; i++)
7081 comments[i].descr = PQgetvalue(res, i, i_description);
7082 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7083 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7084 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7087 /* Do NOT free the PGresult since we are keeping pointers into it */
7088 destroyPQExpBuffer(query);
7095 * dumpDumpableObject
7097 * This routine and its subsidiaries are responsible for creating
7098 * ArchiveEntries (TOC objects) for each object to be dumped.
7101 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7106 switch (dobj->objType)
7111 case DO_FK_CONSTRAINT:
7113 skip = !(dumpSections & DUMP_POST_DATA);
7116 skip = !(dumpSections & DUMP_DATA);
7119 skip = !(dumpSections & DUMP_PRE_DATA);
7125 switch (dobj->objType)
7128 dumpNamespace(fout, (NamespaceInfo *) dobj);
7131 dumpExtension(fout, (ExtensionInfo *) dobj);
7134 dumpType(fout, (TypeInfo *) dobj);
7137 dumpShellType(fout, (ShellTypeInfo *) dobj);
7140 dumpFunc(fout, (FuncInfo *) dobj);
7143 dumpAgg(fout, (AggInfo *) dobj);
7146 dumpOpr(fout, (OprInfo *) dobj);
7149 dumpOpclass(fout, (OpclassInfo *) dobj);
7152 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7155 dumpCollation(fout, (CollInfo *) dobj);
7158 dumpConversion(fout, (ConvInfo *) dobj);
7161 dumpTable(fout, (TableInfo *) dobj);
7164 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7167 dumpIndex(fout, (IndxInfo *) dobj);
7170 dumpRule(fout, (RuleInfo *) dobj);
7173 dumpTrigger(fout, (TriggerInfo *) dobj);
7176 dumpConstraint(fout, (ConstraintInfo *) dobj);
7178 case DO_FK_CONSTRAINT:
7179 dumpConstraint(fout, (ConstraintInfo *) dobj);
7182 dumpProcLang(fout, (ProcLangInfo *) dobj);
7185 dumpCast(fout, (CastInfo *) dobj);
7188 dumpTableData(fout, (TableDataInfo *) dobj);
7191 /* table rowtypes and array types are never dumped separately */
7194 dumpTSParser(fout, (TSParserInfo *) dobj);
7197 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7200 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7203 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7206 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7208 case DO_FOREIGN_SERVER:
7209 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7211 case DO_DEFAULT_ACL:
7212 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7215 dumpBlob(fout, (BlobInfo *) dobj);
7218 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7219 dobj->name, NULL, NULL, "",
7220 false, "BLOBS", SECTION_DATA,
7222 dobj->dependencies, dobj->nDeps,
7230 * writes out to fout the queries to recreate a user-defined namespace
7233 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7240 /* Skip if not to be dumped */
7241 if (!nspinfo->dobj.dump || dataOnly)
7244 /* don't dump dummy namespace from pre-7.3 source */
7245 if (strlen(nspinfo->dobj.name) == 0)
7248 q = createPQExpBuffer();
7249 delq = createPQExpBuffer();
7250 labelq = createPQExpBuffer();
7252 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7254 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7256 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7258 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7261 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7263 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7267 false, "SCHEMA", SECTION_PRE_DATA,
7268 q->data, delq->data, NULL,
7269 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7272 /* Dump Schema Comments and Security Labels */
7273 dumpComment(fout, labelq->data,
7274 NULL, nspinfo->rolname,
7275 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7276 dumpSecLabel(fout, labelq->data,
7277 NULL, nspinfo->rolname,
7278 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7280 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7281 qnspname, NULL, nspinfo->dobj.name, NULL,
7282 nspinfo->rolname, nspinfo->nspacl);
7286 destroyPQExpBuffer(q);
7287 destroyPQExpBuffer(delq);
7288 destroyPQExpBuffer(labelq);
7293 * writes out to fout the queries to recreate an extension
7296 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7303 /* Skip if not to be dumped */
7304 if (!extinfo->dobj.dump || dataOnly)
7307 q = createPQExpBuffer();
7308 delq = createPQExpBuffer();
7309 labelq = createPQExpBuffer();
7311 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7313 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7315 if (!binary_upgrade)
7318 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7319 * problem if the extension already exists in the target database;
7320 * this is essential for installed-by-default extensions such as
7323 * In binary-upgrade mode, that doesn't work well, so instead we skip
7324 * built-in extensions based on their OIDs; see
7325 * selectDumpableExtension.
7327 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7328 qextname, fmtId(extinfo->namespace));
7335 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7336 appendPQExpBuffer(q,
7337 "SELECT binary_upgrade.create_empty_extension(");
7338 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7339 appendPQExpBuffer(q, ", ");
7340 appendStringLiteralAH(q, extinfo->namespace, fout);
7341 appendPQExpBuffer(q, ", ");
7342 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7343 appendStringLiteralAH(q, extinfo->extversion, fout);
7344 appendPQExpBuffer(q, ", ");
7347 * Note that we're pushing extconfig (an OID array) back into
7348 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7349 * preserved in binary upgrade.
7351 if (strlen(extinfo->extconfig) > 2)
7352 appendStringLiteralAH(q, extinfo->extconfig, fout);
7354 appendPQExpBuffer(q, "NULL");
7355 appendPQExpBuffer(q, ", ");
7356 if (strlen(extinfo->extcondition) > 2)
7357 appendStringLiteralAH(q, extinfo->extcondition, fout);
7359 appendPQExpBuffer(q, "NULL");
7360 appendPQExpBuffer(q, ", ");
7361 appendPQExpBuffer(q, "ARRAY[");
7363 for (i = 0; i < extinfo->dobj.nDeps; i++)
7365 DumpableObject *extobj;
7367 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7368 if (extobj && extobj->objType == DO_EXTENSION)
7371 appendPQExpBuffer(q, ",");
7372 appendStringLiteralAH(q, extobj->name, fout);
7375 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7376 appendPQExpBuffer(q, ");\n");
7379 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7381 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7385 false, "EXTENSION", SECTION_PRE_DATA,
7386 q->data, delq->data, NULL,
7387 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7390 /* Dump Extension Comments and Security Labels */
7391 dumpComment(fout, labelq->data,
7393 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7394 dumpSecLabel(fout, labelq->data,
7396 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7400 destroyPQExpBuffer(q);
7401 destroyPQExpBuffer(delq);
7402 destroyPQExpBuffer(labelq);
7407 * writes out to fout the queries to recreate a user-defined type
7410 dumpType(Archive *fout, TypeInfo *tyinfo)
7412 /* Skip if not to be dumped */
7413 if (!tyinfo->dobj.dump || dataOnly)
7416 /* Dump out in proper style */
7417 if (tyinfo->typtype == TYPTYPE_BASE)
7418 dumpBaseType(fout, tyinfo);
7419 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7420 dumpDomain(fout, tyinfo);
7421 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7422 dumpCompositeType(fout, tyinfo);
7423 else if (tyinfo->typtype == TYPTYPE_ENUM)
7424 dumpEnumType(fout, tyinfo);
7425 else if (tyinfo->typtype == TYPTYPE_RANGE)
7426 dumpRangeType(fout, tyinfo);
7428 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7434 * writes out to fout the queries to recreate a user-defined enum type
7437 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7439 PQExpBuffer q = createPQExpBuffer();
7440 PQExpBuffer delq = createPQExpBuffer();
7441 PQExpBuffer labelq = createPQExpBuffer();
7442 PQExpBuffer query = createPQExpBuffer();
7449 /* Set proper schema search path */
7450 selectSourceSchema(fout, "pg_catalog");
7452 if (fout->remoteVersion >= 90100)
7453 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7454 "FROM pg_catalog.pg_enum "
7455 "WHERE enumtypid = '%u'"
7456 "ORDER BY enumsortorder",
7457 tyinfo->dobj.catId.oid);
7459 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7460 "FROM pg_catalog.pg_enum "
7461 "WHERE enumtypid = '%u'"
7463 tyinfo->dobj.catId.oid);
7465 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7467 num = PQntuples(res);
7470 * DROP must be fully qualified in case same name appears in pg_catalog.
7471 * CASCADE shouldn't be required here as for normal types since the I/O
7472 * functions are generic and do not get dropped.
7474 appendPQExpBuffer(delq, "DROP TYPE %s.",
7475 fmtId(tyinfo->dobj.namespace->dobj.name));
7476 appendPQExpBuffer(delq, "%s;\n",
7477 fmtId(tyinfo->dobj.name));
7480 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7481 tyinfo->dobj.catId.oid);
7483 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7484 fmtId(tyinfo->dobj.name));
7486 if (!binary_upgrade)
7488 /* Labels with server-assigned oids */
7489 for (i = 0; i < num; i++)
7491 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7493 appendPQExpBuffer(q, ",");
7494 appendPQExpBuffer(q, "\n ");
7495 appendStringLiteralAH(q, label, fout);
7499 appendPQExpBuffer(q, "\n);\n");
7503 /* Labels with dump-assigned (preserved) oids */
7504 for (i = 0; i < num; i++)
7506 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7507 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7510 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7511 appendPQExpBuffer(q,
7512 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7514 appendPQExpBuffer(q, "ALTER TYPE %s.",
7515 fmtId(tyinfo->dobj.namespace->dobj.name));
7516 appendPQExpBuffer(q, "%s ADD VALUE ",
7517 fmtId(tyinfo->dobj.name));
7518 appendStringLiteralAH(q, label, fout);
7519 appendPQExpBuffer(q, ";\n\n");
7523 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7526 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7528 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7530 tyinfo->dobj.namespace->dobj.name,
7532 tyinfo->rolname, false,
7533 "TYPE", SECTION_PRE_DATA,
7534 q->data, delq->data, NULL,
7535 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7538 /* Dump Type Comments and Security Labels */
7539 dumpComment(fout, labelq->data,
7540 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7541 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7542 dumpSecLabel(fout, labelq->data,
7543 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7544 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7547 destroyPQExpBuffer(q);
7548 destroyPQExpBuffer(delq);
7549 destroyPQExpBuffer(labelq);
7550 destroyPQExpBuffer(query);
7555 * writes out to fout the queries to recreate a user-defined range type
7558 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7560 PQExpBuffer q = createPQExpBuffer();
7561 PQExpBuffer delq = createPQExpBuffer();
7562 PQExpBuffer labelq = createPQExpBuffer();
7563 PQExpBuffer query = createPQExpBuffer();
7569 * select appropriate schema to ensure names in CREATE are properly
7572 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7574 appendPQExpBuffer(query,
7575 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7576 "opc.opcname AS opcname, "
7577 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7578 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7580 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7581 " ELSE rngcollation END AS collation, "
7582 "rngcanonical, rngsubdiff "
7583 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7584 " pg_catalog.pg_opclass opc "
7585 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7587 tyinfo->dobj.catId.oid);
7589 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7592 * DROP must be fully qualified in case same name appears in pg_catalog.
7593 * CASCADE shouldn't be required here as for normal types since the I/O
7594 * functions are generic and do not get dropped.
7596 appendPQExpBuffer(delq, "DROP TYPE %s.",
7597 fmtId(tyinfo->dobj.namespace->dobj.name));
7598 appendPQExpBuffer(delq, "%s;\n",
7599 fmtId(tyinfo->dobj.name));
7602 binary_upgrade_set_type_oids_by_type_oid(fout,
7603 q, tyinfo->dobj.catId.oid);
7605 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7606 fmtId(tyinfo->dobj.name));
7608 appendPQExpBuffer(q, "\n subtype = %s",
7609 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7611 /* print subtype_opclass only if not default for subtype */
7612 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7614 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7615 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7617 /* always schema-qualify, don't try to be smart */
7618 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7620 appendPQExpBuffer(q, "%s", fmtId(opcname));
7623 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7624 if (OidIsValid(collationOid))
7626 CollInfo *coll = findCollationByOid(collationOid);
7630 /* always schema-qualify, don't try to be smart */
7631 appendPQExpBuffer(q, ",\n collation = %s.",
7632 fmtId(coll->dobj.namespace->dobj.name));
7633 appendPQExpBuffer(q, "%s",
7634 fmtId(coll->dobj.name));
7638 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7639 if (strcmp(procname, "-") != 0)
7640 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7642 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7643 if (strcmp(procname, "-") != 0)
7644 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7646 appendPQExpBuffer(q, "\n);\n");
7648 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7651 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7653 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7655 tyinfo->dobj.namespace->dobj.name,
7657 tyinfo->rolname, false,
7658 "TYPE", SECTION_PRE_DATA,
7659 q->data, delq->data, NULL,
7660 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7663 /* Dump Type Comments and Security Labels */
7664 dumpComment(fout, labelq->data,
7665 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7666 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7667 dumpSecLabel(fout, labelq->data,
7668 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7669 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7672 destroyPQExpBuffer(q);
7673 destroyPQExpBuffer(delq);
7674 destroyPQExpBuffer(labelq);
7675 destroyPQExpBuffer(query);
7680 * writes out to fout the queries to recreate a user-defined base type
7683 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7685 PQExpBuffer q = createPQExpBuffer();
7686 PQExpBuffer delq = createPQExpBuffer();
7687 PQExpBuffer labelq = createPQExpBuffer();
7688 PQExpBuffer query = createPQExpBuffer();
7704 char *typispreferred;
7709 char *typcollatable;
7711 bool typdefault_is_literal = false;
7713 /* Set proper schema search path so regproc references list correctly */
7714 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7716 /* Fetch type-specific details */
7717 if (fout->remoteVersion >= 90100)
7719 appendPQExpBuffer(query, "SELECT typlen, "
7720 "typinput, typoutput, typreceive, typsend, "
7721 "typmodin, typmodout, typanalyze, "
7722 "typreceive::pg_catalog.oid AS typreceiveoid, "
7723 "typsend::pg_catalog.oid AS typsendoid, "
7724 "typmodin::pg_catalog.oid AS typmodinoid, "
7725 "typmodout::pg_catalog.oid AS typmodoutoid, "
7726 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7727 "typcategory, typispreferred, "
7728 "typdelim, typbyval, typalign, typstorage, "
7729 "(typcollation <> 0) AS typcollatable, "
7730 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7731 "FROM pg_catalog.pg_type "
7732 "WHERE oid = '%u'::pg_catalog.oid",
7733 tyinfo->dobj.catId.oid);
7735 else if (fout->remoteVersion >= 80400)
7737 appendPQExpBuffer(query, "SELECT typlen, "
7738 "typinput, typoutput, typreceive, typsend, "
7739 "typmodin, typmodout, typanalyze, "
7740 "typreceive::pg_catalog.oid AS typreceiveoid, "
7741 "typsend::pg_catalog.oid AS typsendoid, "
7742 "typmodin::pg_catalog.oid AS typmodinoid, "
7743 "typmodout::pg_catalog.oid AS typmodoutoid, "
7744 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7745 "typcategory, typispreferred, "
7746 "typdelim, typbyval, typalign, typstorage, "
7747 "false AS typcollatable, "
7748 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7749 "FROM pg_catalog.pg_type "
7750 "WHERE oid = '%u'::pg_catalog.oid",
7751 tyinfo->dobj.catId.oid);
7753 else if (fout->remoteVersion >= 80300)
7755 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7756 appendPQExpBuffer(query, "SELECT typlen, "
7757 "typinput, typoutput, typreceive, typsend, "
7758 "typmodin, typmodout, typanalyze, "
7759 "typreceive::pg_catalog.oid AS typreceiveoid, "
7760 "typsend::pg_catalog.oid AS typsendoid, "
7761 "typmodin::pg_catalog.oid AS typmodinoid, "
7762 "typmodout::pg_catalog.oid AS typmodoutoid, "
7763 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7764 "'U' AS typcategory, false AS typispreferred, "
7765 "typdelim, typbyval, typalign, typstorage, "
7766 "false AS typcollatable, "
7767 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7768 "FROM pg_catalog.pg_type "
7769 "WHERE oid = '%u'::pg_catalog.oid",
7770 tyinfo->dobj.catId.oid);
7772 else if (fout->remoteVersion >= 80000)
7774 appendPQExpBuffer(query, "SELECT typlen, "
7775 "typinput, typoutput, typreceive, typsend, "
7776 "'-' AS typmodin, '-' AS typmodout, "
7778 "typreceive::pg_catalog.oid AS typreceiveoid, "
7779 "typsend::pg_catalog.oid AS typsendoid, "
7780 "0 AS typmodinoid, 0 AS typmodoutoid, "
7781 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7782 "'U' AS typcategory, false AS typispreferred, "
7783 "typdelim, typbyval, typalign, typstorage, "
7784 "false AS typcollatable, "
7785 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7786 "FROM pg_catalog.pg_type "
7787 "WHERE oid = '%u'::pg_catalog.oid",
7788 tyinfo->dobj.catId.oid);
7790 else if (fout->remoteVersion >= 70400)
7792 appendPQExpBuffer(query, "SELECT typlen, "
7793 "typinput, typoutput, typreceive, typsend, "
7794 "'-' AS typmodin, '-' AS typmodout, "
7795 "'-' AS typanalyze, "
7796 "typreceive::pg_catalog.oid AS typreceiveoid, "
7797 "typsend::pg_catalog.oid AS typsendoid, "
7798 "0 AS typmodinoid, 0 AS typmodoutoid, "
7799 "0 AS typanalyzeoid, "
7800 "'U' AS typcategory, false AS typispreferred, "
7801 "typdelim, typbyval, typalign, typstorage, "
7802 "false AS typcollatable, "
7803 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7804 "FROM pg_catalog.pg_type "
7805 "WHERE oid = '%u'::pg_catalog.oid",
7806 tyinfo->dobj.catId.oid);
7808 else if (fout->remoteVersion >= 70300)
7810 appendPQExpBuffer(query, "SELECT typlen, "
7811 "typinput, typoutput, "
7812 "'-' AS typreceive, '-' AS typsend, "
7813 "'-' AS typmodin, '-' AS typmodout, "
7814 "'-' AS typanalyze, "
7815 "0 AS typreceiveoid, 0 AS typsendoid, "
7816 "0 AS typmodinoid, 0 AS typmodoutoid, "
7817 "0 AS typanalyzeoid, "
7818 "'U' AS typcategory, false AS typispreferred, "
7819 "typdelim, typbyval, typalign, typstorage, "
7820 "false AS typcollatable, "
7821 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7822 "FROM pg_catalog.pg_type "
7823 "WHERE oid = '%u'::pg_catalog.oid",
7824 tyinfo->dobj.catId.oid);
7826 else if (fout->remoteVersion >= 70200)
7829 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7830 * ignore them because they are not right.
7832 appendPQExpBuffer(query, "SELECT typlen, "
7833 "typinput, typoutput, "
7834 "'-' AS typreceive, '-' AS typsend, "
7835 "'-' AS typmodin, '-' AS typmodout, "
7836 "'-' AS typanalyze, "
7837 "0 AS typreceiveoid, 0 AS typsendoid, "
7838 "0 AS typmodinoid, 0 AS typmodoutoid, "
7839 "0 AS typanalyzeoid, "
7840 "'U' AS typcategory, false AS typispreferred, "
7841 "typdelim, typbyval, typalign, typstorage, "
7842 "false AS typcollatable, "
7843 "NULL AS typdefaultbin, typdefault "
7845 "WHERE oid = '%u'::oid",
7846 tyinfo->dobj.catId.oid);
7848 else if (fout->remoteVersion >= 70100)
7851 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7854 appendPQExpBuffer(query, "SELECT typlen, "
7855 "typinput, typoutput, "
7856 "'-' AS typreceive, '-' AS typsend, "
7857 "'-' AS typmodin, '-' AS typmodout, "
7858 "'-' AS typanalyze, "
7859 "0 AS typreceiveoid, 0 AS typsendoid, "
7860 "0 AS typmodinoid, 0 AS typmodoutoid, "
7861 "0 AS typanalyzeoid, "
7862 "'U' AS typcategory, false AS typispreferred, "
7863 "typdelim, typbyval, typalign, typstorage, "
7864 "false AS typcollatable, "
7865 "NULL AS typdefaultbin, NULL AS typdefault "
7867 "WHERE oid = '%u'::oid",
7868 tyinfo->dobj.catId.oid);
7872 appendPQExpBuffer(query, "SELECT typlen, "
7873 "typinput, typoutput, "
7874 "'-' AS typreceive, '-' AS typsend, "
7875 "'-' AS typmodin, '-' AS typmodout, "
7876 "'-' AS typanalyze, "
7877 "0 AS typreceiveoid, 0 AS typsendoid, "
7878 "0 AS typmodinoid, 0 AS typmodoutoid, "
7879 "0 AS typanalyzeoid, "
7880 "'U' AS typcategory, false AS typispreferred, "
7881 "typdelim, typbyval, typalign, "
7882 "'p'::char AS typstorage, "
7883 "false AS typcollatable, "
7884 "NULL AS typdefaultbin, NULL AS typdefault "
7886 "WHERE oid = '%u'::oid",
7887 tyinfo->dobj.catId.oid);
7890 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7892 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7893 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7894 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7895 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7896 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7897 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7898 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7899 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7900 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7901 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7902 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7903 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7904 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7905 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7906 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7907 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7908 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7909 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7910 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7911 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7912 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7913 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7914 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7916 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7917 typdefault_is_literal = true; /* it needs quotes */
7923 * DROP must be fully qualified in case same name appears in pg_catalog.
7924 * The reason we include CASCADE is that the circular dependency between
7925 * the type and its I/O functions makes it impossible to drop the type any
7928 appendPQExpBuffer(delq, "DROP TYPE %s.",
7929 fmtId(tyinfo->dobj.namespace->dobj.name));
7930 appendPQExpBuffer(delq, "%s CASCADE;\n",
7931 fmtId(tyinfo->dobj.name));
7933 /* We might already have a shell type, but setting pg_type_oid is harmless */
7935 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7936 tyinfo->dobj.catId.oid);
7938 appendPQExpBuffer(q,
7939 "CREATE TYPE %s (\n"
7940 " INTERNALLENGTH = %s",
7941 fmtId(tyinfo->dobj.name),
7942 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7944 if (fout->remoteVersion >= 70300)
7946 /* regproc result is correctly quoted as of 7.3 */
7947 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7948 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7949 if (OidIsValid(typreceiveoid))
7950 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7951 if (OidIsValid(typsendoid))
7952 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7953 if (OidIsValid(typmodinoid))
7954 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7955 if (OidIsValid(typmodoutoid))
7956 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7957 if (OidIsValid(typanalyzeoid))
7958 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7962 /* regproc delivers an unquoted name before 7.3 */
7963 /* cannot combine these because fmtId uses static result area */
7964 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7965 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7966 /* receive/send/typmodin/typmodout/analyze need not be printed */
7969 if (strcmp(typcollatable, "t") == 0)
7970 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7972 if (typdefault != NULL)
7974 appendPQExpBuffer(q, ",\n DEFAULT = ");
7975 if (typdefault_is_literal)
7976 appendStringLiteralAH(q, typdefault, fout);
7978 appendPQExpBufferStr(q, typdefault);
7981 if (OidIsValid(tyinfo->typelem))
7985 /* reselect schema in case changed by function dump */
7986 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7987 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7988 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
7992 if (strcmp(typcategory, "U") != 0)
7994 appendPQExpBuffer(q, ",\n CATEGORY = ");
7995 appendStringLiteralAH(q, typcategory, fout);
7998 if (strcmp(typispreferred, "t") == 0)
7999 appendPQExpBuffer(q, ",\n PREFERRED = true");
8001 if (typdelim && strcmp(typdelim, ",") != 0)
8003 appendPQExpBuffer(q, ",\n DELIMITER = ");
8004 appendStringLiteralAH(q, typdelim, fout);
8007 if (strcmp(typalign, "c") == 0)
8008 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8009 else if (strcmp(typalign, "s") == 0)
8010 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8011 else if (strcmp(typalign, "i") == 0)
8012 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8013 else if (strcmp(typalign, "d") == 0)
8014 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8016 if (strcmp(typstorage, "p") == 0)
8017 appendPQExpBuffer(q, ",\n STORAGE = plain");
8018 else if (strcmp(typstorage, "e") == 0)
8019 appendPQExpBuffer(q, ",\n STORAGE = external");
8020 else if (strcmp(typstorage, "x") == 0)
8021 appendPQExpBuffer(q, ",\n STORAGE = extended");
8022 else if (strcmp(typstorage, "m") == 0)
8023 appendPQExpBuffer(q, ",\n STORAGE = main");
8025 if (strcmp(typbyval, "t") == 0)
8026 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8028 appendPQExpBuffer(q, "\n);\n");
8030 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8033 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8035 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8037 tyinfo->dobj.namespace->dobj.name,
8039 tyinfo->rolname, false,
8040 "TYPE", SECTION_PRE_DATA,
8041 q->data, delq->data, NULL,
8042 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8045 /* Dump Type Comments and Security Labels */
8046 dumpComment(fout, labelq->data,
8047 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8048 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8049 dumpSecLabel(fout, labelq->data,
8050 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8051 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8054 destroyPQExpBuffer(q);
8055 destroyPQExpBuffer(delq);
8056 destroyPQExpBuffer(labelq);
8057 destroyPQExpBuffer(query);
8062 * writes out to fout the queries to recreate a user-defined domain
8065 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8067 PQExpBuffer q = createPQExpBuffer();
8068 PQExpBuffer delq = createPQExpBuffer();
8069 PQExpBuffer labelq = createPQExpBuffer();
8070 PQExpBuffer query = createPQExpBuffer();
8077 bool typdefault_is_literal = false;
8079 /* Set proper schema search path so type references list correctly */
8080 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8082 /* Fetch domain specific details */
8083 if (fout->remoteVersion >= 90100)
8085 /* typcollation is new in 9.1 */
8086 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8087 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8088 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8090 "CASE WHEN t.typcollation <> u.typcollation "
8091 "THEN t.typcollation ELSE 0 END AS typcollation "
8092 "FROM pg_catalog.pg_type t "
8093 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8094 "WHERE t.oid = '%u'::pg_catalog.oid",
8095 tyinfo->dobj.catId.oid);
8099 /* We assume here that remoteVersion must be at least 70300 */
8100 appendPQExpBuffer(query, "SELECT typnotnull, "
8101 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8102 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8103 "typdefault, 0 AS typcollation "
8104 "FROM pg_catalog.pg_type "
8105 "WHERE oid = '%u'::pg_catalog.oid",
8106 tyinfo->dobj.catId.oid);
8109 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8111 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8112 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8113 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8114 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8115 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8117 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8118 typdefault_is_literal = true; /* it needs quotes */
8122 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8125 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8126 tyinfo->dobj.catId.oid);
8128 appendPQExpBuffer(q,
8129 "CREATE DOMAIN %s AS %s",
8130 fmtId(tyinfo->dobj.name),
8133 /* Print collation only if different from base type's collation */
8134 if (OidIsValid(typcollation))
8138 coll = findCollationByOid(typcollation);
8141 /* always schema-qualify, don't try to be smart */
8142 appendPQExpBuffer(q, " COLLATE %s.",
8143 fmtId(coll->dobj.namespace->dobj.name));
8144 appendPQExpBuffer(q, "%s",
8145 fmtId(coll->dobj.name));
8149 if (typnotnull[0] == 't')
8150 appendPQExpBuffer(q, " NOT NULL");
8152 if (typdefault != NULL)
8154 appendPQExpBuffer(q, " DEFAULT ");
8155 if (typdefault_is_literal)
8156 appendStringLiteralAH(q, typdefault, fout);
8158 appendPQExpBufferStr(q, typdefault);
8164 * Add any CHECK constraints for the domain
8166 for (i = 0; i < tyinfo->nDomChecks; i++)
8168 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8170 if (!domcheck->separate)
8171 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8172 fmtId(domcheck->dobj.name), domcheck->condef);
8175 appendPQExpBuffer(q, ";\n");
8178 * DROP must be fully qualified in case same name appears in pg_catalog
8180 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8181 fmtId(tyinfo->dobj.namespace->dobj.name));
8182 appendPQExpBuffer(delq, "%s;\n",
8183 fmtId(tyinfo->dobj.name));
8185 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8188 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8190 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8192 tyinfo->dobj.namespace->dobj.name,
8194 tyinfo->rolname, false,
8195 "DOMAIN", SECTION_PRE_DATA,
8196 q->data, delq->data, NULL,
8197 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8200 /* Dump Domain Comments and Security Labels */
8201 dumpComment(fout, labelq->data,
8202 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8203 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8204 dumpSecLabel(fout, labelq->data,
8205 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8206 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8208 destroyPQExpBuffer(q);
8209 destroyPQExpBuffer(delq);
8210 destroyPQExpBuffer(labelq);
8211 destroyPQExpBuffer(query);
8216 * writes out to fout the queries to recreate a user-defined stand-alone
8220 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8222 PQExpBuffer q = createPQExpBuffer();
8223 PQExpBuffer dropped = createPQExpBuffer();
8224 PQExpBuffer delq = createPQExpBuffer();
8225 PQExpBuffer labelq = createPQExpBuffer();
8226 PQExpBuffer query = createPQExpBuffer();
8239 /* Set proper schema search path so type references list correctly */
8240 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8242 /* Fetch type specific details */
8243 if (fout->remoteVersion >= 90100)
8246 * attcollation is new in 9.1. Since we only want to dump COLLATE
8247 * clauses for attributes whose collation is different from their
8248 * type's default, we use a CASE here to suppress uninteresting
8249 * attcollations cheaply. atttypid will be 0 for dropped columns;
8250 * collation does not matter for those.
8252 appendPQExpBuffer(query, "SELECT a.attname, "
8253 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8254 "a.attlen, a.attalign, a.attisdropped, "
8255 "CASE WHEN a.attcollation <> at.typcollation "
8256 "THEN a.attcollation ELSE 0 END AS attcollation, "
8258 "FROM pg_catalog.pg_type ct "
8259 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8260 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8261 "WHERE ct.oid = '%u'::pg_catalog.oid "
8262 "ORDER BY a.attnum ",
8263 tyinfo->dobj.catId.oid);
8268 * We assume here that remoteVersion must be at least 70300. Since
8269 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8272 appendPQExpBuffer(query, "SELECT a.attname, "
8273 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8274 "a.attlen, a.attalign, a.attisdropped, "
8275 "0 AS attcollation, "
8277 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8278 "WHERE ct.oid = '%u'::pg_catalog.oid "
8279 "AND a.attrelid = ct.typrelid "
8280 "ORDER BY a.attnum ",
8281 tyinfo->dobj.catId.oid);
8284 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8286 ntups = PQntuples(res);
8288 i_attname = PQfnumber(res, "attname");
8289 i_atttypdefn = PQfnumber(res, "atttypdefn");
8290 i_attlen = PQfnumber(res, "attlen");
8291 i_attalign = PQfnumber(res, "attalign");
8292 i_attisdropped = PQfnumber(res, "attisdropped");
8293 i_attcollation = PQfnumber(res, "attcollation");
8294 i_typrelid = PQfnumber(res, "typrelid");
8298 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8300 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8301 tyinfo->dobj.catId.oid);
8302 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8305 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8306 fmtId(tyinfo->dobj.name));
8309 for (i = 0; i < ntups; i++)
8318 attname = PQgetvalue(res, i, i_attname);
8319 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8320 attlen = PQgetvalue(res, i, i_attlen);
8321 attalign = PQgetvalue(res, i, i_attalign);
8322 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8323 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8325 if (attisdropped && !binary_upgrade)
8328 /* Format properly if not first attr */
8329 if (actual_atts++ > 0)
8330 appendPQExpBuffer(q, ",");
8331 appendPQExpBuffer(q, "\n\t");
8335 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8337 /* Add collation if not default for the column type */
8338 if (OidIsValid(attcollation))
8342 coll = findCollationByOid(attcollation);
8345 /* always schema-qualify, don't try to be smart */
8346 appendPQExpBuffer(q, " COLLATE %s.",
8347 fmtId(coll->dobj.namespace->dobj.name));
8348 appendPQExpBuffer(q, "%s",
8349 fmtId(coll->dobj.name));
8356 * This is a dropped attribute and we're in binary_upgrade mode.
8357 * Insert a placeholder for it in the CREATE TYPE command, and set
8358 * length and alignment with direct UPDATE to the catalogs
8359 * afterwards. See similar code in dumpTableSchema().
8361 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8363 /* stash separately for insertion after the CREATE TYPE */
8364 appendPQExpBuffer(dropped,
8365 "\n-- For binary upgrade, recreate dropped column.\n");
8366 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8368 "attalign = '%s', attbyval = false\n"
8369 "WHERE attname = ", attlen, attalign);
8370 appendStringLiteralAH(dropped, attname, fout);
8371 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8372 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8373 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8375 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8376 fmtId(tyinfo->dobj.name));
8377 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8381 appendPQExpBuffer(q, "\n);\n");
8382 appendPQExpBufferStr(q, dropped->data);
8385 * DROP must be fully qualified in case same name appears in pg_catalog
8387 appendPQExpBuffer(delq, "DROP TYPE %s.",
8388 fmtId(tyinfo->dobj.namespace->dobj.name));
8389 appendPQExpBuffer(delq, "%s;\n",
8390 fmtId(tyinfo->dobj.name));
8392 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8395 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8397 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8399 tyinfo->dobj.namespace->dobj.name,
8401 tyinfo->rolname, false,
8402 "TYPE", SECTION_PRE_DATA,
8403 q->data, delq->data, NULL,
8404 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8408 /* Dump Type Comments and Security Labels */
8409 dumpComment(fout, labelq->data,
8410 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8411 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8412 dumpSecLabel(fout, labelq->data,
8413 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8414 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8417 destroyPQExpBuffer(q);
8418 destroyPQExpBuffer(dropped);
8419 destroyPQExpBuffer(delq);
8420 destroyPQExpBuffer(labelq);
8421 destroyPQExpBuffer(query);
8423 /* Dump any per-column comments */
8424 dumpCompositeTypeColComments(fout, tyinfo);
8428 * dumpCompositeTypeColComments
8429 * writes out to fout the queries to recreate comments on the columns of
8430 * a user-defined stand-alone composite type
8433 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8435 CommentItem *comments;
8446 query = createPQExpBuffer();
8448 /* We assume here that remoteVersion must be at least 70300 */
8449 appendPQExpBuffer(query,
8450 "SELECT c.tableoid, a.attname, a.attnum "
8451 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8452 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8453 " AND NOT a.attisdropped "
8454 "ORDER BY a.attnum ",
8457 /* Fetch column attnames */
8458 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8460 ntups = PQntuples(res);
8464 destroyPQExpBuffer(query);
8468 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8470 /* Search for comments associated with type's pg_class OID */
8471 ncomments = findComments(fout,
8476 /* If no comments exist, we're done */
8480 destroyPQExpBuffer(query);
8484 /* Build COMMENT ON statements */
8485 target = createPQExpBuffer();
8487 i_attnum = PQfnumber(res, "attnum");
8488 i_attname = PQfnumber(res, "attname");
8489 while (ncomments > 0)
8491 const char *attname;
8494 for (i = 0; i < ntups; i++)
8496 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8498 attname = PQgetvalue(res, i, i_attname);
8502 if (attname) /* just in case we don't find it */
8504 const char *descr = comments->descr;
8506 resetPQExpBuffer(target);
8507 appendPQExpBuffer(target, "COLUMN %s.",
8508 fmtId(tyinfo->dobj.name));
8509 appendPQExpBuffer(target, "%s",
8512 resetPQExpBuffer(query);
8513 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8514 appendStringLiteralAH(query, descr, fout);
8515 appendPQExpBuffer(query, ";\n");
8517 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8519 tyinfo->dobj.namespace->dobj.name,
8520 NULL, tyinfo->rolname,
8521 false, "COMMENT", SECTION_NONE,
8522 query->data, "", NULL,
8523 &(tyinfo->dobj.dumpId), 1,
8532 destroyPQExpBuffer(query);
8533 destroyPQExpBuffer(target);
8538 * writes out to fout the queries to create a shell type
8540 * We dump a shell definition in advance of the I/O functions for the type.
8543 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8547 /* Skip if not to be dumped */
8548 if (!stinfo->dobj.dump || dataOnly)
8551 q = createPQExpBuffer();
8554 * Note the lack of a DROP command for the shell type; any required DROP
8555 * is driven off the base type entry, instead. This interacts with
8556 * _printTocEntry()'s use of the presence of a DROP command to decide
8557 * whether an entry needs an ALTER OWNER command. We don't want to alter
8558 * the shell type's owner immediately on creation; that should happen only
8559 * after it's filled in, otherwise the backend complains.
8563 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8564 stinfo->baseType->dobj.catId.oid);
8566 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8567 fmtId(stinfo->dobj.name));
8569 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8571 stinfo->dobj.namespace->dobj.name,
8573 stinfo->baseType->rolname, false,
8574 "SHELL TYPE", SECTION_PRE_DATA,
8576 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8579 destroyPQExpBuffer(q);
8583 * Determine whether we want to dump definitions for procedural languages.
8584 * Since the languages themselves don't have schemas, we can't rely on
8585 * the normal schema-based selection mechanism. We choose to dump them
8586 * whenever neither --schema nor --table was given. (Before 8.1, we used
8587 * the dump flag of the PL's call handler function, but in 8.1 this will
8588 * probably always be false since call handlers are created in pg_catalog.)
8590 * For some backwards compatibility with the older behavior, we forcibly
8591 * dump a PL if its handler function (and validator if any) are in a
8592 * dumpable namespace. That case is not checked here.
8594 * Also, if the PL belongs to an extension, we do not use this heuristic.
8595 * That case isn't checked here either.
8598 shouldDumpProcLangs(void)
8600 if (!include_everything)
8602 /* And they're schema not data */
8610 * writes out to fout the queries to recreate a user-defined
8611 * procedural language
8614 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8623 FuncInfo *inlineInfo = NULL;
8624 FuncInfo *validatorInfo = NULL;
8626 /* Skip if not to be dumped */
8627 if (!plang->dobj.dump || dataOnly)
8631 * Try to find the support function(s). It is not an error if we don't
8632 * find them --- if the functions are in the pg_catalog schema, as is
8633 * standard in 8.1 and up, then we won't have loaded them. (In this case
8634 * we will emit a parameterless CREATE LANGUAGE command, which will
8635 * require PL template knowledge in the backend to reload.)
8638 funcInfo = findFuncByOid(plang->lanplcallfoid);
8639 if (funcInfo != NULL && !funcInfo->dobj.dump)
8640 funcInfo = NULL; /* treat not-dumped same as not-found */
8642 if (OidIsValid(plang->laninline))
8644 inlineInfo = findFuncByOid(plang->laninline);
8645 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8649 if (OidIsValid(plang->lanvalidator))
8651 validatorInfo = findFuncByOid(plang->lanvalidator);
8652 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8653 validatorInfo = NULL;
8657 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8658 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8661 * However, for a language that belongs to an extension, we must not use
8662 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8663 * told to (via dobj.dump). Generally the support functions will belong
8664 * to the same extension and so have the same dump flags ... if they
8665 * don't, this might not work terribly nicely.
8667 useParams = (funcInfo != NULL &&
8668 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8669 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8671 if (!plang->dobj.ext_member)
8673 if (!useParams && !shouldDumpProcLangs())
8677 defqry = createPQExpBuffer();
8678 delqry = createPQExpBuffer();
8679 labelq = createPQExpBuffer();
8681 qlanname = pg_strdup(fmtId(plang->dobj.name));
8684 * If dumping a HANDLER clause, treat the language as being in the handler
8685 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8686 * it doesn't really have a schema.
8689 lanschema = funcInfo->dobj.namespace->dobj.name;
8693 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8698 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8699 plang->lanpltrusted ? "TRUSTED " : "",
8701 appendPQExpBuffer(defqry, " HANDLER %s",
8702 fmtId(funcInfo->dobj.name));
8703 if (OidIsValid(plang->laninline))
8705 appendPQExpBuffer(defqry, " INLINE ");
8706 /* Cope with possibility that inline is in different schema */
8707 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8708 appendPQExpBuffer(defqry, "%s.",
8709 fmtId(inlineInfo->dobj.namespace->dobj.name));
8710 appendPQExpBuffer(defqry, "%s",
8711 fmtId(inlineInfo->dobj.name));
8713 if (OidIsValid(plang->lanvalidator))
8715 appendPQExpBuffer(defqry, " VALIDATOR ");
8716 /* Cope with possibility that validator is in different schema */
8717 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8718 appendPQExpBuffer(defqry, "%s.",
8719 fmtId(validatorInfo->dobj.namespace->dobj.name));
8720 appendPQExpBuffer(defqry, "%s",
8721 fmtId(validatorInfo->dobj.name));
8727 * If not dumping parameters, then use CREATE OR REPLACE so that the
8728 * command will not fail if the language is preinstalled in the target
8729 * database. We restrict the use of REPLACE to this case so as to
8730 * eliminate the risk of replacing a language with incompatible
8731 * parameter settings: this command will only succeed at all if there
8732 * is a pg_pltemplate entry, and if there is one, the existing entry
8733 * must match it too.
8735 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8738 appendPQExpBuffer(defqry, ";\n");
8740 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8743 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8745 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8747 lanschema, NULL, plang->lanowner,
8748 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8749 defqry->data, delqry->data, NULL,
8750 plang->dobj.dependencies, plang->dobj.nDeps,
8753 /* Dump Proc Lang Comments and Security Labels */
8754 dumpComment(fout, labelq->data,
8756 plang->dobj.catId, 0, plang->dobj.dumpId);
8757 dumpSecLabel(fout, labelq->data,
8759 plang->dobj.catId, 0, plang->dobj.dumpId);
8761 if (plang->lanpltrusted)
8762 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8763 qlanname, NULL, plang->dobj.name,
8765 plang->lanowner, plang->lanacl);
8769 destroyPQExpBuffer(defqry);
8770 destroyPQExpBuffer(delqry);
8771 destroyPQExpBuffer(labelq);
8775 * format_function_arguments: generate function name and argument list
8777 * This is used when we can rely on pg_get_function_arguments to format
8778 * the argument list.
8781 format_function_arguments(FuncInfo *finfo, char *funcargs)
8785 initPQExpBuffer(&fn);
8786 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8791 * format_function_arguments_old: generate function name and argument list
8793 * The argument type names are qualified if needed. The function name
8794 * is never qualified.
8796 * This is used only with pre-8.4 servers, so we aren't expecting to see
8797 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8799 * Any or all of allargtypes, argmodes, argnames may be NULL.
8802 format_function_arguments_old(Archive *fout,
8803 FuncInfo *finfo, int nallargs,
8811 initPQExpBuffer(&fn);
8812 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8813 for (j = 0; j < nallargs; j++)
8817 const char *argmode;
8818 const char *argname;
8820 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8821 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8825 switch (argmodes[j][0])
8830 case PROARGMODE_OUT:
8833 case PROARGMODE_INOUT:
8837 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8845 argname = argnames ? argnames[j] : (char *) NULL;
8846 if (argname && argname[0] == '\0')
8849 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8850 (j > 0) ? ", " : "",
8852 argname ? fmtId(argname) : "",
8857 appendPQExpBuffer(&fn, ")");
8862 * format_function_signature: generate function name and argument list
8864 * This is like format_function_arguments_old except that only a minimal
8865 * list of input argument types is generated; this is sufficient to
8866 * reference the function, but not to define it.
8868 * If honor_quotes is false then the function name is never quoted.
8869 * This is appropriate for use in TOC tags, but not in SQL commands.
8872 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8877 initPQExpBuffer(&fn);
8879 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8881 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8882 for (j = 0; j < finfo->nargs; j++)
8886 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8889 appendPQExpBuffer(&fn, "%s%s",
8890 (j > 0) ? ", " : "",
8894 appendPQExpBuffer(&fn, ")");
8901 * dump out one function
8904 dumpFunc(Archive *fout, FuncInfo *finfo)
8912 char *funcsig; /* identity signature */
8913 char *funcfullsig; /* full signature */
8921 char *proallargtypes;
8935 char **allargtypes = NULL;
8936 char **argmodes = NULL;
8937 char **argnames = NULL;
8938 char **configitems = NULL;
8939 int nconfigitems = 0;
8942 /* Skip if not to be dumped */
8943 if (!finfo->dobj.dump || dataOnly)
8946 query = createPQExpBuffer();
8947 q = createPQExpBuffer();
8948 delqry = createPQExpBuffer();
8949 labelq = createPQExpBuffer();
8950 asPart = createPQExpBuffer();
8952 /* Set proper schema search path so type references list correctly */
8953 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8955 /* Fetch function-specific details */
8956 if (fout->remoteVersion >= 90200)
8959 * proleakproof was added at v9.2
8961 appendPQExpBuffer(query,
8962 "SELECT proretset, prosrc, probin, "
8963 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8964 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8965 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8966 "proiswindow, provolatile, proisstrict, prosecdef, "
8967 "proleakproof, proconfig, procost, prorows, "
8968 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8969 "FROM pg_catalog.pg_proc "
8970 "WHERE oid = '%u'::pg_catalog.oid",
8971 finfo->dobj.catId.oid);
8973 else if (fout->remoteVersion >= 80400)
8976 * In 8.4 and up we rely on pg_get_function_arguments and
8977 * pg_get_function_result instead of examining proallargtypes etc.
8979 appendPQExpBuffer(query,
8980 "SELECT proretset, prosrc, probin, "
8981 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8982 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8983 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8984 "proiswindow, provolatile, proisstrict, prosecdef, "
8985 "false AS proleakproof, "
8986 " proconfig, procost, prorows, "
8987 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8988 "FROM pg_catalog.pg_proc "
8989 "WHERE oid = '%u'::pg_catalog.oid",
8990 finfo->dobj.catId.oid);
8992 else if (fout->remoteVersion >= 80300)
8994 appendPQExpBuffer(query,
8995 "SELECT proretset, prosrc, probin, "
8996 "proallargtypes, proargmodes, proargnames, "
8997 "false AS proiswindow, "
8998 "provolatile, proisstrict, prosecdef, "
8999 "false AS proleakproof, "
9000 "proconfig, procost, prorows, "
9001 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9002 "FROM pg_catalog.pg_proc "
9003 "WHERE oid = '%u'::pg_catalog.oid",
9004 finfo->dobj.catId.oid);
9006 else if (fout->remoteVersion >= 80100)
9008 appendPQExpBuffer(query,
9009 "SELECT proretset, prosrc, probin, "
9010 "proallargtypes, proargmodes, proargnames, "
9011 "false AS proiswindow, "
9012 "provolatile, proisstrict, prosecdef, "
9013 "false AS proleakproof, "
9014 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9015 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9016 "FROM pg_catalog.pg_proc "
9017 "WHERE oid = '%u'::pg_catalog.oid",
9018 finfo->dobj.catId.oid);
9020 else if (fout->remoteVersion >= 80000)
9022 appendPQExpBuffer(query,
9023 "SELECT proretset, prosrc, probin, "
9024 "null AS proallargtypes, "
9025 "null AS proargmodes, "
9027 "false AS proiswindow, "
9028 "provolatile, proisstrict, prosecdef, "
9029 "false AS proleakproof, "
9030 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9031 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9032 "FROM pg_catalog.pg_proc "
9033 "WHERE oid = '%u'::pg_catalog.oid",
9034 finfo->dobj.catId.oid);
9036 else if (fout->remoteVersion >= 70300)
9038 appendPQExpBuffer(query,
9039 "SELECT proretset, prosrc, probin, "
9040 "null AS proallargtypes, "
9041 "null AS proargmodes, "
9042 "null AS proargnames, "
9043 "false AS proiswindow, "
9044 "provolatile, proisstrict, prosecdef, "
9045 "false AS proleakproof, "
9046 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9047 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9048 "FROM pg_catalog.pg_proc "
9049 "WHERE oid = '%u'::pg_catalog.oid",
9050 finfo->dobj.catId.oid);
9052 else if (fout->remoteVersion >= 70100)
9054 appendPQExpBuffer(query,
9055 "SELECT proretset, prosrc, probin, "
9056 "null AS proallargtypes, "
9057 "null AS proargmodes, "
9058 "null AS proargnames, "
9059 "false AS proiswindow, "
9060 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9062 "false AS prosecdef, "
9063 "false AS proleakproof, "
9064 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9065 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9067 "WHERE oid = '%u'::oid",
9068 finfo->dobj.catId.oid);
9072 appendPQExpBuffer(query,
9073 "SELECT proretset, prosrc, probin, "
9074 "null AS proallargtypes, "
9075 "null AS proargmodes, "
9076 "null AS proargnames, "
9077 "false AS proiswindow, "
9078 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9079 "false AS proisstrict, "
9080 "false AS prosecdef, "
9081 "false AS proleakproof, "
9082 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9083 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9085 "WHERE oid = '%u'::oid",
9086 finfo->dobj.catId.oid);
9089 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9091 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9092 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9093 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9094 if (fout->remoteVersion >= 80400)
9096 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9097 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9098 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9099 proallargtypes = proargmodes = proargnames = NULL;
9103 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9104 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9105 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9106 funcargs = funciargs = funcresult = NULL;
9108 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9109 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9110 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9111 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9112 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9113 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9114 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9115 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9116 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9119 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9120 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9121 * versions would set it to "-". There are no known cases in which prosrc
9122 * is unused, so the tests below for "-" are probably useless.
9124 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9126 appendPQExpBuffer(asPart, "AS ");
9127 appendStringLiteralAH(asPart, probin, fout);
9128 if (strcmp(prosrc, "-") != 0)
9130 appendPQExpBuffer(asPart, ", ");
9133 * where we have bin, use dollar quoting if allowed and src
9134 * contains quote or backslash; else use regular quoting.
9136 if (disable_dollar_quoting ||
9137 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9138 appendStringLiteralAH(asPart, prosrc, fout);
9140 appendStringLiteralDQ(asPart, prosrc, NULL);
9145 if (strcmp(prosrc, "-") != 0)
9147 appendPQExpBuffer(asPart, "AS ");
9148 /* with no bin, dollar quote src unconditionally if allowed */
9149 if (disable_dollar_quoting)
9150 appendStringLiteralAH(asPart, prosrc, fout);
9152 appendStringLiteralDQ(asPart, prosrc, NULL);
9156 nallargs = finfo->nargs; /* unless we learn different from allargs */
9158 if (proallargtypes && *proallargtypes)
9162 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9163 nitems < finfo->nargs)
9165 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9174 if (proargmodes && *proargmodes)
9178 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9181 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9188 if (proargnames && *proargnames)
9192 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9195 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9202 if (proconfig && *proconfig)
9204 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9206 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9216 /* 8.4 or later; we rely on server-side code for most of the work */
9217 funcfullsig = format_function_arguments(finfo, funcargs);
9218 funcsig = format_function_arguments(finfo, funciargs);
9222 /* pre-8.4, do it ourselves */
9223 funcsig = format_function_arguments_old(fout,
9224 finfo, nallargs, allargtypes,
9225 argmodes, argnames);
9226 funcfullsig = funcsig;
9229 funcsig_tag = format_function_signature(fout, finfo, false);
9232 * DROP must be fully qualified in case same name appears in pg_catalog
9234 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9235 fmtId(finfo->dobj.namespace->dobj.name),
9238 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9240 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9243 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9245 appendPQExpBuffer(q, "RETURNS %s%s",
9246 (proretset[0] == 't') ? "SETOF " : "",
9251 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9253 if (proiswindow[0] == 't')
9254 appendPQExpBuffer(q, " WINDOW");
9256 if (provolatile[0] != PROVOLATILE_VOLATILE)
9258 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9259 appendPQExpBuffer(q, " IMMUTABLE");
9260 else if (provolatile[0] == PROVOLATILE_STABLE)
9261 appendPQExpBuffer(q, " STABLE");
9262 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9263 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9267 if (proisstrict[0] == 't')
9268 appendPQExpBuffer(q, " STRICT");
9270 if (prosecdef[0] == 't')
9271 appendPQExpBuffer(q, " SECURITY DEFINER");
9273 if (proleakproof[0] == 't')
9274 appendPQExpBuffer(q, " LEAKPROOF");
9277 * COST and ROWS are emitted only if present and not default, so as not to
9278 * break backwards-compatibility of the dump without need. Keep this code
9279 * in sync with the defaults in functioncmds.c.
9281 if (strcmp(procost, "0") != 0)
9283 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9285 /* default cost is 1 */
9286 if (strcmp(procost, "1") != 0)
9287 appendPQExpBuffer(q, " COST %s", procost);
9291 /* default cost is 100 */
9292 if (strcmp(procost, "100") != 0)
9293 appendPQExpBuffer(q, " COST %s", procost);
9296 if (proretset[0] == 't' &&
9297 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9298 appendPQExpBuffer(q, " ROWS %s", prorows);
9300 for (i = 0; i < nconfigitems; i++)
9302 /* we feel free to scribble on configitems[] here */
9303 char *configitem = configitems[i];
9306 pos = strchr(configitem, '=');
9310 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9313 * Some GUC variable names are 'LIST' type and hence must not be
9316 if (pg_strcasecmp(configitem, "DateStyle") == 0
9317 || pg_strcasecmp(configitem, "search_path") == 0)
9318 appendPQExpBuffer(q, "%s", pos);
9320 appendStringLiteralAH(q, pos, fout);
9323 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9325 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9328 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9330 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9332 finfo->dobj.namespace->dobj.name,
9334 finfo->rolname, false,
9335 "FUNCTION", SECTION_PRE_DATA,
9336 q->data, delqry->data, NULL,
9337 finfo->dobj.dependencies, finfo->dobj.nDeps,
9340 /* Dump Function Comments and Security Labels */
9341 dumpComment(fout, labelq->data,
9342 finfo->dobj.namespace->dobj.name, finfo->rolname,
9343 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9344 dumpSecLabel(fout, labelq->data,
9345 finfo->dobj.namespace->dobj.name, finfo->rolname,
9346 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9348 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9349 funcsig, NULL, funcsig_tag,
9350 finfo->dobj.namespace->dobj.name,
9351 finfo->rolname, finfo->proacl);
9355 destroyPQExpBuffer(query);
9356 destroyPQExpBuffer(q);
9357 destroyPQExpBuffer(delqry);
9358 destroyPQExpBuffer(labelq);
9359 destroyPQExpBuffer(asPart);
9374 * Dump a user-defined cast
9377 dumpCast(Archive *fout, CastInfo *cast)
9382 FuncInfo *funcInfo = NULL;
9384 /* Skip if not to be dumped */
9385 if (!cast->dobj.dump || dataOnly)
9388 /* Cannot dump if we don't have the cast function's info */
9389 if (OidIsValid(cast->castfunc))
9391 funcInfo = findFuncByOid(cast->castfunc);
9392 if (funcInfo == NULL)
9397 * As per discussion we dump casts if one or more of the underlying
9398 * objects (the conversion function and the two data types) are not
9399 * builtin AND if all of the non-builtin objects are included in the dump.
9400 * Builtin meaning, the namespace name does not start with "pg_".
9402 * However, for a cast that belongs to an extension, we must not use this
9403 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9405 if (!cast->dobj.ext_member)
9407 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9408 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9410 if (sourceInfo == NULL || targetInfo == NULL)
9414 * Skip this cast if all objects are from pg_
9416 if ((funcInfo == NULL ||
9417 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9418 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9419 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9423 * Skip cast if function isn't from pg_ and is not to be dumped.
9426 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9427 !funcInfo->dobj.dump)
9431 * Same for the source type
9433 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9434 !sourceInfo->dobj.dump)
9438 * and the target type.
9440 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9441 !targetInfo->dobj.dump)
9445 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9446 selectSourceSchema(fout, "pg_catalog");
9448 defqry = createPQExpBuffer();
9449 delqry = createPQExpBuffer();
9450 labelq = createPQExpBuffer();
9452 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9453 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9454 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9456 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9457 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9458 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9460 switch (cast->castmethod)
9462 case COERCION_METHOD_BINARY:
9463 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9465 case COERCION_METHOD_INOUT:
9466 appendPQExpBuffer(defqry, "WITH INOUT");
9468 case COERCION_METHOD_FUNCTION:
9471 char *fsig = format_function_signature(fout, funcInfo, true);
9474 * Always qualify the function name, in case it is not in
9475 * pg_catalog schema (format_function_signature won't qualify it).
9477 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9478 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9482 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9485 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9488 if (cast->castcontext == 'a')
9489 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9490 else if (cast->castcontext == 'i')
9491 appendPQExpBuffer(defqry, " AS IMPLICIT");
9492 appendPQExpBuffer(defqry, ";\n");
9494 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9495 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9496 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9499 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9501 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9503 "pg_catalog", NULL, "",
9504 false, "CAST", SECTION_PRE_DATA,
9505 defqry->data, delqry->data, NULL,
9506 cast->dobj.dependencies, cast->dobj.nDeps,
9509 /* Dump Cast Comments */
9510 dumpComment(fout, labelq->data,
9512 cast->dobj.catId, 0, cast->dobj.dumpId);
9514 destroyPQExpBuffer(defqry);
9515 destroyPQExpBuffer(delqry);
9516 destroyPQExpBuffer(labelq);
9521 * write out a single operator definition
9524 dumpOpr(Archive *fout, OprInfo *oprinfo)
9531 PQExpBuffer details;
9555 /* Skip if not to be dumped */
9556 if (!oprinfo->dobj.dump || dataOnly)
9560 * some operators are invalid because they were the result of user
9561 * defining operators before commutators exist
9563 if (!OidIsValid(oprinfo->oprcode))
9566 query = createPQExpBuffer();
9567 q = createPQExpBuffer();
9568 delq = createPQExpBuffer();
9569 labelq = createPQExpBuffer();
9570 oprid = createPQExpBuffer();
9571 details = createPQExpBuffer();
9573 /* Make sure we are in proper schema so regoperator works correctly */
9574 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9576 if (fout->remoteVersion >= 80300)
9578 appendPQExpBuffer(query, "SELECT oprkind, "
9579 "oprcode::pg_catalog.regprocedure, "
9580 "oprleft::pg_catalog.regtype, "
9581 "oprright::pg_catalog.regtype, "
9582 "oprcom::pg_catalog.regoperator, "
9583 "oprnegate::pg_catalog.regoperator, "
9584 "oprrest::pg_catalog.regprocedure, "
9585 "oprjoin::pg_catalog.regprocedure, "
9586 "oprcanmerge, oprcanhash "
9587 "FROM pg_catalog.pg_operator "
9588 "WHERE oid = '%u'::pg_catalog.oid",
9589 oprinfo->dobj.catId.oid);
9591 else if (fout->remoteVersion >= 70300)
9593 appendPQExpBuffer(query, "SELECT oprkind, "
9594 "oprcode::pg_catalog.regprocedure, "
9595 "oprleft::pg_catalog.regtype, "
9596 "oprright::pg_catalog.regtype, "
9597 "oprcom::pg_catalog.regoperator, "
9598 "oprnegate::pg_catalog.regoperator, "
9599 "oprrest::pg_catalog.regprocedure, "
9600 "oprjoin::pg_catalog.regprocedure, "
9601 "(oprlsortop != 0) AS oprcanmerge, "
9603 "FROM pg_catalog.pg_operator "
9604 "WHERE oid = '%u'::pg_catalog.oid",
9605 oprinfo->dobj.catId.oid);
9607 else if (fout->remoteVersion >= 70100)
9609 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9610 "CASE WHEN oprleft = 0 THEN '-' "
9611 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9612 "CASE WHEN oprright = 0 THEN '-' "
9613 "ELSE format_type(oprright, NULL) END AS oprright, "
9614 "oprcom, oprnegate, oprrest, oprjoin, "
9615 "(oprlsortop != 0) AS oprcanmerge, "
9618 "WHERE oid = '%u'::oid",
9619 oprinfo->dobj.catId.oid);
9623 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9624 "CASE WHEN oprleft = 0 THEN '-'::name "
9625 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9626 "CASE WHEN oprright = 0 THEN '-'::name "
9627 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9628 "oprcom, oprnegate, oprrest, oprjoin, "
9629 "(oprlsortop != 0) AS oprcanmerge, "
9632 "WHERE oid = '%u'::oid",
9633 oprinfo->dobj.catId.oid);
9636 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9638 i_oprkind = PQfnumber(res, "oprkind");
9639 i_oprcode = PQfnumber(res, "oprcode");
9640 i_oprleft = PQfnumber(res, "oprleft");
9641 i_oprright = PQfnumber(res, "oprright");
9642 i_oprcom = PQfnumber(res, "oprcom");
9643 i_oprnegate = PQfnumber(res, "oprnegate");
9644 i_oprrest = PQfnumber(res, "oprrest");
9645 i_oprjoin = PQfnumber(res, "oprjoin");
9646 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9647 i_oprcanhash = PQfnumber(res, "oprcanhash");
9649 oprkind = PQgetvalue(res, 0, i_oprkind);
9650 oprcode = PQgetvalue(res, 0, i_oprcode);
9651 oprleft = PQgetvalue(res, 0, i_oprleft);
9652 oprright = PQgetvalue(res, 0, i_oprright);
9653 oprcom = PQgetvalue(res, 0, i_oprcom);
9654 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9655 oprrest = PQgetvalue(res, 0, i_oprrest);
9656 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9657 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9658 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9660 appendPQExpBuffer(details, " PROCEDURE = %s",
9661 convertRegProcReference(fout, oprcode));
9663 appendPQExpBuffer(oprid, "%s (",
9664 oprinfo->dobj.name);
9667 * right unary means there's a left arg and left unary means there's a
9670 if (strcmp(oprkind, "r") == 0 ||
9671 strcmp(oprkind, "b") == 0)
9673 if (fout->remoteVersion >= 70100)
9676 name = fmtId(oprleft);
9677 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9678 appendPQExpBuffer(oprid, "%s", name);
9681 appendPQExpBuffer(oprid, "NONE");
9683 if (strcmp(oprkind, "l") == 0 ||
9684 strcmp(oprkind, "b") == 0)
9686 if (fout->remoteVersion >= 70100)
9689 name = fmtId(oprright);
9690 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9691 appendPQExpBuffer(oprid, ", %s)", name);
9694 appendPQExpBuffer(oprid, ", NONE)");
9696 name = convertOperatorReference(fout, oprcom);
9698 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9700 name = convertOperatorReference(fout, oprnegate);
9702 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9704 if (strcmp(oprcanmerge, "t") == 0)
9705 appendPQExpBuffer(details, ",\n MERGES");
9707 if (strcmp(oprcanhash, "t") == 0)
9708 appendPQExpBuffer(details, ",\n HASHES");
9710 name = convertRegProcReference(fout, oprrest);
9712 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9714 name = convertRegProcReference(fout, oprjoin);
9716 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9719 * DROP must be fully qualified in case same name appears in pg_catalog
9721 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9722 fmtId(oprinfo->dobj.namespace->dobj.name),
9725 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9726 oprinfo->dobj.name, details->data);
9728 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9731 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9733 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9735 oprinfo->dobj.namespace->dobj.name,
9738 false, "OPERATOR", SECTION_PRE_DATA,
9739 q->data, delq->data, NULL,
9740 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9743 /* Dump Operator Comments */
9744 dumpComment(fout, labelq->data,
9745 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9746 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9750 destroyPQExpBuffer(query);
9751 destroyPQExpBuffer(q);
9752 destroyPQExpBuffer(delq);
9753 destroyPQExpBuffer(labelq);
9754 destroyPQExpBuffer(oprid);
9755 destroyPQExpBuffer(details);
9759 * Convert a function reference obtained from pg_operator
9761 * Returns what to print, or NULL if function references is InvalidOid
9763 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9764 * argument-types part. In prior versions, the input is a REGPROC display.
9767 convertRegProcReference(Archive *fout, const char *proc)
9769 /* In all cases "-" means a null reference */
9770 if (strcmp(proc, "-") == 0)
9773 if (fout->remoteVersion >= 70300)
9779 name = pg_strdup(proc);
9780 /* find non-double-quoted left paren */
9782 for (paren = name; *paren; paren++)
9784 if (*paren == '(' && !inquote)
9795 /* REGPROC before 7.3 does not quote its result */
9800 * Convert an operator cross-reference obtained from pg_operator
9802 * Returns what to print, or NULL to print nothing
9804 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9805 * argument-types part, and add OPERATOR() decoration if the name is
9806 * schema-qualified. In older versions, the input is just a numeric OID,
9807 * which we search our operator list for.
9810 convertOperatorReference(Archive *fout, const char *opr)
9814 /* In all cases "0" means a null reference */
9815 if (strcmp(opr, "0") == 0)
9818 if (fout->remoteVersion >= 70300)
9826 name = pg_strdup(opr);
9827 /* find non-double-quoted left paren, and check for non-quoted dot */
9830 for (ptr = name; *ptr; ptr++)
9834 else if (*ptr == '.' && !inquote)
9836 else if (*ptr == '(' && !inquote)
9842 /* If not schema-qualified, don't need to add OPERATOR() */
9845 oname = pg_malloc(strlen(name) + 11);
9846 sprintf(oname, "OPERATOR(%s)", name);
9851 oprInfo = findOprByOid(atooid(opr));
9852 if (oprInfo == NULL)
9854 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9858 return oprInfo->dobj.name;
9862 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9864 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9865 * argument lists of these functions are predetermined. Note that the
9866 * caller should ensure we are in the proper schema, because the results
9867 * are search path dependent!
9870 convertTSFunction(Archive *fout, Oid funcOid)
9876 snprintf(query, sizeof(query),
9877 "SELECT '%u'::pg_catalog.regproc", funcOid);
9878 res = ExecuteSqlQueryForSingleRow(fout, query);
9880 result = pg_strdup(PQgetvalue(res, 0, 0));
9890 * write out a single operator class definition
9893 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9905 int i_opcfamilyname;
9912 int i_sortfamilynsp;
9915 int i_amproclefttype;
9916 int i_amprocrighttype;
9921 char *opcfamilyname;
9928 char *sortfamilynsp;
9931 char *amproclefttype;
9932 char *amprocrighttype;
9936 /* Skip if not to be dumped */
9937 if (!opcinfo->dobj.dump || dataOnly)
9941 * XXX currently we do not implement dumping of operator classes from
9942 * pre-7.3 databases. This could be done but it seems not worth the
9945 if (fout->remoteVersion < 70300)
9948 query = createPQExpBuffer();
9949 q = createPQExpBuffer();
9950 delq = createPQExpBuffer();
9951 labelq = createPQExpBuffer();
9953 /* Make sure we are in proper schema so regoperator works correctly */
9954 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9956 /* Get additional fields from the pg_opclass row */
9957 if (fout->remoteVersion >= 80300)
9959 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9960 "opckeytype::pg_catalog.regtype, "
9961 "opcdefault, opcfamily, "
9962 "opfname AS opcfamilyname, "
9963 "nspname AS opcfamilynsp, "
9964 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9965 "FROM pg_catalog.pg_opclass c "
9966 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9967 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9968 "WHERE c.oid = '%u'::pg_catalog.oid",
9969 opcinfo->dobj.catId.oid);
9973 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9974 "opckeytype::pg_catalog.regtype, "
9975 "opcdefault, NULL AS opcfamily, "
9976 "NULL AS opcfamilyname, "
9977 "NULL AS opcfamilynsp, "
9978 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9979 "FROM pg_catalog.pg_opclass "
9980 "WHERE oid = '%u'::pg_catalog.oid",
9981 opcinfo->dobj.catId.oid);
9984 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9986 i_opcintype = PQfnumber(res, "opcintype");
9987 i_opckeytype = PQfnumber(res, "opckeytype");
9988 i_opcdefault = PQfnumber(res, "opcdefault");
9989 i_opcfamily = PQfnumber(res, "opcfamily");
9990 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9991 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9992 i_amname = PQfnumber(res, "amname");
9994 opcintype = PQgetvalue(res, 0, i_opcintype);
9995 opckeytype = PQgetvalue(res, 0, i_opckeytype);
9996 opcdefault = PQgetvalue(res, 0, i_opcdefault);
9997 /* opcfamily will still be needed after we PQclear res */
9998 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9999 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10000 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10001 /* amname will still be needed after we PQclear res */
10002 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10005 * DROP must be fully qualified in case same name appears in pg_catalog
10007 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10008 fmtId(opcinfo->dobj.namespace->dobj.name));
10009 appendPQExpBuffer(delq, ".%s",
10010 fmtId(opcinfo->dobj.name));
10011 appendPQExpBuffer(delq, " USING %s;\n",
10014 /* Build the fixed portion of the CREATE command */
10015 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10016 fmtId(opcinfo->dobj.name));
10017 if (strcmp(opcdefault, "t") == 0)
10018 appendPQExpBuffer(q, "DEFAULT ");
10019 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10022 if (strlen(opcfamilyname) > 0 &&
10023 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10024 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10026 appendPQExpBuffer(q, " FAMILY ");
10027 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10028 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10029 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10031 appendPQExpBuffer(q, " AS\n ");
10035 if (strcmp(opckeytype, "-") != 0)
10037 appendPQExpBuffer(q, "STORAGE %s",
10045 * Now fetch and print the OPERATOR entries (pg_amop rows).
10047 * Print only those opfamily members that are tied to the opclass by
10048 * pg_depend entries.
10050 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10051 * older server's opclass in which it is used. This is to avoid
10052 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10053 * older server and then reload into that old version. This can go away
10054 * once 8.3 is so old as to not be of interest to anyone.
10056 resetPQExpBuffer(query);
10058 if (fout->remoteVersion >= 90100)
10060 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10061 "amopopr::pg_catalog.regoperator, "
10062 "opfname AS sortfamily, "
10063 "nspname AS sortfamilynsp "
10064 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10065 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10066 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10067 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10068 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10069 "AND refobjid = '%u'::pg_catalog.oid "
10070 "AND amopfamily = '%s'::pg_catalog.oid "
10071 "ORDER BY amopstrategy",
10072 opcinfo->dobj.catId.oid,
10075 else if (fout->remoteVersion >= 80400)
10077 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10078 "amopopr::pg_catalog.regoperator, "
10079 "NULL AS sortfamily, "
10080 "NULL AS sortfamilynsp "
10081 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10082 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10083 "AND refobjid = '%u'::pg_catalog.oid "
10084 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10085 "AND objid = ao.oid "
10086 "ORDER BY amopstrategy",
10087 opcinfo->dobj.catId.oid);
10089 else if (fout->remoteVersion >= 80300)
10091 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10092 "amopopr::pg_catalog.regoperator, "
10093 "NULL AS sortfamily, "
10094 "NULL AS sortfamilynsp "
10095 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10096 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10097 "AND refobjid = '%u'::pg_catalog.oid "
10098 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10099 "AND objid = ao.oid "
10100 "ORDER BY amopstrategy",
10101 opcinfo->dobj.catId.oid);
10106 * Here, we print all entries since there are no opfamilies and hence
10107 * no loose operators to worry about.
10109 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10110 "amopopr::pg_catalog.regoperator, "
10111 "NULL AS sortfamily, "
10112 "NULL AS sortfamilynsp "
10113 "FROM pg_catalog.pg_amop "
10114 "WHERE amopclaid = '%u'::pg_catalog.oid "
10115 "ORDER BY amopstrategy",
10116 opcinfo->dobj.catId.oid);
10119 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10121 ntups = PQntuples(res);
10123 i_amopstrategy = PQfnumber(res, "amopstrategy");
10124 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10125 i_amopopr = PQfnumber(res, "amopopr");
10126 i_sortfamily = PQfnumber(res, "sortfamily");
10127 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10129 for (i = 0; i < ntups; i++)
10131 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10132 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10133 amopopr = PQgetvalue(res, i, i_amopopr);
10134 sortfamily = PQgetvalue(res, i, i_sortfamily);
10135 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10138 appendPQExpBuffer(q, " ,\n ");
10140 appendPQExpBuffer(q, "OPERATOR %s %s",
10141 amopstrategy, amopopr);
10143 if (strlen(sortfamily) > 0)
10145 appendPQExpBuffer(q, " FOR ORDER BY ");
10146 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10147 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10148 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10151 if (strcmp(amopreqcheck, "t") == 0)
10152 appendPQExpBuffer(q, " RECHECK");
10160 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10162 * Print only those opfamily members that are tied to the opclass by
10163 * pg_depend entries.
10165 * We print the amproclefttype/amprocrighttype even though in most cases
10166 * the backend could deduce the right values, because of the corner case
10167 * of a btree sort support function for a cross-type comparison. That's
10168 * only allowed in 9.2 and later, but for simplicity print them in all
10169 * versions that have the columns.
10171 resetPQExpBuffer(query);
10173 if (fout->remoteVersion >= 80300)
10175 appendPQExpBuffer(query, "SELECT amprocnum, "
10176 "amproc::pg_catalog.regprocedure, "
10177 "amproclefttype::pg_catalog.regtype, "
10178 "amprocrighttype::pg_catalog.regtype "
10179 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10180 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10181 "AND refobjid = '%u'::pg_catalog.oid "
10182 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10183 "AND objid = ap.oid "
10184 "ORDER BY amprocnum",
10185 opcinfo->dobj.catId.oid);
10189 appendPQExpBuffer(query, "SELECT amprocnum, "
10190 "amproc::pg_catalog.regprocedure, "
10191 "'' AS amproclefttype, "
10192 "'' AS amprocrighttype "
10193 "FROM pg_catalog.pg_amproc "
10194 "WHERE amopclaid = '%u'::pg_catalog.oid "
10195 "ORDER BY amprocnum",
10196 opcinfo->dobj.catId.oid);
10199 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10201 ntups = PQntuples(res);
10203 i_amprocnum = PQfnumber(res, "amprocnum");
10204 i_amproc = PQfnumber(res, "amproc");
10205 i_amproclefttype = PQfnumber(res, "amproclefttype");
10206 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10208 for (i = 0; i < ntups; i++)
10210 amprocnum = PQgetvalue(res, i, i_amprocnum);
10211 amproc = PQgetvalue(res, i, i_amproc);
10212 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10213 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10216 appendPQExpBuffer(q, " ,\n ");
10218 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10220 if (*amproclefttype && *amprocrighttype)
10221 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10223 appendPQExpBuffer(q, " %s", amproc);
10230 appendPQExpBuffer(q, ";\n");
10232 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10233 fmtId(opcinfo->dobj.name));
10234 appendPQExpBuffer(labelq, " USING %s",
10237 if (binary_upgrade)
10238 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10240 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10241 opcinfo->dobj.name,
10242 opcinfo->dobj.namespace->dobj.name,
10245 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10246 q->data, delq->data, NULL,
10247 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10250 /* Dump Operator Class Comments */
10251 dumpComment(fout, labelq->data,
10252 NULL, opcinfo->rolname,
10253 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10256 destroyPQExpBuffer(query);
10257 destroyPQExpBuffer(q);
10258 destroyPQExpBuffer(delq);
10259 destroyPQExpBuffer(labelq);
10264 * write out a single operator family definition
10266 * Note: this also dumps any "loose" operator members that aren't bound to a
10267 * specific opclass within the opfamily.
10270 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10275 PQExpBuffer labelq;
10278 PGresult *res_procs;
10281 int i_amopstrategy;
10282 int i_amopreqcheck;
10285 int i_sortfamilynsp;
10288 int i_amproclefttype;
10289 int i_amprocrighttype;
10291 char *amopstrategy;
10292 char *amopreqcheck;
10295 char *sortfamilynsp;
10298 char *amproclefttype;
10299 char *amprocrighttype;
10303 /* Skip if not to be dumped */
10304 if (!opfinfo->dobj.dump || dataOnly)
10308 * We want to dump the opfamily only if (1) it contains "loose" operators
10309 * or functions, or (2) it contains an opclass with a different name or
10310 * owner. Otherwise it's sufficient to let it be created during creation
10311 * of the contained opclass, and not dumping it improves portability of
10312 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10316 query = createPQExpBuffer();
10317 q = createPQExpBuffer();
10318 delq = createPQExpBuffer();
10319 labelq = createPQExpBuffer();
10321 /* Make sure we are in proper schema so regoperator works correctly */
10322 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10325 * Fetch only those opfamily members that are tied directly to the
10326 * opfamily by pg_depend entries.
10328 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10329 * older server's opclass in which it is used. This is to avoid
10330 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10331 * older server and then reload into that old version. This can go away
10332 * once 8.3 is so old as to not be of interest to anyone.
10334 if (fout->remoteVersion >= 90100)
10336 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10337 "amopopr::pg_catalog.regoperator, "
10338 "opfname AS sortfamily, "
10339 "nspname AS sortfamilynsp "
10340 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10341 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10342 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10343 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10344 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10345 "AND refobjid = '%u'::pg_catalog.oid "
10346 "AND amopfamily = '%u'::pg_catalog.oid "
10347 "ORDER BY amopstrategy",
10348 opfinfo->dobj.catId.oid,
10349 opfinfo->dobj.catId.oid);
10351 else if (fout->remoteVersion >= 80400)
10353 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10354 "amopopr::pg_catalog.regoperator, "
10355 "NULL AS sortfamily, "
10356 "NULL AS sortfamilynsp "
10357 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10358 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10359 "AND refobjid = '%u'::pg_catalog.oid "
10360 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10361 "AND objid = ao.oid "
10362 "ORDER BY amopstrategy",
10363 opfinfo->dobj.catId.oid);
10367 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10368 "amopopr::pg_catalog.regoperator, "
10369 "NULL AS sortfamily, "
10370 "NULL AS sortfamilynsp "
10371 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10372 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10373 "AND refobjid = '%u'::pg_catalog.oid "
10374 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10375 "AND objid = ao.oid "
10376 "ORDER BY amopstrategy",
10377 opfinfo->dobj.catId.oid);
10380 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10382 resetPQExpBuffer(query);
10384 appendPQExpBuffer(query, "SELECT amprocnum, "
10385 "amproc::pg_catalog.regprocedure, "
10386 "amproclefttype::pg_catalog.regtype, "
10387 "amprocrighttype::pg_catalog.regtype "
10388 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10389 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10390 "AND refobjid = '%u'::pg_catalog.oid "
10391 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10392 "AND objid = ap.oid "
10393 "ORDER BY amprocnum",
10394 opfinfo->dobj.catId.oid);
10396 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10398 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10400 /* No loose members, so check contained opclasses */
10401 resetPQExpBuffer(query);
10403 appendPQExpBuffer(query, "SELECT 1 "
10404 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10405 "WHERE f.oid = '%u'::pg_catalog.oid "
10406 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10407 "AND refobjid = f.oid "
10408 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10409 "AND objid = c.oid "
10410 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10412 opfinfo->dobj.catId.oid);
10414 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10416 if (PQntuples(res) == 0)
10418 /* no need to dump it, so bail out */
10421 PQclear(res_procs);
10422 destroyPQExpBuffer(query);
10423 destroyPQExpBuffer(q);
10424 destroyPQExpBuffer(delq);
10425 destroyPQExpBuffer(labelq);
10432 /* Get additional fields from the pg_opfamily row */
10433 resetPQExpBuffer(query);
10435 appendPQExpBuffer(query, "SELECT "
10436 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10437 "FROM pg_catalog.pg_opfamily "
10438 "WHERE oid = '%u'::pg_catalog.oid",
10439 opfinfo->dobj.catId.oid);
10441 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10443 i_amname = PQfnumber(res, "amname");
10445 /* amname will still be needed after we PQclear res */
10446 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10449 * DROP must be fully qualified in case same name appears in pg_catalog
10451 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10452 fmtId(opfinfo->dobj.namespace->dobj.name));
10453 appendPQExpBuffer(delq, ".%s",
10454 fmtId(opfinfo->dobj.name));
10455 appendPQExpBuffer(delq, " USING %s;\n",
10458 /* Build the fixed portion of the CREATE command */
10459 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10460 fmtId(opfinfo->dobj.name));
10461 appendPQExpBuffer(q, " USING %s;\n",
10466 /* Do we need an ALTER to add loose members? */
10467 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10469 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10470 fmtId(opfinfo->dobj.name));
10471 appendPQExpBuffer(q, " USING %s ADD\n ",
10477 * Now fetch and print the OPERATOR entries (pg_amop rows).
10479 ntups = PQntuples(res_ops);
10481 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10482 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10483 i_amopopr = PQfnumber(res_ops, "amopopr");
10484 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10485 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10487 for (i = 0; i < ntups; i++)
10489 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10490 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10491 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10492 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10493 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10496 appendPQExpBuffer(q, " ,\n ");
10498 appendPQExpBuffer(q, "OPERATOR %s %s",
10499 amopstrategy, amopopr);
10501 if (strlen(sortfamily) > 0)
10503 appendPQExpBuffer(q, " FOR ORDER BY ");
10504 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10505 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10506 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10509 if (strcmp(amopreqcheck, "t") == 0)
10510 appendPQExpBuffer(q, " RECHECK");
10516 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10518 ntups = PQntuples(res_procs);
10520 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10521 i_amproc = PQfnumber(res_procs, "amproc");
10522 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10523 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10525 for (i = 0; i < ntups; i++)
10527 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10528 amproc = PQgetvalue(res_procs, i, i_amproc);
10529 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10530 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10533 appendPQExpBuffer(q, " ,\n ");
10535 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10536 amprocnum, amproclefttype, amprocrighttype,
10542 appendPQExpBuffer(q, ";\n");
10545 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10546 fmtId(opfinfo->dobj.name));
10547 appendPQExpBuffer(labelq, " USING %s",
10550 if (binary_upgrade)
10551 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10553 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10554 opfinfo->dobj.name,
10555 opfinfo->dobj.namespace->dobj.name,
10558 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10559 q->data, delq->data, NULL,
10560 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10563 /* Dump Operator Family Comments */
10564 dumpComment(fout, labelq->data,
10565 NULL, opfinfo->rolname,
10566 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10570 PQclear(res_procs);
10571 destroyPQExpBuffer(query);
10572 destroyPQExpBuffer(q);
10573 destroyPQExpBuffer(delq);
10574 destroyPQExpBuffer(labelq);
10579 * write out a single collation definition
10582 dumpCollation(Archive *fout, CollInfo *collinfo)
10587 PQExpBuffer labelq;
10591 const char *collcollate;
10592 const char *collctype;
10594 /* Skip if not to be dumped */
10595 if (!collinfo->dobj.dump || dataOnly)
10598 query = createPQExpBuffer();
10599 q = createPQExpBuffer();
10600 delq = createPQExpBuffer();
10601 labelq = createPQExpBuffer();
10603 /* Make sure we are in proper schema */
10604 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10606 /* Get conversion-specific details */
10607 appendPQExpBuffer(query, "SELECT "
10610 "FROM pg_catalog.pg_collation c "
10611 "WHERE c.oid = '%u'::pg_catalog.oid",
10612 collinfo->dobj.catId.oid);
10614 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10616 i_collcollate = PQfnumber(res, "collcollate");
10617 i_collctype = PQfnumber(res, "collctype");
10619 collcollate = PQgetvalue(res, 0, i_collcollate);
10620 collctype = PQgetvalue(res, 0, i_collctype);
10623 * DROP must be fully qualified in case same name appears in pg_catalog
10625 appendPQExpBuffer(delq, "DROP COLLATION %s",
10626 fmtId(collinfo->dobj.namespace->dobj.name));
10627 appendPQExpBuffer(delq, ".%s;\n",
10628 fmtId(collinfo->dobj.name));
10630 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10631 fmtId(collinfo->dobj.name));
10632 appendStringLiteralAH(q, collcollate, fout);
10633 appendPQExpBuffer(q, ", lc_ctype = ");
10634 appendStringLiteralAH(q, collctype, fout);
10635 appendPQExpBuffer(q, ");\n");
10637 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10639 if (binary_upgrade)
10640 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10642 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10643 collinfo->dobj.name,
10644 collinfo->dobj.namespace->dobj.name,
10647 false, "COLLATION", SECTION_PRE_DATA,
10648 q->data, delq->data, NULL,
10649 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10652 /* Dump Collation Comments */
10653 dumpComment(fout, labelq->data,
10654 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10655 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10659 destroyPQExpBuffer(query);
10660 destroyPQExpBuffer(q);
10661 destroyPQExpBuffer(delq);
10662 destroyPQExpBuffer(labelq);
10667 * write out a single conversion definition
10670 dumpConversion(Archive *fout, ConvInfo *convinfo)
10675 PQExpBuffer labelq;
10677 int i_conforencoding;
10678 int i_contoencoding;
10681 const char *conforencoding;
10682 const char *contoencoding;
10683 const char *conproc;
10686 /* Skip if not to be dumped */
10687 if (!convinfo->dobj.dump || dataOnly)
10690 query = createPQExpBuffer();
10691 q = createPQExpBuffer();
10692 delq = createPQExpBuffer();
10693 labelq = createPQExpBuffer();
10695 /* Make sure we are in proper schema */
10696 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10698 /* Get conversion-specific details */
10699 appendPQExpBuffer(query, "SELECT "
10700 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10701 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10702 "conproc, condefault "
10703 "FROM pg_catalog.pg_conversion c "
10704 "WHERE c.oid = '%u'::pg_catalog.oid",
10705 convinfo->dobj.catId.oid);
10707 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10709 i_conforencoding = PQfnumber(res, "conforencoding");
10710 i_contoencoding = PQfnumber(res, "contoencoding");
10711 i_conproc = PQfnumber(res, "conproc");
10712 i_condefault = PQfnumber(res, "condefault");
10714 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10715 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10716 conproc = PQgetvalue(res, 0, i_conproc);
10717 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10720 * DROP must be fully qualified in case same name appears in pg_catalog
10722 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10723 fmtId(convinfo->dobj.namespace->dobj.name));
10724 appendPQExpBuffer(delq, ".%s;\n",
10725 fmtId(convinfo->dobj.name));
10727 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10728 (condefault) ? "DEFAULT " : "",
10729 fmtId(convinfo->dobj.name));
10730 appendStringLiteralAH(q, conforencoding, fout);
10731 appendPQExpBuffer(q, " TO ");
10732 appendStringLiteralAH(q, contoencoding, fout);
10733 /* regproc is automatically quoted in 7.3 and above */
10734 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10736 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10738 if (binary_upgrade)
10739 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10741 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10742 convinfo->dobj.name,
10743 convinfo->dobj.namespace->dobj.name,
10746 false, "CONVERSION", SECTION_PRE_DATA,
10747 q->data, delq->data, NULL,
10748 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10751 /* Dump Conversion Comments */
10752 dumpComment(fout, labelq->data,
10753 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10754 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10758 destroyPQExpBuffer(query);
10759 destroyPQExpBuffer(q);
10760 destroyPQExpBuffer(delq);
10761 destroyPQExpBuffer(labelq);
10765 * format_aggregate_signature: generate aggregate name and argument list
10767 * The argument type names are qualified if needed. The aggregate name
10768 * is never qualified.
10771 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10773 PQExpBufferData buf;
10776 initPQExpBuffer(&buf);
10778 appendPQExpBuffer(&buf, "%s",
10779 fmtId(agginfo->aggfn.dobj.name));
10781 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10783 if (agginfo->aggfn.nargs == 0)
10784 appendPQExpBuffer(&buf, "(*)");
10787 appendPQExpBuffer(&buf, "(");
10788 for (j = 0; j < agginfo->aggfn.nargs; j++)
10792 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10795 appendPQExpBuffer(&buf, "%s%s",
10796 (j > 0) ? ", " : "",
10800 appendPQExpBuffer(&buf, ")");
10807 * write out a single aggregate definition
10810 dumpAgg(Archive *fout, AggInfo *agginfo)
10815 PQExpBuffer labelq;
10816 PQExpBuffer details;
10823 int i_aggtranstype;
10826 const char *aggtransfn;
10827 const char *aggfinalfn;
10828 const char *aggsortop;
10829 const char *aggtranstype;
10830 const char *agginitval;
10833 /* Skip if not to be dumped */
10834 if (!agginfo->aggfn.dobj.dump || dataOnly)
10837 query = createPQExpBuffer();
10838 q = createPQExpBuffer();
10839 delq = createPQExpBuffer();
10840 labelq = createPQExpBuffer();
10841 details = createPQExpBuffer();
10843 /* Make sure we are in proper schema */
10844 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10846 /* Get aggregate-specific details */
10847 if (fout->remoteVersion >= 80100)
10849 appendPQExpBuffer(query, "SELECT aggtransfn, "
10850 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10851 "aggsortop::pg_catalog.regoperator, "
10853 "'t'::boolean AS convertok "
10854 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10855 "WHERE a.aggfnoid = p.oid "
10856 "AND p.oid = '%u'::pg_catalog.oid",
10857 agginfo->aggfn.dobj.catId.oid);
10859 else if (fout->remoteVersion >= 70300)
10861 appendPQExpBuffer(query, "SELECT aggtransfn, "
10862 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10865 "'t'::boolean AS convertok "
10866 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10867 "WHERE a.aggfnoid = p.oid "
10868 "AND p.oid = '%u'::pg_catalog.oid",
10869 agginfo->aggfn.dobj.catId.oid);
10871 else if (fout->remoteVersion >= 70100)
10873 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10874 "format_type(aggtranstype, NULL) AS aggtranstype, "
10877 "'t'::boolean AS convertok "
10878 "FROM pg_aggregate "
10879 "WHERE oid = '%u'::oid",
10880 agginfo->aggfn.dobj.catId.oid);
10884 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10886 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10888 "agginitval1 AS agginitval, "
10889 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10890 "FROM pg_aggregate "
10891 "WHERE oid = '%u'::oid",
10892 agginfo->aggfn.dobj.catId.oid);
10895 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10897 i_aggtransfn = PQfnumber(res, "aggtransfn");
10898 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10899 i_aggsortop = PQfnumber(res, "aggsortop");
10900 i_aggtranstype = PQfnumber(res, "aggtranstype");
10901 i_agginitval = PQfnumber(res, "agginitval");
10902 i_convertok = PQfnumber(res, "convertok");
10904 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10905 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10906 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10907 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10908 agginitval = PQgetvalue(res, 0, i_agginitval);
10909 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10911 aggsig = format_aggregate_signature(agginfo, fout, true);
10912 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10916 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10921 if (fout->remoteVersion >= 70300)
10923 /* If using 7.3's regproc or regtype, data is already quoted */
10924 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10928 else if (fout->remoteVersion >= 70100)
10930 /* format_type quotes, regproc does not */
10931 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10937 /* need quotes all around */
10938 appendPQExpBuffer(details, " SFUNC = %s,\n",
10939 fmtId(aggtransfn));
10940 appendPQExpBuffer(details, " STYPE = %s",
10941 fmtId(aggtranstype));
10944 if (!PQgetisnull(res, 0, i_agginitval))
10946 appendPQExpBuffer(details, ",\n INITCOND = ");
10947 appendStringLiteralAH(details, agginitval, fout);
10950 if (strcmp(aggfinalfn, "-") != 0)
10952 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
10956 aggsortop = convertOperatorReference(fout, aggsortop);
10959 appendPQExpBuffer(details, ",\n SORTOP = %s",
10964 * DROP must be fully qualified in case same name appears in pg_catalog
10966 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10967 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10970 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10971 aggsig, details->data);
10973 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10975 if (binary_upgrade)
10976 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10978 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10980 agginfo->aggfn.dobj.namespace->dobj.name,
10982 agginfo->aggfn.rolname,
10983 false, "AGGREGATE", SECTION_PRE_DATA,
10984 q->data, delq->data, NULL,
10985 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10988 /* Dump Aggregate Comments */
10989 dumpComment(fout, labelq->data,
10990 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10991 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10992 dumpSecLabel(fout, labelq->data,
10993 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10994 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10997 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10998 * command look like a function's GRANT; in particular this affects the
10999 * syntax for zero-argument aggregates.
11004 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11005 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11007 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11009 aggsig, NULL, aggsig_tag,
11010 agginfo->aggfn.dobj.namespace->dobj.name,
11011 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11018 destroyPQExpBuffer(query);
11019 destroyPQExpBuffer(q);
11020 destroyPQExpBuffer(delq);
11021 destroyPQExpBuffer(labelq);
11022 destroyPQExpBuffer(details);
11027 * write out a single text search parser
11030 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11034 PQExpBuffer labelq;
11036 /* Skip if not to be dumped */
11037 if (!prsinfo->dobj.dump || dataOnly)
11040 q = createPQExpBuffer();
11041 delq = createPQExpBuffer();
11042 labelq = createPQExpBuffer();
11044 /* Make sure we are in proper schema */
11045 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11047 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11048 fmtId(prsinfo->dobj.name));
11050 appendPQExpBuffer(q, " START = %s,\n",
11051 convertTSFunction(fout, prsinfo->prsstart));
11052 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11053 convertTSFunction(fout, prsinfo->prstoken));
11054 appendPQExpBuffer(q, " END = %s,\n",
11055 convertTSFunction(fout, prsinfo->prsend));
11056 if (prsinfo->prsheadline != InvalidOid)
11057 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11058 convertTSFunction(fout, prsinfo->prsheadline));
11059 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11060 convertTSFunction(fout, prsinfo->prslextype));
11063 * DROP must be fully qualified in case same name appears in pg_catalog
11065 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11066 fmtId(prsinfo->dobj.namespace->dobj.name));
11067 appendPQExpBuffer(delq, ".%s;\n",
11068 fmtId(prsinfo->dobj.name));
11070 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11071 fmtId(prsinfo->dobj.name));
11073 if (binary_upgrade)
11074 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11076 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11077 prsinfo->dobj.name,
11078 prsinfo->dobj.namespace->dobj.name,
11081 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11082 q->data, delq->data, NULL,
11083 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11086 /* Dump Parser Comments */
11087 dumpComment(fout, labelq->data,
11089 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11091 destroyPQExpBuffer(q);
11092 destroyPQExpBuffer(delq);
11093 destroyPQExpBuffer(labelq);
11098 * write out a single text search dictionary
11101 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11105 PQExpBuffer labelq;
11111 /* Skip if not to be dumped */
11112 if (!dictinfo->dobj.dump || dataOnly)
11115 q = createPQExpBuffer();
11116 delq = createPQExpBuffer();
11117 labelq = createPQExpBuffer();
11118 query = createPQExpBuffer();
11120 /* Fetch name and namespace of the dictionary's template */
11121 selectSourceSchema(fout, "pg_catalog");
11122 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11123 "FROM pg_ts_template p, pg_namespace n "
11124 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11125 dictinfo->dicttemplate);
11126 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11127 nspname = PQgetvalue(res, 0, 0);
11128 tmplname = PQgetvalue(res, 0, 1);
11130 /* Make sure we are in proper schema */
11131 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11133 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11134 fmtId(dictinfo->dobj.name));
11136 appendPQExpBuffer(q, " TEMPLATE = ");
11137 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11138 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11139 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11143 /* the dictinitoption can be dumped straight into the command */
11144 if (dictinfo->dictinitoption)
11145 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11147 appendPQExpBuffer(q, " );\n");
11150 * DROP must be fully qualified in case same name appears in pg_catalog
11152 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11153 fmtId(dictinfo->dobj.namespace->dobj.name));
11154 appendPQExpBuffer(delq, ".%s;\n",
11155 fmtId(dictinfo->dobj.name));
11157 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11158 fmtId(dictinfo->dobj.name));
11160 if (binary_upgrade)
11161 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11163 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11164 dictinfo->dobj.name,
11165 dictinfo->dobj.namespace->dobj.name,
11168 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11169 q->data, delq->data, NULL,
11170 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11173 /* Dump Dictionary Comments */
11174 dumpComment(fout, labelq->data,
11175 NULL, dictinfo->rolname,
11176 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11178 destroyPQExpBuffer(q);
11179 destroyPQExpBuffer(delq);
11180 destroyPQExpBuffer(labelq);
11181 destroyPQExpBuffer(query);
11186 * write out a single text search template
11189 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11193 PQExpBuffer labelq;
11195 /* Skip if not to be dumped */
11196 if (!tmplinfo->dobj.dump || dataOnly)
11199 q = createPQExpBuffer();
11200 delq = createPQExpBuffer();
11201 labelq = createPQExpBuffer();
11203 /* Make sure we are in proper schema */
11204 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11206 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11207 fmtId(tmplinfo->dobj.name));
11209 if (tmplinfo->tmplinit != InvalidOid)
11210 appendPQExpBuffer(q, " INIT = %s,\n",
11211 convertTSFunction(fout, tmplinfo->tmplinit));
11212 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11213 convertTSFunction(fout, tmplinfo->tmpllexize));
11216 * DROP must be fully qualified in case same name appears in pg_catalog
11218 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11219 fmtId(tmplinfo->dobj.namespace->dobj.name));
11220 appendPQExpBuffer(delq, ".%s;\n",
11221 fmtId(tmplinfo->dobj.name));
11223 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11224 fmtId(tmplinfo->dobj.name));
11226 if (binary_upgrade)
11227 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11229 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11230 tmplinfo->dobj.name,
11231 tmplinfo->dobj.namespace->dobj.name,
11234 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11235 q->data, delq->data, NULL,
11236 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11239 /* Dump Template Comments */
11240 dumpComment(fout, labelq->data,
11242 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11244 destroyPQExpBuffer(q);
11245 destroyPQExpBuffer(delq);
11246 destroyPQExpBuffer(labelq);
11251 * write out a single text search configuration
11254 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11258 PQExpBuffer labelq;
11268 /* Skip if not to be dumped */
11269 if (!cfginfo->dobj.dump || dataOnly)
11272 q = createPQExpBuffer();
11273 delq = createPQExpBuffer();
11274 labelq = createPQExpBuffer();
11275 query = createPQExpBuffer();
11277 /* Fetch name and namespace of the config's parser */
11278 selectSourceSchema(fout, "pg_catalog");
11279 appendPQExpBuffer(query, "SELECT nspname, prsname "
11280 "FROM pg_ts_parser p, pg_namespace n "
11281 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11282 cfginfo->cfgparser);
11283 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11284 nspname = PQgetvalue(res, 0, 0);
11285 prsname = PQgetvalue(res, 0, 1);
11287 /* Make sure we are in proper schema */
11288 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11290 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11291 fmtId(cfginfo->dobj.name));
11293 appendPQExpBuffer(q, " PARSER = ");
11294 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11295 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11296 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11300 resetPQExpBuffer(query);
11301 appendPQExpBuffer(query,
11303 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11304 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11305 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11306 "FROM pg_catalog.pg_ts_config_map AS m \n"
11307 "WHERE m.mapcfg = '%u' \n"
11308 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11309 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11311 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11312 ntups = PQntuples(res);
11314 i_tokenname = PQfnumber(res, "tokenname");
11315 i_dictname = PQfnumber(res, "dictname");
11317 for (i = 0; i < ntups; i++)
11319 char *tokenname = PQgetvalue(res, i, i_tokenname);
11320 char *dictname = PQgetvalue(res, i, i_dictname);
11323 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11325 /* starting a new token type, so start a new command */
11327 appendPQExpBuffer(q, ";\n");
11328 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11329 fmtId(cfginfo->dobj.name));
11330 /* tokenname needs quoting, dictname does NOT */
11331 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11332 fmtId(tokenname), dictname);
11335 appendPQExpBuffer(q, ", %s", dictname);
11339 appendPQExpBuffer(q, ";\n");
11344 * DROP must be fully qualified in case same name appears in pg_catalog
11346 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11347 fmtId(cfginfo->dobj.namespace->dobj.name));
11348 appendPQExpBuffer(delq, ".%s;\n",
11349 fmtId(cfginfo->dobj.name));
11351 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11352 fmtId(cfginfo->dobj.name));
11354 if (binary_upgrade)
11355 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11357 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11358 cfginfo->dobj.name,
11359 cfginfo->dobj.namespace->dobj.name,
11362 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11363 q->data, delq->data, NULL,
11364 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11367 /* Dump Configuration Comments */
11368 dumpComment(fout, labelq->data,
11369 NULL, cfginfo->rolname,
11370 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11372 destroyPQExpBuffer(q);
11373 destroyPQExpBuffer(delq);
11374 destroyPQExpBuffer(labelq);
11375 destroyPQExpBuffer(query);
11379 * dumpForeignDataWrapper
11380 * write out a single foreign-data wrapper definition
11383 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11387 PQExpBuffer labelq;
11390 /* Skip if not to be dumped */
11391 if (!fdwinfo->dobj.dump || dataOnly)
11395 * FDWs that belong to an extension are dumped based on their "dump"
11396 * field. Otherwise omit them if we are only dumping some specific object.
11398 if (!fdwinfo->dobj.ext_member)
11399 if (!include_everything)
11402 q = createPQExpBuffer();
11403 delq = createPQExpBuffer();
11404 labelq = createPQExpBuffer();
11406 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11408 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11411 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11412 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11414 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11415 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11417 if (strlen(fdwinfo->fdwoptions) > 0)
11418 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11420 appendPQExpBuffer(q, ";\n");
11422 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11425 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11428 if (binary_upgrade)
11429 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11431 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11432 fdwinfo->dobj.name,
11436 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11437 q->data, delq->data, NULL,
11438 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11441 /* Handle the ACL */
11442 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11443 "FOREIGN DATA WRAPPER",
11444 qfdwname, NULL, fdwinfo->dobj.name,
11445 NULL, fdwinfo->rolname,
11448 /* Dump Foreign Data Wrapper Comments */
11449 dumpComment(fout, labelq->data,
11450 NULL, fdwinfo->rolname,
11451 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11455 destroyPQExpBuffer(q);
11456 destroyPQExpBuffer(delq);
11457 destroyPQExpBuffer(labelq);
11461 * dumpForeignServer
11462 * write out a foreign server definition
11465 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11469 PQExpBuffer labelq;
11475 /* Skip if not to be dumped */
11476 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11479 q = createPQExpBuffer();
11480 delq = createPQExpBuffer();
11481 labelq = createPQExpBuffer();
11482 query = createPQExpBuffer();
11484 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11486 /* look up the foreign-data wrapper */
11487 selectSourceSchema(fout, "pg_catalog");
11488 appendPQExpBuffer(query, "SELECT fdwname "
11489 "FROM pg_foreign_data_wrapper w "
11490 "WHERE w.oid = '%u'",
11492 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11493 fdwname = PQgetvalue(res, 0, 0);
11495 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11496 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11498 appendPQExpBuffer(q, " TYPE ");
11499 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11501 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11503 appendPQExpBuffer(q, " VERSION ");
11504 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11507 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11508 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11510 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11511 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11513 appendPQExpBuffer(q, ";\n");
11515 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11518 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11520 if (binary_upgrade)
11521 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11523 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11524 srvinfo->dobj.name,
11528 false, "SERVER", SECTION_PRE_DATA,
11529 q->data, delq->data, NULL,
11530 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11533 /* Handle the ACL */
11534 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11536 qsrvname, NULL, srvinfo->dobj.name,
11537 NULL, srvinfo->rolname,
11540 /* Dump user mappings */
11541 dumpUserMappings(fout,
11542 srvinfo->dobj.name, NULL,
11544 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11546 /* Dump Foreign Server Comments */
11547 dumpComment(fout, labelq->data,
11548 NULL, srvinfo->rolname,
11549 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11553 destroyPQExpBuffer(q);
11554 destroyPQExpBuffer(delq);
11555 destroyPQExpBuffer(labelq);
11561 * This routine is used to dump any user mappings associated with the
11562 * server handed to this routine. Should be called after ArchiveEntry()
11566 dumpUserMappings(Archive *fout,
11567 const char *servername, const char *namespace,
11569 CatalogId catalogId, DumpId dumpId)
11581 q = createPQExpBuffer();
11582 tag = createPQExpBuffer();
11583 delq = createPQExpBuffer();
11584 query = createPQExpBuffer();
11587 * We read from the publicly accessible view pg_user_mappings, so as not
11588 * to fail if run by a non-superuser. Note that the view will show
11589 * umoptions as null if the user hasn't got privileges for the associated
11590 * server; this means that pg_dump will dump such a mapping, but with no
11591 * OPTIONS clause. A possible alternative is to skip such mappings
11592 * altogether, but it's not clear that that's an improvement.
11594 selectSourceSchema(fout, "pg_catalog");
11596 appendPQExpBuffer(query,
11598 "array_to_string(ARRAY("
11599 "SELECT quote_ident(option_name) || ' ' || "
11600 "quote_literal(option_value) "
11601 "FROM pg_options_to_table(umoptions) "
11602 "ORDER BY option_name"
11603 "), E',\n ') AS umoptions "
11604 "FROM pg_user_mappings "
11605 "WHERE srvid = '%u' "
11606 "ORDER BY usename",
11609 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11611 ntups = PQntuples(res);
11612 i_usename = PQfnumber(res, "usename");
11613 i_umoptions = PQfnumber(res, "umoptions");
11615 for (i = 0; i < ntups; i++)
11620 usename = PQgetvalue(res, i, i_usename);
11621 umoptions = PQgetvalue(res, i, i_umoptions);
11623 resetPQExpBuffer(q);
11624 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11625 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11627 if (umoptions && strlen(umoptions) > 0)
11628 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11630 appendPQExpBuffer(q, ";\n");
11632 resetPQExpBuffer(delq);
11633 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11634 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11636 resetPQExpBuffer(tag);
11637 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11638 usename, servername);
11640 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11645 "USER MAPPING", SECTION_PRE_DATA,
11646 q->data, delq->data, NULL,
11653 destroyPQExpBuffer(query);
11654 destroyPQExpBuffer(delq);
11655 destroyPQExpBuffer(q);
11659 * Write out default privileges information
11662 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11668 /* Skip if not to be dumped */
11669 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11672 q = createPQExpBuffer();
11673 tag = createPQExpBuffer();
11675 switch (daclinfo->defaclobjtype)
11677 case DEFACLOBJ_RELATION:
11680 case DEFACLOBJ_SEQUENCE:
11681 type = "SEQUENCES";
11683 case DEFACLOBJ_FUNCTION:
11684 type = "FUNCTIONS";
11687 /* shouldn't get here */
11688 exit_horribly(NULL,
11689 "unknown object type (%d) in default privileges\n",
11690 (int) daclinfo->defaclobjtype);
11691 type = ""; /* keep compiler quiet */
11694 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11696 /* build the actual command(s) for this tuple */
11697 if (!buildDefaultACLCommands(type,
11698 daclinfo->dobj.namespace != NULL ?
11699 daclinfo->dobj.namespace->dobj.name : NULL,
11700 daclinfo->defaclacl,
11701 daclinfo->defaclrole,
11702 fout->remoteVersion,
11704 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11705 daclinfo->defaclacl);
11707 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11709 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11711 daclinfo->defaclrole,
11712 false, "DEFAULT ACL", SECTION_NONE,
11714 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11717 destroyPQExpBuffer(tag);
11718 destroyPQExpBuffer(q);
11722 * Write out grant/revoke information
11724 * 'objCatId' is the catalog ID of the underlying object.
11725 * 'objDumpId' is the dump ID of the underlying object.
11726 * 'type' must be one of
11727 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11728 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11729 * 'name' is the formatted name of the object. Must be quoted etc. already.
11730 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11731 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11732 * 'nspname' is the namespace the object is in (NULL if none).
11733 * 'owner' is the owner, NULL if there is no owner (for languages).
11734 * 'acls' is the string read out of the fooacl system catalog field;
11735 * it will be parsed here.
11739 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11740 const char *type, const char *name, const char *subname,
11741 const char *tag, const char *nspname, const char *owner,
11746 /* Do nothing if ACL dump is not enabled */
11750 /* --data-only skips ACLs *except* BLOB ACLs */
11751 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11754 sql = createPQExpBuffer();
11756 if (!buildACLCommands(name, subname, type, acls, owner,
11757 "", fout->remoteVersion, sql))
11758 exit_horribly(NULL,
11759 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11763 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11766 owner ? owner : "",
11767 false, "ACL", SECTION_NONE,
11768 sql->data, "", NULL,
11772 destroyPQExpBuffer(sql);
11778 * This routine is used to dump any security labels associated with the
11779 * object handed to this routine. The routine takes a constant character
11780 * string for the target part of the security-label command, plus
11781 * the namespace and owner of the object (for labeling the ArchiveEntry),
11782 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11783 * plus the dump ID for the object (for setting a dependency).
11784 * If a matching pg_seclabel entry is found, it is dumped.
11786 * Note: although this routine takes a dumpId for dependency purposes,
11787 * that purpose is just to mark the dependency in the emitted dump file
11788 * for possible future use by pg_restore. We do NOT use it for determining
11789 * ordering of the label in the dump file, because this routine is called
11790 * after dependency sorting occurs. This routine should be called just after
11791 * calling ArchiveEntry() for the specified object.
11794 dumpSecLabel(Archive *fout, const char *target,
11795 const char *namespace, const char *owner,
11796 CatalogId catalogId, int subid, DumpId dumpId)
11798 SecLabelItem *labels;
11803 /* do nothing, if --no-security-labels is supplied */
11804 if (no_security_labels)
11807 /* Comments are schema not data ... except blob comments are data */
11808 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11819 /* Search for security labels associated with catalogId, using table */
11820 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11822 query = createPQExpBuffer();
11824 for (i = 0; i < nlabels; i++)
11827 * Ignore label entries for which the subid doesn't match.
11829 if (labels[i].objsubid != subid)
11832 appendPQExpBuffer(query,
11833 "SECURITY LABEL FOR %s ON %s IS ",
11834 fmtId(labels[i].provider), target);
11835 appendStringLiteralAH(query, labels[i].label, fout);
11836 appendPQExpBuffer(query, ";\n");
11839 if (query->len > 0)
11841 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11842 target, namespace, NULL, owner,
11843 false, "SECURITY LABEL", SECTION_NONE,
11844 query->data, "", NULL,
11848 destroyPQExpBuffer(query);
11852 * dumpTableSecLabel
11854 * As above, but dump security label for both the specified table (or view)
11858 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11860 SecLabelItem *labels;
11864 PQExpBuffer target;
11866 /* do nothing, if --no-security-labels is supplied */
11867 if (no_security_labels)
11870 /* SecLabel are SCHEMA not data */
11874 /* Search for comments associated with relation, using table */
11875 nlabels = findSecLabels(fout,
11876 tbinfo->dobj.catId.tableoid,
11877 tbinfo->dobj.catId.oid,
11880 /* If security labels exist, build SECURITY LABEL statements */
11884 query = createPQExpBuffer();
11885 target = createPQExpBuffer();
11887 for (i = 0; i < nlabels; i++)
11889 const char *colname;
11890 const char *provider = labels[i].provider;
11891 const char *label = labels[i].label;
11892 int objsubid = labels[i].objsubid;
11894 resetPQExpBuffer(target);
11897 appendPQExpBuffer(target, "%s %s", reltypename,
11898 fmtId(tbinfo->dobj.name));
11902 colname = getAttrName(objsubid, tbinfo);
11903 /* first fmtId result must be consumed before calling it again */
11904 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11905 appendPQExpBuffer(target, ".%s", fmtId(colname));
11907 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11908 fmtId(provider), target->data);
11909 appendStringLiteralAH(query, label, fout);
11910 appendPQExpBuffer(query, ";\n");
11912 if (query->len > 0)
11914 resetPQExpBuffer(target);
11915 appendPQExpBuffer(target, "%s %s", reltypename,
11916 fmtId(tbinfo->dobj.name));
11917 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11919 tbinfo->dobj.namespace->dobj.name,
11920 NULL, tbinfo->rolname,
11921 false, "SECURITY LABEL", SECTION_NONE,
11922 query->data, "", NULL,
11923 &(tbinfo->dobj.dumpId), 1,
11926 destroyPQExpBuffer(query);
11927 destroyPQExpBuffer(target);
11933 * Find the security label(s), if any, associated with the given object.
11934 * All the objsubid values associated with the given classoid/objoid are
11935 * found with one search.
11938 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11940 /* static storage for table of security labels */
11941 static SecLabelItem *labels = NULL;
11942 static int nlabels = -1;
11944 SecLabelItem *middle = NULL;
11946 SecLabelItem *high;
11949 /* Get security labels if we didn't already */
11951 nlabels = collectSecLabels(fout, &labels);
11953 if (nlabels <= 0) /* no labels, so no match is possible */
11960 * Do binary search to find some item matching the object.
11963 high = &labels[nlabels - 1];
11964 while (low <= high)
11966 middle = low + (high - low) / 2;
11968 if (classoid < middle->classoid)
11970 else if (classoid > middle->classoid)
11972 else if (objoid < middle->objoid)
11974 else if (objoid > middle->objoid)
11977 break; /* found a match */
11980 if (low > high) /* no matches */
11987 * Now determine how many items match the object. The search loop
11988 * invariant still holds: only items between low and high inclusive could
11992 while (middle > low)
11994 if (classoid != middle[-1].classoid ||
11995 objoid != middle[-1].objoid)
12004 while (middle <= high)
12006 if (classoid != middle->classoid ||
12007 objoid != middle->objoid)
12019 * Construct a table of all security labels available for database objects.
12020 * It's much faster to pull them all at once.
12022 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12025 collectSecLabels(Archive *fout, SecLabelItem **items)
12036 SecLabelItem *labels;
12038 query = createPQExpBuffer();
12040 appendPQExpBuffer(query,
12041 "SELECT label, provider, classoid, objoid, objsubid "
12042 "FROM pg_catalog.pg_seclabel "
12043 "ORDER BY classoid, objoid, objsubid");
12045 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12047 /* Construct lookup table containing OIDs in numeric form */
12048 i_label = PQfnumber(res, "label");
12049 i_provider = PQfnumber(res, "provider");
12050 i_classoid = PQfnumber(res, "classoid");
12051 i_objoid = PQfnumber(res, "objoid");
12052 i_objsubid = PQfnumber(res, "objsubid");
12054 ntups = PQntuples(res);
12056 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12058 for (i = 0; i < ntups; i++)
12060 labels[i].label = PQgetvalue(res, i, i_label);
12061 labels[i].provider = PQgetvalue(res, i, i_provider);
12062 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12063 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12064 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12067 /* Do NOT free the PGresult since we are keeping pointers into it */
12068 destroyPQExpBuffer(query);
12076 * write out to fout the declarations (not data) of a user-defined table
12079 dumpTable(Archive *fout, TableInfo *tbinfo)
12081 if (tbinfo->dobj.dump)
12085 if (tbinfo->relkind == RELKIND_SEQUENCE)
12086 dumpSequence(fout, tbinfo);
12087 else if (!dataOnly)
12088 dumpTableSchema(fout, tbinfo);
12090 /* Handle the ACL here */
12091 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12092 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12093 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12095 namecopy, NULL, tbinfo->dobj.name,
12096 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12100 * Handle column ACLs, if any. Note: we pull these with a separate
12101 * query rather than trying to fetch them during getTableAttrs, so
12102 * that we won't miss ACLs on system columns.
12104 if (fout->remoteVersion >= 80400)
12106 PQExpBuffer query = createPQExpBuffer();
12110 appendPQExpBuffer(query,
12111 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12112 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12114 tbinfo->dobj.catId.oid);
12115 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12117 for (i = 0; i < PQntuples(res); i++)
12119 char *attname = PQgetvalue(res, i, 0);
12120 char *attacl = PQgetvalue(res, i, 1);
12124 attnamecopy = pg_strdup(fmtId(attname));
12125 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12126 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12127 /* Column's GRANT type is always TABLE */
12128 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12129 namecopy, attnamecopy, acltag,
12130 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12136 destroyPQExpBuffer(query);
12145 * write the declaration (not data) of one user-defined table or view
12148 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12150 PQExpBuffer query = createPQExpBuffer();
12151 PQExpBuffer q = createPQExpBuffer();
12152 PQExpBuffer delq = createPQExpBuffer();
12153 PQExpBuffer labelq = createPQExpBuffer();
12156 TableInfo **parents;
12157 int actual_atts; /* number of attrs in this CREATE statment */
12158 const char *reltypename;
12165 /* Make sure we are in proper schema */
12166 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12168 if (binary_upgrade)
12169 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12170 tbinfo->dobj.catId.oid);
12172 /* Is it a table or a view? */
12173 if (tbinfo->relkind == RELKIND_VIEW)
12177 reltypename = "VIEW";
12179 /* Fetch the view definition */
12180 if (fout->remoteVersion >= 70300)
12182 /* Beginning in 7.3, viewname is not unique; rely on OID */
12183 appendPQExpBuffer(query,
12184 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12185 tbinfo->dobj.catId.oid);
12189 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12190 "FROM pg_views WHERE viewname = ");
12191 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12192 appendPQExpBuffer(query, ";");
12195 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12197 if (PQntuples(res) != 1)
12199 if (PQntuples(res) < 1)
12200 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12201 tbinfo->dobj.name);
12203 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12204 tbinfo->dobj.name);
12207 viewdef = PQgetvalue(res, 0, 0);
12209 if (strlen(viewdef) == 0)
12210 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12211 tbinfo->dobj.name);
12214 * DROP must be fully qualified in case same name appears in
12217 appendPQExpBuffer(delq, "DROP VIEW %s.",
12218 fmtId(tbinfo->dobj.namespace->dobj.name));
12219 appendPQExpBuffer(delq, "%s;\n",
12220 fmtId(tbinfo->dobj.name));
12222 if (binary_upgrade)
12223 binary_upgrade_set_pg_class_oids(fout, q,
12224 tbinfo->dobj.catId.oid, false);
12226 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12227 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12228 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12229 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12231 appendPQExpBuffer(labelq, "VIEW %s",
12232 fmtId(tbinfo->dobj.name));
12238 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12243 reltypename = "FOREIGN TABLE";
12245 /* retrieve name of foreign server and generic options */
12246 appendPQExpBuffer(query,
12247 "SELECT fs.srvname, "
12248 "pg_catalog.array_to_string(ARRAY("
12249 "SELECT pg_catalog.quote_ident(option_name) || "
12250 "' ' || pg_catalog.quote_literal(option_value) "
12251 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12252 "ORDER BY option_name"
12253 "), E',\n ') AS ftoptions "
12254 "FROM pg_catalog.pg_foreign_table ft "
12255 "JOIN pg_catalog.pg_foreign_server fs "
12256 "ON (fs.oid = ft.ftserver) "
12257 "WHERE ft.ftrelid = '%u'",
12258 tbinfo->dobj.catId.oid);
12259 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12260 i_srvname = PQfnumber(res, "srvname");
12261 i_ftoptions = PQfnumber(res, "ftoptions");
12262 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12263 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12268 reltypename = "TABLE";
12272 numParents = tbinfo->numParents;
12273 parents = tbinfo->parents;
12276 * DROP must be fully qualified in case same name appears in
12279 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12280 fmtId(tbinfo->dobj.namespace->dobj.name));
12281 appendPQExpBuffer(delq, "%s;\n",
12282 fmtId(tbinfo->dobj.name));
12284 appendPQExpBuffer(labelq, "%s %s", reltypename,
12285 fmtId(tbinfo->dobj.name));
12287 if (binary_upgrade)
12288 binary_upgrade_set_pg_class_oids(fout, q,
12289 tbinfo->dobj.catId.oid, false);
12291 appendPQExpBuffer(q, "CREATE %s%s %s",
12292 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12295 fmtId(tbinfo->dobj.name));
12298 * Attach to type, if reloftype; except in case of a binary upgrade,
12299 * we dump the table normally and attach it to the type afterward.
12301 if (tbinfo->reloftype && !binary_upgrade)
12302 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12304 /* Dump the attributes */
12306 for (j = 0; j < tbinfo->numatts; j++)
12309 * Normally, dump if it's locally defined in this table, and not
12310 * dropped. But for binary upgrade, we'll dump all the columns,
12311 * and then fix up the dropped and nonlocal cases below.
12313 if (shouldPrintColumn(tbinfo, j))
12316 * Default value --- suppress if to be printed separately.
12318 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12319 !tbinfo->attrdefs[j]->separate);
12322 * Not Null constraint --- suppress if inherited, except in
12323 * binary-upgrade case where that won't work.
12325 bool has_notnull = (tbinfo->notnull[j] &&
12326 (!tbinfo->inhNotNull[j] ||
12329 /* Skip column if fully defined by reloftype */
12330 if (tbinfo->reloftype &&
12331 !has_default && !has_notnull && !binary_upgrade)
12334 /* Format properly if not first attr */
12335 if (actual_atts == 0)
12336 appendPQExpBuffer(q, " (");
12338 appendPQExpBuffer(q, ",");
12339 appendPQExpBuffer(q, "\n ");
12342 /* Attribute name */
12343 appendPQExpBuffer(q, "%s ",
12344 fmtId(tbinfo->attnames[j]));
12346 if (tbinfo->attisdropped[j])
12349 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12350 * so we will not have gotten a valid type name; insert
12351 * INTEGER as a stopgap. We'll clean things up later.
12353 appendPQExpBuffer(q, "INTEGER /* dummy */");
12354 /* Skip all the rest, too */
12358 /* Attribute type */
12359 if (tbinfo->reloftype && !binary_upgrade)
12361 appendPQExpBuffer(q, "WITH OPTIONS");
12363 else if (fout->remoteVersion >= 70100)
12365 appendPQExpBuffer(q, "%s",
12366 tbinfo->atttypnames[j]);
12370 /* If no format_type, fake it */
12371 appendPQExpBuffer(q, "%s",
12372 myFormatType(tbinfo->atttypnames[j],
12373 tbinfo->atttypmod[j]));
12376 /* Add collation if not default for the type */
12377 if (OidIsValid(tbinfo->attcollation[j]))
12381 coll = findCollationByOid(tbinfo->attcollation[j]);
12384 /* always schema-qualify, don't try to be smart */
12385 appendPQExpBuffer(q, " COLLATE %s.",
12386 fmtId(coll->dobj.namespace->dobj.name));
12387 appendPQExpBuffer(q, "%s",
12388 fmtId(coll->dobj.name));
12393 appendPQExpBuffer(q, " DEFAULT %s",
12394 tbinfo->attrdefs[j]->adef_expr);
12397 appendPQExpBuffer(q, " NOT NULL");
12402 * Add non-inherited CHECK constraints, if any.
12404 for (j = 0; j < tbinfo->ncheck; j++)
12406 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12408 if (constr->separate || !constr->conislocal)
12411 if (actual_atts == 0)
12412 appendPQExpBuffer(q, " (\n ");
12414 appendPQExpBuffer(q, ",\n ");
12416 appendPQExpBuffer(q, "CONSTRAINT %s ",
12417 fmtId(constr->dobj.name));
12418 appendPQExpBuffer(q, "%s", constr->condef);
12424 appendPQExpBuffer(q, "\n)");
12425 else if (!(tbinfo->reloftype && !binary_upgrade))
12428 * We must have a parenthesized attribute list, even though empty,
12429 * when not using the OF TYPE syntax.
12431 appendPQExpBuffer(q, " (\n)");
12434 if (numParents > 0 && !binary_upgrade)
12436 appendPQExpBuffer(q, "\nINHERITS (");
12437 for (k = 0; k < numParents; k++)
12439 TableInfo *parentRel = parents[k];
12442 appendPQExpBuffer(q, ", ");
12443 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12444 appendPQExpBuffer(q, "%s.",
12445 fmtId(parentRel->dobj.namespace->dobj.name));
12446 appendPQExpBuffer(q, "%s",
12447 fmtId(parentRel->dobj.name));
12449 appendPQExpBuffer(q, ")");
12452 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12453 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12455 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12456 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12458 bool addcomma = false;
12460 appendPQExpBuffer(q, "\nWITH (");
12461 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12464 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12466 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12468 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12469 tbinfo->toast_reloptions);
12471 appendPQExpBuffer(q, ")");
12474 /* Dump generic options if any */
12475 if (ftoptions && ftoptions[0])
12476 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12478 appendPQExpBuffer(q, ";\n");
12481 * To create binary-compatible heap files, we have to ensure the same
12482 * physical column order, including dropped columns, as in the
12483 * original. Therefore, we create dropped columns above and drop them
12484 * here, also updating their attlen/attalign values so that the
12485 * dropped column can be skipped properly. (We do not bother with
12486 * restoring the original attbyval setting.) Also, inheritance
12487 * relationships are set up by doing ALTER INHERIT rather than using
12488 * an INHERITS clause --- the latter would possibly mess up the column
12489 * order. That also means we have to take care about setting
12490 * attislocal correctly, plus fix up any inherited CHECK constraints.
12491 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12493 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12495 for (j = 0; j < tbinfo->numatts; j++)
12497 if (tbinfo->attisdropped[j])
12499 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12500 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12501 "SET attlen = %d, "
12502 "attalign = '%c', attbyval = false\n"
12503 "WHERE attname = ",
12505 tbinfo->attalign[j]);
12506 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12507 appendPQExpBuffer(q, "\n AND attrelid = ");
12508 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12509 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12511 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12512 fmtId(tbinfo->dobj.name));
12513 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12514 fmtId(tbinfo->attnames[j]));
12516 else if (!tbinfo->attislocal[j])
12518 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12519 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12520 "SET attislocal = false\n"
12521 "WHERE attname = ");
12522 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12523 appendPQExpBuffer(q, "\n AND attrelid = ");
12524 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12525 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12529 for (k = 0; k < tbinfo->ncheck; k++)
12531 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12533 if (constr->separate || constr->conislocal)
12536 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12537 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12538 fmtId(tbinfo->dobj.name));
12539 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12540 fmtId(constr->dobj.name));
12541 appendPQExpBuffer(q, "%s;\n", constr->condef);
12542 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12543 "SET conislocal = false\n"
12544 "WHERE contype = 'c' AND conname = ");
12545 appendStringLiteralAH(q, constr->dobj.name, fout);
12546 appendPQExpBuffer(q, "\n AND conrelid = ");
12547 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12548 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12551 if (numParents > 0)
12553 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12554 for (k = 0; k < numParents; k++)
12556 TableInfo *parentRel = parents[k];
12558 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12559 fmtId(tbinfo->dobj.name));
12560 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12561 appendPQExpBuffer(q, "%s.",
12562 fmtId(parentRel->dobj.namespace->dobj.name));
12563 appendPQExpBuffer(q, "%s;\n",
12564 fmtId(parentRel->dobj.name));
12568 if (tbinfo->reloftype)
12570 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12571 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12572 fmtId(tbinfo->dobj.name),
12573 tbinfo->reloftype);
12576 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12577 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12578 "SET relfrozenxid = '%u'\n"
12580 tbinfo->frozenxid);
12581 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12582 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12584 if (tbinfo->toast_oid)
12586 /* We preserve the toast oids, so we can use it during restore */
12587 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12588 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12589 "SET relfrozenxid = '%u'\n"
12590 "WHERE oid = '%u';\n",
12591 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12596 * Dump additional per-column properties that we can't handle in the
12597 * main CREATE TABLE command.
12599 for (j = 0; j < tbinfo->numatts; j++)
12601 /* None of this applies to dropped columns */
12602 if (tbinfo->attisdropped[j])
12606 * If we didn't dump the column definition explicitly above, and
12607 * it is NOT NULL and did not inherit that property from a parent,
12608 * we have to mark it separately.
12610 if (!shouldPrintColumn(tbinfo, j) &&
12611 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12613 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12614 fmtId(tbinfo->dobj.name));
12615 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12616 fmtId(tbinfo->attnames[j]));
12620 * Dump per-column statistics information. We only issue an ALTER
12621 * TABLE statement if the attstattarget entry for this column is
12622 * non-negative (i.e. it's not the default value)
12624 if (tbinfo->attstattarget[j] >= 0)
12626 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12627 fmtId(tbinfo->dobj.name));
12628 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12629 fmtId(tbinfo->attnames[j]));
12630 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12631 tbinfo->attstattarget[j]);
12635 * Dump per-column storage information. The statement is only
12636 * dumped if the storage has been changed from the type's default.
12638 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12640 switch (tbinfo->attstorage[j])
12646 storage = "EXTERNAL";
12652 storage = "EXTENDED";
12659 * Only dump the statement if it's a storage type we recognize
12661 if (storage != NULL)
12663 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12664 fmtId(tbinfo->dobj.name));
12665 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12666 fmtId(tbinfo->attnames[j]));
12667 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12673 * Dump per-column attributes.
12675 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12677 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12678 fmtId(tbinfo->dobj.name));
12679 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12680 fmtId(tbinfo->attnames[j]));
12681 appendPQExpBuffer(q, "SET (%s);\n",
12682 tbinfo->attoptions[j]);
12686 * Dump per-column fdw options.
12688 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12689 tbinfo->attfdwoptions[j] &&
12690 tbinfo->attfdwoptions[j][0] != '\0')
12692 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12693 fmtId(tbinfo->dobj.name));
12694 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12695 fmtId(tbinfo->attnames[j]));
12696 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12697 tbinfo->attfdwoptions[j]);
12702 if (binary_upgrade)
12703 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12705 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12707 tbinfo->dobj.namespace->dobj.name,
12708 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12710 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12711 reltypename, SECTION_PRE_DATA,
12712 q->data, delq->data, NULL,
12713 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12717 /* Dump Table Comments */
12718 dumpTableComment(fout, tbinfo, reltypename);
12720 /* Dump Table Security Labels */
12721 dumpTableSecLabel(fout, tbinfo, reltypename);
12723 /* Dump comments on inlined table constraints */
12724 for (j = 0; j < tbinfo->ncheck; j++)
12726 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12728 if (constr->separate || !constr->conislocal)
12731 dumpTableConstraintComment(fout, constr);
12734 destroyPQExpBuffer(query);
12735 destroyPQExpBuffer(q);
12736 destroyPQExpBuffer(delq);
12737 destroyPQExpBuffer(labelq);
12741 * dumpAttrDef --- dump an attribute's default-value declaration
12744 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12746 TableInfo *tbinfo = adinfo->adtable;
12747 int adnum = adinfo->adnum;
12751 /* Skip if table definition not to be dumped */
12752 if (!tbinfo->dobj.dump || dataOnly)
12755 /* Skip if not "separate"; it was dumped in the table's definition */
12756 if (!adinfo->separate)
12759 q = createPQExpBuffer();
12760 delq = createPQExpBuffer();
12762 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12763 fmtId(tbinfo->dobj.name));
12764 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12765 fmtId(tbinfo->attnames[adnum - 1]),
12766 adinfo->adef_expr);
12769 * DROP must be fully qualified in case same name appears in pg_catalog
12771 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12772 fmtId(tbinfo->dobj.namespace->dobj.name));
12773 appendPQExpBuffer(delq, "%s ",
12774 fmtId(tbinfo->dobj.name));
12775 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12776 fmtId(tbinfo->attnames[adnum - 1]));
12778 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12779 tbinfo->attnames[adnum - 1],
12780 tbinfo->dobj.namespace->dobj.name,
12783 false, "DEFAULT", SECTION_PRE_DATA,
12784 q->data, delq->data, NULL,
12785 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12788 destroyPQExpBuffer(q);
12789 destroyPQExpBuffer(delq);
12793 * getAttrName: extract the correct name for an attribute
12795 * The array tblInfo->attnames[] only provides names of user attributes;
12796 * if a system attribute number is supplied, we have to fake it.
12797 * We also do a little bit of bounds checking for safety's sake.
12799 static const char *
12800 getAttrName(int attrnum, TableInfo *tblInfo)
12802 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12803 return tblInfo->attnames[attrnum - 1];
12806 case SelfItemPointerAttributeNumber:
12808 case ObjectIdAttributeNumber:
12810 case MinTransactionIdAttributeNumber:
12812 case MinCommandIdAttributeNumber:
12814 case MaxTransactionIdAttributeNumber:
12816 case MaxCommandIdAttributeNumber:
12818 case TableOidAttributeNumber:
12821 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12822 attrnum, tblInfo->dobj.name);
12823 return NULL; /* keep compiler quiet */
12828 * write out to fout a user-defined index
12831 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12833 TableInfo *tbinfo = indxinfo->indextable;
12836 PQExpBuffer labelq;
12841 q = createPQExpBuffer();
12842 delq = createPQExpBuffer();
12843 labelq = createPQExpBuffer();
12845 appendPQExpBuffer(labelq, "INDEX %s",
12846 fmtId(indxinfo->dobj.name));
12849 * If there's an associated constraint, don't dump the index per se, but
12850 * do dump any comment for it. (This is safe because dependency ordering
12851 * will have ensured the constraint is emitted first.)
12853 if (indxinfo->indexconstraint == 0)
12855 if (binary_upgrade)
12856 binary_upgrade_set_pg_class_oids(fout, q,
12857 indxinfo->dobj.catId.oid, true);
12859 /* Plain secondary index */
12860 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12862 /* If the index is clustered, we need to record that. */
12863 if (indxinfo->indisclustered)
12865 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12866 fmtId(tbinfo->dobj.name));
12867 appendPQExpBuffer(q, " ON %s;\n",
12868 fmtId(indxinfo->dobj.name));
12872 * DROP must be fully qualified in case same name appears in
12875 appendPQExpBuffer(delq, "DROP INDEX %s.",
12876 fmtId(tbinfo->dobj.namespace->dobj.name));
12877 appendPQExpBuffer(delq, "%s;\n",
12878 fmtId(indxinfo->dobj.name));
12880 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12881 indxinfo->dobj.name,
12882 tbinfo->dobj.namespace->dobj.name,
12883 indxinfo->tablespace,
12884 tbinfo->rolname, false,
12885 "INDEX", SECTION_POST_DATA,
12886 q->data, delq->data, NULL,
12887 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12891 /* Dump Index Comments */
12892 dumpComment(fout, labelq->data,
12893 tbinfo->dobj.namespace->dobj.name,
12895 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12897 destroyPQExpBuffer(q);
12898 destroyPQExpBuffer(delq);
12899 destroyPQExpBuffer(labelq);
12904 * write out to fout a user-defined constraint
12907 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12909 TableInfo *tbinfo = coninfo->contable;
12913 /* Skip if not to be dumped */
12914 if (!coninfo->dobj.dump || dataOnly)
12917 q = createPQExpBuffer();
12918 delq = createPQExpBuffer();
12920 if (coninfo->contype == 'p' ||
12921 coninfo->contype == 'u' ||
12922 coninfo->contype == 'x')
12924 /* Index-related constraint */
12925 IndxInfo *indxinfo;
12928 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12930 if (indxinfo == NULL)
12931 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12932 coninfo->dobj.name);
12934 if (binary_upgrade)
12935 binary_upgrade_set_pg_class_oids(fout, q,
12936 indxinfo->dobj.catId.oid, true);
12938 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12939 fmtId(tbinfo->dobj.name));
12940 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12941 fmtId(coninfo->dobj.name));
12943 if (coninfo->condef)
12945 /* pg_get_constraintdef should have provided everything */
12946 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12950 appendPQExpBuffer(q, "%s (",
12951 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12952 for (k = 0; k < indxinfo->indnkeys; k++)
12954 int indkey = (int) indxinfo->indkeys[k];
12955 const char *attname;
12957 if (indkey == InvalidAttrNumber)
12959 attname = getAttrName(indkey, tbinfo);
12961 appendPQExpBuffer(q, "%s%s",
12962 (k == 0) ? "" : ", ",
12966 appendPQExpBuffer(q, ")");
12968 if (indxinfo->options && strlen(indxinfo->options) > 0)
12969 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12971 if (coninfo->condeferrable)
12973 appendPQExpBuffer(q, " DEFERRABLE");
12974 if (coninfo->condeferred)
12975 appendPQExpBuffer(q, " INITIALLY DEFERRED");
12978 appendPQExpBuffer(q, ";\n");
12981 /* If the index is clustered, we need to record that. */
12982 if (indxinfo->indisclustered)
12984 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12985 fmtId(tbinfo->dobj.name));
12986 appendPQExpBuffer(q, " ON %s;\n",
12987 fmtId(indxinfo->dobj.name));
12991 * DROP must be fully qualified in case same name appears in
12994 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12995 fmtId(tbinfo->dobj.namespace->dobj.name));
12996 appendPQExpBuffer(delq, "%s ",
12997 fmtId(tbinfo->dobj.name));
12998 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12999 fmtId(coninfo->dobj.name));
13001 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13002 coninfo->dobj.name,
13003 tbinfo->dobj.namespace->dobj.name,
13004 indxinfo->tablespace,
13005 tbinfo->rolname, false,
13006 "CONSTRAINT", SECTION_POST_DATA,
13007 q->data, delq->data, NULL,
13008 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13011 else if (coninfo->contype == 'f')
13014 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13015 * current table data is not processed
13017 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13018 fmtId(tbinfo->dobj.name));
13019 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13020 fmtId(coninfo->dobj.name),
13024 * DROP must be fully qualified in case same name appears in
13027 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13028 fmtId(tbinfo->dobj.namespace->dobj.name));
13029 appendPQExpBuffer(delq, "%s ",
13030 fmtId(tbinfo->dobj.name));
13031 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13032 fmtId(coninfo->dobj.name));
13034 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13035 coninfo->dobj.name,
13036 tbinfo->dobj.namespace->dobj.name,
13038 tbinfo->rolname, false,
13039 "FK CONSTRAINT", SECTION_POST_DATA,
13040 q->data, delq->data, NULL,
13041 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13044 else if (coninfo->contype == 'c' && tbinfo)
13046 /* CHECK constraint on a table */
13048 /* Ignore if not to be dumped separately */
13049 if (coninfo->separate)
13051 /* add ONLY if we do not want it to propagate to children */
13052 appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13053 coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13054 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13055 fmtId(coninfo->dobj.name),
13059 * DROP must be fully qualified in case same name appears in
13062 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13063 fmtId(tbinfo->dobj.namespace->dobj.name));
13064 appendPQExpBuffer(delq, "%s ",
13065 fmtId(tbinfo->dobj.name));
13066 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13067 fmtId(coninfo->dobj.name));
13069 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13070 coninfo->dobj.name,
13071 tbinfo->dobj.namespace->dobj.name,
13073 tbinfo->rolname, false,
13074 "CHECK CONSTRAINT", SECTION_POST_DATA,
13075 q->data, delq->data, NULL,
13076 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13080 else if (coninfo->contype == 'c' && tbinfo == NULL)
13082 /* CHECK constraint on a domain */
13083 TypeInfo *tyinfo = coninfo->condomain;
13085 /* Ignore if not to be dumped separately */
13086 if (coninfo->separate)
13088 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13089 fmtId(tyinfo->dobj.name));
13090 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13091 fmtId(coninfo->dobj.name),
13095 * DROP must be fully qualified in case same name appears in
13098 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13099 fmtId(tyinfo->dobj.namespace->dobj.name));
13100 appendPQExpBuffer(delq, "%s ",
13101 fmtId(tyinfo->dobj.name));
13102 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13103 fmtId(coninfo->dobj.name));
13105 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13106 coninfo->dobj.name,
13107 tyinfo->dobj.namespace->dobj.name,
13109 tyinfo->rolname, false,
13110 "CHECK CONSTRAINT", SECTION_POST_DATA,
13111 q->data, delq->data, NULL,
13112 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13118 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13122 /* Dump Constraint Comments --- only works for table constraints */
13123 if (tbinfo && coninfo->separate)
13124 dumpTableConstraintComment(fout, coninfo);
13126 destroyPQExpBuffer(q);
13127 destroyPQExpBuffer(delq);
13131 * dumpTableConstraintComment --- dump a constraint's comment if any
13133 * This is split out because we need the function in two different places
13134 * depending on whether the constraint is dumped as part of CREATE TABLE
13135 * or as a separate ALTER command.
13138 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13140 TableInfo *tbinfo = coninfo->contable;
13141 PQExpBuffer labelq = createPQExpBuffer();
13143 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13144 fmtId(coninfo->dobj.name));
13145 appendPQExpBuffer(labelq, "ON %s",
13146 fmtId(tbinfo->dobj.name));
13147 dumpComment(fout, labelq->data,
13148 tbinfo->dobj.namespace->dobj.name,
13150 coninfo->dobj.catId, 0,
13151 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13153 destroyPQExpBuffer(labelq);
13157 * findLastBuiltInOid -
13158 * find the last built in oid
13160 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13161 * pg_database entry for the current database
13164 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13168 PQExpBuffer query = createPQExpBuffer();
13170 resetPQExpBuffer(query);
13171 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13172 appendStringLiteralAH(query, dbname, fout);
13174 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13175 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13177 destroyPQExpBuffer(query);
13182 * findLastBuiltInOid -
13183 * find the last built in oid
13185 * For 7.0, we do this by assuming that the last thing that initdb does is to
13186 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13187 * initdb won't be changing anymore, it'll do.
13190 findLastBuiltinOid_V70(Archive *fout)
13195 res = ExecuteSqlQueryForSingleRow(fout,
13196 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13197 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13203 dumpSequence(Archive *fout, TableInfo *tbinfo)
13216 PQExpBuffer query = createPQExpBuffer();
13217 PQExpBuffer delqry = createPQExpBuffer();
13218 PQExpBuffer labelq = createPQExpBuffer();
13220 /* Make sure we are in proper schema */
13221 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13223 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13224 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13226 if (fout->remoteVersion >= 80400)
13228 appendPQExpBuffer(query,
13229 "SELECT sequence_name, "
13230 "start_value, last_value, increment_by, "
13231 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13232 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13234 "END AS max_value, "
13235 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13236 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13238 "END AS min_value, "
13239 "cache_value, is_cycled, is_called from %s",
13241 fmtId(tbinfo->dobj.name));
13245 appendPQExpBuffer(query,
13246 "SELECT sequence_name, "
13247 "0 AS start_value, last_value, increment_by, "
13248 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13249 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13251 "END AS max_value, "
13252 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13253 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13255 "END AS min_value, "
13256 "cache_value, is_cycled, is_called from %s",
13258 fmtId(tbinfo->dobj.name));
13261 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13263 if (PQntuples(res) != 1)
13265 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13266 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13268 tbinfo->dobj.name, PQntuples(res));
13272 /* Disable this check: it fails if sequence has been renamed */
13274 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13276 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13277 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13282 startv = PQgetvalue(res, 0, 1);
13283 last = PQgetvalue(res, 0, 2);
13284 incby = PQgetvalue(res, 0, 3);
13285 if (!PQgetisnull(res, 0, 4))
13286 maxv = PQgetvalue(res, 0, 4);
13287 if (!PQgetisnull(res, 0, 5))
13288 minv = PQgetvalue(res, 0, 5);
13289 cache = PQgetvalue(res, 0, 6);
13290 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13291 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13294 * The logic we use for restoring sequences is as follows:
13296 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13297 * last_val for start if called is false, else use min_val for start_val).
13298 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13299 * BY command for it.
13301 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13306 * DROP must be fully qualified in case same name appears in
13309 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13310 fmtId(tbinfo->dobj.namespace->dobj.name));
13311 appendPQExpBuffer(delqry, "%s;\n",
13312 fmtId(tbinfo->dobj.name));
13314 resetPQExpBuffer(query);
13316 if (binary_upgrade)
13318 binary_upgrade_set_pg_class_oids(fout, query,
13319 tbinfo->dobj.catId.oid, false);
13320 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13321 tbinfo->dobj.catId.oid);
13324 appendPQExpBuffer(query,
13325 "CREATE SEQUENCE %s\n",
13326 fmtId(tbinfo->dobj.name));
13328 if (fout->remoteVersion >= 80400)
13329 appendPQExpBuffer(query, " START WITH %s\n", startv);
13333 * Versions before 8.4 did not remember the true start value. If
13334 * is_called is false then the sequence has never been incremented
13335 * so we can use last_val. Otherwise punt and let it default.
13338 appendPQExpBuffer(query, " START WITH %s\n", last);
13341 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13344 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13346 appendPQExpBuffer(query, " NO MINVALUE\n");
13349 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13351 appendPQExpBuffer(query, " NO MAXVALUE\n");
13353 appendPQExpBuffer(query,
13355 cache, (cycled ? "\n CYCLE" : ""));
13357 appendPQExpBuffer(query, ";\n");
13359 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13361 /* binary_upgrade: no need to clear TOAST table oid */
13363 if (binary_upgrade)
13364 binary_upgrade_extension_member(query, &tbinfo->dobj,
13367 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13369 tbinfo->dobj.namespace->dobj.name,
13372 false, "SEQUENCE", SECTION_PRE_DATA,
13373 query->data, delqry->data, NULL,
13374 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13378 * If the sequence is owned by a table column, emit the ALTER for it
13379 * as a separate TOC entry immediately following the sequence's own
13380 * entry. It's OK to do this rather than using full sorting logic,
13381 * because the dependency that tells us it's owned will have forced
13382 * the table to be created first. We can't just include the ALTER in
13383 * the TOC entry because it will fail if we haven't reassigned the
13384 * sequence owner to match the table's owner.
13386 * We need not schema-qualify the table reference because both
13387 * sequence and table must be in the same schema.
13389 if (OidIsValid(tbinfo->owning_tab))
13391 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13393 if (owning_tab && owning_tab->dobj.dump)
13395 resetPQExpBuffer(query);
13396 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13397 fmtId(tbinfo->dobj.name));
13398 appendPQExpBuffer(query, " OWNED BY %s",
13399 fmtId(owning_tab->dobj.name));
13400 appendPQExpBuffer(query, ".%s;\n",
13401 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13403 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13405 tbinfo->dobj.namespace->dobj.name,
13408 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13409 query->data, "", NULL,
13410 &(tbinfo->dobj.dumpId), 1,
13415 /* Dump Sequence Comments and Security Labels */
13416 dumpComment(fout, labelq->data,
13417 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13418 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13419 dumpSecLabel(fout, labelq->data,
13420 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13421 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13426 resetPQExpBuffer(query);
13427 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13428 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13429 appendPQExpBuffer(query, ", %s, %s);\n",
13430 last, (called ? "true" : "false"));
13432 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13434 tbinfo->dobj.namespace->dobj.name,
13437 false, "SEQUENCE SET", SECTION_PRE_DATA,
13438 query->data, "", NULL,
13439 &(tbinfo->dobj.dumpId), 1,
13445 destroyPQExpBuffer(query);
13446 destroyPQExpBuffer(delqry);
13447 destroyPQExpBuffer(labelq);
13451 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13453 TableInfo *tbinfo = tginfo->tgtable;
13455 PQExpBuffer delqry;
13456 PQExpBuffer labelq;
13465 query = createPQExpBuffer();
13466 delqry = createPQExpBuffer();
13467 labelq = createPQExpBuffer();
13470 * DROP must be fully qualified in case same name appears in pg_catalog
13472 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13473 fmtId(tginfo->dobj.name));
13474 appendPQExpBuffer(delqry, "ON %s.",
13475 fmtId(tbinfo->dobj.namespace->dobj.name));
13476 appendPQExpBuffer(delqry, "%s;\n",
13477 fmtId(tbinfo->dobj.name));
13481 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13485 if (tginfo->tgisconstraint)
13487 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13488 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13492 appendPQExpBuffer(query, "CREATE TRIGGER ");
13493 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13495 appendPQExpBuffer(query, "\n ");
13498 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13499 appendPQExpBuffer(query, "BEFORE");
13500 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13501 appendPQExpBuffer(query, "AFTER");
13502 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13503 appendPQExpBuffer(query, "INSTEAD OF");
13506 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13511 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13513 appendPQExpBuffer(query, " INSERT");
13516 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13519 appendPQExpBuffer(query, " OR DELETE");
13521 appendPQExpBuffer(query, " DELETE");
13524 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13527 appendPQExpBuffer(query, " OR UPDATE");
13529 appendPQExpBuffer(query, " UPDATE");
13532 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13535 appendPQExpBuffer(query, " OR TRUNCATE");
13537 appendPQExpBuffer(query, " TRUNCATE");
13540 appendPQExpBuffer(query, " ON %s\n",
13541 fmtId(tbinfo->dobj.name));
13543 if (tginfo->tgisconstraint)
13545 if (OidIsValid(tginfo->tgconstrrelid))
13547 /* If we are using regclass, name is already quoted */
13548 if (fout->remoteVersion >= 70300)
13549 appendPQExpBuffer(query, " FROM %s\n ",
13550 tginfo->tgconstrrelname);
13552 appendPQExpBuffer(query, " FROM %s\n ",
13553 fmtId(tginfo->tgconstrrelname));
13555 if (!tginfo->tgdeferrable)
13556 appendPQExpBuffer(query, "NOT ");
13557 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13558 if (tginfo->tginitdeferred)
13559 appendPQExpBuffer(query, "DEFERRED\n");
13561 appendPQExpBuffer(query, "IMMEDIATE\n");
13564 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13565 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13567 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13569 /* In 7.3, result of regproc is already quoted */
13570 if (fout->remoteVersion >= 70300)
13571 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13574 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13575 fmtId(tginfo->tgfname));
13577 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13580 for (findx = 0; findx < tginfo->tgnargs; findx++)
13582 /* find the embedded null that terminates this trigger argument */
13583 size_t tlen = strlen(p);
13585 if (p + tlen >= tgargs + lentgargs)
13587 /* hm, not found before end of bytea value... */
13588 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13591 tbinfo->dobj.name);
13596 appendPQExpBuffer(query, ", ");
13597 appendStringLiteralAH(query, p, fout);
13601 appendPQExpBuffer(query, ");\n");
13604 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13606 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13607 fmtId(tbinfo->dobj.name));
13608 switch (tginfo->tgenabled)
13612 appendPQExpBuffer(query, "DISABLE");
13615 appendPQExpBuffer(query, "ENABLE ALWAYS");
13618 appendPQExpBuffer(query, "ENABLE REPLICA");
13621 appendPQExpBuffer(query, "ENABLE");
13624 appendPQExpBuffer(query, " TRIGGER %s;\n",
13625 fmtId(tginfo->dobj.name));
13628 appendPQExpBuffer(labelq, "TRIGGER %s ",
13629 fmtId(tginfo->dobj.name));
13630 appendPQExpBuffer(labelq, "ON %s",
13631 fmtId(tbinfo->dobj.name));
13633 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13635 tbinfo->dobj.namespace->dobj.name,
13637 tbinfo->rolname, false,
13638 "TRIGGER", SECTION_POST_DATA,
13639 query->data, delqry->data, NULL,
13640 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13643 dumpComment(fout, labelq->data,
13644 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13645 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13647 destroyPQExpBuffer(query);
13648 destroyPQExpBuffer(delqry);
13649 destroyPQExpBuffer(labelq);
13657 dumpRule(Archive *fout, RuleInfo *rinfo)
13659 TableInfo *tbinfo = rinfo->ruletable;
13662 PQExpBuffer delcmd;
13663 PQExpBuffer labelq;
13666 /* Skip if not to be dumped */
13667 if (!rinfo->dobj.dump || dataOnly)
13671 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13672 * we do not want to dump it as a separate object.
13674 if (!rinfo->separate)
13678 * Make sure we are in proper schema.
13680 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13682 query = createPQExpBuffer();
13683 cmd = createPQExpBuffer();
13684 delcmd = createPQExpBuffer();
13685 labelq = createPQExpBuffer();
13687 if (fout->remoteVersion >= 70300)
13689 appendPQExpBuffer(query,
13690 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13691 rinfo->dobj.catId.oid);
13695 /* Rule name was unique before 7.3 ... */
13696 appendPQExpBuffer(query,
13697 "SELECT pg_get_ruledef('%s') AS definition",
13701 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13703 if (PQntuples(res) != 1)
13705 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13706 rinfo->dobj.name, tbinfo->dobj.name);
13710 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13713 * Add the command to alter the rules replication firing semantics if it
13714 * differs from the default.
13716 if (rinfo->ev_enabled != 'O')
13718 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13719 fmtId(tbinfo->dobj.namespace->dobj.name));
13720 appendPQExpBuffer(cmd, "%s ",
13721 fmtId(tbinfo->dobj.name));
13722 switch (rinfo->ev_enabled)
13725 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13726 fmtId(rinfo->dobj.name));
13729 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13730 fmtId(rinfo->dobj.name));
13733 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13734 fmtId(rinfo->dobj.name));
13740 * DROP must be fully qualified in case same name appears in pg_catalog
13742 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13743 fmtId(rinfo->dobj.name));
13744 appendPQExpBuffer(delcmd, "ON %s.",
13745 fmtId(tbinfo->dobj.namespace->dobj.name));
13746 appendPQExpBuffer(delcmd, "%s;\n",
13747 fmtId(tbinfo->dobj.name));
13749 appendPQExpBuffer(labelq, "RULE %s",
13750 fmtId(rinfo->dobj.name));
13751 appendPQExpBuffer(labelq, " ON %s",
13752 fmtId(tbinfo->dobj.name));
13754 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13756 tbinfo->dobj.namespace->dobj.name,
13758 tbinfo->rolname, false,
13759 "RULE", SECTION_POST_DATA,
13760 cmd->data, delcmd->data, NULL,
13761 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13764 /* Dump rule comments */
13765 dumpComment(fout, labelq->data,
13766 tbinfo->dobj.namespace->dobj.name,
13768 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13772 destroyPQExpBuffer(query);
13773 destroyPQExpBuffer(cmd);
13774 destroyPQExpBuffer(delcmd);
13775 destroyPQExpBuffer(labelq);
13779 * getExtensionMembership --- obtain extension membership data
13782 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13793 DumpableObject *dobj,
13796 /* Nothing to do if no extensions */
13797 if (numExtensions == 0)
13800 /* Make sure we are in proper schema */
13801 selectSourceSchema(fout, "pg_catalog");
13803 query = createPQExpBuffer();
13805 /* refclassid constraint is redundant but may speed the search */
13806 appendPQExpBuffer(query, "SELECT "
13807 "classid, objid, refclassid, refobjid "
13809 "WHERE refclassid = 'pg_extension'::regclass "
13810 "AND deptype = 'e' "
13813 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13815 ntups = PQntuples(res);
13817 i_classid = PQfnumber(res, "classid");
13818 i_objid = PQfnumber(res, "objid");
13819 i_refclassid = PQfnumber(res, "refclassid");
13820 i_refobjid = PQfnumber(res, "refobjid");
13823 * Since we ordered the SELECT by referenced ID, we can expect that
13824 * multiple entries for the same extension will appear together; this
13825 * saves on searches.
13829 for (i = 0; i < ntups; i++)
13832 CatalogId refobjId;
13834 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13835 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13836 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13837 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13839 if (refdobj == NULL ||
13840 refdobj->catId.tableoid != refobjId.tableoid ||
13841 refdobj->catId.oid != refobjId.oid)
13842 refdobj = findObjectByCatalogId(refobjId);
13845 * Failure to find objects mentioned in pg_depend is not unexpected,
13846 * since for example we don't collect info about TOAST tables.
13848 if (refdobj == NULL)
13851 fprintf(stderr, "no referenced object %u %u\n",
13852 refobjId.tableoid, refobjId.oid);
13857 dobj = findObjectByCatalogId(objId);
13862 fprintf(stderr, "no referencing object %u %u\n",
13863 objId.tableoid, objId.oid);
13868 /* Record dependency so that getDependencies needn't repeat this */
13869 addObjectDependency(dobj, refdobj->dumpId);
13871 dobj->ext_member = true;
13874 * Normally, mark the member object as not to be dumped. But in
13875 * binary upgrades, we still dump the members individually, since the
13876 * idea is to exactly reproduce the database contents rather than
13877 * replace the extension contents with something different.
13879 if (!binary_upgrade)
13880 dobj->dump = false;
13882 dobj->dump = refdobj->dump;
13888 * Now identify extension configuration tables and create TableDataInfo
13889 * objects for them, ensuring their data will be dumped even though the
13890 * tables themselves won't be.
13892 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13893 * user data in a configuration table is treated like schema data. This
13894 * seems appropriate since system data in a config table would get
13895 * reloaded by CREATE EXTENSION.
13897 for (i = 0; i < numExtensions; i++)
13899 ExtensionInfo *curext = &(extinfo[i]);
13900 char *extconfig = curext->extconfig;
13901 char *extcondition = curext->extcondition;
13902 char **extconfigarray = NULL;
13903 char **extconditionarray = NULL;
13905 int nconditionitems;
13907 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13908 if (!curext->dobj.dump)
13911 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13912 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13913 nconfigitems == nconditionitems)
13917 for (j = 0; j < nconfigitems; j++)
13919 TableInfo *configtbl;
13921 configtbl = findTableByOid(atooid(extconfigarray[j]));
13922 if (configtbl == NULL)
13926 * Note: config tables are dumped without OIDs regardless
13927 * of the --oids setting. This is because row filtering
13928 * conditions aren't compatible with dumping OIDs.
13930 makeTableDataInfo(configtbl, false);
13931 if (configtbl->dataObj != NULL)
13933 if (strlen(extconditionarray[j]) > 0)
13934 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13938 if (extconfigarray)
13939 free(extconfigarray);
13940 if (extconditionarray)
13941 free(extconditionarray);
13944 destroyPQExpBuffer(query);
13948 * getDependencies --- obtain available dependency data
13951 getDependencies(Archive *fout)
13962 DumpableObject *dobj,
13965 /* No dependency info available before 7.3 */
13966 if (fout->remoteVersion < 70300)
13970 write_msg(NULL, "reading dependency data\n");
13972 /* Make sure we are in proper schema */
13973 selectSourceSchema(fout, "pg_catalog");
13975 query = createPQExpBuffer();
13978 * PIN dependencies aren't interesting, and EXTENSION dependencies were
13979 * already processed by getExtensionMembership.
13981 appendPQExpBuffer(query, "SELECT "
13982 "classid, objid, refclassid, refobjid, deptype "
13984 "WHERE deptype != 'p' AND deptype != 'e' "
13987 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13989 ntups = PQntuples(res);
13991 i_classid = PQfnumber(res, "classid");
13992 i_objid = PQfnumber(res, "objid");
13993 i_refclassid = PQfnumber(res, "refclassid");
13994 i_refobjid = PQfnumber(res, "refobjid");
13995 i_deptype = PQfnumber(res, "deptype");
13998 * Since we ordered the SELECT by referencing ID, we can expect that
13999 * multiple entries for the same object will appear together; this saves
14004 for (i = 0; i < ntups; i++)
14007 CatalogId refobjId;
14010 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14011 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14012 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14013 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14014 deptype = *(PQgetvalue(res, i, i_deptype));
14016 if (dobj == NULL ||
14017 dobj->catId.tableoid != objId.tableoid ||
14018 dobj->catId.oid != objId.oid)
14019 dobj = findObjectByCatalogId(objId);
14022 * Failure to find objects mentioned in pg_depend is not unexpected,
14023 * since for example we don't collect info about TOAST tables.
14028 fprintf(stderr, "no referencing object %u %u\n",
14029 objId.tableoid, objId.oid);
14034 refdobj = findObjectByCatalogId(refobjId);
14036 if (refdobj == NULL)
14039 fprintf(stderr, "no referenced object %u %u\n",
14040 refobjId.tableoid, refobjId.oid);
14046 * Ordinarily, table rowtypes have implicit dependencies on their
14047 * tables. However, for a composite type the implicit dependency goes
14048 * the other way in pg_depend; which is the right thing for DROP but
14049 * it doesn't produce the dependency ordering we need. So in that one
14050 * case, we reverse the direction of the dependency.
14052 if (deptype == 'i' &&
14053 dobj->objType == DO_TABLE &&
14054 refdobj->objType == DO_TYPE)
14055 addObjectDependency(refdobj, dobj->dumpId);
14058 addObjectDependency(dobj, refdobj->dumpId);
14063 destroyPQExpBuffer(query);
14068 * selectSourceSchema - make the specified schema the active search path
14069 * in the source database.
14071 * NB: pg_catalog is explicitly searched after the specified schema;
14072 * so user names are only qualified if they are cross-schema references,
14073 * and system names are only qualified if they conflict with a user name
14074 * in the current schema.
14076 * Whenever the selected schema is not pg_catalog, be careful to qualify
14077 * references to system catalogs and types in our emitted commands!
14080 selectSourceSchema(Archive *fout, const char *schemaName)
14082 static char *curSchemaName = NULL;
14085 /* Not relevant if fetching from pre-7.3 DB */
14086 if (fout->remoteVersion < 70300)
14088 /* Ignore null schema names */
14089 if (schemaName == NULL || *schemaName == '\0')
14091 /* Optimize away repeated selection of same schema */
14092 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14095 query = createPQExpBuffer();
14096 appendPQExpBuffer(query, "SET search_path = %s",
14097 fmtId(schemaName));
14098 if (strcmp(schemaName, "pg_catalog") != 0)
14099 appendPQExpBuffer(query, ", pg_catalog");
14101 ExecuteSqlStatement(fout, query->data);
14103 destroyPQExpBuffer(query);
14105 free(curSchemaName);
14106 curSchemaName = pg_strdup(schemaName);
14110 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14113 * NB: in 7.3 and up the result may depend on the currently-selected
14114 * schema; this is why we don't try to cache the names.
14117 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14125 if ((opts & zeroAsOpaque) != 0)
14126 return pg_strdup(g_opaque_type);
14127 else if ((opts & zeroAsAny) != 0)
14128 return pg_strdup("'any'");
14129 else if ((opts & zeroAsStar) != 0)
14130 return pg_strdup("*");
14131 else if ((opts & zeroAsNone) != 0)
14132 return pg_strdup("NONE");
14135 query = createPQExpBuffer();
14136 if (fout->remoteVersion >= 70300)
14138 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14141 else if (fout->remoteVersion >= 70100)
14143 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14148 appendPQExpBuffer(query, "SELECT typname "
14150 "WHERE oid = '%u'::oid",
14154 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14156 if (fout->remoteVersion >= 70100)
14158 /* already quoted */
14159 result = pg_strdup(PQgetvalue(res, 0, 0));
14163 /* may need to quote it */
14164 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14168 destroyPQExpBuffer(query);
14174 * myFormatType --- local implementation of format_type for use with 7.0.
14177 myFormatType(const char *typname, int32 typmod)
14180 bool isarray = false;
14181 PQExpBuffer buf = createPQExpBuffer();
14183 /* Handle array types */
14184 if (typname[0] == '_')
14190 /* Show lengths on bpchar and varchar */
14191 if (strcmp(typname, "bpchar") == 0)
14193 int len = (typmod - VARHDRSZ);
14195 appendPQExpBuffer(buf, "character");
14197 appendPQExpBuffer(buf, "(%d)",
14198 typmod - VARHDRSZ);
14200 else if (strcmp(typname, "varchar") == 0)
14202 appendPQExpBuffer(buf, "character varying");
14204 appendPQExpBuffer(buf, "(%d)",
14205 typmod - VARHDRSZ);
14207 else if (strcmp(typname, "numeric") == 0)
14209 appendPQExpBuffer(buf, "numeric");
14216 tmp_typmod = typmod - VARHDRSZ;
14217 precision = (tmp_typmod >> 16) & 0xffff;
14218 scale = tmp_typmod & 0xffff;
14219 appendPQExpBuffer(buf, "(%d,%d)",
14225 * char is an internal single-byte data type; Let's make sure we force it
14226 * through with quotes. - thomas 1998-12-13
14228 else if (strcmp(typname, "char") == 0)
14229 appendPQExpBuffer(buf, "\"char\"");
14231 appendPQExpBuffer(buf, "%s", fmtId(typname));
14233 /* Append array qualifier for array types */
14235 appendPQExpBuffer(buf, "[]");
14237 result = pg_strdup(buf->data);
14238 destroyPQExpBuffer(buf);
14244 * fmtQualifiedId - convert a qualified name to the proper format for
14245 * the source database.
14247 * Like fmtId, use the result before calling again.
14249 static const char *
14250 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14252 static PQExpBuffer id_return = NULL;
14254 if (id_return) /* first time through? */
14255 resetPQExpBuffer(id_return);
14257 id_return = createPQExpBuffer();
14259 /* Suppress schema name if fetching from pre-7.3 DB */
14260 if (fout->remoteVersion >= 70300 && schema && *schema)
14262 appendPQExpBuffer(id_return, "%s.",
14265 appendPQExpBuffer(id_return, "%s",
14268 return id_return->data;
14272 * Return a column list clause for the given relation.
14274 * Special case: if there are no undropped columns in the relation, return
14275 * "", not an invalid "()" column list.
14277 static const char *
14278 fmtCopyColumnList(const TableInfo *ti)
14280 static PQExpBuffer q = NULL;
14281 int numatts = ti->numatts;
14282 char **attnames = ti->attnames;
14283 bool *attisdropped = ti->attisdropped;
14287 if (q) /* first time through? */
14288 resetPQExpBuffer(q);
14290 q = createPQExpBuffer();
14292 appendPQExpBuffer(q, "(");
14294 for (i = 0; i < numatts; i++)
14296 if (attisdropped[i])
14299 appendPQExpBuffer(q, ", ");
14300 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14305 return ""; /* no undropped columns */
14307 appendPQExpBuffer(q, ")");
14312 * Execute an SQL query and verify that we got exactly one row back.
14315 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14320 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14322 /* Expecting a single result only */
14323 ntups = PQntuples(res);
14325 exit_horribly(NULL,
14326 ngettext("query returned %d row instead of one: %s\n",
14327 "query returned %d rows instead of one: %s\n",